From python-checkins at python.org Thu Feb 1 00:31:46 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 1 Feb 2007 00:31:46 +0100 (CET) Subject: [Python-checkins] r53608 - in python/branches/bcannon-objcap: BRANCHNEWS Include/moduleobject.h Objects/moduleobject.c Python/import.c Python/pythonrun.c Message-ID: <20070131233146.8ED181E4006@bag.python.org> Author: brett.cannon Date: Thu Feb 1 00:31:44 2007 New Revision: 53608 Modified: python/branches/bcannon-objcap/BRANCHNEWS python/branches/bcannon-objcap/Include/moduleobject.h python/branches/bcannon-objcap/Objects/moduleobject.c python/branches/bcannon-objcap/Python/import.c python/branches/bcannon-objcap/Python/pythonrun.c Log: Change the import machinery on how it handles importing 'sys'. Before the import code used the cached dictionary that was created after _PySys_Init() was called but before any subsequent items were added (e.g., sys.path). Now, PyImport_FindExtension() (which is what uses the extension module cache for importing new modules) checks if it is dealing with 'sys'. If it is it then sets the module's dict to the interpreter's sysdict instead of the cached version. Modified: python/branches/bcannon-objcap/BRANCHNEWS ============================================================================== --- python/branches/bcannon-objcap/BRANCHNEWS (original) +++ python/branches/bcannon-objcap/BRANCHNEWS Thu Feb 1 00:31:44 2007 @@ -8,6 +8,11 @@ Core and builtins ----------------- +* Make importing the sys module after it has been completely deleted use the + interpreter's sysdict instead of the cached dict used by the import + machinery. This lets the sys module be deleted for security reasons during + startup. + * rev. ????: Added a delegate for import that calls sys.import_. * rev. 51679: Remove the constructor for the 'code' type. This means instances Modified: python/branches/bcannon-objcap/Include/moduleobject.h ============================================================================== --- python/branches/bcannon-objcap/Include/moduleobject.h (original) +++ python/branches/bcannon-objcap/Include/moduleobject.h Thu Feb 1 00:31:44 2007 @@ -14,6 +14,7 @@ PyAPI_FUNC(PyObject *) PyModule_New(const char *); PyAPI_FUNC(PyObject *) PyModule_GetDict(PyObject *); +PyAPI_FUNC(void) PyModule_SetDict(PyObject *, PyObject *); PyAPI_FUNC(char *) PyModule_GetName(PyObject *); PyAPI_FUNC(char *) PyModule_GetFilename(PyObject *); PyAPI_FUNC(void) _PyModule_Clear(PyObject *); Modified: python/branches/bcannon-objcap/Objects/moduleobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/moduleobject.c (original) +++ python/branches/bcannon-objcap/Objects/moduleobject.c Thu Feb 1 00:31:44 2007 @@ -54,6 +54,16 @@ return d; } +void +PyModule_SetDict(PyObject *m, PyObject *new_dict) +{ + PyModuleObject *module = (PyModuleObject *)m; + PyObject *old_dict = module->md_dict; + + Py_XDECREF(old_dict); + module->md_dict = new_dict; +} + char * PyModule_GetName(PyObject *m) { Modified: python/branches/bcannon-objcap/Python/import.c ============================================================================== --- python/branches/bcannon-objcap/Python/import.c (original) +++ python/branches/bcannon-objcap/Python/import.c Thu Feb 1 00:31:44 2007 @@ -563,8 +563,17 @@ mdict = PyModule_GetDict(mod); if (mdict == NULL) return NULL; - if (PyDict_Update(mdict, dict)) - return NULL; + if ((!strcmp("sys", name)) && (!strcmp("sys", filename))) { + PyThreadState *tstate = PyThreadState_GET(); + PyObject *sysdict = tstate->interp->sysdict; + + Py_INCREF(sysdict); + PyModule_SetDict(mod, sysdict); + } + else { + if (PyDict_Update(mdict, dict)) + return NULL; + } if (Py_VerboseFlag) PySys_WriteStderr("import %s # previously loaded (%s)\n", name, filename); Modified: python/branches/bcannon-objcap/Python/pythonrun.c ============================================================================== --- python/branches/bcannon-objcap/Python/pythonrun.c (original) +++ python/branches/bcannon-objcap/Python/pythonrun.c Thu Feb 1 00:31:44 2007 @@ -357,9 +357,6 @@ Current scope of execution. * exceptions Safe to keep around. - * sys - Certain values set during Python initialization that are lost - when the module is deleted and then re-imported. * encodings Does dynamic import of encodings which requires globals() to work; globals() fails when the module has been deleted. @@ -379,7 +376,6 @@ if ((strcmp(module_name, "__builtin__") != 0) && (strcmp(module_name, "exceptions") != 0) && (strcmp(module_name, "__main__") != 0) && - (strcmp(module_name, "sys") != 0) && (strcmp(module_name, "encodings") != 0) && (strcmp(module_name, "encodings.utf_8") != 0) && (strcmp(module_name, "codecs") != 0) && From python-checkins at python.org Thu Feb 1 01:20:26 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 1 Feb 2007 01:20:26 +0100 (CET) Subject: [Python-checkins] r53609 - in python/branches/bcannon-objcap: BRANCHNEWS Python/pythonrun.c Message-ID: <20070201002026.B64561E400D@bag.python.org> Author: brett.cannon Date: Thu Feb 1 01:20:25 2007 New Revision: 53609 Modified: python/branches/bcannon-objcap/BRANCHNEWS python/branches/bcannon-objcap/Python/pythonrun.c Log: Get the 'warnings' module cached away in the C code so that the module is still usable by C code. Modified: python/branches/bcannon-objcap/BRANCHNEWS ============================================================================== --- python/branches/bcannon-objcap/BRANCHNEWS (original) +++ python/branches/bcannon-objcap/BRANCHNEWS Thu Feb 1 01:20:25 2007 @@ -8,6 +8,8 @@ Core and builtins ----------------- +* Force 'warnings' to be cached by the C code. + * Make importing the sys module after it has been completely deleted use the interpreter's sysdict instead of the cached dict used by the import machinery. This lets the sys module be deleted for security reasons during Modified: python/branches/bcannon-objcap/Python/pythonrun.c ============================================================================== --- python/branches/bcannon-objcap/Python/pythonrun.c (original) +++ python/branches/bcannon-objcap/Python/pythonrun.c Thu Feb 1 01:20:25 2007 @@ -334,6 +334,7 @@ PyInterpreterState *interp; Py_ssize_t module_count, x; PyObject* module_names_list; + PyObject* hidden_modules; Py_InitializeEx(1); @@ -359,32 +360,53 @@ Safe to keep around. * encodings Does dynamic import of encodings which requires globals() to - work; globals() fails when the module has been deleted. - * encodings.utf_8 - Many encodings use this. + work; globals() fails when the module has been deleted. Also + fails if you hide module because importing of submodules for + encodings no longer has the parent package. * codecs Incremental codecs fail. - * warnings + * _codecs + Exposed by codecs. + * warnings (hide: needs sys._getframe()) Warnings reset otherwise. */ + /* Get the 'warnings' module cached away at the C level. */ + PyModule_GetWarningsModule(); module_names_list = PyDict_Keys(interp->modules); module_count = PyList_GET_SIZE(module_names_list); + hidden_modules = PyDict_New(); for (x=0; x < module_count; x+=1) { char *module_name = PyString_AS_STRING( PyList_GET_ITEM(module_names_list, x)); - if ((strcmp(module_name, "__builtin__") != 0) && - (strcmp(module_name, "exceptions") != 0) && - (strcmp(module_name, "__main__") != 0) && - (strcmp(module_name, "encodings") != 0) && - (strcmp(module_name, "encodings.utf_8") != 0) && - (strcmp(module_name, "codecs") != 0) && - (strcmp(module_name, "warnings") != 0)) { + /* Modules that *must* stay visible. */ + if ((strcmp(module_name, "__builtin__") == 0) || + (strcmp(module_name, "__main__") == 0) || + (strcmp(module_name, "exceptions") == 0) || + (strcmp(module_name, "encodings") == 0) || + (strcmp(module_name, "codecs") == 0) || + (strcmp(module_name, "_codecs") == 0)) { + continue; + } + /* Modules that *must* stay but can be invisible. */ + /*else if ((strcmp(module_name, "warnings") == 0)) { + PyObject *module = + PyDict_GetItemString(interp->modules, + module_name); + PyDict_SetItemString(hidden_modules, module_name, + module); + PyDict_DelItemString(interp->modules, module_name); + }*/ + /* Everything else can go. */ + else { PyDict_DelItemString(interp->modules, module_name); } } - PyDict_SetItemString(interp->sysdict, "modules", interp->modules); + /* Store away modules that must stick around but should not be exposed. + */ + PyDict_SetItemString(interp->modules, ".hidden", hidden_modules); + PyDict_SetItemString(interp->sysdict, "modules", interp->modules); } From buildbot at python.org Thu Feb 1 03:39:53 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 01 Feb 2007 02:39:53 +0000 Subject: [Python-checkins] buildbot failure in x86 OpenBSD 2.5 Message-ID: <20070201023953.DD27A1E4006@bag.python.org> The Buildbot has detected a new failure of x86 OpenBSD 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520OpenBSD%25202.5/builds/183 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Reynaldo': Robbie Build Source Stamp: [branch Addison] Dylan Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Thu Feb 1 03:40:23 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 01 Feb 2007 02:40:23 +0000 Subject: [Python-checkins] buildbot failure in x86 gentoo 2.5 Message-ID: <20070201024023.0D9591E400D@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/201 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Nicholas': Rodney Build Source Stamp: [branch Roberto] Chris Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Thu Feb 1 03:42:51 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 01 Feb 2007 02:42:51 +0000 Subject: [Python-checkins] buildbot failure in x86 XP 2.5 Message-ID: <20070201024251.95A611E4006@bag.python.org> The Buildbot has detected a new failure of x86 XP 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%25202.5/builds/104 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Daquan': Jayden Build Source Stamp: [branch Elian] River Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Thu Feb 1 03:53:51 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 01 Feb 2007 02:53:51 +0000 Subject: [Python-checkins] buildbot failure in amd64 gentoo 2.5 Message-ID: <20070201025352.0B1171E4006@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%25202.5/builds/204 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Mauro': Wyatt Build Source Stamp: [branch Igor] Ali Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Thu Feb 1 04:00:08 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 01 Feb 2007 03:00:08 +0000 Subject: [Python-checkins] buildbot failure in g4 osx.4 2.5 Message-ID: <20070201030008.5ED2D1E4006@bag.python.org> The Buildbot has detected a new failure of g4 osx.4 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/g4%2520osx.4%25202.5/builds/193 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Carey': Chance Build Source Stamp: [branch Fernando] Marcos Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Thu Feb 1 04:00:24 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 01 Feb 2007 03:00:24 +0000 Subject: [Python-checkins] buildbot failure in sparc solaris10 gcc 2.5 Message-ID: <20070201030024.7FEE91E4006@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%25202.5/builds/194 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Emmett': Markus Build Source Stamp: [branch Jace] Kenny Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From python-checkins at python.org Thu Feb 1 19:02:39 2007 From: python-checkins at python.org (thomas.wouters) Date: Thu, 1 Feb 2007 19:02:39 +0100 (CET) Subject: [Python-checkins] r53610 - in python/branches/p3yk: Doc/api/concrete.tex Doc/commontex/license.tex Doc/dist/dist.tex Doc/lib/libmailbox.tex Doc/lib/librandom.tex Doc/lib/libstruct.tex Doc/lib/libtime.tex Doc/ref/ref3.tex Include/Python-ast.h Include/object.h Lib/logging/handlers.py Lib/mailbox.py Lib/ntpath.py Lib/pdb.py Lib/random.py Lib/rfc822.py Lib/smtplib.py Lib/socket.py Lib/tarfile.py Lib/test/crashers/weakref_in_del.py Lib/test/output/test_new Lib/test/output/test_popen Lib/test/output/test_resource Lib/test/test_array.py Lib/test/test_deque.py Lib/test/test_dumbdbm.py Lib/test/test_itertools.py Lib/test/test_mailbox.py Lib/test/test_new.py Lib/test/test_ntpath.py Lib/test/test_old_mailbox.py Lib/test/test_popen.py Lib/test/test_posixpath.py Lib/test/test_random.py Lib/test/test_resource.py Lib/test/test_socket.py Lib/test/test_struct.py Lib/test/test_urllib2net.py Lib/test/test_uu.py Lib/test/test_weakref.py Lib/urllib.py Lib/urllib2.py Modules/_ctypes/_ctypes_test.c Modules/_randommodule.c Modules/_struct.c Modules/arraymodule.c Modules/collectionsmodule.c Modules/itertoolsmodule.c Objects/fileobject.c Objects/object.c Objects/typeobject.c Objects/weakrefobject.c PCbuild/_bsddb.vcproj PCbuild/_elementtree.vcproj PCbuild/_msi.vcproj PCbuild/_socket.vcproj PCbuild/_sqlite3.vcproj PCbuild/_ssl.mak PCbuild/_testcapi.vcproj PCbuild/_tkinter.vcproj PCbuild/build_ssl.py PCbuild/bz2.vcproj PCbuild/pyexpat.vcproj PCbuild/python.vcproj PCbuild/pythoncore.vcproj PCbuild/pythonw.vcproj PCbuild/select.vcproj PCbuild/unicodedata.vcproj PCbuild/winsound.vcproj Parser/asdl_c.py Python/pythonrun.c Python/sysmodule.c Python/traceback.c Tools/msi/uuids.py configure configure.in pyconfig.h.in Message-ID: <20070201180239.E2C411E4009@bag.python.org> Author: thomas.wouters Date: Thu Feb 1 19:02:27 2007 New Revision: 53610 Removed: python/branches/p3yk/Lib/test/output/test_new python/branches/p3yk/Lib/test/output/test_popen python/branches/p3yk/Lib/test/output/test_resource Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/api/concrete.tex python/branches/p3yk/Doc/commontex/license.tex python/branches/p3yk/Doc/dist/dist.tex python/branches/p3yk/Doc/lib/libmailbox.tex python/branches/p3yk/Doc/lib/librandom.tex python/branches/p3yk/Doc/lib/libstruct.tex python/branches/p3yk/Doc/lib/libtime.tex python/branches/p3yk/Doc/ref/ref3.tex python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Include/object.h python/branches/p3yk/Lib/logging/handlers.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/ntpath.py python/branches/p3yk/Lib/pdb.py python/branches/p3yk/Lib/random.py python/branches/p3yk/Lib/rfc822.py python/branches/p3yk/Lib/smtplib.py python/branches/p3yk/Lib/socket.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/test/crashers/weakref_in_del.py python/branches/p3yk/Lib/test/test_array.py python/branches/p3yk/Lib/test/test_deque.py python/branches/p3yk/Lib/test/test_dumbdbm.py python/branches/p3yk/Lib/test/test_itertools.py python/branches/p3yk/Lib/test/test_mailbox.py python/branches/p3yk/Lib/test/test_new.py python/branches/p3yk/Lib/test/test_ntpath.py python/branches/p3yk/Lib/test/test_old_mailbox.py python/branches/p3yk/Lib/test/test_popen.py python/branches/p3yk/Lib/test/test_posixpath.py python/branches/p3yk/Lib/test/test_random.py python/branches/p3yk/Lib/test/test_resource.py python/branches/p3yk/Lib/test/test_socket.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_urllib2net.py python/branches/p3yk/Lib/test/test_uu.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/urllib.py python/branches/p3yk/Lib/urllib2.py python/branches/p3yk/Modules/_ctypes/_ctypes_test.c python/branches/p3yk/Modules/_randommodule.c python/branches/p3yk/Modules/_struct.c python/branches/p3yk/Modules/arraymodule.c python/branches/p3yk/Modules/collectionsmodule.c python/branches/p3yk/Modules/itertoolsmodule.c python/branches/p3yk/Objects/fileobject.c python/branches/p3yk/Objects/object.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/Objects/weakrefobject.c python/branches/p3yk/PCbuild/_bsddb.vcproj python/branches/p3yk/PCbuild/_elementtree.vcproj python/branches/p3yk/PCbuild/_msi.vcproj python/branches/p3yk/PCbuild/_socket.vcproj python/branches/p3yk/PCbuild/_sqlite3.vcproj python/branches/p3yk/PCbuild/_ssl.mak python/branches/p3yk/PCbuild/_testcapi.vcproj python/branches/p3yk/PCbuild/_tkinter.vcproj python/branches/p3yk/PCbuild/build_ssl.py python/branches/p3yk/PCbuild/bz2.vcproj python/branches/p3yk/PCbuild/pyexpat.vcproj python/branches/p3yk/PCbuild/python.vcproj python/branches/p3yk/PCbuild/pythoncore.vcproj python/branches/p3yk/PCbuild/pythonw.vcproj python/branches/p3yk/PCbuild/select.vcproj python/branches/p3yk/PCbuild/unicodedata.vcproj python/branches/p3yk/PCbuild/winsound.vcproj python/branches/p3yk/Parser/asdl_c.py python/branches/p3yk/Python/pythonrun.c python/branches/p3yk/Python/sysmodule.c python/branches/p3yk/Python/traceback.c python/branches/p3yk/Tools/msi/uuids.py python/branches/p3yk/configure python/branches/p3yk/configure.in python/branches/p3yk/pyconfig.h.in Log: Merged revisions 53451-53537 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53454 | brett.cannon | 2007-01-15 20:12:08 +0100 (Mon, 15 Jan 2007) | 3 lines Add a note for strptime that just because strftime supports some extra directive that is not documented that strptime will as well. ........ r53458 | vinay.sajip | 2007-01-16 10:50:07 +0100 (Tue, 16 Jan 2007) | 1 line Updated rotating file handlers to use _open(). ........ r53459 | marc-andre.lemburg | 2007-01-16 14:03:06 +0100 (Tue, 16 Jan 2007) | 2 lines Add news items for the recent pybench and platform changes. ........ r53460 | sjoerd.mullender | 2007-01-16 17:42:38 +0100 (Tue, 16 Jan 2007) | 4 lines Fixed ntpath.expandvars to not replace references to non-existing variables with nothing. Also added tests. This fixes bug #494589. ........ r53464 | neal.norwitz | 2007-01-17 07:23:51 +0100 (Wed, 17 Jan 2007) | 1 line Give Calvin Spealman access for python-dev summaries. ........ r53465 | neal.norwitz | 2007-01-17 09:37:26 +0100 (Wed, 17 Jan 2007) | 1 line Remove Calvin since he only has access to the website currently. ........ r53466 | thomas.heller | 2007-01-17 10:40:34 +0100 (Wed, 17 Jan 2007) | 2 lines Replace C++ comments with C comments. ........ r53472 | andrew.kuchling | 2007-01-17 20:55:06 +0100 (Wed, 17 Jan 2007) | 1 line [Part of bug #1599254] Add suggestion to Mailbox docs to use Maildir, and warn user to lock/unlock mailboxes when modifying them ........ r53475 | georg.brandl | 2007-01-17 22:09:04 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1637967: missing //= operator in list. ........ r53477 | georg.brandl | 2007-01-17 22:19:58 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1629125: fix wrong data type (int -> Py_ssize_t) in PyDict_Next docs. ........ r53481 | neal.norwitz | 2007-01-18 06:40:58 +0100 (Thu, 18 Jan 2007) | 1 line Try reverting part of r53145 that seems to cause the Windows buildbots to fail in test_uu.UUFileTest.test_encode ........ r53482 | fred.drake | 2007-01-18 06:42:30 +0100 (Thu, 18 Jan 2007) | 1 line add missing version entry ........ r53483 | neal.norwitz | 2007-01-18 07:20:55 +0100 (Thu, 18 Jan 2007) | 7 lines This test doesn't pass on Windows. The cause seems to be that chmod doesn't support the same funcationality as on Unix. I'm not sure if this fix is the best (or if it will even work)--it's a test to see if the buildbots start passing again. It might be better to not even run this test if it's windows (or non-posix). ........ r53488 | neal.norwitz | 2007-01-19 06:53:33 +0100 (Fri, 19 Jan 2007) | 1 line SF #1635217, Fix unbalanced paren ........ r53489 | martin.v.loewis | 2007-01-19 07:42:22 +0100 (Fri, 19 Jan 2007) | 3 lines Prefix AST symbols with _Py_. Fixes #1637022. Will backport. ........ r53497 | martin.v.loewis | 2007-01-19 19:01:38 +0100 (Fri, 19 Jan 2007) | 2 lines Add UUIDs for 2.5.1 and 2.5.2 ........ r53499 | raymond.hettinger | 2007-01-19 19:07:18 +0100 (Fri, 19 Jan 2007) | 1 line SF# 1635892: Fix docs for betavariate's input parameters . ........ r53503 | martin.v.loewis | 2007-01-20 15:05:39 +0100 (Sat, 20 Jan 2007) | 2 lines Merge 53501 and 53502 from 25 branch: Add /GS- for AMD64 and Itanium builds where missing. ........ r53504 | walter.doerwald | 2007-01-20 18:28:31 +0100 (Sat, 20 Jan 2007) | 2 lines Port test_resource.py to unittest. ........ r53505 | walter.doerwald | 2007-01-20 19:19:33 +0100 (Sat, 20 Jan 2007) | 2 lines Add argument tests an calls of resource.getrusage(). ........ r53506 | walter.doerwald | 2007-01-20 20:03:17 +0100 (Sat, 20 Jan 2007) | 2 lines resource.RUSAGE_BOTH might not exist. ........ r53507 | walter.doerwald | 2007-01-21 00:07:28 +0100 (Sun, 21 Jan 2007) | 2 lines Port test_new.py to unittest. ........ r53508 | martin.v.loewis | 2007-01-21 10:33:07 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1610575: Add support for _Bool to struct. ........ r53509 | georg.brandl | 2007-01-21 11:28:43 +0100 (Sun, 21 Jan 2007) | 3 lines Bug #1486663: don't reject keyword arguments for subclasses of builtin types. ........ r53511 | georg.brandl | 2007-01-21 11:35:10 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1627441: close sockets properly in urllib2. ........ r53517 | georg.brandl | 2007-01-22 20:40:21 +0100 (Mon, 22 Jan 2007) | 3 lines Use new email module names (#1637162, #1637159, #1637157). ........ r53518 | andrew.kuchling | 2007-01-22 21:26:40 +0100 (Mon, 22 Jan 2007) | 1 line Improve pattern used for mbox 'From' lines; add a simple test ........ r53519 | andrew.kuchling | 2007-01-22 21:27:50 +0100 (Mon, 22 Jan 2007) | 1 line Make comment match the code ........ r53522 | georg.brandl | 2007-01-22 22:10:33 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1249573: fix rfc822.parsedate not accepting a certain date format ........ r53524 | georg.brandl | 2007-01-22 22:23:41 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1627316: handle error in condition/ignore pdb commands more gracefully. ........ r53526 | lars.gustaebel | 2007-01-23 12:17:33 +0100 (Tue, 23 Jan 2007) | 4 lines Patch #1507247: tarfile.py: use current umask for intermediate directories. ........ r53527 | thomas.wouters | 2007-01-23 14:42:00 +0100 (Tue, 23 Jan 2007) | 13 lines SF patch #1630975: Fix crash when replacing sys.stdout in sitecustomize When running the interpreter in an environment that would cause it to set stdout/stderr/stdin's encoding, having a sitecustomize that would replace them with something other than PyFile objects would crash the interpreter. Fix it by simply ignoring the encoding-setting for non-files. This could do with a test, but I can think of no maintainable and portable way to test this bug, short of adding a sitecustomize.py to the buildsystem and have it always run with it (hmmm....) ........ r53528 | thomas.wouters | 2007-01-23 14:50:49 +0100 (Tue, 23 Jan 2007) | 4 lines Add news entry about last checkin (oops.) ........ r53531 | martin.v.loewis | 2007-01-23 22:11:47 +0100 (Tue, 23 Jan 2007) | 4 lines Make PyTraceBack_Here use the current thread, not the frame's thread state. Fixes #1579370. Will backport. ........ r53535 | brett.cannon | 2007-01-24 00:21:22 +0100 (Wed, 24 Jan 2007) | 5 lines Fix crasher for when an object's __del__ creates a new weakref to itself. Patch only fixes new-style classes; classic classes still buggy. Closes bug #1377858. Already backported. ........ r53536 | walter.doerwald | 2007-01-24 01:42:19 +0100 (Wed, 24 Jan 2007) | 2 lines Port test_popen.py to unittest. ........ Modified: python/branches/p3yk/Doc/api/concrete.tex ============================================================================== --- python/branches/p3yk/Doc/api/concrete.tex (original) +++ python/branches/p3yk/Doc/api/concrete.tex Thu Feb 1 19:02:27 2007 @@ -2082,7 +2082,7 @@ \begin{verbatim} PyObject *key, *value; -int pos = 0; +Py_ssize_t pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { /* do something interesting with the values... */ @@ -2097,7 +2097,7 @@ \begin{verbatim} PyObject *key, *value; -int pos = 0; +Py_ssize_t pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { int i = PyInt_AS_LONG(value) + 1; Modified: python/branches/p3yk/Doc/commontex/license.tex ============================================================================== --- python/branches/p3yk/Doc/commontex/license.tex (original) +++ python/branches/p3yk/Doc/commontex/license.tex Thu Feb 1 19:02:27 2007 @@ -50,6 +50,7 @@ \linev{2.4.1}{2.4}{2005}{PSF}{yes} \linev{2.4.2}{2.4.1}{2005}{PSF}{yes} \linev{2.4.3}{2.4.2}{2006}{PSF}{yes} + \linev{2.4.4}{2.4.3}{2006}{PSF}{yes} \linev{2.5}{2.4}{2006}{PSF}{yes} \end{tablev} Modified: python/branches/p3yk/Doc/dist/dist.tex ============================================================================== --- python/branches/p3yk/Doc/dist/dist.tex (original) +++ python/branches/p3yk/Doc/dist/dist.tex Thu Feb 1 19:02:27 2007 @@ -692,7 +692,7 @@ \begin{tableii}{l|l}{code}{Provides Expression}{Explanation} \lineii{mypkg} {Provide \code{mypkg}, using the distribution version} - \lineii{mypkg (1.1} {Provide \code{mypkg} version 1.1, regardless of the + \lineii{mypkg (1.1)} {Provide \code{mypkg} version 1.1, regardless of the distribution version} \end{tableii} Modified: python/branches/p3yk/Doc/lib/libmailbox.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libmailbox.tex (original) +++ python/branches/p3yk/Doc/lib/libmailbox.tex Thu Feb 1 19:02:27 2007 @@ -25,22 +25,29 @@ A mailbox, which may be inspected and modified. \end{classdesc*} +The \class{Mailbox} class defines an interface and +is not intended to be instantiated. Instead, format-specific +subclasses should inherit from \class{Mailbox} and your code +should instantiate a particular subclass. + The \class{Mailbox} interface is dictionary-like, with small keys -corresponding to messages. Keys are issued by the \class{Mailbox} instance -with which they will be used and are only meaningful to that \class{Mailbox} -instance. A key continues to identify a message even if the corresponding -message is modified, such as by replacing it with another message. Messages may -be added to a \class{Mailbox} instance using the set-like method -\method{add()} and removed using a \code{del} statement or the set-like methods -\method{remove()} and \method{discard()}. +corresponding to messages. Keys are issued by the \class{Mailbox} +instance with which they will be used and are only meaningful to that +\class{Mailbox} instance. A key continues to identify a message even +if the corresponding message is modified, such as by replacing it with +another message. + +Messages may be added to a \class{Mailbox} instance using the set-like +method \method{add()} and removed using a \code{del} statement or the +set-like methods \method{remove()} and \method{discard()}. \class{Mailbox} interface semantics differ from dictionary semantics in some -noteworthy ways. Each time a message is requested, a new representation -(typically a \class{Message} instance) is generated, based upon the current -state of the mailbox. Similarly, when a message is added to a \class{Mailbox} -instance, the provided message representation's contents are copied. In neither -case is a reference to the message representation kept by the \class{Mailbox} -instance. +noteworthy ways. Each time a message is requested, a new +representation (typically a \class{Message} instance) is generated +based upon the current state of the mailbox. Similarly, when a message +is added to a \class{Mailbox} instance, the provided message +representation's contents are copied. In neither case is a reference +to the message representation kept by the \class{Mailbox} instance. The default \class{Mailbox} iterator iterates over message representations, not keys as the default dictionary iterator does. Moreover, modification of a @@ -51,9 +58,14 @@ \exception{KeyError} exception if the corresponding message is subsequently removed. -\class{Mailbox} itself is intended to define an interface and to be inherited -from by format-specific subclasses but is not intended to be instantiated. -Instead, you should instantiate a subclass. +Be very cautious when modifying mailboxes that might also be changed +by some other process. The safest mailbox format to use for such +tasks is Maildir; try to avoid using single-file formats such as mbox +for concurrent writing. If you're modifying a mailbox, no matter what +the format, you must lock it by calling the \method{lock()} and +\method{unlock()} methods before making any changes. Failing to lock +the mailbox runs the risk of losing data if some other process makes +changes to the mailbox while your Python code is running. \class{Mailbox} instances have the following methods: @@ -202,15 +214,16 @@ \begin{methoddesc}{flush}{} Write any pending changes to the filesystem. For some \class{Mailbox} -subclasses, changes are always written immediately and this method does -nothing. +subclasses, changes are always written immediately and \method{flush()} does +nothing, but you should still make a habit of calling this method. \end{methoddesc} \begin{methoddesc}{lock}{} Acquire an exclusive advisory lock on the mailbox so that other processes know not to modify it. An \exception{ExternalClashError} is raised if the lock is not available. The particular locking mechanisms used depend upon the mailbox -format. +format. You should \emph{always} lock the mailbox before making any +modifications to its contents. \end{methoddesc} \begin{methoddesc}{unlock}{} @@ -1373,36 +1386,55 @@ \begin{verbatim} import mailbox destination = mailbox.MH('~/Mail') +destination.lock() for message in mailbox.Babyl('~/RMAIL'): destination.add(MHMessage(message)) +destination.flush() +destination.unlock() \end{verbatim} -An example of sorting mail from numerous mailing lists, being careful to avoid -mail corruption due to concurrent modification by other programs, mail loss due -to interruption of the program, or premature termination due to malformed -messages in the mailbox: +This example sorts mail from several mailing lists into different +mailboxes, being careful to avoid mail corruption due to concurrent +modification by other programs, mail loss due to interruption of the +program, or premature termination due to malformed messages in the +mailbox: \begin{verbatim} import mailbox import email.Errors + list_names = ('python-list', 'python-dev', 'python-bugs') + boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names) -inbox = mailbox.Maildir('~/Maildir', None) +inbox = mailbox.Maildir('~/Maildir', factory=None) + for key in inbox.iterkeys(): try: message = inbox[key] except email.Errors.MessageParseError: continue # The message is malformed. Just leave it. + for name in list_names: list_id = message['list-id'] if list_id and name in list_id: + # Get mailbox to use box = boxes[name] + + # Write copy to disk before removing original. + # If there's a crash, you might duplicate a message, but + # that's better than losing a message completely. box.lock() box.add(message) - box.flush() # Write copy to disk before removing original. + box.flush() box.unlock() + + # Remove original message + inbox.lock() inbox.discard(key) + inbox.flush() + inbox.unlock() break # Found destination, so stop looking. + for box in boxes.itervalues(): box.close() \end{verbatim} Modified: python/branches/p3yk/Doc/lib/librandom.tex ============================================================================== --- python/branches/p3yk/Doc/lib/librandom.tex (original) +++ python/branches/p3yk/Doc/lib/librandom.tex Thu Feb 1 19:02:27 2007 @@ -185,7 +185,7 @@ \begin{funcdesc}{betavariate}{alpha, beta} Beta distribution. Conditions on the parameters are - \code{\var{alpha} > -1} and \code{\var{beta} > -1}. + \code{\var{alpha} > 0} and \code{\var{beta} > 0}. Returned values range between 0 and 1. \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/libstruct.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstruct.tex (original) +++ python/branches/p3yk/Doc/lib/libstruct.tex Thu Feb 1 19:02:27 2007 @@ -50,14 +50,15 @@ \lineiv{c}{\ctype{char}}{string of length 1}{} \lineiv{b}{\ctype{signed char}}{integer}{} \lineiv{B}{\ctype{unsigned char}}{integer}{} + \lineiv{t}{\ctype{_Bool}}{bool}{(1)} \lineiv{h}{\ctype{short}}{integer}{} \lineiv{H}{\ctype{unsigned short}}{integer}{} \lineiv{i}{\ctype{int}}{integer}{} \lineiv{I}{\ctype{unsigned int}}{long}{} \lineiv{l}{\ctype{long}}{integer}{} \lineiv{L}{\ctype{unsigned long}}{long}{} - \lineiv{q}{\ctype{long long}}{long}{(1)} - \lineiv{Q}{\ctype{unsigned long long}}{long}{(1)} + \lineiv{q}{\ctype{long long}}{long}{(2)} + \lineiv{Q}{\ctype{unsigned long long}}{long}{(2)} \lineiv{f}{\ctype{float}}{float}{} \lineiv{d}{\ctype{double}}{float}{} \lineiv{s}{\ctype{char[]}}{string}{} @@ -70,6 +71,11 @@ \begin{description} \item[(1)] + The \character{t} conversion code corresponds to the \ctype{_Bool} type + defined by C99. If this type is not available, it is simulated using a + \ctype{char}. In standard mode, it is always represented by one byte. + \versionadded{2.6} +\item[(2)] The \character{q} and \character{Q} conversion codes are available in native mode only if the platform C compiler supports C \ctype{long long}, or, on Windows, \ctype{__int64}. They are always available in standard @@ -118,6 +124,12 @@ meaning a Python long integer will be used to hold the pointer; other platforms use 32-bit pointers and will use a Python integer. +For the \character{t} format character, the return value is either +\constant{True} or \constant{False}. When packing, the truth value +of the argument object is used. Either 0 or 1 in the native or standard +bool representation will be packed, and any non-zero value will be True +when unpacking. + By default, C numbers are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). @@ -151,6 +163,7 @@ \ctype{long long} (\ctype{__int64} on Windows) is 8 bytes; \ctype{float} and \ctype{double} are 32-bit and 64-bit IEEE floating point numbers, respectively. +\ctype{_Bool} is 1 byte. Note the difference between \character{@} and \character{=}: both use native byte order, but the size and alignment of the latter is Modified: python/branches/p3yk/Doc/lib/libtime.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtime.tex (original) +++ python/branches/p3yk/Doc/lib/libtime.tex Thu Feb 1 19:02:27 2007 @@ -324,6 +324,12 @@ it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones). + +Only the directives specified in the documentation are supported. Because +\code{strftime()} is implemented per platform it can sometimes offer more +directives than those listed. But \code{strptime()} is independent of any +platform and thus does not necessarily support all directives available that +are not documented as supported. \end{funcdesc} \begin{datadesc}{struct_time} Modified: python/branches/p3yk/Doc/ref/ref3.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref3.tex (original) +++ python/branches/p3yk/Doc/ref/ref3.tex Thu Feb 1 19:02:27 2007 @@ -1997,8 +1997,8 @@ \methodline[numeric object]{__ixor__}{self, other} \methodline[numeric object]{__ior__}{self, other} These methods are called to implement the augmented arithmetic -operations (\code{+=}, \code{-=}, \code{*=}, \code{/=}, \code{\%=}, -\code{**=}, \code{<<=}, \code{>>=}, \code{\&=}, +operations (\code{+=}, \code{-=}, \code{*=}, \code{/=}, \code{//=}, +\code{\%=}, \code{**=}, \code{<<=}, \code{>>=}, \code{\&=}, \code{\textasciicircum=}, \code{|=}). These methods should attempt to do the operation in-place (modifying \var{self}) and return the result (which could be, but does not have to be, \var{self}). If a specific method Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Thu Feb 1 19:02:27 2007 @@ -366,97 +366,157 @@ }; -mod_ty Module(asdl_seq * body, PyArena *arena); -mod_ty Interactive(asdl_seq * body, PyArena *arena); -mod_ty Expression(expr_ty body, PyArena *arena); -mod_ty Suite(asdl_seq * body, PyArena *arena); -stmt_ty FunctionDef(identifier name, arguments_ty args, asdl_seq * body, - asdl_seq * decorators, expr_ty returns, int lineno, int - col_offset, PyArena *arena); -stmt_ty ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int - lineno, int col_offset, PyArena *arena); -stmt_ty Return(expr_ty value, int lineno, int col_offset, PyArena *arena); -stmt_ty Delete(asdl_seq * targets, int lineno, int col_offset, PyArena *arena); -stmt_ty Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, - PyArena *arena); -stmt_ty AugAssign(expr_ty target, operator_ty op, expr_ty value, int lineno, - int col_offset, PyArena *arena); -stmt_ty Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int - col_offset, PyArena *arena); -stmt_ty For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, - int lineno, int col_offset, PyArena *arena); -stmt_ty While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int - col_offset, PyArena *arena); -stmt_ty If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int - col_offset, PyArena *arena); -stmt_ty With(expr_ty context_expr, expr_ty optional_vars, asdl_seq * body, int - lineno, int col_offset, PyArena *arena); -stmt_ty Raise(expr_ty type, expr_ty inst, expr_ty tback, int lineno, int - col_offset, PyArena *arena); -stmt_ty TryExcept(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, int - lineno, int col_offset, PyArena *arena); -stmt_ty TryFinally(asdl_seq * body, asdl_seq * finalbody, int lineno, int +#define Module(a0, a1) _Py_Module(a0, a1) +mod_ty _Py_Module(asdl_seq * body, PyArena *arena); +#define Interactive(a0, a1) _Py_Interactive(a0, a1) +mod_ty _Py_Interactive(asdl_seq * body, PyArena *arena); +#define Expression(a0, a1) _Py_Expression(a0, a1) +mod_ty _Py_Expression(expr_ty body, PyArena *arena); +#define Suite(a0, a1) _Py_Suite(a0, a1) +mod_ty _Py_Suite(asdl_seq * body, PyArena *arena); +#define FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) _Py_FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) +stmt_ty _Py_FunctionDef(identifier name, arguments_ty args, asdl_seq * body, + asdl_seq * decorators, expr_ty returns, int lineno, int + col_offset, PyArena *arena); +#define ClassDef(a0, a1, a2, a3, a4, a5) _Py_ClassDef(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int + lineno, int col_offset, PyArena *arena); +#define Return(a0, a1, a2, a3) _Py_Return(a0, a1, a2, a3) +stmt_ty _Py_Return(expr_ty value, int lineno, int col_offset, PyArena *arena); +#define Delete(a0, a1, a2, a3) _Py_Delete(a0, a1, a2, a3) +stmt_ty _Py_Delete(asdl_seq * targets, int lineno, int col_offset, PyArena + *arena); +#define Assign(a0, a1, a2, a3, a4) _Py_Assign(a0, a1, a2, a3, a4) +stmt_ty _Py_Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, PyArena *arena); -stmt_ty Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, PyArena - *arena); -stmt_ty Import(asdl_seq * names, int lineno, int col_offset, PyArena *arena); -stmt_ty ImportFrom(identifier module, asdl_seq * names, int level, int lineno, - int col_offset, PyArena *arena); -stmt_ty Global(asdl_seq * names, int lineno, int col_offset, PyArena *arena); -stmt_ty Expr(expr_ty value, int lineno, int col_offset, PyArena *arena); -stmt_ty Pass(int lineno, int col_offset, PyArena *arena); -stmt_ty Break(int lineno, int col_offset, PyArena *arena); -stmt_ty Continue(int lineno, int col_offset, PyArena *arena); -expr_ty BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset, - PyArena *arena); -expr_ty BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int - col_offset, PyArena *arena); -expr_ty UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset, - PyArena *arena); -expr_ty Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset, - PyArena *arena); -expr_ty IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int - col_offset, PyArena *arena); -expr_ty Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, - PyArena *arena); -expr_ty Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena); -expr_ty ListComp(expr_ty elt, asdl_seq * generators, int lineno, int +#define AugAssign(a0, a1, a2, a3, a4, a5) _Py_AugAssign(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_AugAssign(expr_ty target, operator_ty op, expr_ty value, int + lineno, int col_offset, PyArena *arena); +#define Print(a0, a1, a2, a3, a4, a5) _Py_Print(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int + col_offset, PyArena *arena); +#define For(a0, a1, a2, a3, a4, a5, a6) _Py_For(a0, a1, a2, a3, a4, a5, a6) +stmt_ty _Py_For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * + orelse, int lineno, int col_offset, PyArena *arena); +#define While(a0, a1, a2, a3, a4, a5) _Py_While(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, + int col_offset, PyArena *arena); +#define If(a0, a1, a2, a3, a4, a5) _Py_If(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, + int col_offset, PyArena *arena); +#define With(a0, a1, a2, a3, a4, a5) _Py_With(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_With(expr_ty context_expr, expr_ty optional_vars, asdl_seq * body, + int lineno, int col_offset, PyArena *arena); +#define Raise(a0, a1, a2, a3, a4, a5) _Py_Raise(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_Raise(expr_ty type, expr_ty inst, expr_ty tback, int lineno, int + col_offset, PyArena *arena); +#define TryExcept(a0, a1, a2, a3, a4, a5) _Py_TryExcept(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_TryExcept(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, + int lineno, int col_offset, PyArena *arena); +#define TryFinally(a0, a1, a2, a3, a4) _Py_TryFinally(a0, a1, a2, a3, a4) +stmt_ty _Py_TryFinally(asdl_seq * body, asdl_seq * finalbody, int lineno, int + col_offset, PyArena *arena); +#define Assert(a0, a1, a2, a3, a4) _Py_Assert(a0, a1, a2, a3, a4) +stmt_ty _Py_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, + PyArena *arena); +#define Import(a0, a1, a2, a3) _Py_Import(a0, a1, a2, a3) +stmt_ty _Py_Import(asdl_seq * names, int lineno, int col_offset, PyArena + *arena); +#define ImportFrom(a0, a1, a2, a3, a4, a5) _Py_ImportFrom(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_ImportFrom(identifier module, asdl_seq * names, int level, int + lineno, int col_offset, PyArena *arena); +#define Global(a0, a1, a2, a3) _Py_Global(a0, a1, a2, a3) +stmt_ty _Py_Global(asdl_seq * names, int lineno, int col_offset, PyArena + *arena); +#define Expr(a0, a1, a2, a3) _Py_Expr(a0, a1, a2, a3) +stmt_ty _Py_Expr(expr_ty value, int lineno, int col_offset, PyArena *arena); +#define Pass(a0, a1, a2) _Py_Pass(a0, a1, a2) +stmt_ty _Py_Pass(int lineno, int col_offset, PyArena *arena); +#define Break(a0, a1, a2) _Py_Break(a0, a1, a2) +stmt_ty _Py_Break(int lineno, int col_offset, PyArena *arena); +#define Continue(a0, a1, a2) _Py_Continue(a0, a1, a2) +stmt_ty _Py_Continue(int lineno, int col_offset, PyArena *arena); +#define BoolOp(a0, a1, a2, a3, a4) _Py_BoolOp(a0, a1, a2, a3, a4) +expr_ty _Py_BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset, + PyArena *arena); +#define BinOp(a0, a1, a2, a3, a4, a5) _Py_BinOp(a0, a1, a2, a3, a4, a5) +expr_ty _Py_BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int + col_offset, PyArena *arena); +#define UnaryOp(a0, a1, a2, a3, a4) _Py_UnaryOp(a0, a1, a2, a3, a4) +expr_ty _Py_UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset, + PyArena *arena); +#define Lambda(a0, a1, a2, a3, a4) _Py_Lambda(a0, a1, a2, a3, a4) +expr_ty _Py_Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset, + PyArena *arena); +#define IfExp(a0, a1, a2, a3, a4, a5) _Py_IfExp(a0, a1, a2, a3, a4, a5) +expr_ty _Py_IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int + col_offset, PyArena *arena); +#define Dict(a0, a1, a2, a3, a4) _Py_Dict(a0, a1, a2, a3, a4) +expr_ty _Py_Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, PyArena *arena); -expr_ty GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int +#define Set(a0, a1, a2, a3) _Py_Set(a0, a1, a2, a3) +expr_ty _Py_Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena); +#define ListComp(a0, a1, a2, a3, a4) _Py_ListComp(a0, a1, a2, a3, a4) +expr_ty _Py_ListComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena); -expr_ty Yield(expr_ty value, int lineno, int col_offset, PyArena *arena); -expr_ty Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, int - lineno, int col_offset, PyArena *arena); -expr_ty Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty - starargs, expr_ty kwargs, int lineno, int col_offset, PyArena - *arena); -expr_ty Num(object n, int lineno, int col_offset, PyArena *arena); -expr_ty Str(string s, int lineno, int col_offset, PyArena *arena); -expr_ty Ellipsis(int lineno, int col_offset, PyArena *arena); -expr_ty Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int - lineno, int col_offset, PyArena *arena); -expr_ty Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int - lineno, int col_offset, PyArena *arena); -expr_ty Name(identifier id, expr_context_ty ctx, int lineno, int col_offset, - PyArena *arena); -expr_ty List(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, - PyArena *arena); -expr_ty Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, - PyArena *arena); -slice_ty Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena); -slice_ty ExtSlice(asdl_seq * dims, PyArena *arena); -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, 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, - asdl_seq * kw_defaults, PyArena *arena); -arg_ty SimpleArg(identifier arg, expr_ty annotation, PyArena *arena); -arg_ty NestedArgs(asdl_seq * args, PyArena *arena); -keyword_ty keyword(identifier arg, expr_ty value, PyArena *arena); -alias_ty alias(identifier name, identifier asname, PyArena *arena); +#define GeneratorExp(a0, a1, a2, a3, a4) _Py_GeneratorExp(a0, a1, a2, a3, a4) +expr_ty _Py_GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int + col_offset, PyArena *arena); +#define Yield(a0, a1, a2, a3) _Py_Yield(a0, a1, a2, a3) +expr_ty _Py_Yield(expr_ty value, int lineno, int col_offset, PyArena *arena); +#define Compare(a0, a1, a2, a3, a4, a5) _Py_Compare(a0, a1, a2, a3, a4, a5) +expr_ty _Py_Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, + int lineno, int col_offset, PyArena *arena); +#define Call(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Call(a0, a1, a2, a3, a4, a5, a6, a7) +expr_ty _Py_Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty + starargs, expr_ty kwargs, int lineno, int col_offset, PyArena + *arena); +#define Num(a0, a1, a2, a3) _Py_Num(a0, a1, a2, a3) +expr_ty _Py_Num(object n, int lineno, int col_offset, PyArena *arena); +#define Str(a0, a1, a2, a3) _Py_Str(a0, a1, a2, a3) +expr_ty _Py_Str(string s, int lineno, int col_offset, PyArena *arena); +#define Ellipsis(a0, a1, a2) _Py_Ellipsis(a0, a1, a2) +expr_ty _Py_Ellipsis(int lineno, int col_offset, PyArena *arena); +#define Attribute(a0, a1, a2, a3, a4, a5) _Py_Attribute(a0, a1, a2, a3, a4, a5) +expr_ty _Py_Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int + lineno, int col_offset, PyArena *arena); +#define Subscript(a0, a1, a2, a3, a4, a5) _Py_Subscript(a0, a1, a2, a3, a4, a5) +expr_ty _Py_Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int + lineno, int col_offset, PyArena *arena); +#define Name(a0, a1, a2, a3, a4) _Py_Name(a0, a1, a2, a3, a4) +expr_ty _Py_Name(identifier id, expr_context_ty ctx, int lineno, int + col_offset, PyArena *arena); +#define List(a0, a1, a2, a3, a4) _Py_List(a0, a1, a2, a3, a4) +expr_ty _Py_List(asdl_seq * elts, expr_context_ty ctx, int lineno, int + col_offset, PyArena *arena); +#define Tuple(a0, a1, a2, a3, a4) _Py_Tuple(a0, a1, a2, a3, a4) +expr_ty _Py_Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int + col_offset, PyArena *arena); +#define Slice(a0, a1, a2, a3) _Py_Slice(a0, a1, a2, a3) +slice_ty _Py_Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena); +#define ExtSlice(a0, a1) _Py_ExtSlice(a0, a1) +slice_ty _Py_ExtSlice(asdl_seq * dims, PyArena *arena); +#define Index(a0, a1) _Py_Index(a0, a1) +slice_ty _Py_Index(expr_ty value, PyArena *arena); +#define comprehension(a0, a1, a2, a3) _Py_comprehension(a0, a1, a2, a3) +comprehension_ty _Py_comprehension(expr_ty target, expr_ty iter, asdl_seq * + ifs, PyArena *arena); +#define excepthandler(a0, a1, a2, a3, a4, a5) _Py_excepthandler(a0, a1, a2, a3, a4, a5) +excepthandler_ty _Py_excepthandler(expr_ty type, identifier name, asdl_seq * + body, int lineno, int col_offset, PyArena + *arena); +#define arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8) _Py_arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8) +arguments_ty _Py_arguments(asdl_seq * args, identifier vararg, expr_ty + varargannotation, asdl_seq * kwonlyargs, identifier + kwarg, expr_ty kwargannotation, asdl_seq * defaults, + asdl_seq * kw_defaults, PyArena *arena); +#define SimpleArg(a0, a1, a2) _Py_SimpleArg(a0, a1, a2) +arg_ty _Py_SimpleArg(identifier arg, expr_ty annotation, PyArena *arena); +#define NestedArgs(a0, a1) _Py_NestedArgs(a0, a1) +arg_ty _Py_NestedArgs(asdl_seq * args, PyArena *arena); +#define keyword(a0, a1, a2) _Py_keyword(a0, a1, a2) +keyword_ty _Py_keyword(identifier arg, expr_ty value, PyArena *arena); +#define alias(a0, a1, a2) _Py_alias(a0, a1, a2) +alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); PyObject* PyAST_mod2obj(mod_ty t); Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Thu Feb 1 19:02:27 2007 @@ -368,7 +368,7 @@ /* Generic operations on objects */ PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int); -PyAPI_FUNC(void) _Py_Break(void); +PyAPI_FUNC(void) _Py_BreakPoint(void); PyAPI_FUNC(void) _PyObject_Dump(PyObject *); PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *); PyAPI_FUNC(PyObject *) _PyObject_Str(PyObject *); Modified: python/branches/p3yk/Lib/logging/handlers.py ============================================================================== --- python/branches/p3yk/Lib/logging/handlers.py (original) +++ python/branches/p3yk/Lib/logging/handlers.py Thu Feb 1 19:02:27 2007 @@ -1,4 +1,4 @@ -# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, @@ -22,7 +22,7 @@ Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. -Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ @@ -135,10 +135,8 @@ os.remove(dfn) os.rename(self.baseFilename, dfn) #print "%s -> %s" % (self.baseFilename, dfn) - if self.encoding: - self.stream = codecs.open(self.baseFilename, 'w', self.encoding) - else: - self.stream = open(self.baseFilename, 'w') + self.mode = 'w' + self.stream = self._open() def shouldRollover(self, record): """ @@ -281,10 +279,8 @@ s.sort() os.remove(s[0]) #print "%s -> %s" % (self.baseFilename, dfn) - if self.encoding: - self.stream = codecs.open(self.baseFilename, 'w', self.encoding) - else: - self.stream = open(self.baseFilename, 'w') + self.mode = 'w' + self.stream = self._open() self.rolloverAt = self.rolloverAt + self.interval class WatchedFileHandler(logging.FileHandler): @@ -786,7 +782,7 @@ try: import smtplib try: - from email.Utils import formatdate + from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Thu Feb 1 19:02:27 2007 @@ -16,8 +16,8 @@ import errno import copy import email -import email.Message -import email.Generator +import email.message +import email.generator import rfc822 import StringIO try: @@ -193,9 +193,9 @@ # To get native line endings on disk, the user-friendly \n line endings # used in strings and by email.Message are translated here. """Dump message contents to target file.""" - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): buffer = StringIO.StringIO() - gen = email.Generator.Generator(buffer, mangle_from_, 0) + gen = email.generator.Generator(buffer, mangle_from_, 0) gen.flatten(message) buffer.seek(0) target.write(buffer.read().replace('\n', os.linesep)) @@ -704,7 +704,7 @@ message = '' elif isinstance(message, _mboxMMDFMessage): from_line = 'From ' + message.get_from() - elif isinstance(message, email.Message.Message): + elif isinstance(message, email.message.Message): from_line = message.get_unixfrom() # May be None. if from_line is None: from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime()) @@ -1254,9 +1254,9 @@ self._file.write(os.linesep) else: self._file.write('1,,' + os.linesep) - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): orig_buffer = StringIO.StringIO() - orig_generator = email.Generator.Generator(orig_buffer, False, 0) + orig_generator = email.generator.Generator(orig_buffer, False, 0) orig_generator.flatten(message) orig_buffer.seek(0) while True: @@ -1267,7 +1267,7 @@ self._file.write('*** EOOH ***' + os.linesep) if isinstance(message, BabylMessage): vis_buffer = StringIO.StringIO() - vis_generator = email.Generator.Generator(vis_buffer, False, 0) + vis_generator = email.generator.Generator(vis_buffer, False, 0) vis_generator.flatten(message.get_visible()) while True: line = vis_buffer.readline() @@ -1323,12 +1323,12 @@ return (start, stop) -class Message(email.Message.Message): +class Message(email.message.Message): """Message with mailbox-format-specific properties.""" def __init__(self, message=None): """Initialize a Message instance.""" - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): self._become_message(copy.deepcopy(message)) if isinstance(message, Message): message._explain_to(self) @@ -1337,7 +1337,7 @@ elif hasattr(message, "read"): self._become_message(email.message_from_file(message)) elif message is None: - email.Message.Message.__init__(self) + email.message.Message.__init__(self) else: raise TypeError('Invalid message type: %s' % type(message)) @@ -1468,7 +1468,7 @@ def __init__(self, message=None): """Initialize an mboxMMDFMessage instance.""" self.set_from('MAILER-DAEMON', True) - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): unixfrom = message.get_unixfrom() if unixfrom is not None and unixfrom.startswith('From '): self.set_from(unixfrom[5:]) @@ -1990,10 +1990,12 @@ # that the two characters preceding "From " are \n\n or the beginning of # the file. Fixing this would require a more extensive rewrite than is # necessary. For convenience, we've added a PortableUnixMailbox class - # which uses the more lenient _fromlinepattern regular expression. + # which does no checking of the format of the 'From' line. - _fromlinepattern = r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" \ - r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*$" + _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" + r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*" + r"[^\s]*\s*" + "$") _regexp = None def _strict_isrealfromline(self, line): Modified: python/branches/p3yk/Lib/ntpath.py ============================================================================== --- python/branches/p3yk/Lib/ntpath.py (original) +++ python/branches/p3yk/Lib/ntpath.py Thu Feb 1 19:02:27 2007 @@ -344,8 +344,10 @@ var = path[:index] if var in os.environ: res = res + os.environ[var] + else: + res = res + '${' + var + '}' except ValueError: - res = res + path + res = res + '${' + path index = pathlen - 1 else: var = '' @@ -357,8 +359,10 @@ c = path[index:index + 1] if var in os.environ: res = res + os.environ[var] + else: + res = res + '$' + var if c != '': - res = res + c + index = index - 1 else: res = res + c index = index + 1 Modified: python/branches/p3yk/Lib/pdb.py ============================================================================== --- python/branches/p3yk/Lib/pdb.py (original) +++ python/branches/p3yk/Lib/pdb.py Thu Feb 1 19:02:27 2007 @@ -479,7 +479,12 @@ def do_condition(self, arg): # arg is breakpoint number and condition args = arg.split(' ', 1) - bpnum = int(args[0].strip()) + try: + bpnum = int(args[0].strip()) + except ValueError: + # something went wrong + print >>self.stdout, \ + 'Breakpoint index %r is not a number' % args[0] try: cond = args[1] except: @@ -494,7 +499,12 @@ def do_ignore(self,arg): """arg is bp number followed by ignore count.""" args = arg.split() - bpnum = int(args[0].strip()) + try: + bpnum = int(args[0].strip()) + except ValueError: + # something went wrong + print >>self.stdout, \ + 'Breakpoint index %r is not a number' % args[0] try: count = int(args[1].strip()) except: Modified: python/branches/p3yk/Lib/random.py ============================================================================== --- python/branches/p3yk/Lib/random.py (original) +++ python/branches/p3yk/Lib/random.py Thu Feb 1 19:02:27 2007 @@ -569,7 +569,7 @@ def betavariate(self, alpha, beta): """Beta distribution. - Conditions on the parameters are alpha > -1 and beta} > -1. + Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. """ Modified: python/branches/p3yk/Lib/rfc822.py ============================================================================== --- python/branches/p3yk/Lib/rfc822.py (original) +++ python/branches/p3yk/Lib/rfc822.py Thu Feb 1 19:02:27 2007 @@ -850,6 +850,11 @@ if data[0][-1] in (',', '.') or data[0].lower() in _daynames: # There's a dayname here. Skip it del data[0] + else: + # no space after the "weekday,"? + i = data[0].rfind(',') + if i >= 0: + data[0] = data[0][i+1:] if len(data) == 3: # RFC 850 date, deprecated stuff = data[0].split('-') if len(stuff) == 3: Modified: python/branches/p3yk/Lib/smtplib.py ============================================================================== --- python/branches/p3yk/Lib/smtplib.py (original) +++ python/branches/p3yk/Lib/smtplib.py Thu Feb 1 19:02:27 2007 @@ -43,10 +43,10 @@ import socket import re -import email.Utils +import email.utils import base64 import hmac -from email.base64MIME import encode as encode_base64 +from email.base64mime import encode as encode_base64 from sys import stderr __all__ = ["SMTPException","SMTPServerDisconnected","SMTPResponseException", @@ -172,7 +172,7 @@ """ m = (None, None) try: - m = email.Utils.parseaddr(addr)[1] + m = email.utils.parseaddr(addr)[1] except AttributeError: pass if m == (None, None): # Indicates parse failure or AttributeError Modified: python/branches/p3yk/Lib/socket.py ============================================================================== --- python/branches/p3yk/Lib/socket.py (original) +++ python/branches/p3yk/Lib/socket.py Thu Feb 1 19:02:27 2007 @@ -204,9 +204,10 @@ __slots__ = ["mode", "bufsize", "softspace", # "closed" is a property, see below - "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"] + "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", + "_close"] - def __init__(self, sock, mode='rb', bufsize=-1): + def __init__(self, sock, mode='rb', bufsize=-1, close=False): self._sock = sock self.mode = mode # Not actually used in this version if bufsize < 0: @@ -222,6 +223,7 @@ self._wbufsize = bufsize self._rbuf = "" # A string self._wbuf = [] # A list of strings + self._close = close def _getclosed(self): return self._sock is None @@ -232,6 +234,8 @@ if self._sock: self.flush() finally: + if self._close: + self._sock.close() self._sock = None def __del__(self): Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Thu Feb 1 19:02:27 2007 @@ -1632,19 +1632,7 @@ # Create all upper directories. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): - ti = TarInfo() - ti.name = upperdirs - ti.type = DIRTYPE - ti.mode = 0777 - ti.mtime = tarinfo.mtime - ti.uid = tarinfo.uid - ti.gid = tarinfo.gid - ti.uname = tarinfo.uname - ti.gname = tarinfo.gname - try: - self._extract_member(ti, ti.name) - except: - pass + os.makedirs(upperdirs) if tarinfo.islnk() or tarinfo.issym(): self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) Modified: python/branches/p3yk/Lib/test/crashers/weakref_in_del.py ============================================================================== --- python/branches/p3yk/Lib/test/crashers/weakref_in_del.py (original) +++ python/branches/p3yk/Lib/test/crashers/weakref_in_del.py Thu Feb 1 19:02:27 2007 @@ -1,11 +1,12 @@ import weakref # http://python.org/sf/1377858 +# Fixed for new-style classes in 2.5c1. ref = None def test_weakref_in_del(): - class Target(object): + class Target(): def __del__(self): global ref ref = weakref.ref(self) Deleted: /python/branches/p3yk/Lib/test/output/test_new ============================================================================== --- /python/branches/p3yk/Lib/test/output/test_new Thu Feb 1 19:02:27 2007 +++ (empty file) @@ -1,6 +0,0 @@ -test_new -new.module() -new.classobj() -new.instancemethod() -new.function() -new.code() Deleted: /python/branches/p3yk/Lib/test/output/test_popen ============================================================================== --- /python/branches/p3yk/Lib/test/output/test_popen Thu Feb 1 19:02:27 2007 +++ (empty file) @@ -1,3 +0,0 @@ -test_popen -Test popen: -popen seemed to process the command-line correctly Deleted: /python/branches/p3yk/Lib/test/output/test_resource ============================================================================== --- /python/branches/p3yk/Lib/test/output/test_resource Thu Feb 1 19:02:27 2007 +++ (empty file) @@ -1,2 +0,0 @@ -test_resource -True 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 Thu Feb 1 19:02:27 2007 @@ -12,6 +12,10 @@ class ArraySubclass(array.array): pass +class ArraySubclassWithKwargs(array.array): + def __init__(self, typecode, newarg=None): + array.array.__init__(typecode) + tests = [] # list to accumulate all tests typecodes = "cubBhHiIlLfd" @@ -683,6 +687,9 @@ b = array.array('B', range(64)) self.assertEqual(rc, sys.getrefcount(10)) + def test_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError + ArraySubclassWithKwargs('b', newarg=1) class StringTest(BaseTest): 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 Thu Feb 1 19:02:27 2007 @@ -486,6 +486,16 @@ d1 == d2 # not clear if this is supposed to be True or False, # but it used to give a SystemError + +class SubclassWithKwargs(deque): + def __init__(self, newarg=1): + deque.__init__(self) + +class TestSubclassWithKwargs(unittest.TestCase): + def test_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError + SubclassWithKwargs(newarg=1) + #============================================================================== libreftest = """ @@ -599,6 +609,7 @@ TestBasic, TestVariousIteratorArgs, TestSubclass, + TestSubclassWithKwargs, ) test_support.run_unittest(*test_classes) 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 Thu Feb 1 19:02:27 2007 @@ -50,11 +50,17 @@ finally: os.umask(old_umask) + expected_mode = 0635 + if os.name != 'posix': + # Windows only supports setting the read-only attribute. + # This shouldn't fail, but doesn't work like Unix either. + expected_mode = 0666 + import stat st = os.stat(_fname + '.dat') - self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) st = os.stat(_fname + '.dir') - self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) def test_close_twice(self): f = dumbdbm.open(_fname) Modified: python/branches/p3yk/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_itertools.py (original) +++ python/branches/p3yk/Lib/test/test_itertools.py Thu Feb 1 19:02:27 2007 @@ -744,6 +744,21 @@ self.assertRaises(AssertionError, list, cycle(gen1())) self.assertEqual(hist, [0,1]) +class SubclassWithKwargsTest(unittest.TestCase): + def test_keywords_in_subclass(self): + # count is not subclassable... + for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap, + starmap, islice, takewhile, dropwhile, cycle): + class Subclass(cls): + def __init__(self, newarg=None, *args): + cls.__init__(self, *args) + try: + Subclass(newarg=1) + except TypeError as err: + # we expect type errors because of wrong argument count + self.failIf("does not take keyword arguments" in err.args[0]) + + libreftest = """ Doctest for examples in the library reference: libitertools.tex @@ -938,7 +953,8 @@ def test_main(verbose=None): test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC, - RegressionTests, LengthTransparency) + RegressionTests, LengthTransparency, + SubclassWithKwargsTest) test_support.run_unittest(*test_classes) # verify reference counting Modified: python/branches/p3yk/Lib/test/test_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_mailbox.py Thu Feb 1 19:02:27 2007 @@ -4,7 +4,7 @@ import stat import socket import email -import email.Message +import email.message import rfc822 import re import StringIO @@ -22,7 +22,7 @@ def _check_sample(self, msg): # Inspect a mailbox.Message representation of the sample message - self.assert_(isinstance(msg, email.Message.Message)) + self.assert_(isinstance(msg, email.message.Message)) self.assert_(isinstance(msg, mailbox.Message)) for key, value in _sample_headers.iteritems(): self.assert_(value in msg.get_all(key)) @@ -30,7 +30,7 @@ self.assert_(len(msg.get_payload()) == len(_sample_payloads)) for i, payload in enumerate(_sample_payloads): part = msg.get_payload(i) - self.assert_(isinstance(part, email.Message.Message)) + self.assert_(isinstance(part, email.message.Message)) self.assert_(not isinstance(part, mailbox.Message)) self.assert_(part.get_payload() == payload) @@ -939,7 +939,7 @@ self._delete_recursively(self._path) def test_initialize_with_eMM(self): - # Initialize based on email.Message.Message instance + # Initialize based on email.message.Message instance eMM = email.message_from_string(_sample_message) msg = self._factory(eMM) self._post_initialize_hook(msg) @@ -965,7 +965,7 @@ # Initialize without arguments msg = self._factory() self._post_initialize_hook(msg) - self.assert_(isinstance(msg, email.Message.Message)) + self.assert_(isinstance(msg, email.message.Message)) self.assert_(isinstance(msg, mailbox.Message)) self.assert_(isinstance(msg, self._factory)) self.assert_(msg.keys() == []) @@ -992,7 +992,7 @@ mailbox.BabylMessage, mailbox.MMDFMessage): other_msg = class_() msg._explain_to(other_msg) - other_msg = email.Message.Message() + other_msg = email.message.Message() self.assertRaises(TypeError, lambda: msg._explain_to(other_msg)) def _post_initialize_hook(self, msg): @@ -1732,11 +1732,11 @@ def test_unix_mbox(self): ### should be better! - import email.Parser + import email.parser fname = self.createMessage("cur", True) n = 0 for msg in mailbox.PortableUnixMailbox(open(fname), - email.Parser.Parser().parse): + email.parser.Parser().parse): n += 1 self.assertEqual(msg["subject"], "Simple Test") self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE)) Modified: python/branches/p3yk/Lib/test/test_new.py ============================================================================== --- python/branches/p3yk/Lib/test/test_new.py (original) +++ python/branches/p3yk/Lib/test/test_new.py Thu Feb 1 19:02:27 2007 @@ -1,180 +1,158 @@ -from test.test_support import verbose, verify, TestFailed -import sys -import new - -class Eggs: - def get_yolks(self): - return self.yolks - -print 'new.module()' -m = new.module('Spam') -if verbose: - print m -m.Eggs = Eggs -sys.modules['Spam'] = m -import Spam - -def get_more_yolks(self): - return self.yolks + 3 - -print 'new.classobj()' -C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks}) -if verbose: - print C - -def break_yolks(self): - self.yolks = self.yolks - 2 -print 'new.instancemethod()' -c = C() -c.yolks = 3 -im = new.instancemethod(break_yolks, c, C) -if verbose: - print im - -verify(c.get_yolks() == 3 and c.get_more_yolks() == 6, - 'Broken call of hand-crafted class instance') -im() -verify(c.get_yolks() == 1 and c.get_more_yolks() == 4, - 'Broken call of hand-crafted instance method') - -im = new.instancemethod(break_yolks, c) -im() -verify(c.get_yolks() == -1) -try: - new.instancemethod(break_yolks, None) -except TypeError: - pass -else: - raise TestFailed, "dangerous instance method creation allowed" - -# Verify that instancemethod() doesn't allow keyword args -try: - new.instancemethod(break_yolks, c, kw=1) -except TypeError: - pass -else: - raise TestFailed, "instancemethod shouldn't accept keyword args" - -# It's unclear what the semantics should be for a code object compiled at -# module scope, but bound and run in a function. In CPython, `c' is global -# (by accident?) while in Jython, `c' is local. The intent of the test -# clearly is to make `c' global, so let's be explicit about it. -codestr = ''' -global c -a = 1 -b = 2 -c = a + b -''' - -ccode = compile(codestr, '', 'exec') -# Jython doesn't have a __builtins__, so use a portable alternative -import __builtin__ -g = {'c': 0, '__builtins__': __builtin__} -# this test could be more robust -print 'new.function()' -func = new.function(ccode, g) -if verbose: - print func -func() -verify(g['c'] == 3, - 'Could not create a proper function object') - -# test the various extended flavors of function.new -def f(x): - def g(y): - return x + y - return g -g = f(4) -new.function(f.func_code, {}, "blah") -g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure) -verify(g2() == 6) -g3 = new.function(g.func_code, {}, "blah", None, g.func_closure) -verify(g3(5) == 9) -def test_closure(func, closure, exc): - try: - new.function(func.func_code, {}, "", None, closure) - except exc: - pass - else: - print "corrupt closure accepted" - -test_closure(g, None, TypeError) # invalid closure -test_closure(g, (1,), TypeError) # non-cell in closure -test_closure(g, (1, 1), ValueError) # closure is wrong size -test_closure(f, g.func_closure, ValueError) # no closure needed - -print 'new.code()' -# bogus test of new.code() -# Note: Jython will never have new.code() -if hasattr(new, 'code'): - def f(a): pass - - c = f.func_code - argcount = c.co_argcount - kwonlyargcount = c.co_kwonlyargcount - nlocals = c.co_nlocals - stacksize = c.co_stacksize - flags = c.co_flags - codestring = c.co_code - constants = c.co_consts - names = c.co_names - varnames = c.co_varnames - filename = c.co_filename - name = c.co_name - firstlineno = c.co_firstlineno - lnotab = c.co_lnotab - freevars = c.co_freevars - cellvars = c.co_cellvars - - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab, freevars, cellvars) - - # test backwards-compatibility version with no freevars or cellvars - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab) - - try: # this used to trigger a SystemError - d = new.code(-argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab) - except ValueError: - pass - else: - raise TestFailed, "negative co_argcount didn't trigger an exception" - - try: # this used to trigger a SystemError - d = new.code(argcount, kwonlyargcount, - -nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab) - except ValueError: - pass - else: - raise TestFailed, "negative co_nlocals didn't trigger an exception" - - try: # this used to trigger a Py_FatalError! - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, (5,), varnames, filename, name, - firstlineno, lnotab) - except TypeError: - pass - else: - raise TestFailed, "non-string co_name didn't trigger an exception" - - # new.code used to be a way to mutate a tuple... - class S(str): pass - t = (S("ab"),) - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, t, varnames, filename, name, - firstlineno, lnotab) - verify(type(t[0]) is S, "eek, tuple changed under us!") +import unittest +from test import test_support +import sys, new + +class NewTest(unittest.TestCase): + def test_spam(self): + class Eggs: + def get_yolks(self): + return self.yolks + + m = new.module('Spam') + m.Eggs = Eggs + sys.modules['Spam'] = m + import Spam + + def get_more_yolks(self): + return self.yolks + 3 + + # new.classobj() + C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks}) + + def break_yolks(self): + self.yolks = self.yolks - 2 + + # new.instancemethod() + c = C() + c.yolks = 3 + im = new.instancemethod(break_yolks, c, C) + + self.assertEqual(c.get_yolks(), 3, + 'Broken call of hand-crafted class instance') + self.assertEqual(c.get_more_yolks(), 6, + 'Broken call of hand-crafted class instance') + + im() + self.assertEqual(c.get_yolks(), 1, + 'Broken call of hand-crafted instance method') + self.assertEqual(c.get_more_yolks(), 4, + 'Broken call of hand-crafted instance method') + + im = new.instancemethod(break_yolks, c) + im() + self.assertEqual(c.get_yolks(), -1) + + # Verify that dangerous instance method creation is forbidden + self.assertRaises(TypeError, new.instancemethod, break_yolks, None) + + # Verify that instancemethod() doesn't allow keyword args + self.assertRaises(TypeError, new.instancemethod, break_yolks, c, kw=1) + + def test_scope(self): + # It's unclear what the semantics should be for a code object compiled + # at module scope, but bound and run in a function. In CPython, `c' is + # global (by accident?) while in Jython, `c' is local. The intent of + # the test clearly is to make `c' global, so let's be explicit about it. + codestr = ''' + global c + a = 1 + b = 2 + c = a + b + ''' + + codestr = "\n".join(l.strip() for l in codestr.splitlines()) + + ccode = compile(codestr, '', 'exec') + # Jython doesn't have a __builtins__, so use a portable alternative + import __builtin__ + g = {'c': 0, '__builtins__': __builtin__} + + # this test could be more robust + func = new.function(ccode, g) + func() + self.assertEqual(g['c'], 3, 'Could not create a proper function object') + + def test_function(self): + # test the various extended flavors of function.new + def f(x): + def g(y): + return x + y + return g + g = f(4) + new.function(f.func_code, {}, "blah") + g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure) + self.assertEqual(g2(), 6) + g3 = new.function(g.func_code, {}, "blah", None, g.func_closure) + self.assertEqual(g3(5), 9) + def test_closure(func, closure, exc): + self.assertRaises(exc, new.function, func.func_code, {}, "", None, closure) + + test_closure(g, None, TypeError) # invalid closure + test_closure(g, (1,), TypeError) # non-cell in closure + test_closure(g, (1, 1), ValueError) # closure is wrong size + test_closure(f, g.func_closure, ValueError) # no closure needed + + # Note: Jython will never have new.code() + if hasattr(new, 'code'): + def test_code(self): + # bogus test of new.code() + def f(a): pass + + c = f.func_code + argcount = c.co_argcount + kwonlyargcount = c.co_kwonlyargcount + nlocals = c.co_nlocals + stacksize = c.co_stacksize + flags = c.co_flags + codestring = c.co_code + constants = c.co_consts + names = c.co_names + varnames = c.co_varnames + filename = c.co_filename + name = c.co_name + firstlineno = c.co_firstlineno + lnotab = c.co_lnotab + freevars = c.co_freevars + cellvars = c.co_cellvars + + d = new.code(argcount, kwonlyargcount, nlocals, stacksize, flags, + codestring, constants, names, varnames, filename, + name, firstlineno, lnotab, freevars, cellvars) + + # test backwards-compatibility version with no freevars or cellvars + d = new.code(argcount, kwonlyargcount, nlocals, stacksize, + flags, codestring, constants, names, varnames, + filename, name, firstlineno, lnotab) + + # negative co_argcount used to trigger a SystemError + self.assertRaises(ValueError, new.code, + -argcount, kwonlyargcount, nlocals, stacksize, flags, + codestring, constants, names, varnames, filename, name, + firstlineno, lnotab) + + # negative co_nlocals used to trigger a SystemError + self.assertRaises(ValueError, new.code, + argcount, kwonlyargcount, -nlocals, stacksize, flags, + codestring, constants, names, varnames, filename, name, + firstlineno, lnotab) + + # non-string co_name used to trigger a Py_FatalError + self.assertRaises(TypeError, new.code, + argcount, kwonlyargcount, nlocals, stacksize, flags, + codestring, constants, (5,), varnames, filename, name, + firstlineno, lnotab) + + # new.code used to be a way to mutate a tuple... + class S(str): + pass + t = (S("ab"),) + d = new.code(argcount, kwonlyargcount, nlocals, stacksize, + flags, codestring, constants, t, varnames, + filename, name, firstlineno, lnotab) + self.assert_(type(t[0]) is S, "eek, tuple changed under us!") - if verbose: - print d +def test_main(): + test_support.run_unittest(NewTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk/Lib/test/test_ntpath.py ============================================================================== --- python/branches/p3yk/Lib/test/test_ntpath.py (original) +++ python/branches/p3yk/Lib/test/test_ntpath.py Thu Feb 1 19:02:27 2007 @@ -115,6 +115,28 @@ tester("ntpath.normpath('C:////a/b')", r'C:\a\b') tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b') +oldenv = os.environ.copy() +try: + os.environ.clear() + os.environ["foo"] = "bar" + os.environ["{foo"] = "baz1" + os.environ["{foo}"] = "baz2" + tester('ntpath.expandvars("foo")', "foo") + tester('ntpath.expandvars("$foo bar")', "bar bar") + tester('ntpath.expandvars("${foo}bar")', "barbar") + tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar") + tester('ntpath.expandvars("$bar bar")', "$bar bar") + tester('ntpath.expandvars("$?bar")', "$?bar") + tester('ntpath.expandvars("${foo}bar")', "barbar") + tester('ntpath.expandvars("$foo}bar")', "bar}bar") + tester('ntpath.expandvars("${foo")', "${foo") + tester('ntpath.expandvars("${{foo}}")', "baz1}") + tester('ntpath.expandvars("$foo$foo")', "barbar") + tester('ntpath.expandvars("$bar$bar")', "$bar$bar") +finally: + os.environ.clear() + os.environ.update(oldenv) + # ntpath.abspath() can only be used on a system with the "nt" module # (reasonably), so we protect this test with "import nt". This allows # the rest of the tests for the ntpath module to be run to completion Modified: python/branches/p3yk/Lib/test/test_old_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_old_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_old_mailbox.py Thu Feb 1 19:02:27 2007 @@ -109,11 +109,44 @@ self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE)) self.assertEqual(n, 1) +class MboxTestCase(unittest.TestCase): + def setUp(self): + # create a new maildir mailbox to work with: + self._path = test_support.TESTFN + + def tearDown(self): + os.unlink(self._path) + + def test_from_regex (self): + # Testing new regex from bug #1633678 + f = open(self._path, 'w') + f.write("""From fred at example.com Mon May 31 13:24:50 2004 +0200 +Subject: message 1 + +body1 +From fred at example.com Mon May 31 13:24:50 2004 -0200 +Subject: message 2 + +body2 +From fred at example.com Mon May 31 13:24:50 2004 +Subject: message 3 + +body3 +From fred at example.com Mon May 31 13:24:50 2004 +Subject: message 4 + +body4 +""") + f.close() + box = mailbox.UnixMailbox(open(self._path, 'r')) + self.assert_(len(list(iter(box))) == 4) + + # XXX We still need more tests! def test_main(): - test_support.run_unittest(MaildirTestCase) + test_support.run_unittest(MaildirTestCase, MboxTestCase) if __name__ == "__main__": Modified: python/branches/p3yk/Lib/test/test_popen.py ============================================================================== --- python/branches/p3yk/Lib/test/test_popen.py (original) +++ python/branches/p3yk/Lib/test/test_popen.py Thu Feb 1 19:02:27 2007 @@ -4,10 +4,9 @@ Particularly useful for platforms that fake popen. """ -import os -import sys -from test.test_support import TestSkipped, reap_children -from os import popen +import unittest +from test import test_support +import os, sys # Test that command-lines get down as we expect. # To do this we execute: @@ -17,24 +16,32 @@ python = sys.executable if ' ' in python: python = '"' + python + '"' # quote embedded space for cmdline -def _do_test_commandline(cmdline, expected): - cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline) - data = popen(cmd).read() - got = eval(data)[1:] # strip off argv[0] - if got != expected: - print "Error in popen commandline handling." - print " executed '%s', expected '%r', but got '%r'" \ - % (cmdline, expected, got) - -def _test_commandline(): - _do_test_commandline("foo bar", ["foo", "bar"]) - _do_test_commandline('foo "spam and eggs" "silly walk"', ["foo", "spam and eggs", "silly walk"]) - _do_test_commandline('foo "a \\"quoted\\" arg" bar', ["foo", 'a "quoted" arg', "bar"]) - print "popen seemed to process the command-line correctly" - -def main(): - print "Test popen:" - _test_commandline() - reap_children() -main() +class PopenTest(unittest.TestCase): + def _do_test_commandline(self, cmdline, expected): + cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline) + data = os.popen(cmd).read() + got = eval(data)[1:] # strip off argv[0] + self.assertEqual(got, expected) + + def test_popen(self): + self.assertRaises(TypeError, os.popen) + self._do_test_commandline( + "foo bar", + ["foo", "bar"] + ) + self._do_test_commandline( + 'foo "spam and eggs" "silly walk"', + ["foo", "spam and eggs", "silly walk"] + ) + self._do_test_commandline( + 'foo "a \\"quoted\\" arg" bar', + ["foo", 'a "quoted" arg', "bar"] + ) + test_support.reap_children() + +def test_main(): + test_support.run_unittest(PopenTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk/Lib/test/test_posixpath.py ============================================================================== --- python/branches/p3yk/Lib/test/test_posixpath.py (original) +++ python/branches/p3yk/Lib/test/test_posixpath.py Thu Feb 1 19:02:27 2007 @@ -374,6 +374,8 @@ self.assertEqual(posixpath.expandvars("$foo}bar"), "bar}bar") self.assertEqual(posixpath.expandvars("${foo"), "${foo") self.assertEqual(posixpath.expandvars("${{foo}}"), "baz1}") + self.assertEqual(posixpath.expandvars("$foo$foo"), "barbar") + self.assertEqual(posixpath.expandvars("$bar$bar"), "$bar$bar") finally: os.environ.clear() os.environ.update(oldenv) 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 Thu Feb 1 19:02:27 2007 @@ -517,6 +517,14 @@ # tests validity but not completeness of the __all__ list self.failUnless(set(random.__all__) <= set(dir(random))) + def test_random_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError + class Subclass(random.Random): + def __init__(self, newarg=None): + random.Random.__init__(self) + Subclass(newarg=1) + + def test_main(verbose=None): testclasses = [WichmannHill_TestBasicOps, MersenneTwister_TestBasicOps, 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 Thu Feb 1 19:02:27 2007 @@ -1,56 +1,96 @@ -import os -import resource +import unittest +from test import test_support -from test.test_support import TESTFN -# This test is checking a few specific problem spots. RLIMIT_FSIZE -# should be RLIM_INFINITY, which will be a really big number on a -# platform with large file support. On these platforms, we need to -# test that the get/setrlimit functions properly convert the number to -# a C long long and that the conversion doesn't raise an error. - -try: - cur, max = resource.getrlimit(resource.RLIMIT_FSIZE) -except AttributeError: - pass -else: - print resource.RLIM_INFINITY == max - resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) - -# Now check to see what happens when the RLIMIT_FSIZE is small. Some -# versions of Python were terminated by an uncaught SIGXFSZ, but -# pythonrun.c has been fixed to ignore that exception. If so, the -# write() should return EFBIG when the limit is exceeded. - -# At least one platform has an unlimited RLIMIT_FSIZE and attempts to -# change it raise ValueError instead. - -try: - try: - resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max)) - limit_set = 1 - except ValueError: - limit_set = 0 - f = open(TESTFN, "wb") - f.write("X" * 1024) - try: - f.write("Y") - f.flush() - except IOError: - if not limit_set: - raise - f.close() - os.unlink(TESTFN) -finally: - resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) - -# And be sure that setrlimit is checking for really large values -too_big = 10**50 -try: - resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max)) -except (OverflowError, ValueError): - pass -try: - resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big)) -except (OverflowError, ValueError): - pass +import os, resource + +# This test is checking a few specific problem spots with the resource module. + +class ResourceTest(unittest.TestCase): + + def test_args(self): + self.assertRaises(TypeError, resource.getrlimit) + self.assertRaises(TypeError, resource.getrlimit, 42, 42) + self.assertRaises(TypeError, resource.setrlimit) + self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42) + + def test_fsize_ismax(self): + + try: + (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) + except AttributeError: + pass + else: + # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really big + # number on a platform with large file support. On these platforms, + # we need to test that the get/setrlimit functions properly convert + # the number to a C long long and that the conversion doesn't raise + # an error. + self.assertEqual(resource.RLIM_INFINITY, max) + resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) + + def test_fsize_enforced(self): + try: + (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) + except AttributeError: + pass + else: + # Check to see what happens when the RLIMIT_FSIZE is small. Some + # versions of Python were terminated by an uncaught SIGXFSZ, but + # pythonrun.c has been fixed to ignore that exception. If so, the + # write() should return EFBIG when the limit is exceeded. + + # At least one platform has an unlimited RLIMIT_FSIZE and attempts + # to change it raise ValueError instead. + try: + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max)) + limit_set = True + except ValueError: + limit_set = False + f = open(test_support.TESTFN, "wb") + f.write("X" * 1024) + try: + f.write("Y") + f.flush() + except IOError: + if not limit_set: + raise + f.close() + os.unlink(test_support.TESTFN) + finally: + resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) + + def test_fsize_toobig(self): + # Be sure that setrlimit is checking for really large values + too_big = 10**50 + try: + (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) + except AttributeError: + pass + else: + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max)) + except (OverflowError, ValueError): + pass + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big)) + except (OverflowError, ValueError): + pass + + def test_getrusage(self): + self.assertRaises(TypeError, resource.getrusage) + self.assertRaises(TypeError, resource.getrusage, 42, 42) + usageself = resource.getrusage(resource.RUSAGE_SELF) + usagechildren = resource.getrusage(resource.RUSAGE_CHILDREN) + # May not be available on all systems. + try: + usageboth = resource.getrusage(resource.RUSAGE_BOTH) + except (ValueError, AttributeError): + pass + +def test_main(verbose=None): + test_support.run_unittest(ResourceTest) + +if __name__ == "__main__": + test_main() 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 Thu Feb 1 19:02:27 2007 @@ -809,6 +809,31 @@ bufsize = 2 # Exercise the buffering code + +class Urllib2FileobjectTest(unittest.TestCase): + + # urllib2.HTTPHandler has "borrowed" socket._fileobject, and requires that + # it close the socket if the close c'tor argument is true + + def testClose(self): + class MockSocket: + closed = False + def flush(self): pass + def close(self): self.closed = True + + # must not close unless we request it: the original use of _fileobject + # by module socket requires that the underlying socket not be closed until + # the _socketobject that created the _fileobject is closed + s = MockSocket() + f = socket._fileobject(s) + f.close() + self.assert_(not s.closed) + + s = MockSocket() + f = socket._fileobject(s, close=True) + f.close() + self.assert_(s.closed) + class TCPTimeoutTest(SocketTCPTest): def testTCPTimeout(self): @@ -961,7 +986,8 @@ FileObjectClassTestCase, UnbufferedFileObjectClassTestCase, LineBufferedFileObjectClassTestCase, - SmallBufferedFileObjectClassTestCase + SmallBufferedFileObjectClassTestCase, + Urllib2FileobjectTest, ]) if hasattr(socket, "socketpair"): tests.append(BasicSocketPairTest) 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 Thu Feb 1 19:02:27 2007 @@ -84,8 +84,8 @@ if sz * 3 != struct.calcsize('iii'): raise TestFailed, 'inconsistent sizes' -fmt = 'cbxxxxxxhhhhiillffd' -fmt3 = '3c3b18x12h6i6l6f3d' +fmt = 'cbxxxxxxhhhhiillffdt' +fmt3 = '3c3b18x12h6i6l6f3d3t' sz = struct.calcsize(fmt) sz3 = struct.calcsize(fmt3) if sz * 3 != sz3: @@ -108,19 +108,21 @@ l = 65536 f = 3.1415 d = 3.1415 +t = True for prefix in ('', '@', '<', '>', '=', '!'): - for format in ('xcbhilfd', 'xcBHILfd'): + for format in ('xcbhilfdt', 'xcBHILfdt'): format = prefix + format if verbose: print "trying:", format - s = struct.pack(format, c, b, h, i, l, f, d) - cp, bp, hp, ip, lp, fp, dp = struct.unpack(format, s) + s = struct.pack(format, c, b, h, i, l, f, d, t) + cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s) if (cp != c or bp != b or hp != h or ip != i or lp != l or - int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d)): + int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d) or + tp != t): # ^^^ calculate only to two decimal places raise TestFailed, "unpack/pack not transitive (%s, %s)" % ( - str(format), str((cp, bp, hp, ip, lp, fp, dp))) + str(format), str((cp, bp, hp, ip, lp, fp, dp, tp))) # Test some of the new features in detail @@ -158,6 +160,11 @@ ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0), ('d', -2.0, '\300\000\000\000\000\000\000\000', '\000\000\000\000\000\000\000\300', 0), + ('t', 0, '\0', '\0', 0), + ('t', 3, '\1', '\1', 1), + ('t', True, '\1', '\1', 0), + ('t', [], '\0', '\0', 1), + ('t', (1,), '\1', '\1', 1), ] for fmt, arg, big, lil, asy in tests: @@ -612,3 +619,50 @@ test_unpack_from() test_pack_into() test_pack_into_fn() + +def test_bool(): + for prefix in tuple("<>!=")+('',): + false = (), [], [], '', 0 + true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2 + + falseFormat = prefix + 't' * len(false) + if verbose: + print 'trying bool pack/unpack on', false, 'using format', falseFormat + packedFalse = struct.pack(falseFormat, *false) + unpackedFalse = struct.unpack(falseFormat, packedFalse) + + trueFormat = prefix + 't' * len(true) + if verbose: + print 'trying bool pack/unpack on', true, 'using format', trueFormat + packedTrue = struct.pack(trueFormat, *true) + unpackedTrue = struct.unpack(trueFormat, packedTrue) + + if len(true) != len(unpackedTrue): + raise TestFailed('unpacked true array is not of same size as input') + if len(false) != len(unpackedFalse): + raise TestFailed('unpacked false array is not of same size as input') + + for t in unpackedFalse: + if t is not False: + raise TestFailed('%r did not unpack as False' % t) + for t in unpackedTrue: + if t is not True: + raise TestFailed('%r did not unpack as false' % t) + + if prefix and verbose: + print 'trying size of bool with format %r' % (prefix+'t') + packed = struct.pack(prefix+'t', 1) + + if len(packed) != struct.calcsize(prefix+'t'): + raise TestFailed('packed length is not equal to calculated size') + + if len(packed) != 1 and prefix: + raise TestFailed('encoded bool is not one byte: %r' % packed) + elif not prefix and verbose: + print 'size of bool in native format is %i' % (len(packed)) + + for c in '\x01\x7f\xff\x0f\xf0': + if struct.unpack('>t', c)[0] is not True: + raise TestFailed('%c did not unpack as True' % c) + +test_bool() 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 Thu Feb 1 19:02:27 2007 @@ -64,6 +64,27 @@ # urllib2.urlopen, "http://evil:thing at example.com") +class CloseSocketTest(unittest.TestCase): + + def test_close(self): + import socket, httplib, gc + + # calling .close() on urllib2's response objects should close the + # underlying socket + + # delve deep into response to fetch socket._socketobject + response = urllib2.urlopen("http://www.python.org/") + abused_fileobject = response.fp + self.assert_(abused_fileobject.__class__ is socket._fileobject) + httpresponse = abused_fileobject._sock + self.assert_(httpresponse.__class__ is httplib.HTTPResponse) + fileobject = httpresponse.fp + self.assert_(fileobject.__class__ is socket._fileobject) + + self.assert_(not fileobject.closed) + response.close() + self.assert_(fileobject.closed) + class urlopenNetworkTests(unittest.TestCase): """Tests urllib2.urlopen using the network. @@ -263,8 +284,12 @@ def test_main(): test_support.requires("network") - test_support.run_unittest(URLTimeoutTest, urlopenNetworkTests, - AuthTests, OtherNetworkTests) + test_support.run_unittest(URLTimeoutTest, + urlopenNetworkTests, + AuthTests, + OtherNetworkTests, + CloseSocketTest, + ) if __name__ == "__main__": test_main() 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 Thu Feb 1 19:02:27 2007 @@ -114,11 +114,11 @@ def test_encode(self): try: - fin = open(self.tmpin, 'w') + fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() - fin = open(self.tmpin, 'r') + fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() 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 Thu Feb 1 19:02:27 2007 @@ -6,6 +6,8 @@ from test import test_support +# Used in ReferencesTestCase.test_ref_created_during_del() . +ref_from_del = None class C: def method(self): @@ -630,6 +632,18 @@ finally: gc.set_threshold(*thresholds) + def test_ref_created_during_del(self): + # Bug #1377858 + # A weakref created in an object's __del__() would crash the + # interpreter when the weakref was cleaned up since it would refer to + # non-existent memory. This test should not segfault the interpreter. + class Target(object): + def __del__(self): + global ref_from_del + ref_from_del = weakref.ref(self) + + w = Target() + class SubclassableWeakrefTestCase(unittest.TestCase): Modified: python/branches/p3yk/Lib/urllib.py ============================================================================== --- python/branches/p3yk/Lib/urllib.py (original) +++ python/branches/p3yk/Lib/urllib.py Thu Feb 1 19:02:27 2007 @@ -452,7 +452,7 @@ def open_local_file(self, url): """Use local file.""" - import mimetypes, mimetools, email.Utils + import mimetypes, mimetools, email.utils try: from cStringIO import StringIO except ImportError: @@ -464,7 +464,7 @@ 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) + modified = email.utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % Modified: python/branches/p3yk/Lib/urllib2.py ============================================================================== --- python/branches/p3yk/Lib/urllib2.py (original) +++ python/branches/p3yk/Lib/urllib2.py Thu Feb 1 19:02:27 2007 @@ -1087,7 +1087,7 @@ # out of socket._fileobject() and into a base class. r.recv = r.read - fp = socket._fileobject(r) + fp = socket._fileobject(r, close=True) resp = addinfourl(fp, r.msg, req.get_full_url()) resp.code = r.status @@ -1209,14 +1209,14 @@ # not entirely sure what the rules are here def open_local_file(self, req): - import email.Utils + import email.utils import mimetypes host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats.st_size - modified = email.Utils.formatdate(stats.st_mtime, usegmt=True) + modified = email.utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(file)[0] headers = mimetools.Message(StringIO( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % Modified: python/branches/p3yk/Modules/_ctypes/_ctypes_test.c ============================================================================== --- python/branches/p3yk/Modules/_ctypes/_ctypes_test.c (original) +++ python/branches/p3yk/Modules/_ctypes/_ctypes_test.c Thu Feb 1 19:02:27 2007 @@ -68,22 +68,25 @@ EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d) { -// printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", -// b, h, i, l, f, d); +/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ return (int)(b + h + i + l + f + d); } EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d) { -// printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", -// b, h, i, l, f, d); +/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ return (float)(b + h + i + l + f + d); } EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d) { -// printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", -// b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ return (double)(b + h + i + l + f + d); } @@ -378,8 +381,9 @@ } PyMethodDef module_methods[] = { -// {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, -// {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, + {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +*/ {"func_si", py_func_si, METH_VARARGS}, {"func", py_func, METH_NOARGS}, { NULL, NULL, 0, NULL}, Modified: python/branches/p3yk/Modules/_randommodule.c ============================================================================== --- python/branches/p3yk/Modules/_randommodule.c (original) +++ python/branches/p3yk/Modules/_randommodule.c Thu Feb 1 19:02:27 2007 @@ -481,7 +481,7 @@ RandomObject *self; PyObject *tmp; - if (!_PyArg_NoKeywords("Random()", kwds)) + if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds)) return NULL; self = (RandomObject *)type->tp_alloc(type, 0); Modified: python/branches/p3yk/Modules/_struct.c ============================================================================== --- python/branches/p3yk/Modules/_struct.c (original) +++ python/branches/p3yk/Modules/_struct.c Thu Feb 1 19:02:27 2007 @@ -104,6 +104,15 @@ #define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG)) #endif +#ifdef HAVE_C99_BOOL +#define BOOL_TYPE _Bool +typedef struct { char c; _Bool x; } s_bool; +#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE)) +#else +#define BOOL_TYPE char +#define BOOL_ALIGN 0 +#endif + #define STRINGIFY(x) #x #ifdef __powerc @@ -534,6 +543,15 @@ #endif static PyObject * +nu_bool(const char *p, const formatdef *f) +{ + BOOL_TYPE x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); +} + + +static PyObject * nu_float(const char *p, const formatdef *f) { float x; @@ -709,6 +727,16 @@ } #endif + +static int +np_bool(char *p, PyObject *v, const formatdef *f) +{ + BOOL_TYPE y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; +} + static int np_float(char *p, PyObject *v, const formatdef *f) { @@ -769,6 +797,7 @@ {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, #endif + {'t', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, @@ -863,6 +892,14 @@ return unpack_double(p, 0); } +static PyObject * +bu_bool(const char *p, const formatdef *f) +{ + char x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); +} + static int bp_int(char *p, PyObject *v, const formatdef *f) { @@ -967,6 +1004,15 @@ return _PyFloat_Pack8(x, (unsigned char *)p, 0); } +static int +bp_bool(char *p, PyObject *v, const formatdef *f) +{ + char y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; +} + static formatdef bigendian_table[] = { {'x', 1, 0, NULL}, #ifdef PY_STRUCT_OVERFLOW_MASKING @@ -988,6 +1034,7 @@ {'L', 4, 0, bu_uint, bp_uint}, {'q', 8, 0, bu_longlong, bp_longlong}, {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, + {'t', 1, 0, bu_bool, bp_bool}, {'f', 4, 0, bu_float, bp_float}, {'d', 8, 0, bu_double, bp_double}, {0} @@ -1206,6 +1253,8 @@ {'L', 4, 0, lu_uint, lp_uint}, {'q', 8, 0, lu_longlong, lp_longlong}, {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, + {'t', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, + but potentially different from native rep -- reuse bx_bool funcs. */ {'f', 4, 0, lu_float, lp_float}, {'d', 8, 0, lu_double, lp_double}, {0} Modified: python/branches/p3yk/Modules/arraymodule.c ============================================================================== --- python/branches/p3yk/Modules/arraymodule.c (original) +++ python/branches/p3yk/Modules/arraymodule.c Thu Feb 1 19:02:27 2007 @@ -1797,7 +1797,7 @@ PyObject *initial = NULL, *it = NULL; struct arraydescr *descr; - if (!_PyArg_NoKeywords("array.array()", kwds)) + if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds)) return NULL; if (!PyArg_ParseTuple(args, "c|O:array", &c, &initial)) Modified: python/branches/p3yk/Modules/collectionsmodule.c ============================================================================== --- python/branches/p3yk/Modules/collectionsmodule.c (original) +++ python/branches/p3yk/Modules/collectionsmodule.c Thu Feb 1 19:02:27 2007 @@ -95,7 +95,7 @@ dequeobject *deque; block *b; - if (!_PyArg_NoKeywords("deque()", kwds)) + if (type == &deque_type && !_PyArg_NoKeywords("deque()", kwds)) return NULL; /* create dequeobject structure */ Modified: python/branches/p3yk/Modules/itertoolsmodule.c ============================================================================== --- python/branches/p3yk/Modules/itertoolsmodule.c (original) +++ python/branches/p3yk/Modules/itertoolsmodule.c Thu Feb 1 19:02:27 2007 @@ -681,7 +681,7 @@ PyObject *saved; cycleobject *lz; - if (!_PyArg_NoKeywords("cycle()", kwds)) + if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable)) @@ -831,7 +831,7 @@ PyObject *it; dropwhileobject *lz; - if (!_PyArg_NoKeywords("dropwhile()", kwds)) + if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq)) @@ -975,7 +975,7 @@ PyObject *it; takewhileobject *lz; - if (!_PyArg_NoKeywords("takewhile()", kwds)) + if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq)) @@ -1120,7 +1120,7 @@ Py_ssize_t numargs; isliceobject *lz; - if (!_PyArg_NoKeywords("islice()", kwds)) + if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3)) @@ -1311,7 +1311,7 @@ PyObject *it; starmapobject *lz; - if (!_PyArg_NoKeywords("starmap()", kwds)) + if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq)) @@ -1443,7 +1443,7 @@ imapobject *lz; Py_ssize_t numargs, i; - if (!_PyArg_NoKeywords("imap()", kwds)) + if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds)) return NULL; numargs = PyTuple_Size(args); @@ -1625,7 +1625,7 @@ Py_ssize_t i; PyObject *ittuple; - if (!_PyArg_NoKeywords("chain()", kwds)) + if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) return NULL; /* obtain iterators */ @@ -1768,7 +1768,7 @@ PyObject *it; ifilterobject *lz; - if (!_PyArg_NoKeywords("ifilter()", kwds)) + if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq)) @@ -1912,7 +1912,8 @@ PyObject *it; ifilterfalseobject *lz; - if (!_PyArg_NoKeywords("ifilterfalse()", kwds)) + if (type == &ifilterfalse_type && + !_PyArg_NoKeywords("ifilterfalse()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq)) @@ -2054,7 +2055,7 @@ countobject *lz; Py_ssize_t cnt = 0; - if (!_PyArg_NoKeywords("count()", kwds)) + if (type == &count_type && !_PyArg_NoKeywords("count()", kwds)) return NULL; if (!PyArg_ParseTuple(args, "|n:count", &cnt)) @@ -2153,7 +2154,7 @@ PyObject *result; Py_ssize_t tuplesize = PySequence_Length(args); - if (!_PyArg_NoKeywords("izip()", kwds)) + if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds)) return NULL; /* args must be a tuple */ @@ -2336,7 +2337,7 @@ PyObject *element; Py_ssize_t cnt = -1; - if (!_PyArg_NoKeywords("repeat()", kwds)) + if (type == &repeat_type && !_PyArg_NoKeywords("repeat()", kwds)) return NULL; if (!PyArg_ParseTuple(args, "O|n:repeat", &element, &cnt)) Modified: python/branches/p3yk/Objects/fileobject.c ============================================================================== --- python/branches/p3yk/Objects/fileobject.c (original) +++ python/branches/p3yk/Objects/fileobject.c Thu Feb 1 19:02:27 2007 @@ -354,6 +354,8 @@ { PyFileObject *file = (PyFileObject*)f; PyObject *str = PyString_FromString(enc); + + assert(PyFile_Check(f)); if (!str) return 0; Py_DECREF(file->f_encoding); Modified: python/branches/p3yk/Objects/object.c ============================================================================== --- python/branches/p3yk/Objects/object.c (original) +++ python/branches/p3yk/Objects/object.c Thu Feb 1 19:02:27 2007 @@ -314,7 +314,7 @@ /* For debugging convenience. Set a breakpoint here and call it from your DLL */ void -_Py_Break(void) +_Py_BreakPoint(void) { } Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Thu Feb 1 19:02:27 2007 @@ -655,6 +655,17 @@ goto endlabel; /* resurrected */ else _PyObject_GC_UNTRACK(self); + /* New weakrefs could be created during the finalizer call. + If this occurs, clear them out without calling their + finalizers since they might rely on part of the object + being finalized that has already been destroyed. */ + if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { + /* Modeled after GET_WEAKREFS_LISTPTR() */ + PyWeakReference **list = (PyWeakReference **) \ + PyObject_GET_WEAKREFS_LISTPTR(self); + while (*list) + _PyWeakref_ClearRef(*list); + } } /* Clear slots up to the nearest base with a different tp_dealloc */ Modified: python/branches/p3yk/Objects/weakrefobject.c ============================================================================== --- python/branches/p3yk/Objects/weakrefobject.c (original) +++ python/branches/p3yk/Objects/weakrefobject.c Thu Feb 1 19:02:27 2007 @@ -57,6 +57,9 @@ PyWeakref_GET_OBJECT(self)); if (*list == self) + /* If 'self' is the end of the list (and thus self->wr_next == NULL) + then the weakref list itself (and thus the value of *list) will + end up being set to NULL. */ *list = self->wr_next; self->wr_object = Py_None; if (self->wr_prev != NULL) Modified: python/branches/p3yk/PCbuild/_bsddb.vcproj ============================================================================== --- python/branches/p3yk/PCbuild/_bsddb.vcproj (original) +++ python/branches/p3yk/PCbuild/_bsddb.vcproj Thu Feb 1 19:02:27 2007 @@ -130,7 +130,7 @@ ATLMinimizesCRunTimeLibraryUsage="FALSE"> f_tstate; + PyThreadState *tstate = PyThreadState_GET(); PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback; PyTracebackObject *tb = newtracebackobject(oldtb, frame); if (tb == NULL) Modified: python/branches/p3yk/Tools/msi/uuids.py ============================================================================== --- python/branches/p3yk/Tools/msi/uuids.py (original) +++ python/branches/p3yk/Tools/msi/uuids.py Thu Feb 1 19:02:27 2007 @@ -33,4 +33,8 @@ '2.5.121': '{8e9321bc-6b24-48a3-8fd4-c95f8e531e5f}', # 2.5c1 '2.5.122': '{a6cd508d-9599-45da-a441-cbffa9f7e070}', # 2.5c2 '2.5.150': '{0a2c5854-557e-48c8-835a-3b9f074bdcaa}', # 2.5.0 + '2.5.1121':'{0378b43e-6184-4c2f-be1a-4a367781cd54}', # 2.5.1c1 + '2.5.1150':'{31800004-6386-4999-a519-518f2d78d8f0}', # 2.5.1 + '2.5.2150':'{6304a7da-1132-4e91-a343-a296269eab8a}', # 2.5.2c1 + '2.5.2150':'{6b976adf-8ae8-434e-b282-a06c7f624d2f}', # 2.5.2 } Modified: python/branches/p3yk/configure ============================================================================== --- python/branches/p3yk/configure (original) +++ python/branches/p3yk/configure Thu Feb 1 19:02:27 2007 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 51211 . +# From configure.in Revision: 53017 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -10608,6 +10608,467 @@ fi +{ echo "$as_me:$LINENO: checking for _Bool support" >&5 +echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; } +have_c99_bool=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +_Bool x; x = (_Bool)0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + + +cat >>confdefs.h <<\_ACEOF +#define HAVE_C99_BOOL 1 +_ACEOF + + have_c99_bool=yes + +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5 +echo "${ECHO_T}$have_c99_bool" >&6; } +if test "$have_c99_bool" = yes ; then +{ echo "$as_me:$LINENO: checking for _Bool" >&5 +echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } +if test "${ac_cv_type__Bool+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +typedef _Bool ac__type_new_; +int +main () +{ +if ((ac__type_new_ *) 0) + return 0; +if (sizeof (ac__type_new_)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type__Bool=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type__Bool=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 +echo "${ECHO_T}$ac_cv_type__Bool" >&6; } + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ echo "$as_me:$LINENO: checking size of _Bool" >&5 +echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; } +if test "${ac_cv_sizeof__Bool+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then + # Depending upon the size, compute the lo and hi bounds. +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_lo=0 ac_mid=0 + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=$ac_mid; break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo=`expr $ac_mid + 1` + if test $ac_lo -le $ac_mid; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid + 1` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=-1 ac_mid=-1 + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_lo=$ac_mid; break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_hi=`expr '(' $ac_mid ')' - 1` + if test $ac_mid -le $ac_hi; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo= ac_hi= +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# Binary search between lo and hi bounds. +while test "x$ac_lo" != "x$ac_hi"; do + ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=$ac_mid +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo=`expr '(' $ac_mid ')' + 1` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +done +case $ac_lo in +?*) ac_cv_sizeof__Bool=$ac_lo;; +'') if test "$ac_cv_type__Bool" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } + else + ac_cv_sizeof__Bool=0 + fi ;; +esac +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } +static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +#include +#include +int +main () +{ + + FILE *f = fopen ("conftest.val", "w"); + if (! f) + return 1; + if (((long int) (sizeof (ac__type_sizeof_))) < 0) + { + long int i = longval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; + fprintf (f, "%ld\n", i); + } + else + { + unsigned long int i = ulongval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; + fprintf (f, "%lu\n", i); + } + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_sizeof__Bool=`cat conftest.val` +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +if test "$ac_cv_type__Bool" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } + else + ac_cv_sizeof__Bool=0 + fi +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi +rm -f conftest.val +fi +{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 +echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF__BOOL $ac_cv_sizeof__Bool +_ACEOF + + +fi + { echo "$as_me:$LINENO: checking for uintptr_t" >&5 echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } if test "${ac_cv_type_uintptr_t+set}" = set; then Modified: python/branches/p3yk/configure.in ============================================================================== --- python/branches/p3yk/configure.in (original) +++ python/branches/p3yk/configure.in Thu Feb 1 19:02:27 2007 @@ -1218,6 +1218,17 @@ AC_CHECK_SIZEOF(long long, 8) fi +AC_MSG_CHECKING(for _Bool support) +have_c99_bool=no +AC_TRY_COMPILE([], [_Bool x; x = (_Bool)0;], [ + AC_DEFINE(HAVE_C99_BOOL, 1, [Define this if you have the type _Bool.]) + have_c99_bool=yes +]) +AC_MSG_RESULT($have_c99_bool) +if test "$have_c99_bool" = yes ; then +AC_CHECK_SIZEOF(_Bool, 1) +fi + AC_CHECK_TYPES(uintptr_t, [AC_CHECK_SIZEOF(uintptr_t, 4)], [], [#ifdef HAVE_STDINT_H Modified: python/branches/p3yk/pyconfig.h.in ============================================================================== --- python/branches/p3yk/pyconfig.h.in (original) +++ python/branches/p3yk/pyconfig.h.in Thu Feb 1 19:02:27 2007 @@ -64,6 +64,9 @@ /* Define if pthread_sigmask() does not work on your system. */ #undef HAVE_BROKEN_PTHREAD_SIGMASK +/* Define this if you have the type _Bool. */ +#undef HAVE_C99_BOOL + /* Define to 1 if you have the `chown' function. */ #undef HAVE_CHOWN @@ -835,6 +838,9 @@ /* The size of a `wchar_t', as computed by sizeof. */ #undef SIZEOF_WCHAR_T +/* The size of a `_Bool', as computed by sizeof. */ +#undef SIZEOF__BOOL + /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS From python-checkins at python.org Thu Feb 1 19:57:07 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 1 Feb 2007 19:57:07 +0100 (CET) Subject: [Python-checkins] r53611 - sandbox/trunk/setuptools/setuptools/command/easy_install.py Message-ID: <20070201185707.80FF41E4017@bag.python.org> Author: phillip.eby Date: Thu Feb 1 19:57:06 2007 New Revision: 53611 Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py Log: Fixed mangling line endings when an old-style source script came from Windows. Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/easy_install.py (original) +++ sandbox/trunk/setuptools/setuptools/command/easy_install.py Thu Feb 1 19:57:06 2007 @@ -373,7 +373,7 @@ for script_name in dist.metadata_listdir('scripts'): self.install_script( dist, script_name, - dist.get_metadata('scripts/'+script_name).replace('\r','\n') + '\n'.join(dist.get_metadata('scripts/'+script_name).splitlines()) ) self.install_wrapper_scripts(dist) From python-checkins at python.org Thu Feb 1 20:03:19 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 1 Feb 2007 20:03:19 +0100 (CET) Subject: [Python-checkins] r53612 - in sandbox/branches/setuptools-0.6: EasyInstall.txt setuptools/command/easy_install.py Message-ID: <20070201190319.5710B1E4006@bag.python.org> Author: phillip.eby Date: Thu Feb 1 20:03:18 2007 New Revision: 53612 Modified: sandbox/branches/setuptools-0.6/EasyInstall.txt sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Log: Fixed distutils-style scripts originally built on Windows having their line endings doubled when installed on any platform. (backport) Modified: sandbox/branches/setuptools-0.6/EasyInstall.txt ============================================================================== --- sandbox/branches/setuptools-0.6/EasyInstall.txt (original) +++ sandbox/branches/setuptools-0.6/EasyInstall.txt Thu Feb 1 20:03:18 2007 @@ -1198,7 +1198,10 @@ * EasyInstall no longer aborts the installation process if a URL it wants to retrieve can't be downloaded, unless the URL is an actual package download. Instead, it issues a warning and tries to keep going. - + + * Fixed distutils-style scripts originally built on Windows having their line + endings doubled when installed on any platform. + 0.6c5 * Fixed ``.dll`` files on Cygwin not having executable permisions when an egg is installed unzipped. Modified: sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Thu Feb 1 20:03:18 2007 @@ -373,7 +373,7 @@ for script_name in dist.metadata_listdir('scripts'): self.install_script( dist, script_name, - dist.get_metadata('scripts/'+script_name).replace('\r','\n') + '\n'.join(dist.get_metadata('scripts/'+script_name).splitlines()) ) self.install_wrapper_scripts(dist) From python-checkins at python.org Thu Feb 1 20:50:30 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 1 Feb 2007 20:50:30 +0100 (CET) Subject: [Python-checkins] r53613 - in python/branches/bcannon-objcap: BRANCHNEWS Python/pythonrun.c Message-ID: <20070201195030.D91C81E4009@bag.python.org> Author: brett.cannon Date: Thu Feb 1 20:50:30 2007 New Revision: 53613 Modified: python/branches/bcannon-objcap/BRANCHNEWS python/branches/bcannon-objcap/Python/pythonrun.c Log: Clear sys.path_importer_cache. Modified: python/branches/bcannon-objcap/BRANCHNEWS ============================================================================== --- python/branches/bcannon-objcap/BRANCHNEWS (original) +++ python/branches/bcannon-objcap/BRANCHNEWS Thu Feb 1 20:50:30 2007 @@ -8,6 +8,8 @@ Core and builtins ----------------- +* Clear out sys.path_importer_cache. + * Force 'warnings' to be cached by the C code. * Make importing the sys module after it has been completely deleted use the Modified: python/branches/bcannon-objcap/Python/pythonrun.c ============================================================================== --- python/branches/bcannon-objcap/Python/pythonrun.c (original) +++ python/branches/bcannon-objcap/Python/pythonrun.c Thu Feb 1 20:50:30 2007 @@ -367,8 +367,8 @@ Incremental codecs fail. * _codecs Exposed by codecs. - * warnings (hide: needs sys._getframe()) - Warnings reset otherwise. + * warnings (cache in C code) + Warnings reset otherwise. Requires 'sys' module to work. */ /* Get the 'warnings' module cached away at the C level. */ PyModule_GetWarningsModule(); @@ -407,6 +407,10 @@ PyDict_SetItemString(interp->modules, ".hidden", hidden_modules); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); + + /* Clear out sys.path_importer_cache. */ + PyDict_Clear(PyDict_GetItemString(interp->sysdict, + "path_importer_cache")); } From python-checkins at python.org Thu Feb 1 20:59:49 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 1 Feb 2007 20:59:49 +0100 (CET) Subject: [Python-checkins] r53614 - sandbox/trunk/setuptools/setuptools/command/easy_install.py Message-ID: <20070201195949.BC10E1E4009@bag.python.org> Author: phillip.eby Date: Thu Feb 1 20:59:49 2007 New Revision: 53614 Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py Log: Fix script language detection so that scripts built on Windows are correctly identified as still being Python code! Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/easy_install.py (original) +++ sandbox/trunk/setuptools/setuptools/command/easy_install.py Thu Feb 1 20:59:49 2007 @@ -373,7 +373,7 @@ for script_name in dist.metadata_listdir('scripts'): self.install_script( dist, script_name, - '\n'.join(dist.get_metadata('scripts/'+script_name).splitlines()) + dist.get_metadata('scripts/'+script_name) ) self.install_wrapper_scripts(dist) @@ -593,7 +593,7 @@ "import pkg_resources\n" "pkg_resources.run_script(%(spec)r, %(script_name)r)\n" ) % locals() - self.write_script(script_name, script_text) + self.write_script(script_name, script_text, 'b') def write_script(self, script_name, contents, mode="t", blockers=()): """Write an executable file to the scripts directory""" @@ -1518,22 +1518,16 @@ def is_python_script(script_text, filename): """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. """ - if script_text.startswith('#!'): - # It begins with a '#!' line, so check if 'python' is in it somewhere - from distutils.command.build_scripts import first_line_re - lines = script_text.splitlines() - - if first_line_re.match(lines[0]): - return True # It's got a python "#!" line, consider it Python - else: - return False # It's some other scripting language - if filename.endswith('.py') or filename.endswith('.pyw'): return True # extension says it's Python if is_python(script_text, filename): return True # it's syntactically valid Python + if script_text.startswith('#!'): + # It begins with a '#!' line, so check if 'python' is in it somewhere + return 'python' in script_text.splitlines()[0].lower() + return False # Not any Python I can recognize @@ -1556,6 +1550,12 @@ + + + + + + def get_script_args(dist, executable=sys_executable, wininst=False): """Yield write_script() argument tuples for a distribution's entrypoints""" spec = str(dist.as_requirement()) From python-checkins at python.org Thu Feb 1 21:03:41 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 1 Feb 2007 21:03:41 +0100 (CET) Subject: [Python-checkins] r53615 - sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Message-ID: <20070201200341.943A31E400A@bag.python.org> Author: phillip.eby Date: Thu Feb 1 21:03:39 2007 New Revision: 53615 Modified: sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Log: Fix script language detection problem (backport from trunk) Modified: sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Thu Feb 1 21:03:39 2007 @@ -373,7 +373,7 @@ for script_name in dist.metadata_listdir('scripts'): self.install_script( dist, script_name, - '\n'.join(dist.get_metadata('scripts/'+script_name).splitlines()) + dist.get_metadata('scripts/'+script_name) ) self.install_wrapper_scripts(dist) @@ -593,7 +593,7 @@ "import pkg_resources\n" "pkg_resources.run_script(%(spec)r, %(script_name)r)\n" ) % locals() - self.write_script(script_name, script_text) + self.write_script(script_name, script_text, 'b') def write_script(self, script_name, contents, mode="t", blockers=()): """Write an executable file to the scripts directory""" @@ -1518,22 +1518,16 @@ def is_python_script(script_text, filename): """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. """ - if script_text.startswith('#!'): - # It begins with a '#!' line, so check if 'python' is in it somewhere - from distutils.command.build_scripts import first_line_re - lines = script_text.splitlines() - - if first_line_re.match(lines[0]): - return True # It's got a python "#!" line, consider it Python - else: - return False # It's some other scripting language - if filename.endswith('.py') or filename.endswith('.pyw'): return True # extension says it's Python if is_python(script_text, filename): return True # it's syntactically valid Python + if script_text.startswith('#!'): + # It begins with a '#!' line, so check if 'python' is in it somewhere + return 'python' in script_text.splitlines()[0].lower() + return False # Not any Python I can recognize @@ -1556,6 +1550,12 @@ + + + + + + def get_script_args(dist, executable=sys_executable, wininst=False): """Yield write_script() argument tuples for a distribution's entrypoints""" spec = str(dist.as_requirement()) From python-checkins at python.org Thu Feb 1 21:53:45 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 1 Feb 2007 21:53:45 +0100 (CET) Subject: [Python-checkins] r53616 - in python/branches/bcannon-objcap: BRANCHNEWS Python/pythonrun.c Message-ID: <20070201205345.430341E4006@bag.python.org> Author: brett.cannon Date: Thu Feb 1 21:53:44 2007 New Revision: 53616 Modified: python/branches/bcannon-objcap/BRANCHNEWS python/branches/bcannon-objcap/Python/pythonrun.c Log: Start using importlib for imports. Required moving other modules into .hidden for support reasons. Need to tweak importlib to block imports starting with '.'. Modified: python/branches/bcannon-objcap/BRANCHNEWS ============================================================================== --- python/branches/bcannon-objcap/BRANCHNEWS (original) +++ python/branches/bcannon-objcap/BRANCHNEWS Thu Feb 1 21:53:44 2007 @@ -8,6 +8,10 @@ Core and builtins ----------------- +* Use an instance of importlib.Import as what __import__ delegates to. This + necessitates storing a large chunk of modules into sys.modules['.hidden'] so + that importlib can keep working. + * Clear out sys.path_importer_cache. * Force 'warnings' to be cached by the C code. Modified: python/branches/bcannon-objcap/Python/pythonrun.c ============================================================================== --- python/branches/bcannon-objcap/Python/pythonrun.c (original) +++ python/branches/bcannon-objcap/Python/pythonrun.c Thu Feb 1 21:53:44 2007 @@ -333,24 +333,32 @@ { PyInterpreterState *interp; Py_ssize_t module_count, x; - PyObject* module_names_list; - PyObject* hidden_modules; + PyObject *module_names_list; + PyObject *hidden_modules; + PyObject *import_module; + PyObject *import_callable; Py_InitializeEx(1); interp = PyThreadState_GET()->interp; + import_module = PyImport_ImportModule("importlib"); + + import_callable = PyObject_CallMethod(import_module, "Import", ""); + /* Store import machinery somewhere so that a reference is held as needed. */ - PyDict_SetItemString(interp->sysdict, "import_", - PyDict_GetItemString(interp->builtins, "__import__")); + PyDict_SetItemString(interp->sysdict, "import_", import_callable); PyDict_SetItemString(interp->builtins, "__import__", PyDict_GetItemString(interp->sysdict, "import_delegate")); + Py_DECREF(import_module); + Py_DECREF(import_callable); + /* Clear out sys.modules. - Some modules must be kept around (at least for now; **XXX need to do - a security audit of each one!): + Some modules must be kept around in order for Python to function + properly. * __builtin__ Lose this and Python will not run. @@ -369,6 +377,9 @@ Exposed by codecs. * warnings (cache in C code) Warnings reset otherwise. Requires 'sys' module to work. + + All other modules are kept in the '.hidden' dict in sys.modules for + use by importlib. */ /* Get the 'warnings' module cached away at the C level. */ PyModule_GetWarningsModule(); @@ -388,21 +399,18 @@ (strcmp(module_name, "_codecs") == 0)) { continue; } - /* Modules that *must* stay but can be invisible. */ - /*else if ((strcmp(module_name, "warnings") == 0)) { + /* All other modules must be stored away for importlib. */ + else { PyObject *module = PyDict_GetItemString(interp->modules, module_name); PyDict_SetItemString(hidden_modules, module_name, module); PyDict_DelItemString(interp->modules, module_name); - }*/ - /* Everything else can go. */ - else { - PyDict_DelItemString(interp->modules, module_name); } } - /* Store away modules that must stick around but should not be exposed. + /* Store away modules that must stick around but should not be exposed; + this is done for importlib's benefit. */ PyDict_SetItemString(interp->modules, ".hidden", hidden_modules); From python-checkins at python.org Thu Feb 1 22:01:24 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 1 Feb 2007 22:01:24 +0100 (CET) Subject: [Python-checkins] r53617 - in python/branches/release25-maint: Misc/NEWS Objects/setobject.c Message-ID: <20070201210124.B1F221E4011@bag.python.org> Author: raymond.hettinger Date: Thu Feb 1 22:01:21 2007 New Revision: 53617 Modified: python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Objects/setobject.c Log: Bug #1648179: set.update() not recognizing __iter__ overrides in dict subclasses. Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Thu Feb 1 22:01:21 2007 @@ -16,6 +16,9 @@ a weakref on itself during a __del__ call for new-style classes (classic classes still have the bug). +- Bug #1648179: set.update() did not recognize an overridden __iter__ + method in subclasses of dict. + - Bug #1579370: Make PyTraceBack_Here use the current thread, not the frame's thread state. Modified: python/branches/release25-maint/Objects/setobject.c ============================================================================== --- python/branches/release25-maint/Objects/setobject.c (original) +++ python/branches/release25-maint/Objects/setobject.c Thu Feb 1 22:01:21 2007 @@ -915,7 +915,7 @@ if (PyAnySet_Check(other)) return set_merge(so, other); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; while (PyDict_Next(other, &pos, &key, &value)) { @@ -1363,7 +1363,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other) && !PyDict_Check(other)) { + if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1377,7 +1377,7 @@ if (result == NULL) return NULL; - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { while (set_next(so, &pos, &entry)) { setentry entrycopy; entrycopy.hash = entry->hash; @@ -1450,7 +1450,7 @@ if ((PyObject *)so == other) return set_clear(so); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; int rv; while (PyDict_Next(other, &pos, &key, &value)) { From python-checkins at python.org Thu Feb 1 22:03:00 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 1 Feb 2007 22:03:00 +0100 (CET) Subject: [Python-checkins] r53618 - python/trunk/Objects/setobject.c Message-ID: <20070201210300.31F8F1E400B@bag.python.org> Author: raymond.hettinger Date: Thu Feb 1 22:02:59 2007 New Revision: 53618 Modified: python/trunk/Objects/setobject.c Log: Bug #1648179: set.update() not recognizing __iter__ overrides in dict subclasses. Modified: python/trunk/Objects/setobject.c ============================================================================== --- python/trunk/Objects/setobject.c (original) +++ python/trunk/Objects/setobject.c Thu Feb 1 22:02:59 2007 @@ -915,7 +915,7 @@ if (PyAnySet_Check(other)) return set_merge(so, other); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; while (PyDict_Next(other, &pos, &key, &value)) { @@ -1363,7 +1363,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other) && !PyDict_Check(other)) { + if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1377,7 +1377,7 @@ if (result == NULL) return NULL; - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { while (set_next(so, &pos, &entry)) { setentry entrycopy; entrycopy.hash = entry->hash; @@ -1450,7 +1450,7 @@ if ((PyObject *)so == other) return set_clear(so); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; int rv; while (PyDict_Next(other, &pos, &key, &value)) { From python-checkins at python.org Thu Feb 1 22:03:08 2007 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 1 Feb 2007 22:03:08 +0100 (CET) Subject: [Python-checkins] r53619 - peps/trunk/pep-0008.txt Message-ID: <20070201210308.1FE4A1E4006@bag.python.org> Author: andrew.kuchling Date: Thu Feb 1 22:03:07 2007 New Revision: 53619 Modified: peps/trunk/pep-0008.txt Log: Be stricter about string exceptions Modified: peps/trunk/pep-0008.txt ============================================================================== --- peps/trunk/pep-0008.txt (original) +++ peps/trunk/pep-0008.txt Thu Feb 1 22:03:07 2007 @@ -641,9 +641,8 @@ - Use class-based exceptions. - String exceptions in new code are strongly discouraged, as they will - eventually (in Python 2.5) be deprecated and then (in Python 3000 or - perhaps sooner) removed. + String exceptions in new code are forbidden, because this language + feature is being removed in Python 2.6. Modules or packages should define their own domain-specific base exception class, which should be subclassed from the built-in Exception From python-checkins at python.org Thu Feb 1 22:04:20 2007 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 1 Feb 2007 22:04:20 +0100 (CET) Subject: [Python-checkins] r53620 - peps/trunk/pep-0008.txt Message-ID: <20070201210420.24BC91E4007@bag.python.org> Author: andrew.kuchling Date: Thu Feb 1 22:04:19 2007 New Revision: 53620 Modified: peps/trunk/pep-0008.txt Log: Wording fix Modified: peps/trunk/pep-0008.txt ============================================================================== --- peps/trunk/pep-0008.txt (original) +++ peps/trunk/pep-0008.txt Thu Feb 1 22:04:19 2007 @@ -628,7 +628,7 @@ in-place string concatenation for statements in the form a+=b or a=a+b. Those statements run more slowly in Jython. In performance sensitive parts of the library, the ''.join() form should be used instead. This - will assure that concatenation occurs in linear time across various + will ensure that concatenation occurs in linear time across various implementations. - Comparisons to singletons like None should always be done with From python-checkins at python.org Thu Feb 1 22:10:22 2007 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 1 Feb 2007 22:10:22 +0100 (CET) Subject: [Python-checkins] r53621 - peps/trunk/pep-0008.txt Message-ID: <20070201211022.F17E51E4006@bag.python.org> Author: andrew.kuchling Date: Thu Feb 1 22:09:28 2007 New Revision: 53621 Modified: peps/trunk/pep-0008.txt Log: Mention bare except: clauses in PEP 8; see the python-dev archive around Dec. 22 2007 for a short discussion Modified: peps/trunk/pep-0008.txt ============================================================================== --- peps/trunk/pep-0008.txt (original) +++ peps/trunk/pep-0008.txt Thu Feb 1 22:09:28 2007 @@ -663,6 +663,32 @@ continuation characters thanks to the containing parentheses. The older form will be removed in Python 3000. + - When catching exceptions, mention specific exceptions + whenever possible instead of using a bare 'except:' clause. + + For example, use: + + try: + import platform_specific_module + except ImportError: + platform_specific_module = None + + A bare 'except:' clause will catch SystemExit and KeyboardInterrupt + exceptions, making it harder to interrupt a program with Control-C, + and can disguise other problems. If you want to catch all + exceptions that signal program errors, use 'except StandardError:'. + + A good rule of thumb is to limit use of bare 'except' clauses to two + cases: + + 1) If the exception handler will be printing out or logging + the traceback; at least the user will be aware that an + error has occurred. + + 2) If the code needs to do some cleanup work, but then lets + the exception propagate upwards with 'raise'. + 'try...finally' is a better way to handle this case. + - Use string methods instead of the string module. String methods are always much faster and share the same API with From fdrake at acm.org Thu Feb 1 22:16:59 2007 From: fdrake at acm.org (Fred L. Drake, Jr.) Date: Thu, 1 Feb 2007 16:16:59 -0500 Subject: [Python-checkins] r53621 - peps/trunk/pep-0008.txt In-Reply-To: <20070201211022.F17E51E4006@bag.python.org> References: <20070201211022.F17E51E4006@bag.python.org> Message-ID: <200702011616.59728.fdrake@acm.org> On Thursday 01 February 2007 16:10, andrew.kuchling wrote: > Author: andrew.kuchling > Date: Thu Feb 1 22:09:28 2007 > New Revision: 53621 ... > Mention bare except: clauses in PEP 8; see the python-dev archive around > Dec. 22 2007 for a short discussion Now that's forward-looking! ;-) -Fred -- Fred L. Drake, Jr. From buildbot at python.org Thu Feb 1 23:22:13 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 01 Feb 2007 22:22:13 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) 2.5 Message-ID: <20070201222214.1FC581E4006@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%25202.5/builds/151 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildbot/Buildbot/2.5.baxter-ubuntu/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (3.5154) is more than 2 seconds more than expected (0.001) sincerely, -The Buildbot From python-checkins at python.org Fri Feb 2 00:15:48 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 2 Feb 2007 00:15:48 +0100 (CET) Subject: [Python-checkins] r53622 - sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/test_importlib.py Message-ID: <20070201231548.D3A981E4016@bag.python.org> Author: brett.cannon Date: Fri Feb 2 00:15:47 2007 New Revision: 53622 Modified: sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/test_importlib.py Log: Abstract out getting a module from the cache, sys.modules. Allows for more fine-grained control over whether the existence of a module in sys.modules should allow for it to be returned or should be blocked for security reasons. Modified: sandbox/trunk/import_in_py/importlib.py ============================================================================== --- sandbox/trunk/import_in_py/importlib.py (original) +++ sandbox/trunk/import_in_py/importlib.py Fri Feb 2 00:15:47 2007 @@ -692,6 +692,16 @@ return loader else: raise ImportError("No module found named %s" % name) + + def module_from_cache(self, name): + """Try to return the named module from sys.modules. + + Return False if the module is not in the cache. + """ + if name in sys.modules: + return sys.modules[name] + else: + return False def _import_module(self, name, path=None): """Import the specified module with no handling of parent modules. @@ -700,12 +710,12 @@ import was attempted and failed) then ImportError is raised. """ - if name in sys.modules: - value = sys.modules[name] - if value is None: + cached_module = self.module_from_cache(name) + if cached_module is not False: + if cached_module is None: raise ImportError("relative import redirect") else: - return value + return cached_module try: # Attempt to find a loader on sys.meta_path. loader = self._search_meta_path(name, path) Modified: sandbox/trunk/import_in_py/test_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_importlib.py (original) +++ sandbox/trunk/import_in_py/test_importlib.py Fri Feb 2 00:15:47 2007 @@ -1141,6 +1141,17 @@ for level in (-1, 0): self.failUnlessRaises(ValueError, self.importer, '', {}, {}, level) + def test_module_from_cache(self): + # If a value is in sys.modules it should be returned (no matter the + # object type), else return False. + value = "a 'module'" + mod_name = "module name" + sys.modules[mod_name] = value + returned = self.importer.module_from_cache(mod_name) + self.failUnless(returned is value) + returned = self.importer.module_from_cache(mod_name + 'asdfeddf') + self.failUnless(returned is False) + class ImportMetaPathTests(ImportHelper): From buildbot at python.org Fri Feb 2 00:26:42 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 01 Feb 2007 23:26:42 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) trunk Message-ID: <20070201232642.31A161E4006@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%2520trunk/builds/1159 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout sincerely, -The Buildbot From python-checkins at python.org Fri Feb 2 01:27:14 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 2 Feb 2007 01:27:14 +0100 (CET) Subject: [Python-checkins] r53623 - sandbox/trunk/import_in_py/controlled_importlib.py sandbox/trunk/import_in_py/test_controlled_importlib.py Message-ID: <20070202002714.17FE81E4006@bag.python.org> Author: brett.cannon Date: Fri Feb 2 01:27:13 2007 New Revision: 53623 Added: sandbox/trunk/import_in_py/controlled_importlib.py (contents, props changed) sandbox/trunk/import_in_py/test_controlled_importlib.py (contents, props changed) Log: Begin implementation of a controlling import that usees whitelisting to restrict what can and cannot be imported. Added: sandbox/trunk/import_in_py/controlled_importlib.py ============================================================================== --- (empty file) +++ sandbox/trunk/import_in_py/controlled_importlib.py Fri Feb 2 01:27:13 2007 @@ -0,0 +1,86 @@ +"""Create a controllable import. + +One should be able to do several things to control imports: + + * Whitelisting of modules based on name and type + + built-ins + + frozen + + extensions + * Block all modules based on type + + .pyc + * Allow all modules of a certain type + + .py +""" +import importlib +import sys + +class Whitelister(object): + + """Whitelist the finding and/or loading of modules.""" + + def __init__(self, whitelist, *args, **kwargs): + """Store whitelist and continue on with instantiation.""" + self._whitelist = frozenset(whitelist) + super(Whitelister, self).__init__(*args, **kwargs) + + def check_name(self, name): + """Check a module name against the whitelist, returning True if it + passes or False otherwise.""" + if name in self._whitelist: + return True + return False + + def find_module(self, name, path=None): + """If the module name passes the whitelist, allow the finding of the + modules to continue, otherwise return None.""" + if self.check_name(name): + return super(Whitelister, self).find_module(name, path) + return None + + def load_module(self, name): + """If the module names passes the whitelist, allow the loading of the + module to continue, otherwise raise ImportError.""" + if self.check_name(name): + return super(Whitelister, self).load_module(name) + raise ImportError("cannot import module") + + +class WhitelistBuiltin(Whitelister, importlib.BuiltinImporter): + + """Whitelisting importer/loader for built-in modules.""" + + pass + + +class WhitelistFrozen(Whitelister, importlib.FrozenImporter): + + """Whitelisting importer/loader for frozen modules.""" + + pass + + +class ControlledImport(importlib.Import): + + """Represent a controllable version of import that allows for more + fine-grained control over what can and cannot be imported.""" + + def __init__(self, safe_builtins, safe_frozen, safe_extensions): + """Set up importation where built-in, frozen, and extension modules + must be whitelisted and .pyc files are completely blocked + while all. py files are allowed.""" + # Clear out any traces of the previous import machinery. + sys.path_importer_cache.clear() + # Whitelist built-in and frozen modules on sys.meta_path. + # XXX + # Whitelist extension modules on sys.path. + # XXX + # Allow all .py files but not .pyc files on sys.path. + # XXX + + def module_from_cache(self, name): + """Override so that any module name starting with a dot raises + ImportError.""" + if name.startswith('.'): + raise ImportError("module names starting with '.' cannot be " + "imported") + return importlib.Import.module_from_cache(self, name) Added: sandbox/trunk/import_in_py/test_controlled_importlib.py ============================================================================== --- (empty file) +++ sandbox/trunk/import_in_py/test_controlled_importlib.py Fri Feb 2 01:27:13 2007 @@ -0,0 +1,117 @@ +import controlled_importlib + +import StringIO +import sys +import unittest +from test import test_support + + +class DummyImporterLoader(object): + + def find_module(self, name, path=None): + return True + + def load_module(self, name): + return True + +class DummyWhitelist(controlled_importlib.Whitelister, DummyImporterLoader): + + pass + + +class WhitelistTests(unittest.TestCase): + + """Test the general whitelisting mechanism.""" + + def test_whitelist_module(self): + # A direct module name should be allowed. + whitelist = 'ok_mod' + imp_load = DummyWhitelist([whitelist]) + self.failUnless(imp_load.find_module(whitelist) is True) + self.failUnless(imp_load.find_module('fdssdf') is None) + self.failUnless(imp_load.load_module(whitelist) is True) + self.failUnlessRaises(ImportError, imp_load.load_module, 'asdfadsf') + + def test_whitelist_list(self): + # When the whitelist is a list it should be able to properly whitelist + # no matter where a module is listed. + whitelist1 = 'A' + whitelist2 = 'B' + imp_load = DummyWhitelist([whitelist1, whitelist2]) + for whitelist in (whitelist1, whitelist2): + self.failUnless(imp_load.find_module(whitelist) is True) + self.failUnless(imp_load.load_module(whitelist) is True) + + def test_block_partial_name(self): + # A module that happens to be a prefix of a whitelisted module or has a + # whitelisted module as a prefix should still be blocked. + whitelist = 'mod' + imp_load = DummyWhitelist([whitelist]) + # Module has a whitelisted module as a prefix. + self.failUnless(imp_load.find_module(whitelist+'2') is None) + self.failUnlessRaises(ImportError, imp_load.load_module, whitelist+'2') + # Module is a prefix of a whitelisted module. + self.failUnless(imp_load.find_module(whitelist[:-1]) is None) + self.failUnlessRaises(ImportError, imp_load.load_module, + whitelist[:-1]) + + def test_package(self): + # Whitelisting a package does not automatically allow the submodules. + whitelist = 'pkg' + imp_load = DummyWhitelist([whitelist]) + mod = whitelist + '.' + 'mod' + self.failUnless(imp_load.find_module(mod) is None) + self.failUnlessRaises(ImportError, imp_load.load_module, mod) + + +class WhitelistBuiltinTests(unittest.TestCase): + + """Test the whitelisting support for built-in modules.""" + + def setUp(self): + self.whitelist = sys.builtin_module_names[0] + self.blacklist = sys.builtin_module_names[1] + + def test_whitelist(self): + # Only modules on the whitelist should be allowed to be imported. + # Everything else should return None. + imp_load = controlled_importlib.WhitelistBuiltin([self.whitelist]) + # Importer + self.failUnless(imp_load.find_module(self.whitelist) is not None) + self.failUnless(imp_load.find_module(self.blacklist) is None) + # Loader + self.failUnless(imp_load.load_module(self.whitelist)) + self.failUnlessRaises(ImportError, imp_load.load_module, + self.blacklist) + + +class WhitelistFrozenTests(unittest.TestCase): + + """Test whitelisting of frozen modules.""" + + def setUp(self): + sys.stdout = StringIO.StringIO() + self.whitelist = '__phello__' + self.blacklist = ('__hello__', '__phello__.spam') + + def tearDown(self): + sys.stdout = sys.__stdout__ + + def test_whitelist(self): + imp_load = controlled_importlib.WhitelistFrozen([self.whitelist]) + self.failUnless(imp_load.find_module(self.whitelist) is not None) + self.failUnless(imp_load.load_module(self.whitelist)) + for blacklist in self.blacklist: + self.failUnless(imp_load.find_module(blacklist) is None) + self.failUnlessRaises(ImportError, imp_load.load_module, blacklist) + + + +def test_main(): + test_support.run_unittest(WhitelistTests, + WhitelistBuiltinTests, + WhitelistFrozenTests) + + +if __name__ == '__main__': + test_main() From buildbot at python.org Fri Feb 2 07:41:08 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 02 Feb 2007 06:41:08 +0000 Subject: [Python-checkins] buildbot failure in MIPS Debian 2.5 Message-ID: <20070202064108.E5EEE1E4011@bag.python.org> The Buildbot has detected a new failure of MIPS Debian 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/MIPS%2520Debian%25202.5/builds/125 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'James': test Build Source Stamp: [branch sytem] net Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From python-checkins at python.org Fri Feb 2 20:06:37 2007 From: python-checkins at python.org (peter.astrand) Date: Fri, 2 Feb 2007 20:06:37 +0100 (CET) Subject: [Python-checkins] r53624 - python/trunk/Lib/subprocess.py Message-ID: <20070202190637.642981E4009@bag.python.org> Author: peter.astrand Date: Fri Feb 2 20:06:36 2007 New Revision: 53624 Modified: python/trunk/Lib/subprocess.py Log: We had several if statements checking the value of a fd. This is unsafe, since valid fds might be zero. We should check for not None instead. Modified: python/trunk/Lib/subprocess.py ============================================================================== --- python/trunk/Lib/subprocess.py (original) +++ python/trunk/Lib/subprocess.py Fri Feb 2 20:06:36 2007 @@ -592,14 +592,14 @@ c2pread, c2pwrite, errread, errwrite) - if p2cwrite: + if p2cwrite is not None: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) - if c2pread: + if c2pread is not None: if universal_newlines: self.stdout = os.fdopen(c2pread, 'rU', bufsize) else: self.stdout = os.fdopen(c2pread, 'rb', bufsize) - if errread: + if errread is not None: if universal_newlines: self.stderr = os.fdopen(errread, 'rU', bufsize) else: @@ -986,29 +986,29 @@ # Child try: # Close parent's pipe ends - if p2cwrite: + if p2cwrite is not None: os.close(p2cwrite) - if c2pread: + if c2pread is not None: os.close(c2pread) - if errread: + if errread is not None: os.close(errread) os.close(errpipe_read) # Dup fds for child - if p2cread: + if p2cread is not None: os.dup2(p2cread, 0) - if c2pwrite: + if c2pwrite is not None: os.dup2(c2pwrite, 1) - if errwrite: + if errwrite is not None: os.dup2(errwrite, 2) # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - if p2cread and p2cread not in (0,): + if p2cread is not None and p2cread not in (0,): os.close(p2cread) - if c2pwrite and c2pwrite not in (p2cread, 1): + if c2pwrite is not None and c2pwrite not in (p2cread, 1): os.close(c2pwrite) - if errwrite and errwrite not in (p2cread, c2pwrite, 2): + if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2): os.close(errwrite) # Close all other fds, if asked for @@ -1041,11 +1041,11 @@ # Parent os.close(errpipe_write) - if p2cread and p2cwrite: + if p2cread is not None and p2cwrite is not None: os.close(p2cread) - if c2pwrite and c2pread: + if c2pwrite is not None and c2pread is not None: os.close(c2pwrite) - if errwrite and errread: + if errwrite is not None and errread is not None: os.close(errwrite) # Wait for exec to fail or succeed; possibly raising exception From buildbot at python.org Fri Feb 2 20:46:46 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 02 Feb 2007 19:46:46 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP trunk Message-ID: <20070202194646.437171E4012@bag.python.org> The Buildbot has detected a new failure of x86 XP trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%2520trunk/builds/185 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: peter.astrand Build had warnings: warnings failed slave lost sincerely, -The Buildbot From python-checkins at python.org Sat Feb 3 06:18:41 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 3 Feb 2007 06:18:41 +0100 (CET) Subject: [Python-checkins] r53625 - sandbox/trunk/import_in_py/controlled_importlib.py sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/test_controlled_importlib.py sandbox/trunk/import_in_py/test_importlib.py Message-ID: <20070203051841.A079C1E4009@bag.python.org> Author: brett.cannon Date: Sat Feb 3 06:18:40 2007 New Revision: 53625 Modified: sandbox/trunk/import_in_py/controlled_importlib.py sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/test_controlled_importlib.py sandbox/trunk/import_in_py/test_importlib.py Log: Add a post-import method. This allows for the stripping of __loader__ from newly imported modules so that the global namespace of the loader is not exposed. Also add tests for module_from_cache. Modified: sandbox/trunk/import_in_py/controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/controlled_importlib.py Sat Feb 3 06:18:40 2007 @@ -84,3 +84,12 @@ raise ImportError("module names starting with '.' cannot be " "imported") return importlib.Import.module_from_cache(self, name) + + def post_import(self, module): + """Strip off the __loader__ attribute so that the object's global + namespace is not exposed.""" + try: + del module.__loader__ + except AttributeError: + pass + return module Modified: sandbox/trunk/import_in_py/importlib.py ============================================================================== --- sandbox/trunk/import_in_py/importlib.py (original) +++ sandbox/trunk/import_in_py/importlib.py Sat Feb 3 06:18:40 2007 @@ -702,6 +702,10 @@ return sys.modules[name] else: return False + + def post_import(self, module): + """Perform any desired post-import processing on the module.""" + return module def _import_module(self, name, path=None): """Import the specified module with no handling of parent modules. @@ -725,7 +729,7 @@ loader = self._search_std_path(name, path) # A loader was found. It is the loader's responsibility to have put an # entry in sys.modules. - return loader.load_module(name) + return self.post_import(loader.load_module(name)) def _import_full_module(self, name): """Import a module along with its parent modules and set into Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/test_controlled_importlib.py Sat Feb 3 06:18:40 2007 @@ -1,5 +1,7 @@ import controlled_importlib +import mock_importlib +from contextlib import contextmanager import StringIO import sys import unittest @@ -106,11 +108,77 @@ self.failUnlessRaises(ImportError, imp_load.load_module, blacklist) + at contextmanager +def mutate_sys_modules(module, name): + try: + old_module = sys.modules.get(name) + sys.modules[name] = module + yield + finally: + if old_module: + sys.modules[name] = old_module + else: + del sys.modules[name] + + +class ControlledImportMethodTests(unittest.TestCase): + + """Test explicit methods of ControlledImport.""" + + def setUp(self): + self.import_ = controlled_importlib.ControlledImport([], [], []) + + def test_module_from_cache(self): + # Importing of module names with a leading dot should not occur. + module = 'module' + module_name = '.blocked' + assert module_name.startswith('.') + with mutate_sys_modules(module, module_name): + self.failUnlessRaises(ImportError, self.import_.module_from_cache, + module_name) + + def test_post_import(self): + # Any __loader__ attribute should be indiscriminately removed. + module = mock_importlib.MockModule() + self.failUnless(self.import_.post_import(module) is module) + module.__loader__ = None + stripped_module = self.import_.post_import(module) + self.failUnless(stripped_module is module) + self.failUnless(not hasattr(stripped_module, '__loader__')) + + +class ControlledImportUsageTests(unittest.TestCase): + + """Make sure that usage of ControlledImport works properly.""" + + def test_block_dot_modules(self): + # Modules with a leading dot should not be imported. + pass + + def test_builtin_whitelisting(self): + pass + + def test_frozen_whitelisting(self): + pass + + def test_extension_whitelisting(self): + pass + + def test_pyc_blocking(self): + pass + + def test_py(self): + # XXX try importing something with the same name as a built-in that is + # not whitelisted. + pass + def test_main(): test_support.run_unittest(WhitelistTests, WhitelistBuiltinTests, - WhitelistFrozenTests) + WhitelistFrozenTests, + ControlledImportMethodTests, + ControlledImportUsageTests) if __name__ == '__main__': Modified: sandbox/trunk/import_in_py/test_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_importlib.py (original) +++ sandbox/trunk/import_in_py/test_importlib.py Sat Feb 3 06:18:40 2007 @@ -1152,6 +1152,12 @@ returned = self.importer.module_from_cache(mod_name + 'asdfeddf') self.failUnless(returned is False) + def test_post_import(self): + # Post-import processing should do nothing but return the module + # unscathed. + module = "mod" + self.failUnless(self.importer.post_import(module) is module) + class ImportMetaPathTests(ImportHelper): From python-checkins at python.org Sat Feb 3 06:20:26 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 3 Feb 2007 06:20:26 +0100 (CET) Subject: [Python-checkins] r53626 - sandbox/trunk/import_in_py/test_controlled_importlib.py Message-ID: <20070203052026.E3E761E4009@bag.python.org> Author: brett.cannon Date: Sat Feb 3 06:20:26 2007 New Revision: 53626 Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py Log: Note some specifics on what to test when checking for __loader__ removal in integration tests. Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/test_controlled_importlib.py Sat Feb 3 06:20:26 2007 @@ -172,6 +172,10 @@ # not whitelisted. pass + def test_no_loader_attribute(self): + # No __loader__ attribute should be exposed on any module or package. + # XXX check both modules, packages, and submodules. + def test_main(): test_support.run_unittest(WhitelistTests, From python-checkins at python.org Sat Feb 3 23:05:24 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 3 Feb 2007 23:05:24 +0100 (CET) Subject: [Python-checkins] r53628 - sandbox/trunk/import_in_py/controlled_importlib.py Message-ID: <20070203220524.200391E400A@bag.python.org> Author: brett.cannon Date: Sat Feb 3 23:05:21 2007 New Revision: 53628 Modified: sandbox/trunk/import_in_py/controlled_importlib.py Log: Prep the 'sys' module more in ControlledImport.__init__. Also provide default arguments. Modified: sandbox/trunk/import_in_py/controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/controlled_importlib.py Sat Feb 3 23:05:21 2007 @@ -64,14 +64,18 @@ """Represent a controllable version of import that allows for more fine-grained control over what can and cannot be imported.""" - def __init__(self, safe_builtins, safe_frozen, safe_extensions): + def __init__(self, safe_builtins=(), safe_frozen=(), safe_extensions=()): """Set up importation where built-in, frozen, and extension modules must be whitelisted and .pyc files are completely blocked while all. py files are allowed.""" + importlib.Import.__init__(self, (), ()) # Clear out any traces of the previous import machinery. sys.path_importer_cache.clear() + sys.meta_path = [] + sys.path_hooks = [] # Whitelist built-in and frozen modules on sys.meta_path. - # XXX + sys.meta_path.append(WhitelistBuiltin(safe_builtins)) + sys.meta_path.append(WhitelistFrozen(safe_frozen)) # Whitelist extension modules on sys.path. # XXX # Allow all .py files but not .pyc files on sys.path. From python-checkins at python.org Sat Feb 3 23:08:13 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 3 Feb 2007 23:08:13 +0100 (CET) Subject: [Python-checkins] r53629 - sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/test_importlib.py Message-ID: <20070203220813.D67D41E400A@bag.python.org> Author: brett.cannon Date: Sat Feb 3 23:08:12 2007 New Revision: 53629 Modified: sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/test_importlib.py Log: Make the built-in and frozen module meta_path objects not use classmethods. Modified: sandbox/trunk/import_in_py/importlib.py ============================================================================== --- sandbox/trunk/import_in_py/importlib.py (original) +++ sandbox/trunk/import_in_py/importlib.py Sat Feb 3 23:08:12 2007 @@ -158,22 +158,19 @@ """Base class for meta_path importers for built-in and frozen modules. - Subclasses must provide the _find and _load methods. The methods are - expected to be defined on the subclass itself and not on an instance. + Subclasses must provide the _find and _load methods. """ - @classmethod - def find_module(cls, fullname, path=None): + def find_module(self, fullname, path=None): """See if a built-in or frozen module can be imported based on the specified name.""" - if cls._find(fullname): - return cls + if self._find(fullname): + return self else: return None - @classmethod - def load_module(cls, fullname): + def load_module(self, fullname): """Load a built-in or frozen module. 'imp' code for loading a built-in or frozen module handles the setting @@ -184,7 +181,7 @@ try: return sys.modules[fullname] except KeyError: - mod = cls._load(fullname) + mod = self._load(fullname) if not mod: raise ImportError("expected built-in module not loaded") return mod @@ -605,7 +602,7 @@ """ def __init__(self, default_path_hook=None, - extended_meta_path=(BuiltinImporter, FrozenImporter)): + extended_meta_path=(BuiltinImporter(), FrozenImporter())): """Store a default path hook entry and a sequence to internally extend sys.meta_path by.""" self.extended_meta_path = extended_meta_path Modified: sandbox/trunk/import_in_py/test_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_importlib.py (original) +++ sandbox/trunk/import_in_py/test_importlib.py Sat Feb 3 23:08:12 2007 @@ -85,7 +85,7 @@ """Test the built-in module importer.""" - importer = importlib.BuiltinImporter + importer = importlib.BuiltinImporter() module_name = 'sys' bad_module_names = ('tokenize', 'time', '__hello__') @@ -100,7 +100,7 @@ """ - importer = importlib.FrozenImporter + importer = importlib.FrozenImporter() module_name = '__hello__' bad_module_names = ('tokenize', 'time', 'sys') From python-checkins at python.org Sat Feb 3 23:09:03 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 3 Feb 2007 23:09:03 +0100 (CET) Subject: [Python-checkins] r53630 - sandbox/trunk/import_in_py/test_controlled_importlib.py Message-ID: <20070203220903.5D7631E400A@bag.python.org> Author: brett.cannon Date: Sat Feb 3 23:09:02 2007 New Revision: 53630 Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py Log: Test that keys starting with a dot in sys.modules and whitelisting of built-in modules works for ControlledImport. Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/test_controlled_importlib.py Sat Feb 3 23:09:02 2007 @@ -110,6 +110,7 @@ @contextmanager def mutate_sys_modules(module, name): + """Temporarily mutate sys.modules with a new module.""" try: old_module = sys.modules.get(name) sys.modules[name] = module @@ -120,6 +121,19 @@ else: del sys.modules[name] + at contextmanager +def remove_from_sys_modules(*modules): + """Temporarily remove modules from sys.modules.""" + try: + cached = [] + for name in modules: + cached.append(sys.modules[name]) + del sys.modules[name] + yield + finally: + for name, module in zip(modules, cached): + sys.modules[name] = module + class ControlledImportMethodTests(unittest.TestCase): @@ -153,10 +167,20 @@ def test_block_dot_modules(self): # Modules with a leading dot should not be imported. - pass + import_ = controlled_importlib.ControlledImport() + module = mock_importlib.MockModule() + module_name = '.block' + with mutate_sys_modules(module, module_name): + self.failUnlessRaises(ImportError, import_, module_name, {}, {}, 0) def test_builtin_whitelisting(self): - pass + whitelist = sys.builtin_module_names[0] + blacklist = sys.builtin_module_names[1] + with remove_from_sys_modules(whitelist, blacklist): + import_ = controlled_importlib.ControlledImport([whitelist]) + module = import_(whitelist, {}, {}, 0) + self.failUnlessEqual(module.__name__, whitelist) + self.failUnlessRaises(ImportError, import_, blacklist, {}, {}, 0) def test_frozen_whitelisting(self): pass @@ -175,6 +199,7 @@ def test_no_loader_attribute(self): # No __loader__ attribute should be exposed on any module or package. # XXX check both modules, packages, and submodules. + pass def test_main(): From python-checkins at python.org Sat Feb 3 23:44:49 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 3 Feb 2007 23:44:49 +0100 (CET) Subject: [Python-checkins] r53631 - sandbox/trunk/import_in_py/test_controlled_importlib.py Message-ID: <20070203224449.9596F1E400A@bag.python.org> Author: brett.cannon Date: Sat Feb 3 23:44:47 2007 New Revision: 53631 Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py Log: Test whitelisting of frozen modules. Also use frozen modules to test that inra-package relative importing does not break past whitelisting. Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/test_controlled_importlib.py Sat Feb 3 23:44:47 2007 @@ -1,7 +1,7 @@ import controlled_importlib import mock_importlib -from contextlib import contextmanager +from contextlib import contextmanager, nested import StringIO import sys import unittest @@ -127,13 +127,25 @@ try: cached = [] for name in modules: - cached.append(sys.modules[name]) - del sys.modules[name] + if name in sys.modules: + cached.append(sys.modules[name]) + del sys.modules[name] yield finally: for name, module in zip(modules, cached): sys.modules[name] = module + at contextmanager +def temp_setattr(obj, attribute, value): + """Temporarily set an attribute on an object.""" + try: + if hasattr(obj, attribute): + old_value = getattr(obj, attribute) + setattr(obj, attribute, value) + yield value + finally: + setattr(obj, attribute, old_value) + class ControlledImportMethodTests(unittest.TestCase): @@ -171,19 +183,27 @@ module = mock_importlib.MockModule() module_name = '.block' with mutate_sys_modules(module, module_name): - self.failUnlessRaises(ImportError, import_, module_name, {}, {}, 0) + self.failUnlessRaises(ImportError, import_, module_name, level=0) def test_builtin_whitelisting(self): whitelist = sys.builtin_module_names[0] blacklist = sys.builtin_module_names[1] with remove_from_sys_modules(whitelist, blacklist): import_ = controlled_importlib.ControlledImport([whitelist]) - module = import_(whitelist, {}, {}, 0) + module = import_(whitelist, level=0) self.failUnlessEqual(module.__name__, whitelist) - self.failUnlessRaises(ImportError, import_, blacklist, {}, {}, 0) + self.failUnlessRaises(ImportError, import_, blacklist, level=0) def test_frozen_whitelisting(self): - pass + whitelist = '__phello__' + blacklist = ('__hello__', '__phello__.spam') + with nested(temp_setattr(sys, 'stdout', StringIO.StringIO()), + remove_from_sys_modules(whitelist, *blacklist)): + import_ = controlled_importlib.ControlledImport((), [whitelist]) + module = import_(whitelist, level=0) + self.failUnlessEqual(module.__name__, whitelist) + for blacklisted in blacklist: + self.failUnlessRaises(ImportError, import_, blacklisted, level=0) def test_extension_whitelisting(self): pass @@ -201,6 +221,20 @@ # XXX check both modules, packages, and submodules. pass + def test_relative_import(self): + # A relative import within a package should not be able to circumvent + # whitelisting. + whitelist ='__phello__' + blacklist = '__phello__.spam' + blacklist_module = blacklist.split('.')[1] + with nested(temp_setattr(sys, 'stdout', StringIO.StringIO()), + remove_from_sys_modules(whitelist, blacklist)): + import_ = controlled_importlib.ControlledImport((), [whitelist]) + pkg = import_(whitelist, level=0) + pkg_fromlist = import_('', pkg.__dict__, {}, [blacklist_module], 1) + assert pkg_fromlist.__name__ == whitelist + self.failUnless(not hasattr(pkg_fromlist, blacklist_module)) + def test_main(): test_support.run_unittest(WhitelistTests, From buildbot at python.org Sun Feb 4 00:31:09 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 03 Feb 2007 23:31:09 +0000 Subject: [Python-checkins] buildbot failure in g4 osx.4 2.5 Message-ID: <20070203233109.30D391E401C@bag.python.org> The Buildbot has detected a new failure of g4 osx.4 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/g4%2520osx.4%25202.5/builds/195 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Adrian': Reilly Build Source Stamp: [branch Dallas] Danny Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sun Feb 4 00:32:12 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 03 Feb 2007 23:32:12 +0000 Subject: [Python-checkins] buildbot failure in x86 gentoo 2.5 Message-ID: <20070203233216.208E41E4020@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/205 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Eddy': Derick Build Source Stamp: [branch Aubrey] Brody Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sun Feb 4 00:32:26 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 03 Feb 2007 23:32:26 +0000 Subject: [Python-checkins] buildbot failure in sparc solaris10 gcc 2.5 Message-ID: <20070203233226.71C441E4017@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%25202.5/builds/197 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Antony': Lawrence Build Source Stamp: [branch Nico] Cale Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sun Feb 4 00:34:51 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 03 Feb 2007 23:34:51 +0000 Subject: [Python-checkins] buildbot failure in x86 XP 2.5 Message-ID: <20070203233451.4CC051E400A@bag.python.org> The Buildbot has detected a new failure of x86 XP 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%25202.5/builds/107 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Jordan': Amari Build Source Stamp: [branch Dillan] Kristofer Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sun Feb 4 00:40:24 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 03 Feb 2007 23:40:24 +0000 Subject: [Python-checkins] buildbot failure in x86 OpenBSD 2.5 Message-ID: <20070203234024.7F31A1E400A@bag.python.org> The Buildbot has detected a new failure of x86 OpenBSD 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520OpenBSD%25202.5/builds/187 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Tariq': Lee Build Source Stamp: [branch Michael] Timothy Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sun Feb 4 00:45:31 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 03 Feb 2007 23:45:31 +0000 Subject: [Python-checkins] buildbot failure in amd64 gentoo 2.5 Message-ID: <20070203234531.666131E400C@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%25202.5/builds/208 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Morgan': Trevon Build Source Stamp: [branch Lazaro] Cameron Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From python-checkins at python.org Sun Feb 4 02:04:07 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 4 Feb 2007 02:04:07 +0100 (CET) Subject: [Python-checkins] r53632 - sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/test_controlled_importlib.py Message-ID: <20070204010407.305511E400A@bag.python.org> Author: brett.cannon Date: Sun Feb 4 02:04:05 2007 New Revision: 53632 Modified: sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/test_controlled_importlib.py Log: Touch up some docstrings and comments. Modified: sandbox/trunk/import_in_py/importlib.py ============================================================================== --- sandbox/trunk/import_in_py/importlib.py (original) +++ sandbox/trunk/import_in_py/importlib.py Sun Feb 4 02:04:05 2007 @@ -270,6 +270,8 @@ If the module's name is dotted then only search for the trailing module's name on the path entry. An importer is already created for each directory in the __path__ attribute for a package. + + 'path' is ignored as that is meant for meta_path entries only. """ tail_module = fullname.rsplit('.', 1)[-1] @@ -462,10 +464,10 @@ package location of 'package'. The loader needs to implement several methods in order to this handler - to be able to load needed data. A key point with some of these methods - is the idea of opaque code objects which are not directly touched by - the handler but are passed back to the loader so as to allow for a way - to keep state: + to be able to load the needed data. A key point with some of these + methods is the idea of opaque code objects which are not directly + touched by the handler but are passed back to the loader so as to allow + for a way to keep state: * split_path(path) Take in an opaque path object and split it into a base path and a Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/test_controlled_importlib.py Sun Feb 4 02:04:05 2007 @@ -206,9 +206,11 @@ self.failUnlessRaises(ImportError, import_, blacklisted, level=0) def test_extension_whitelisting(self): + # XXX pass def test_pyc_blocking(self): + # XXX pass def test_py(self): From python-checkins at python.org Sun Feb 4 04:33:46 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 4 Feb 2007 04:33:46 +0100 (CET) Subject: [Python-checkins] r53633 - sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/mock_importlib.py sandbox/trunk/import_in_py/test_importlib.py Message-ID: <20070204033346.03D131E400A@bag.python.org> Author: brett.cannon Date: Sun Feb 4 04:33:38 2007 New Revision: 53633 Modified: sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/mock_importlib.py sandbox/trunk/import_in_py/test_importlib.py Log: Add the cannot_handle method for handlers. This gives handlers a way to say they will not handle a module based on its name. This has been introduced for the purpose of allowing a whitelisting of modules based on the handler and not the importer/loader. Modified: sandbox/trunk/import_in_py/importlib.py ============================================================================== --- sandbox/trunk/import_in_py/importlib.py (original) +++ sandbox/trunk/import_in_py/importlib.py Sun Feb 4 04:33:38 2007 @@ -277,6 +277,8 @@ tail_module = fullname.rsplit('.', 1)[-1] package_directory = os.path.join(self.path_entry, tail_module) for handler in self.handlers: + if handler.cannot_handle(fullname): + continue for file_ext in handler.handles: # XXX Backwards-incompatible to use anything but .py/.pyc # files for __init__? @@ -326,6 +328,8 @@ deal with initializing the module passed to it. """ + if self.handler.cannot_handle(fullname): + raise ImportError("cannot load") try: module = self.handler.handle_code(self, fullname, self.file_path, self.package) @@ -424,6 +428,11 @@ else: self.bytecode_handles = bytecode_handles self.handles = self.bytecode_handles + self.source_handles + + def cannot_handle(self, name): + """Allow the handler to tell an importer whether it does not + want to handle a module.""" + return False def new_module(self, name): """Retun a new module to be initialized (with __name__ set).""" @@ -570,6 +579,11 @@ """Set 'handles'.""" self.handles = tuple(suffix[0] for suffix in imp.get_suffixes() if suffix[2] == imp.C_EXTENSION) + + def cannot_handle(self, name): + """Tell an importer whether the handler cannot handle a specific + module.""" + return False def handle_code(self, loader, mod_name, extension_path, package=None): """Import an extension module.""" Modified: sandbox/trunk/import_in_py/mock_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/mock_importlib.py (original) +++ sandbox/trunk/import_in_py/mock_importlib.py Sun Feb 4 04:33:38 2007 @@ -32,6 +32,9 @@ def __init__(self, *handles): self.handles = handles + + def cannot_handle(self, name): + return False def handle_code(self, loader, mod_name, path, package=None): """Mock implementation of a handler. Modified: sandbox/trunk/import_in_py/test_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_importlib.py (original) +++ sandbox/trunk/import_in_py/test_importlib.py Sun Feb 4 04:33:38 2007 @@ -495,6 +495,7 @@ def test_sys_module_cleared_on_error(self): # Any entry made for module into sys.modules should be cleared upon error. class RaiseErrorHandler(object): + def cannot_handle(*args): return False def handle_code(*args): raise ImportError @@ -602,6 +603,10 @@ self.failUnlessEqual(self.handler.source_handles, source) self.failUnlessEqual(self.handler.bytecode_handles, bytecode) self.failUnlessEqual(self.handler.handles, bytecode + source) + + def test_cannot_handle(self): + # Should always return False. + self.failUnless(not self.handler.cannot_handle('asdfddss')) def test_new_module(self): # Should return a new module with the proper value for __name__. @@ -796,6 +801,10 @@ self.ext_path = os.path.join(entry, ext_paths[0]) self.module_name = os.path.splitext(os.path.split(self.ext_path)[1])[0] self.loader = mock_importlib.MockHandler() + + def test_cannot_handle(self): + # Should always return False. + self.failUnless(not self.handler.cannot_handle('asdfdd')) def test_handle_code(self): # Make sure an extension module can be loaded. From python-checkins at python.org Mon Feb 5 02:24:26 2007 From: python-checkins at python.org (thomas.wouters) Date: Mon, 5 Feb 2007 02:24:26 +0100 (CET) Subject: [Python-checkins] r53634 - in python/branches/p3yk: Doc/howto/TODO Doc/howto/curses.tex Doc/howto/doanddont.tex Doc/howto/regex.tex Doc/lib/libexcs.tex Doc/lib/libimageop.tex Doc/lib/libmailbox.tex Doc/ref/ref4.tex Doc/tut/tut.tex Doc/whatsnew/whatsnew26.tex Lib/CGIHTTPServer.py Lib/_strptime.py Lib/compiler/pycodegen.py Lib/compiler/transformer.py Lib/cookielib.py Lib/dumbdbm.py Lib/dummy_thread.py Lib/dummy_threading.py Lib/email/charset.py Lib/encodings/aliases.py Lib/ftplib.py Lib/httplib.py Lib/idlelib/CodeContext.py Lib/lib-tk/tkSimpleDialog.py Lib/mailbox.py Lib/platform.py Lib/pty.py Lib/subprocess.py Lib/test/test_cfgparser.py Lib/test/test_compiler.py Lib/test/test_dumbdbm.py Lib/test/test_exceptions.py Lib/test/test_gzip.py Lib/test/test_mailbox.py Lib/test/test_old_mailbox.py Lib/test/test_pep352.py Lib/test/test_pty.py Lib/test/test_resource.py Lib/test/test_set.py Lib/test/test_strptime.py Lib/test/test_struct.py Lib/test/test_support.py Modules/_ctypes/cfield.c Modules/posixmodule.c Objects/setobject.c Python/ceval.c Message-ID: <20070205012426.3D9891E4002@bag.python.org> Author: thomas.wouters Date: Mon Feb 5 02:24:16 2007 New Revision: 53634 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/howto/TODO python/branches/p3yk/Doc/howto/curses.tex python/branches/p3yk/Doc/howto/doanddont.tex python/branches/p3yk/Doc/howto/regex.tex python/branches/p3yk/Doc/lib/libexcs.tex python/branches/p3yk/Doc/lib/libimageop.tex python/branches/p3yk/Doc/lib/libmailbox.tex python/branches/p3yk/Doc/ref/ref4.tex python/branches/p3yk/Doc/tut/tut.tex python/branches/p3yk/Doc/whatsnew/whatsnew26.tex python/branches/p3yk/Lib/CGIHTTPServer.py python/branches/p3yk/Lib/_strptime.py python/branches/p3yk/Lib/compiler/pycodegen.py python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/cookielib.py python/branches/p3yk/Lib/dumbdbm.py python/branches/p3yk/Lib/dummy_thread.py python/branches/p3yk/Lib/dummy_threading.py python/branches/p3yk/Lib/email/charset.py python/branches/p3yk/Lib/encodings/aliases.py python/branches/p3yk/Lib/ftplib.py python/branches/p3yk/Lib/httplib.py python/branches/p3yk/Lib/idlelib/CodeContext.py python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/platform.py python/branches/p3yk/Lib/pty.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/test/test_cfgparser.py python/branches/p3yk/Lib/test/test_compiler.py python/branches/p3yk/Lib/test/test_dumbdbm.py python/branches/p3yk/Lib/test/test_exceptions.py python/branches/p3yk/Lib/test/test_gzip.py python/branches/p3yk/Lib/test/test_mailbox.py python/branches/p3yk/Lib/test/test_old_mailbox.py python/branches/p3yk/Lib/test/test_pep352.py python/branches/p3yk/Lib/test/test_pty.py python/branches/p3yk/Lib/test/test_resource.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Lib/test/test_strptime.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_support.py python/branches/p3yk/Modules/_ctypes/cfield.c python/branches/p3yk/Modules/posixmodule.c python/branches/p3yk/Objects/setobject.c python/branches/p3yk/Python/ceval.c Log: Merged revisions 53538-53622 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53545 | andrew.kuchling | 2007-01-24 21:06:41 +0100 (Wed, 24 Jan 2007) | 1 line Strengthen warning about using lock() ........ r53556 | thomas.heller | 2007-01-25 19:34:14 +0100 (Thu, 25 Jan 2007) | 3 lines Fix for #1643874: When calling SysAllocString, create a PyCObject which will eventually call SysFreeString to free the BSTR resource. ........ r53563 | andrew.kuchling | 2007-01-25 21:02:13 +0100 (Thu, 25 Jan 2007) | 1 line Add item ........ r53564 | brett.cannon | 2007-01-25 21:22:02 +0100 (Thu, 25 Jan 2007) | 8 lines Fix time.strptime's %U support. Basically rewrote the algorithm to be more generic so that one only has to shift certain values based on whether the week was specified to start on Monday or Sunday. Cut out a lot of edge case code compared to the previous version. Also broke algorithm out into its own function (that is private to the module). Fixes bug #1643943 (thanks Biran Nahas for the report). ........ r53570 | brett.cannon | 2007-01-26 00:30:39 +0100 (Fri, 26 Jan 2007) | 4 lines Remove specific mention of my name and email address from modules. Not really needed and all bug reports should go to the bug tracker, not directly to me. Plus I am not the only person to have edited these files at this point. ........ r53573 | fred.drake | 2007-01-26 17:28:44 +0100 (Fri, 26 Jan 2007) | 1 line fix typo (extraneous ")") ........ r53575 | georg.brandl | 2007-01-27 18:43:02 +0100 (Sat, 27 Jan 2007) | 4 lines Patch #1638243: the compiler package is now able to correctly compile a with statement; previously, executing code containing a with statement compiled by the compiler package crashed the interpreter. ........ r53578 | georg.brandl | 2007-01-27 18:59:42 +0100 (Sat, 27 Jan 2007) | 3 lines Patch #1634778: add missing encoding aliases for iso8859_15 and iso8859_16. ........ r53579 | georg.brandl | 2007-01-27 20:38:50 +0100 (Sat, 27 Jan 2007) | 2 lines Bug #1645944: os.access now returns bool but docstring is not updated ........ r53590 | brett.cannon | 2007-01-28 21:58:00 +0100 (Sun, 28 Jan 2007) | 2 lines Use the thread lock's context manager instead of a try/finally statement. ........ r53591 | brett.cannon | 2007-01-29 05:41:44 +0100 (Mon, 29 Jan 2007) | 2 lines Add a test for slicing an exception. ........ r53594 | andrew.kuchling | 2007-01-29 21:21:43 +0100 (Mon, 29 Jan 2007) | 1 line Minor edits to the curses HOWTO ........ r53596 | andrew.kuchling | 2007-01-29 21:55:40 +0100 (Mon, 29 Jan 2007) | 1 line Various minor edits ........ r53597 | andrew.kuchling | 2007-01-29 22:28:48 +0100 (Mon, 29 Jan 2007) | 1 line More edits ........ r53601 | tim.peters | 2007-01-30 04:03:46 +0100 (Tue, 30 Jan 2007) | 2 lines Whitespace normalization. ........ r53603 | georg.brandl | 2007-01-30 21:21:30 +0100 (Tue, 30 Jan 2007) | 2 lines Bug #1648191: typo in docs. ........ r53605 | brett.cannon | 2007-01-30 22:34:36 +0100 (Tue, 30 Jan 2007) | 8 lines No more raising of string exceptions! The next step of PEP 352 (for 2.6) causes raising a string exception to trigger a TypeError. Trying to catch a string exception raises a DeprecationWarning. References to string exceptions has been removed from the docs since they are now just an error. ........ r53618 | raymond.hettinger | 2007-02-01 22:02:59 +0100 (Thu, 01 Feb 2007) | 1 line Bug #1648179: set.update() not recognizing __iter__ overrides in dict subclasses. ........ Modified: python/branches/p3yk/Doc/howto/TODO ============================================================================== --- python/branches/p3yk/Doc/howto/TODO (original) +++ python/branches/p3yk/Doc/howto/TODO Mon Feb 5 02:24:16 2007 @@ -1,7 +1,7 @@ Short-term tasks: - Quick revision pass to make HOWTOs match the current state of Python: -curses doanddont regex sockets sorting + Quick revision pass to make HOWTOs match the current state of Python +doanddont regex sockets Medium-term tasks: Revisit the regex howto. Modified: python/branches/p3yk/Doc/howto/curses.tex ============================================================================== --- python/branches/p3yk/Doc/howto/curses.tex (original) +++ python/branches/p3yk/Doc/howto/curses.tex Mon Feb 5 02:24:16 2007 @@ -2,7 +2,7 @@ \title{Curses Programming with Python} -\release{2.01} +\release{2.02} \author{A.M. Kuchling, Eric S. Raymond} \authoraddress{\email{amk at amk.ca}, \email{esr at thyrsus.com}} @@ -147,10 +147,10 @@ In Python you can avoid these complications and make debugging much easier by importing the module \module{curses.wrapper}. It supplies a -function \function{wrapper} that takes a hook argument. It does the +\function{wrapper()} function that takes a callable. It does the initializations described above, and also initializes colors if color -support is present. It then runs your hook, and then finally -deinitializes appropriately. The hook is called inside a try-catch +support is present. It then runs your provided callable and finally +deinitializes appropriately. The callable is called inside a try-catch clause which catches exceptions, performs curses deinitialization, and then passes the exception upwards. Thus, your terminal won't be left in a funny state on exception. @@ -159,7 +159,7 @@ Windows are the basic abstraction in curses. A window object represents a rectangular area of the screen, and supports various - methods to display text, erase it, allow the user to input strings, +methods to display text, erase it, allow the user to input strings, and so forth. The \code{stdscr} object returned by the \function{initscr()} function @@ -223,14 +223,14 @@ The \function{refresh()} call displays a section of the pad in the rectangle extending from coordinate (5,5) to coordinate (20,75) on the -screen;the upper left corner of the displayed section is coordinate +screen; the upper left corner of the displayed section is coordinate (0,0) on the pad. Beyond that difference, pads are exactly like ordinary windows and support the same methods. If you have multiple windows and pads on screen there is a more efficient way to go, which will prevent annoying screen flicker at -refresh time. Use the methods \method{noutrefresh()} and/or -\method{noutrefresh()} of each window to update the data structure +refresh time. Use the \method{noutrefresh()} method +of each window to update the data structure representing the desired state of the screen; then change the physical screen to match the desired state in one go with the function \function{doupdate()}. The normal \method{refresh()} method calls @@ -254,9 +254,9 @@ \begin{tableii}{|c|l|}{textrm}{Form}{Description} \lineii{\var{str} or \var{ch}}{Display the string \var{str} or -character \var{ch}} +character \var{ch} at the current position} \lineii{\var{str} or \var{ch}, \var{attr}}{Display the string \var{str} or -character \var{ch}, using attribute \var{attr}} +character \var{ch}, using attribute \var{attr} at the current position} \lineii{\var{y}, \var{x}, \var{str} or \var{ch}} {Move to position \var{y,x} within the window, and display \var{str} or \var{ch}} @@ -271,7 +271,7 @@ The \function{addstr()} function takes a Python string as the value to be displayed, while the \function{addch()} functions take a character, -which can be either a Python string of length 1, or an integer. If +which can be either a Python string of length 1 or an integer. If it's a string, you're limited to displaying characters between 0 and 255. SVr4 curses provides constants for extension characters; these constants are integers greater than 255. For example, @@ -331,15 +331,15 @@ provide it, The most common such terminal is probably the Linux console, followed by color xterms. -To use color, you must call the \function{start_color()} function -soon after calling \function{initscr()}, to initialize the default -color set (the \function{curses.wrapper.wrapper()} function does this +To use color, you must call the \function{start_color()} function soon +after calling \function{initscr()}, to initialize the default color +set (the \function{curses.wrapper.wrapper()} function does this automatically). Once that's done, the \function{has_colors()} function returns TRUE if the terminal in use can actually display -color. (Note from AMK: curses uses the American spelling -'color', instead of the Canadian/British spelling 'colour'. If you're -like me, you'll have to resign yourself to misspelling it for the sake -of these functions.) +color. (Note: curses uses the American spelling 'color', instead of +the Canadian/British spelling 'colour'. If you're used to the British +spelling, you'll have to resign yourself to misspelling it for the +sake of these functions.) The curses library maintains a finite number of color pairs, containing a foreground (or text) color and a background color. You @@ -400,18 +400,19 @@ lack. The most common way to get input to a window is to use its -\method{getch()} method. that pauses, and waits for the user to hit -a key, displaying it if \function{echo()} has been called earlier. -You can optionally specify a coordinate to which the cursor should be -moved before pausing. +\method{getch()} method. \method{getch()} pauses and waits for the +user to hit a key, displaying it if \function{echo()} has been called +earlier. You can optionally specify a coordinate to which the cursor +should be moved before pausing. It's possible to change this behavior with the method \method{nodelay()}. After \method{nodelay(1)}, \method{getch()} for -the window becomes non-blocking and returns ERR (-1) when no input is -ready. There's also a \function{halfdelay()} function, which can be -used to (in effect) set a timer on each \method{getch()}; if no input -becomes available within the number of milliseconds specified as the -argument to \function{halfdelay()}, curses throws an exception. +the window becomes non-blocking and returns \code{curses.ERR} (a value +of -1) when no input is ready. There's also a \function{halfdelay()} +function, which can be used to (in effect) set a timer on each +\method{getch()}; if no input becomes available within the number of +milliseconds specified as the argument to \function{halfdelay()}, +curses raises an exception. The \method{getch()} method returns an integer; if it's between 0 and 255, it represents the ASCII code of the key pressed. Values greater Modified: python/branches/p3yk/Doc/howto/doanddont.tex ============================================================================== --- python/branches/p3yk/Doc/howto/doanddont.tex (original) +++ python/branches/p3yk/Doc/howto/doanddont.tex Mon Feb 5 02:24:16 2007 @@ -32,7 +32,7 @@ \subsubsection{Inside Function Definitions} \code{from module import *} is {\em invalid} inside function definitions. -While many versions of Python do no check for the invalidity, it does not +While many versions of Python do not check for the invalidity, it does not make it more valid, no more then having a smart lawyer makes a man innocent. Do not use it like that ever. Even in versions where it was accepted, it made the function execution slower, because the compiler could not be certain Modified: python/branches/p3yk/Doc/howto/regex.tex ============================================================================== --- python/branches/p3yk/Doc/howto/regex.tex (original) +++ python/branches/p3yk/Doc/howto/regex.tex Mon Feb 5 02:24:16 2007 @@ -34,17 +34,18 @@ The \module{re} module was added in Python 1.5, and provides Perl-style regular expression patterns. Earlier versions of Python came with the \module{regex} module, which provided Emacs-style -patterns. \module{regex} module was removed in Python 2.5. +patterns. The \module{regex} module was removed completely in Python 2.5. -Regular expressions (or REs) are essentially a tiny, highly -specialized programming language embedded inside Python and made -available through the \module{re} module. Using this little language, -you specify the rules for the set of possible strings that you want to -match; this set might contain English sentences, or e-mail addresses, -or TeX commands, or anything you like. You can then ask questions -such as ``Does this string match the pattern?'', or ``Is there a match -for the pattern anywhere in this string?''. You can also use REs to -modify a string or to split it apart in various ways. +Regular expressions (called REs, or regexes, or regex patterns) are +essentially a tiny, highly specialized programming language embedded +inside Python and made available through the \module{re} module. +Using this little language, you specify the rules for the set of +possible strings that you want to match; this set might contain +English sentences, or e-mail addresses, or TeX commands, or anything +you like. You can then ask questions such as ``Does this string match +the pattern?'', or ``Is there a match for the pattern anywhere in this +string?''. You can also use REs to modify a string or to split it +apart in various ways. Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For @@ -80,11 +81,12 @@ would let this RE match \samp{Test} or \samp{TEST} as well; more about this later.) -There are exceptions to this rule; some characters are -special, and don't match themselves. Instead, they signal that some -out-of-the-ordinary thing should be matched, or they affect other -portions of the RE by repeating them. Much of this document is -devoted to discussing various metacharacters and what they do. +There are exceptions to this rule; some characters are special +\dfn{metacharacters}, and don't match themselves. Instead, they +signal that some out-of-the-ordinary thing should be matched, or they +affect other portions of the RE by repeating them or changing their +meaning. Much of this document is devoted to discussing various +metacharacters and what they do. Here's a complete list of the metacharacters; their meanings will be discussed in the rest of this HOWTO. @@ -111,9 +113,10 @@ usually a metacharacter, but inside a character class it's stripped of its special nature. -You can match the characters not within a range by \dfn{complementing} -the set. This is indicated by including a \character{\^} as the first -character of the class; \character{\^} elsewhere will simply match the +You can match the characters not listed within the class by +\dfn{complementing} the set. This is indicated by including a +\character{\^} as the first character of the class; \character{\^} +outside a character class will simply match the \character{\^} character. For example, \verb|[^5]| will match any character except \character{5}. @@ -176,7 +179,7 @@ For example, \regexp{ca*t} will match \samp{ct} (0 \samp{a} characters), \samp{cat} (1 \samp{a}), \samp{caaat} (3 \samp{a} characters), and so forth. The RE engine has various internal -limitations stemming from the size of C's \code{int} type, that will +limitations stemming from the size of C's \code{int} type that will prevent it from matching over 2 billion \samp{a} characters; you probably don't have enough memory to construct a string that large, so you shouldn't run into that limit. @@ -238,9 +241,9 @@ You can omit either \var{m} or \var{n}; in that case, a reasonable value is assumed for the missing value. Omitting \var{m} is -interpreted as a lower limit of 0, while omitting \var{n} results in an -upper bound of infinity --- actually, the 2 billion limit mentioned -earlier, but that might as well be infinity. +interpreted as a lower limit of 0, while omitting \var{n} results in +an upper bound of infinity --- actually, the upper bound is the +2-billion limit mentioned earlier, but that might as well be infinity. Readers of a reductionist bent may notice that the three other qualifiers can all be expressed using this notation. \regexp{\{0,\}} is the same @@ -285,7 +288,7 @@ no need to bloat the language specification by including them.) Instead, the \module{re} module is simply a C extension module included with Python, just like the \module{socket} or \module{zlib} -module. +modules. Putting REs in strings keeps the Python language simpler, but has one disadvantage which is the topic of the next section. @@ -326,7 +329,7 @@ a string literal prefixed with \character{r}, so \code{r"\e n"} is a two-character string containing \character{\e} and \character{n}, while \code{"\e n"} is a one-character string containing a newline. -Frequently regular expressions will be expressed in Python +Regular expressions will often be written in Python code using this raw string notation. \begin{tableii}{c|c}{code}{Regular String}{Raw string} @@ -368,9 +371,9 @@ \file{redemo.py} can be quite useful when trying to debug a complicated RE. Phil Schwartz's \ulink{Kodos}{http://www.phil-schwartz.com/kodos.spy} is also an interactive -tool for developing and testing RE patterns. This HOWTO will use the -standard Python interpreter for its examples. +tool for developing and testing RE patterns. +This HOWTO uses the standard Python interpreter for its examples. First, run the Python interpreter, import the \module{re} module, and compile a RE: @@ -401,7 +404,7 @@ later use. \begin{verbatim} ->>> m = p.match( 'tempo') +>>> m = p.match('tempo') >>> print m <_sre.SRE_Match object at 80c4f68> \end{verbatim} @@ -472,9 +475,9 @@ \end{verbatim} \method{findall()} has to create the entire list before it can be -returned as the result. In Python 2.2, the \method{finditer()} method -is also available, returning a sequence of \class{MatchObject} instances -as an iterator. +returned as the result. The \method{finditer()} method returns a +sequence of \class{MatchObject} instances as an +iterator.\footnote{Introduced in Python 2.2.2.} \begin{verbatim} >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...') @@ -491,13 +494,13 @@ \subsection{Module-Level Functions} -You don't have to produce a \class{RegexObject} and call its methods; +You don't have to create a \class{RegexObject} and call its methods; the \module{re} module also provides top-level functions called -\function{match()}, \function{search()}, \function{sub()}, and so -forth. These functions take the same arguments as the corresponding -\class{RegexObject} method, with the RE string added as the first -argument, and still return either \code{None} or a \class{MatchObject} -instance. +\function{match()}, \function{search()}, \function{findall()}, +\function{sub()}, and so forth. These functions take the same +arguments as the corresponding \class{RegexObject} method, with the RE +string added as the first argument, and still return either +\code{None} or a \class{MatchObject} instance. \begin{verbatim} >>> print re.match(r'From\s+', 'Fromage amk') @@ -514,7 +517,7 @@ Should you use these module-level functions, or should you get the \class{RegexObject} and call its methods yourself? That choice depends on how frequently the RE will be used, and on your personal -coding style. If a RE is being used at only one point in the code, +coding style. If the RE is being used at only one point in the code, then the module functions are probably more convenient. If a program contains a lot of regular expressions, or re-uses the same ones in several locations, then it might be worthwhile to collect all the @@ -537,7 +540,7 @@ Compilation flags let you modify some aspects of how regular expressions work. Flags are available in the \module{re} module under -two names, a long name such as \constant{IGNORECASE}, and a short, +two names, a long name such as \constant{IGNORECASE} and a short, one-letter form such as \constant{I}. (If you're familiar with Perl's pattern modifiers, the one-letter forms use the same letters; the short form of \constant{re.VERBOSE} is \constant{re.X}, for example.) @@ -617,7 +620,7 @@ format them. When this flag has been specified, whitespace within the RE string is ignored, except when the whitespace is in a character class or preceded by an unescaped backslash; this lets you organize -and indent the RE more clearly. It also enables you to put comments +and indent the RE more clearly. This flag also lets you put comments within a RE that will be ignored by the engine; comments are marked by a \character{\#} that's neither in a character class or preceded by an unescaped backslash. @@ -629,18 +632,19 @@ charref = re.compile(r""" &[#] # Start of a numeric entity reference ( - [0-9]+[^0-9] # Decimal form - | 0[0-7]+[^0-7] # Octal form - | x[0-9a-fA-F]+[^0-9a-fA-F] # Hexadecimal form + 0[0-7]+ # Octal form + | [0-9]+ # Decimal form + | x[0-9a-fA-F]+ # Hexadecimal form ) + ; # Trailing semicolon """, re.VERBOSE) \end{verbatim} Without the verbose setting, the RE would look like this: \begin{verbatim} -charref = re.compile("&#([0-9]+[^0-9]" - "|0[0-7]+[^0-7]" - "|x[0-9a-fA-F]+[^0-9a-fA-F])") +charref = re.compile("&#(0[0-7]+" + "|[0-9]+" + "|x[0-9a-fA-F]+);") \end{verbatim} In the above example, Python's automatic concatenation of string @@ -722,12 +726,12 @@ \item[\regexp{\e A}] Matches only at the start of the string. When not in \constant{MULTILINE} mode, \regexp{\e A} and \regexp{\^} are -effectively the same. In \constant{MULTILINE} mode, however, they're -different; \regexp{\e A} still matches only at the beginning of the +effectively the same. In \constant{MULTILINE} mode, they're +different: \regexp{\e A} still matches only at the beginning of the string, but \regexp{\^} may match at any location inside the string that follows a newline character. -\item[\regexp{\e Z}]Matches only at the end of the string. +\item[\regexp{\e Z}] Matches only at the end of the string. \item[\regexp{\e b}] Word boundary. This is a zero-width assertion that matches only at the @@ -782,14 +786,23 @@ strings by writing a RE divided into several subgroups which match different components of interest. For example, an RFC-822 header line is divided into a header name and a value, separated by a -\character{:}. This can be handled by writing a regular expression +\character{:}, like this: + +\begin{verbatim} +From: author at example.com +User-Agent: Thunderbird 1.5.0.9 (X11/20061227) +MIME-Version: 1.0 +To: editor at example.com +\end{verbatim} + +This can be handled by writing a regular expression which matches an entire header line, and has one group which matches the header name, and another group which matches the header's value. Groups are marked by the \character{(}, \character{)} metacharacters. \character{(} and \character{)} have much the same meaning as they do in mathematical expressions; they group together the expressions -contained inside them. For example, you can repeat the contents of a +contained inside them, and you can repeat the contents of a group with a repeating qualifier, such as \regexp{*}, \regexp{+}, \regexp{?}, or \regexp{\{\var{m},\var{n}\}}. For example, \regexp{(ab)*} will match zero or more repetitions of \samp{ab}. @@ -881,12 +894,13 @@ syntax for regular expression extensions, so we'll look at that first. Perl 5 added several additional features to standard regular -expressions, and the Python \module{re} module supports most of them. -It would have been difficult to choose new single-keystroke -metacharacters or new special sequences beginning with \samp{\e} to -represent the new features without making Perl's regular expressions -confusingly different from standard REs. If you chose \samp{\&} as a -new metacharacter, for example, old expressions would be assuming that +expressions, and the Python \module{re} module supports most of them. +It would have been difficult to choose new +single-keystroke metacharacters or new special sequences beginning +with \samp{\e} to represent the new features without making Perl's +regular expressions confusingly different from standard REs. If you +chose \samp{\&} as a new metacharacter, for example, old expressions +would be assuming that \samp{\&} was a regular character and wouldn't have escaped it by writing \regexp{\e \&} or \regexp{[\&]}. @@ -913,15 +927,15 @@ to the features that simplify working with groups in complex REs. Since groups are numbered from left to right and a complex expression may use many groups, it can become difficult to keep track of the -correct numbering, and modifying such a complex RE is annoying. -Insert a new group near the beginning, and you change the numbers of +correct numbering. Modifying such a complex RE is annoying, too: +insert a new group near the beginning and you change the numbers of everything that follows it. -First, sometimes you'll want to use a group to collect a part of a -regular expression, but aren't interested in retrieving the group's -contents. You can make this fact explicit by using a non-capturing -group: \regexp{(?:...)}, where you can put any other regular -expression inside the parentheses. +Sometimes you'll want to use a group to collect a part of a regular +expression, but aren't interested in retrieving the group's contents. +You can make this fact explicit by using a non-capturing group: +\regexp{(?:...)}, where you can replace the \regexp{...} +with any other regular expression. \begin{verbatim} >>> m = re.match("([abc])+", "abc") @@ -937,23 +951,23 @@ capturing group; you can put anything inside it, repeat it with a repetition metacharacter such as \samp{*}, and nest it within other groups (capturing or non-capturing). \regexp{(?:...)} is particularly -useful when modifying an existing group, since you can add new groups +useful when modifying an existing pattern, since you can add new groups without changing how all the other groups are numbered. It should be mentioned that there's no performance difference in searching between capturing and non-capturing groups; neither form is any faster than the other. -The second, and more significant, feature is named groups; instead of +A more significant feature is named groups: instead of referring to them by numbers, groups can be referenced by a name. The syntax for a named group is one of the Python-specific extensions: \regexp{(?P<\var{name}>...)}. \var{name} is, obviously, the name of -the group. Except for associating a name with a group, named groups -also behave identically to capturing groups. The \class{MatchObject} -methods that deal with capturing groups all accept either integers, to -refer to groups by number, or a string containing the group name. -Named groups are still given numbers, so you can retrieve information -about a group in two ways: +the group. Named groups also behave exactly like capturing groups, +and additionally associate a name with a group. The +\class{MatchObject} methods that deal with capturing groups all accept +either integers that refer to the group by number or strings that +contain the desired group's name. Named groups are still given +numbers, so you can retrieve information about a group in two ways: \begin{verbatim} >>> p = re.compile(r'(?P\b\w+\b)') @@ -980,11 +994,11 @@ It's obviously much easier to retrieve \code{m.group('zonem')}, instead of having to remember to retrieve group 9. -Since the syntax for backreferences, in an expression like -\regexp{(...)\e 1}, refers to the number of the group there's +The syntax for backreferences in an expression such as +\regexp{(...)\e 1} refers to the number of the group. There's naturally a variant that uses the group name instead of the number. -This is also a Python extension: \regexp{(?P=\var{name})} indicates -that the contents of the group called \var{name} should again be found +This is another Python extension: \regexp{(?P=\var{name})} indicates +that the contents of the group called \var{name} should again be matched at the current point. The regular expression for finding doubled words, \regexp{(\e b\e w+)\e s+\e 1} can also be written as \regexp{(?P\e b\e w+)\e s+(?P=word)}: @@ -1014,11 +1028,11 @@ \emph{doesn't} match at the current position in the string. \end{itemize} -An example will help make this concrete by demonstrating a case -where a lookahead is useful. Consider a simple pattern to match a -filename and split it apart into a base name and an extension, -separated by a \samp{.}. For example, in \samp{news.rc}, \samp{news} -is the base name, and \samp{rc} is the filename's extension. +To make this concrete, let's look at a case where a lookahead is +useful. Consider a simple pattern to match a filename and split it +apart into a base name and an extension, separated by a \samp{.}. For +example, in \samp{news.rc}, \samp{news} is the base name, and +\samp{rc} is the filename's extension. The pattern to match this is quite simple: @@ -1065,12 +1079,12 @@ exclude both \samp{bat} and \samp{exe} as extensions, the pattern would get even more complicated and confusing. -A negative lookahead cuts through all this: +A negative lookahead cuts through all this confusion: \regexp{.*[.](?!bat\$).*\$} % $ -The lookahead means: if the expression \regexp{bat} doesn't match at +The negative lookahead means: if the expression \regexp{bat} doesn't match at this point, try the rest of the pattern; if \regexp{bat\$} does match, the whole pattern will fail. The trailing \regexp{\$} is required to ensure that something like \samp{sample.batch}, where the extension @@ -1087,7 +1101,7 @@ \section{Modifying Strings} Up to this point, we've simply performed searches against a static -string. Regular expressions are also commonly used to modify a string +string. Regular expressions are also commonly used to modify strings in various ways, using the following \class{RegexObject} methods: \begin{tableii}{c|l}{code}{Method/Attribute}{Purpose} Modified: python/branches/p3yk/Doc/lib/libexcs.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libexcs.tex (original) +++ python/branches/p3yk/Doc/lib/libexcs.tex Mon Feb 5 02:24:16 2007 @@ -10,22 +10,6 @@ provided in the built-in namespace as well as the \module{exceptions} module. -\begin{notice} -In past versions of Python string exceptions were supported. In -Python 1.5 and newer versions, all standard exceptions have been -converted to class objects and users are encouraged to do the same. -String exceptions will raise a \code{DeprecationWarning} in Python 2.5 and -newer. -In future versions, support for string exceptions will be removed. - -Two distinct string objects with the same value are considered different -exceptions. This is done to force programmers to use exception names -rather than their string value when specifying exception handlers. -The string value of all built-in exceptions is their name, but this is -not a requirement for user-defined exceptions or exceptions defined by -library modules. -\end{notice} - For class exceptions, in a \keyword{try}\stindex{try} statement with an \keyword{except}\stindex{except} clause that mentions a particular class, that clause also handles any exception classes derived from Modified: python/branches/p3yk/Doc/lib/libimageop.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libimageop.tex (original) +++ python/branches/p3yk/Doc/lib/libimageop.tex Mon Feb 5 02:24:16 2007 @@ -19,7 +19,7 @@ \begin{funcdesc}{crop}{image, psize, width, height, x0, y0, x1, y1} -Return the selected part of \var{image}, which should by +Return the selected part of \var{image}, which should be \var{width} by \var{height} in size and consist of pixels of \var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like the \function{gl.lrectread()} parameters, i.e.\ the boundary is Modified: python/branches/p3yk/Doc/lib/libmailbox.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libmailbox.tex (original) +++ python/branches/p3yk/Doc/lib/libmailbox.tex Mon Feb 5 02:24:16 2007 @@ -58,14 +58,18 @@ \exception{KeyError} exception if the corresponding message is subsequently removed. -Be very cautious when modifying mailboxes that might also be changed -by some other process. The safest mailbox format to use for such -tasks is Maildir; try to avoid using single-file formats such as mbox -for concurrent writing. If you're modifying a mailbox, no matter what -the format, you must lock it by calling the \method{lock()} and -\method{unlock()} methods before making any changes. Failing to lock -the mailbox runs the risk of losing data if some other process makes -changes to the mailbox while your Python code is running. +\begin{notice}[warning] +Be very cautious when modifying mailboxes that might be +simultaneously changed by some other process. The safest mailbox +format to use for such tasks is Maildir; try to avoid using +single-file formats such as mbox for concurrent writing. If you're +modifying a mailbox, you +\emph{must} lock it by calling the \method{lock()} and +\method{unlock()} methods \emph{before} reading any messages in the file +or making any changes by adding or deleting a message. Failing to +lock the mailbox runs the risk of losing messages or corrupting the entire +mailbox. +\end{notice} \class{Mailbox} instances have the following methods: Modified: python/branches/p3yk/Doc/ref/ref4.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref4.tex (original) +++ python/branches/p3yk/Doc/ref/ref4.tex Mon Feb 5 02:24:16 2007 @@ -197,10 +197,6 @@ value can be raised along with the identifying string which can be passed to the handler. -\deprecated{2.5}{String exceptions should not be used in new code. -They will not be supported in a future version of Python. Old code -should be rewritten to use class exceptions instead.} - \begin{notice}[warning] Messages to exceptions are not part of the Python API. Their contents may change from one version of Python to the next without warning and should not Modified: python/branches/p3yk/Doc/tut/tut.tex ============================================================================== --- python/branches/p3yk/Doc/tut/tut.tex (original) +++ python/branches/p3yk/Doc/tut/tut.tex Mon Feb 5 02:24:16 2007 @@ -1991,7 +1991,7 @@ There is a way to remove an item from a list given its index instead of its value: the \keyword{del} statement. This differs from the -\method{pop()}) method which returns a value. The \keyword{del} +\method{pop()} method which returns a value. The \keyword{del} statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example: Modified: python/branches/p3yk/Doc/whatsnew/whatsnew26.tex ============================================================================== --- python/branches/p3yk/Doc/whatsnew/whatsnew26.tex (original) +++ python/branches/p3yk/Doc/whatsnew/whatsnew26.tex Mon Feb 5 02:24:16 2007 @@ -72,6 +72,12 @@ This class supports an interface identical to the existing \class{SMTP} class. (Contributed by Monty Taylor.) +\item The \module{test.test_support} module now contains a +\function{EnvironmentVarGuard} context manager that +supports temporarily changing environment variables and +automatically restores them to their old values. +(Contributed by Brett Cannon.) + \end{itemize} Modified: python/branches/p3yk/Lib/CGIHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/CGIHTTPServer.py (original) +++ python/branches/p3yk/Lib/CGIHTTPServer.py Mon Feb 5 02:24:16 2007 @@ -107,7 +107,7 @@ """Execute a CGI script.""" path = self.path dir, rest = self.cgi_info - + i = path.find('/', len(dir) + 1) while i >= 0: nextdir = path[:i] Modified: python/branches/p3yk/Lib/_strptime.py ============================================================================== --- python/branches/p3yk/Lib/_strptime.py (original) +++ python/branches/p3yk/Lib/_strptime.py Mon Feb 5 02:24:16 2007 @@ -22,9 +22,6 @@ except: from dummy_thread import allocate_lock as _thread_allocate_lock -__author__ = "Brett Cannon" -__email__ = "brett at python.org" - __all__ = ['strptime'] def _getlang(): @@ -273,11 +270,31 @@ _CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache _regex_cache = {} +def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon): + """Calculate the Julian day based on the year, week of the year, and day of + the week, with week_start_day representing whether the week of the year + assumes the week starts on Sunday or Monday (6 or 0).""" + first_weekday = datetime_date(year, 1, 1).weekday() + # If we are dealing with the %U directive (week starts on Sunday), it's + # easier to just shift the view to Sunday being the first day of the + # week. + if not week_starts_Mon: + first_weekday = (first_weekday + 1) % 7 + day_of_week = (day_of_week + 1) % 7 + # Need to watch out for a week 0 (when the first day of the year is not + # the same as that specified by %U or %W). + week_0_length = (7 - first_weekday) % 7 + if week_of_year == 0: + return 1 + day_of_week - first_weekday + else: + days_to_week = week_0_length + (7 * (week_of_year - 1)) + return 1 + days_to_week + day_of_week + + def strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a time struct based on the input string and the format string.""" global _TimeRE_cache, _regex_cache - _cache_lock.acquire() - try: + with _cache_lock: time_re = _TimeRE_cache locale_time = time_re.locale_time if _getlang() != locale_time.lang: @@ -302,8 +319,6 @@ except IndexError: raise ValueError("stray %% in format '%s'" % format) _regex_cache[format] = format_regex - finally: - _cache_lock.release() found = format_regex.match(data_string) if not found: raise ValueError("time data %r does not match format %r" % @@ -385,10 +400,10 @@ elif group_key in ('U', 'W'): week_of_year = int(found_dict[group_key]) if group_key == 'U': - # U starts week on Sunday + # U starts week on Sunday. week_of_year_start = 6 else: - # W starts week on Monday + # W starts week on Monday. week_of_year_start = 0 elif group_key == 'Z': # Since -1 is default value only need to worry about setting tz if @@ -406,42 +421,20 @@ tz = value break # If we know the week of the year and what day of that week, we can figure - # out the Julian day of the year - # Calculations below assume 0 is a Monday + # out the Julian day of the year. if julian == -1 and week_of_year != -1 and weekday != -1: - # Calculate how many days in week 0 - first_weekday = datetime_date(year, 1, 1).weekday() - preceeding_days = 7 - first_weekday - if preceeding_days == 7: - preceeding_days = 0 - # Adjust for U directive so that calculations are not dependent on - # directive used to figure out week of year - if weekday == 6 and week_of_year_start == 6: - week_of_year -= 1 - # If a year starts and ends on a Monday but a week is specified to - # start on a Sunday we need to up the week to counter-balance the fact - # that with %W that first Monday starts week 1 while with %U that is - # week 0 and thus shifts everything by a week - if weekday == 0 and first_weekday == 0 and week_of_year_start == 6: - week_of_year += 1 - # If in week 0, then just figure out how many days from Jan 1 to day of - # week specified, else calculate by multiplying week of year by 7, - # adding in days in week 0, and the number of days from Monday to the - # day of the week - if week_of_year == 0: - julian = 1 + weekday - first_weekday - else: - days_to_week = preceeding_days + (7 * (week_of_year - 1)) - julian = 1 + days_to_week + weekday + week_starts_Mon = True if week_of_year_start == 0 else False + julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, + week_starts_Mon) # Cannot pre-calculate datetime_date() since can change in Julian - #calculation and thus could have different value for the day of the week - #calculation + # calculation and thus could have different value for the day of the week + # calculation. if julian == -1: # Need to add 1 to result since first day of the year is 1, not 0. julian = datetime_date(year, month, day).toordinal() - \ datetime_date(year, 1, 1).toordinal() + 1 else: # Assume that if they bothered to include Julian day it will - #be accurate + # be accurate. datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal()) year = datetime_result.year month = datetime_result.month Modified: python/branches/p3yk/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk/Lib/compiler/pycodegen.py Mon Feb 5 02:24:16 2007 @@ -914,6 +914,8 @@ self.emit('LOAD_CONST', None) self.nextBlock(final) self.setups.push((END_FINALLY, final)) + self._implicitNameOp('LOAD', exitvar) + self._implicitNameOp('DELETE', exitvar) self.emit('WITH_CLEANUP') self.emit('END_FINALLY') self.setups.pop() Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Mon Feb 5 02:24:16 2007 @@ -1018,7 +1018,7 @@ if nodelist[2][0] == token.COLON: var = None else: - var = self.com_node(nodelist[2]) + var = self.com_assign(nodelist[2][2], OP_ASSIGN) return With(expr, var, body, lineno=nodelist[0][2]) def com_with_var(self, nodelist): Modified: python/branches/p3yk/Lib/cookielib.py ============================================================================== --- python/branches/p3yk/Lib/cookielib.py (original) +++ python/branches/p3yk/Lib/cookielib.py Mon Feb 5 02:24:16 2007 @@ -1318,26 +1318,26 @@ self._cookies_lock.acquire() try: - self._policy._now = self._now = int(time.time()) + self._policy._now = self._now = int(time.time()) + + cookies = self._cookies_for_request(request) - cookies = self._cookies_for_request(request) + 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 - 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._cookies_lock.release() self.clear_expired_cookies() @@ -1609,7 +1609,7 @@ if self._policy.set_ok(cookie, request): self.set_cookie(cookie) - + finally: self._cookies_lock.release() @@ -1632,14 +1632,14 @@ _debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() try: - self._policy._now = self._now = int(time.time()) + 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) + 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() + self._cookies_lock.release() def clear(self, domain=None, path=None, name=None): """Clear some cookies. @@ -1677,11 +1677,11 @@ """ self._cookies_lock.acquire() try: - for cookie in self: - if cookie.discard: - self.clear(cookie.domain, cookie.path, cookie.name) + for cookie in self: + if cookie.discard: + self.clear(cookie.domain, cookie.path, cookie.name) finally: - self._cookies_lock.release() + self._cookies_lock.release() def clear_expired_cookies(self): """Discard all expired cookies. @@ -1695,12 +1695,12 @@ """ self._cookies_lock.acquire() try: - now = time.time() - for cookie in self: - if cookie.is_expired(now): - self.clear(cookie.domain, cookie.path, cookie.name) + 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() + self._cookies_lock.release() def __iter__(self): return deepvalues(self._cookies) @@ -1774,16 +1774,16 @@ self._cookies_lock.acquire() try: - old_state = copy.deepcopy(self._cookies) - self._cookies = {} - try: - self.load(filename, ignore_discard, ignore_expires) - except (LoadError, IOError): - self._cookies = old_state - raise + 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() + self._cookies_lock.release() from _LWPCookieJar import LWPCookieJar, lwp_cookie_str from _MozillaCookieJar import MozillaCookieJar Modified: python/branches/p3yk/Lib/dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/dumbdbm.py (original) +++ python/branches/p3yk/Lib/dumbdbm.py Mon Feb 5 02:24:16 2007 @@ -243,5 +243,5 @@ else: # Turn off any bits that are set in the umask mode = mode & (~um) - + return _Database(file, mode) Modified: python/branches/p3yk/Lib/dummy_thread.py ============================================================================== --- python/branches/p3yk/Lib/dummy_thread.py (original) +++ python/branches/p3yk/Lib/dummy_thread.py Mon Feb 5 02:24:16 2007 @@ -11,11 +11,8 @@ import dummy_thread as thread """ -__author__ = "Brett Cannon" -__email__ = "brett at python.org" - -# Exports only things specified by thread documentation -# (skipping obsolete synonyms allocate(), start_new(), exit_thread()) +# Exports only things specified by thread documentation; +# skipping obsolete synonyms allocate(), start_new(), exit_thread(). __all__ = ['error', 'start_new_thread', 'exit', 'get_ident', 'allocate_lock', 'interrupt_main', 'LockType'] Modified: python/branches/p3yk/Lib/dummy_threading.py ============================================================================== --- python/branches/p3yk/Lib/dummy_threading.py (original) +++ python/branches/p3yk/Lib/dummy_threading.py Mon Feb 5 02:24:16 2007 @@ -5,11 +5,6 @@ directly imported it would have made all subsequent imports succeed regardless of whether ``thread`` was available which is not desired. -:Author: Brett Cannon -:Contact: brett at python.org - -XXX: Try to get rid of ``_dummy_threading``. - """ from sys import modules as sys_modules Modified: python/branches/p3yk/Lib/email/charset.py ============================================================================== --- python/branches/p3yk/Lib/email/charset.py (original) +++ python/branches/p3yk/Lib/email/charset.py Mon Feb 5 02:24:16 2007 @@ -46,6 +46,7 @@ 'iso-8859-13': (QP, QP, None), 'iso-8859-14': (QP, QP, None), 'iso-8859-15': (QP, QP, None), + 'iso-8859-16': (QP, QP, None), 'windows-1252':(QP, QP, None), 'viscii': (QP, QP, None), 'us-ascii': (None, None, None), @@ -81,6 +82,8 @@ 'latin-8': 'iso-8859-14', 'latin_9': 'iso-8859-15', 'latin-9': 'iso-8859-15', + 'latin_10':'iso-8859-16', + 'latin-10':'iso-8859-16', 'cp949': 'ks_c_5601-1987', 'euc_jp': 'euc-jp', 'euc_kr': 'euc-kr', Modified: python/branches/p3yk/Lib/encodings/aliases.py ============================================================================== --- python/branches/p3yk/Lib/encodings/aliases.py (original) +++ python/branches/p3yk/Lib/encodings/aliases.py Mon Feb 5 02:24:16 2007 @@ -301,6 +301,8 @@ # iso8859_13 codec 'iso_8859_13' : 'iso8859_13', + 'l7' : 'iso8859_13', + 'latin7' : 'iso8859_13', # iso8859_14 codec 'iso_8859_14' : 'iso8859_14', @@ -312,6 +314,8 @@ # iso8859_15 codec 'iso_8859_15' : 'iso8859_15', + 'l9' : 'iso8859_15', + 'latin9' : 'iso8859_15', # iso8859_16 codec 'iso_8859_16' : 'iso8859_16', Modified: python/branches/p3yk/Lib/ftplib.py ============================================================================== --- python/branches/p3yk/Lib/ftplib.py (original) +++ python/branches/p3yk/Lib/ftplib.py Mon Feb 5 02:24:16 2007 @@ -333,7 +333,7 @@ # 1xx or error messages for LIST), so we just discard # this response. if resp[0] == '2': - resp = self.getresp() + resp = self.getresp() if resp[0] != '1': raise error_reply, resp else: @@ -343,7 +343,7 @@ resp = self.sendcmd(cmd) # See above. if resp[0] == '2': - resp = self.getresp() + resp = self.getresp() if resp[0] != '1': raise error_reply, resp conn, sockaddr = sock.accept() Modified: python/branches/p3yk/Lib/httplib.py ============================================================================== --- python/branches/p3yk/Lib/httplib.py (original) +++ python/branches/p3yk/Lib/httplib.py Mon Feb 5 02:24:16 2007 @@ -899,7 +899,7 @@ except (AttributeError, OSError): # Don't send a length if this failed if self.debuglevel > 0: print "Cannot stat!!" - + if thelen is not None: self.putheader('Content-Length',thelen) for hdr, value in headers.iteritems(): Modified: python/branches/p3yk/Lib/idlelib/CodeContext.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/CodeContext.py (original) +++ python/branches/p3yk/Lib/idlelib/CodeContext.py Mon Feb 5 02:24:16 2007 @@ -71,7 +71,7 @@ # # To avoid possible errors, all references to the inner workings # of Tk are executed inside try/except blocks. - + widgets_for_width_calc = self.editwin.text, self.editwin.text_frame # calculate the required vertical padding @@ -113,7 +113,7 @@ # above it. self.label.pack(side="top", fill="x", expand=False, before=self.editwin.text_frame) - + else: self.label.destroy() self.label = None Modified: python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py (original) +++ python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py Mon Feb 5 02:24:16 2007 @@ -50,9 +50,9 @@ # If the master is not viewable, don't # make the child transient, or else it # would be opened withdrawn - if parent.winfo_viewable(): + if parent.winfo_viewable(): self.transient(parent) - + if title: self.title(title) Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Mon Feb 5 02:24:16 2007 @@ -569,7 +569,7 @@ # 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) @@ -578,7 +578,7 @@ 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 = {} @@ -1219,7 +1219,7 @@ 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' % Modified: python/branches/p3yk/Lib/platform.py ============================================================================== --- python/branches/p3yk/Lib/platform.py (original) +++ python/branches/p3yk/Lib/platform.py Mon Feb 5 02:24:16 2007 @@ -236,7 +236,7 @@ '[^(]*(?:\((.+)\))?') # See also http://www.novell.com/coolsolutions/feature/11251.html -# and http://linuxmafia.com/faq/Admin/release-files.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 @@ -245,7 +245,7 @@ 'gentoo', 'UnitedLinux') def _parse_release_file(firstline): - + # Parse the first line m = _lsb_release_version.match(firstline) if m is not None: @@ -268,7 +268,7 @@ return '', version, id 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')) @@ -324,7 +324,7 @@ break else: return _dist_try_harder(distname,version,id) - + # Read the first line f = open('/etc/'+file, 'r') firstline = f.readline() @@ -340,7 +340,7 @@ return distname, version, id # To maintain backwards compatibility: - + def dist(distname='',version='',id='', supported_dists=_supported_dists): @@ -1358,7 +1358,7 @@ If not available, an empty string is returned. """ - + return _sys_version()[2] def python_revision(): Modified: python/branches/p3yk/Lib/pty.py ============================================================================== --- python/branches/p3yk/Lib/pty.py (original) +++ python/branches/p3yk/Lib/pty.py Mon Feb 5 02:24:16 2007 @@ -123,7 +123,7 @@ os.close(tmp_fd) else: os.close(slave_fd) - + # Parent and child process. return pid, master_fd Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Mon Feb 5 02:24:16 2007 @@ -1121,7 +1121,7 @@ # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) - input_offset += bytes_written + input_offset += bytes_written if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) 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 Mon Feb 5 02:24:16 2007 @@ -15,7 +15,7 @@ result = self.data.keys() result.sort() return result - + def values(self): result = self.items() return [i[1] for i in values] @@ -446,12 +446,12 @@ "o2=3\n" "o1=4\n" "[a]\n" - "k=v\n") + "k=v\n") output = StringIO.StringIO() self.cf.write(output) self.assertEquals(output.getvalue(), "[a]\n" - "k = v\n\n" + "k = v\n\n" "[b]\n" "o1 = 4\n" "o2 = 3\n" 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 Mon Feb 5 02:24:16 2007 @@ -7,6 +7,12 @@ # How much time in seconds can pass before we print a 'Still working' message. _PRINT_WORKING_MSG_INTERVAL = 5 * 60 +class TrivialContext(object): + def __enter__(self): + return self + def __exit__(self, *exc_info): + pass + class CompilerTest(unittest.TestCase): def testCompileLibrary(self): @@ -157,6 +163,31 @@ exec(c, dct) self.assertEquals(dct['f'].func_annotations, expected) + def testWith(self): + # SF bug 1638243 + c = compiler.compile('from __future__ import with_statement\n' + 'def f():\n' + ' with TrivialContext():\n' + ' return 1\n' + 'result = f()', + '', + 'exec' ) + dct = {'TrivialContext': TrivialContext} + exec(c, dct) + self.assertEquals(dct.get('result'), 1) + + def testWithAss(self): + c = compiler.compile('from __future__ import with_statement\n' + 'def f():\n' + ' with TrivialContext() as tc:\n' + ' return 1\n' + 'result = f()', + '', + 'exec' ) + dct = {'TrivialContext': TrivialContext} + exec(c, dct) + self.assertEquals(dct.get('result'), 1) + NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard) 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 Mon Feb 5 02:24:16 2007 @@ -49,7 +49,7 @@ f.close() finally: os.umask(old_umask) - + expected_mode = 0635 if os.name != 'posix': # Windows only supports setting the read-only attribute. @@ -61,7 +61,7 @@ self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) st = os.stat(_fname + '.dir') self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) - + 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 Mon Feb 5 02:24:16 2007 @@ -311,6 +311,13 @@ 'pickled "%r", attribute "%s' % (e, checkArgName)) + def testSlicing(self): + # Test that you can slice an exception directly instead of requiring + # going through the 'args' attribute. + args = (1, 2, 3) + exc = BaseException(*args) + self.failUnlessEqual(exc[:], args) + def testKeywordArgs(self): # test that builtin exception don't take keyword args, # but user-defined subclasses can if they want Modified: python/branches/p3yk/Lib/test/test_gzip.py ============================================================================== --- python/branches/p3yk/Lib/test/test_gzip.py (original) +++ python/branches/p3yk/Lib/test/test_gzip.py Mon Feb 5 02:24:16 2007 @@ -138,7 +138,7 @@ y = f.read(10) f.close() self.assertEquals(y, data1[20:30]) - + def test_seek_write(self): # Try seek, write test f = gzip.GzipFile(self.filename, 'w') Modified: python/branches/p3yk/Lib/test/test_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_mailbox.py Mon Feb 5 02:24:16 2007 @@ -674,11 +674,11 @@ box = self._factory(self._path, factory=dummy_factory) folder = box.add_folder('folder1') self.assert_(folder._factory is dummy_factory) - + folder1_alias = box.get_folder('folder1') self.assert_(folder1_alias._factory is dummy_factory) - + class _TestMboxMMDF(TestMailbox): @@ -798,7 +798,7 @@ def dummy_factory (s): return None self._box = self._factory(self._path, dummy_factory) - + new_folder = self._box.add_folder('foo.bar') folder0 = self._box.get_folder('foo.bar') folder0.add(self._template % 'bar') @@ -894,7 +894,7 @@ self.assert_(self._box.get_sequences() == {'foo':[1, 2, 3, 4, 5], 'unseen':[1], 'bar':[3], 'replied':[3]}) - + def _get_lock_path(self): return os.path.join(self._path, '.mh_sequences.lock') Modified: python/branches/p3yk/Lib/test/test_old_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_old_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_old_mailbox.py Mon Feb 5 02:24:16 2007 @@ -116,7 +116,7 @@ def tearDown(self): os.unlink(self._path) - + def test_from_regex (self): # Testing new regex from bug #1633678 f = open(self._path, 'w') Modified: python/branches/p3yk/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep352.py (original) +++ python/branches/p3yk/Lib/test/test_pep352.py Mon Feb 5 02:24:16 2007 @@ -2,7 +2,7 @@ import __builtin__ import exceptions import warnings -from test.test_support import run_unittest +from test.test_support import run_unittest, guard_warnings_filter import os from platform import system as platform_system @@ -113,13 +113,11 @@ """Test usage of exceptions""" - def setUp(self): - self._filters = warnings.filters[:] - - def tearDown(self): - warnings.filters = self._filters[:] - def test_raise_new_style_non_exception(self): + # You cannot raise a new-style class that does not inherit from + # BaseException; the ability was not possible until BaseException's + # introduction so no need to support new-style objects that do not + # inherit from it. class NewStyleClass(object): pass try: @@ -127,13 +125,51 @@ except TypeError: pass except: - self.fail("unable to raise new-style class") + self.fail("able to raise new-style class") try: raise NewStyleClass() except TypeError: pass except: - self.fail("unable to raise new-style class instance") + self.fail("able to raise new-style class instance") + + def test_raise_string(self): + # Raising a string raises TypeError. + try: + raise "spam" + except TypeError: + pass + except: + self.fail("was able to raise a string exception") + + def test_catch_string(self): + # Catching a string should trigger a DeprecationWarning. + with guard_warnings_filter(): + warnings.resetwarnings() + warnings.filterwarnings("error") + str_exc = "spam" + try: + try: + raise StandardError + except str_exc: + pass + except DeprecationWarning: + pass + except StandardError: + self.fail("catching a string exception did not raise " + "DeprecationWarning") + # Make sure that even if the string exception is listed in a tuple + # that a warning is raised. + try: + try: + raise StandardError + except (AssertionError, str_exc): + pass + except DeprecationWarning: + pass + except StandardError: + self.fail("catching a string exception specified in a tuple did " + "not raise DeprecationWarning") def test_main(): run_unittest(ExceptionClassTests, UsageTests) 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 Mon Feb 5 02:24:16 2007 @@ -120,7 +120,7 @@ ##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)) @@ -140,8 +140,8 @@ ## 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_resource.py ============================================================================== --- python/branches/p3yk/Lib/test/test_resource.py (original) +++ python/branches/p3yk/Lib/test/test_resource.py Mon Feb 5 02:24:16 2007 @@ -15,7 +15,7 @@ self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42) def test_fsize_ismax(self): - + try: (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) except AttributeError: @@ -39,7 +39,7 @@ # versions of Python were terminated by an uncaught SIGXFSZ, but # pythonrun.c has been fixed to ignore that exception. If so, the # write() should return EFBIG when the limit is exceeded. - + # At least one platform has an unlimited RLIMIT_FSIZE and attempts # to change it raise ValueError instead. try: 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 Feb 5 02:24:16 2007 @@ -481,7 +481,7 @@ 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) @@ -1464,7 +1464,7 @@ test_classes = ( TestSet, TestSetSubclass, - TestSetSubclassWithKeywordArgs, + TestSetSubclassWithKeywordArgs, TestFrozenSet, TestFrozenSetSubclass, TestSetOfSets, 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 Mon Feb 5 02:24:16 2007 @@ -463,6 +463,10 @@ "of the year") test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and " "ending on Monday") + test_helper((2007, 01, 07), "First Sunday of 2007") + test_helper((2007, 01, 14), "Second Sunday of 2007") + test_helper((2006, 12, 31), "Last Sunday of 2006") + test_helper((2006, 12, 24), "Second to last Sunday of 2006") class CacheTests(unittest.TestCase): 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 Mon Feb 5 02:24:16 2007 @@ -119,7 +119,7 @@ cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s) if (cp != c or bp != b or hp != h or ip != i or lp != l or int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d) or - tp != t): + tp != t): # ^^^ calculate only to two decimal places raise TestFailed, "unpack/pack not transitive (%s, %s)" % ( str(format), str((cp, bp, hp, ip, lp, fp, dp, tp))) @@ -160,11 +160,11 @@ ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0), ('d', -2.0, '\300\000\000\000\000\000\000\000', '\000\000\000\000\000\000\000\300', 0), - ('t', 0, '\0', '\0', 0), - ('t', 3, '\1', '\1', 1), - ('t', True, '\1', '\1', 0), - ('t', [], '\0', '\0', 1), - ('t', (1,), '\1', '\1', 1), + ('t', 0, '\0', '\0', 0), + ('t', 3, '\1', '\1', 1), + ('t', True, '\1', '\1', 0), + ('t', [], '\0', '\0', 1), + ('t', (1,), '\1', '\1', 1), ] for fmt, arg, big, lil, asy in tests: @@ -621,48 +621,48 @@ test_pack_into_fn() def test_bool(): - for prefix in tuple("<>!=")+('',): - false = (), [], [], '', 0 - true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2 - - falseFormat = prefix + 't' * len(false) - if verbose: - print 'trying bool pack/unpack on', false, 'using format', falseFormat - packedFalse = struct.pack(falseFormat, *false) - unpackedFalse = struct.unpack(falseFormat, packedFalse) - - trueFormat = prefix + 't' * len(true) - if verbose: - print 'trying bool pack/unpack on', true, 'using format', trueFormat - packedTrue = struct.pack(trueFormat, *true) - unpackedTrue = struct.unpack(trueFormat, packedTrue) - - if len(true) != len(unpackedTrue): - raise TestFailed('unpacked true array is not of same size as input') - if len(false) != len(unpackedFalse): - raise TestFailed('unpacked false array is not of same size as input') - - for t in unpackedFalse: - if t is not False: - raise TestFailed('%r did not unpack as False' % t) - for t in unpackedTrue: - if t is not True: - raise TestFailed('%r did not unpack as false' % t) - - if prefix and verbose: - print 'trying size of bool with format %r' % (prefix+'t') - packed = struct.pack(prefix+'t', 1) - - if len(packed) != struct.calcsize(prefix+'t'): - raise TestFailed('packed length is not equal to calculated size') - - if len(packed) != 1 and prefix: - raise TestFailed('encoded bool is not one byte: %r' % packed) - elif not prefix and verbose: - print 'size of bool in native format is %i' % (len(packed)) - - for c in '\x01\x7f\xff\x0f\xf0': - if struct.unpack('>t', c)[0] is not True: - raise TestFailed('%c did not unpack as True' % c) + for prefix in tuple("<>!=")+('',): + false = (), [], [], '', 0 + true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2 + + falseFormat = prefix + 't' * len(false) + if verbose: + print 'trying bool pack/unpack on', false, 'using format', falseFormat + packedFalse = struct.pack(falseFormat, *false) + unpackedFalse = struct.unpack(falseFormat, packedFalse) + + trueFormat = prefix + 't' * len(true) + if verbose: + print 'trying bool pack/unpack on', true, 'using format', trueFormat + packedTrue = struct.pack(trueFormat, *true) + unpackedTrue = struct.unpack(trueFormat, packedTrue) + + if len(true) != len(unpackedTrue): + raise TestFailed('unpacked true array is not of same size as input') + if len(false) != len(unpackedFalse): + raise TestFailed('unpacked false array is not of same size as input') + + for t in unpackedFalse: + if t is not False: + raise TestFailed('%r did not unpack as False' % t) + for t in unpackedTrue: + if t is not True: + raise TestFailed('%r did not unpack as false' % t) + + if prefix and verbose: + print 'trying size of bool with format %r' % (prefix+'t') + packed = struct.pack(prefix+'t', 1) + + if len(packed) != struct.calcsize(prefix+'t'): + raise TestFailed('packed length is not equal to calculated size') + + if len(packed) != 1 and prefix: + raise TestFailed('encoded bool is not one byte: %r' % packed) + elif not prefix and verbose: + print 'size of bool in native format is %i' % (len(packed)) + + for c in '\x01\x7f\xff\x0f\xf0': + if struct.unpack('>t', c)[0] is not True: + raise TestFailed('%c did not unpack as True' % c) test_bool() 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 Mon Feb 5 02:24:16 2007 @@ -270,7 +270,7 @@ print >> get_original_stdout(), '\tfetching %s ...' % url fn, _ = urllib.urlretrieve(url, filename) return open(fn) - + @contextmanager def guard_warnings_filter(): """Guard the warnings filter from being permanently changed.""" Modified: python/branches/p3yk/Modules/_ctypes/cfield.c ============================================================================== --- python/branches/p3yk/Modules/_ctypes/cfield.c (original) +++ python/branches/p3yk/Modules/_ctypes/cfield.c Mon Feb 5 02:24:16 2007 @@ -1432,10 +1432,19 @@ #endif #ifdef MS_WIN32 +/* We cannot use SysFreeString as the PyCObject_FromVoidPtr + because of different calling convention +*/ +static void _my_SysFreeString(void *p) +{ + SysFreeString((BSTR)p); +} + static PyObject * BSTR_set(void *ptr, PyObject *value, unsigned size) { BSTR bstr; + PyObject *result; /* convert value into a PyUnicodeObject or NULL */ if (Py_None == value) { @@ -1463,15 +1472,19 @@ } else bstr = NULL; - /* free the previous contents, if any */ - if (*(BSTR *)ptr) - SysFreeString(*(BSTR *)ptr); - - /* and store it */ - *(BSTR *)ptr = bstr; + if (bstr) { + result = PyCObject_FromVoidPtr((void *)bstr, _my_SysFreeString); + if (result == NULL) { + SysFreeString(bstr); + return NULL; + } + } else { + result = Py_None; + Py_INCREF(result); + } - /* We don't need to keep any other object */ - _RET(value); + *(BSTR *)ptr = bstr; + return result; } Modified: python/branches/p3yk/Modules/posixmodule.c ============================================================================== --- python/branches/p3yk/Modules/posixmodule.c (original) +++ python/branches/p3yk/Modules/posixmodule.c Mon Feb 5 02:24:16 2007 @@ -1462,7 +1462,7 @@ /* POSIX methods */ PyDoc_STRVAR(posix_access__doc__, -"access(path, mode) -> 1 if granted, 0 otherwise\n\n\ +"access(path, mode) -> True if granted, False otherwise\n\n\ Use the real uid/gid to test for access to a path. Note that most\n\ operations will use the effective uid/gid, therefore this routine can\n\ be used in a suid/sgid environment to test if the invoking user has the\n\ Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Mon Feb 5 02:24:16 2007 @@ -935,7 +935,7 @@ if (PyAnySet_Check(other)) return set_merge(so, other); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; while (PyDict_Next(other, &pos, &key, &value)) { @@ -1383,7 +1383,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other) && !PyDict_Check(other)) { + if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1397,7 +1397,7 @@ if (result == NULL) return NULL; - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { while (set_next(so, &pos, &entry)) { setentry entrycopy; entrycopy.hash = entry->hash; @@ -1470,7 +1470,7 @@ if ((PyObject *)so == other) return set_clear(so); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; int rv; while (PyDict_Next(other, &pos, &key, &value)) { Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Mon Feb 5 02:24:16 2007 @@ -2174,8 +2174,9 @@ case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: - /* NOTE: If you add any new block-setup opcodes that are not try/except/finally - handlers, you may need to update the PyGen_NeedsFinalizing() function. */ + /* NOTE: If you add any new block-setup opcodes that are + not try/except/finally handlers, you may need to + update the PyGen_NeedsFinalizing() function. */ PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, STACK_LEVEL()); @@ -4010,6 +4011,35 @@ res = !res; break; case PyCmp_EXC_MATCH: + if (PyTuple_Check(w)) { + Py_ssize_t i, length; + length = PyTuple_Size(w); + for (i = 0; i < length; i += 1) { + PyObject *exc = PyTuple_GET_ITEM(w, i); + if (PyString_Check(exc)) { + int ret_val; + ret_val = PyErr_WarnEx( + PyExc_DeprecationWarning, + "catching of string " + "exceptions is " + "deprecated", 1); + if (ret_val == -1) + return NULL; + } + } + } + else { + if (PyString_Check(w)) { + int ret_val; + ret_val = PyErr_WarnEx( + PyExc_DeprecationWarning, + "catching of string " + "exceptions is deprecated", + 1); + if (ret_val == -1) + return NULL; + } + } res = PyErr_GivenExceptionMatches(v, w); break; default: From python-checkins at python.org Mon Feb 5 07:03:19 2007 From: python-checkins at python.org (kurt.kaiser) Date: Mon, 5 Feb 2007 07:03:19 +0100 (CET) Subject: [Python-checkins] r53635 - python/trunk/Lib/idlelib/NEWS.txt python/trunk/Lib/idlelib/configHandler.py Message-ID: <20070205060319.DBAAC1E4002@bag.python.org> Author: kurt.kaiser Date: Mon Feb 5 07:03:18 2007 New Revision: 53635 Modified: python/trunk/Lib/idlelib/NEWS.txt python/trunk/Lib/idlelib/configHandler.py Log: Add 'raw' support to configHandler. Patch 1650174 Tal Einat. Modified: python/trunk/Lib/idlelib/NEWS.txt ============================================================================== --- python/trunk/Lib/idlelib/NEWS.txt (original) +++ python/trunk/Lib/idlelib/NEWS.txt Mon Feb 5 07:03:18 2007 @@ -3,6 +3,8 @@ *Release date: XX-XXX-200X* +- Add 'raw' support to configHandler. Patch 1650174 Tal Einat. + - Avoid hang when encountering a duplicate in a completion list. Bug 1571112. - Patch #1362975: Rework CodeContext indentation algorithm to Modified: python/trunk/Lib/idlelib/configHandler.py ============================================================================== --- python/trunk/Lib/idlelib/configHandler.py (original) +++ python/trunk/Lib/idlelib/configHandler.py Mon Feb 5 07:03:18 2007 @@ -39,22 +39,19 @@ self.file=cfgFile ConfigParser.__init__(self,defaults=cfgDefaults) - def Get(self, section, option, type=None, default=None): + def Get(self, section, option, type=None, default=None, raw=False): """ Get an option value for given section/option or return default. If type is specified, return as type. """ + if not self.has_option(section, option): + return default if type=='bool': - getVal=self.getboolean + return self.getboolean(section, option) elif type=='int': - getVal=self.getint - else: - getVal=self.get - if self.has_option(section,option): - #return getVal(section, option, raw, vars, default) - return getVal(section, option) + return self.getint(section, option) else: - return default + return self.get(section, option, raw=raw) def GetOptionList(self,section): """ @@ -219,7 +216,7 @@ return userDir def GetOption(self, configType, section, option, default=None, type=None, - warn_on_default=True): + warn_on_default=True, raw=False): """ Get an option value for given config type and given general configuration section/option or return a default. If type is specified, @@ -233,9 +230,11 @@ """ if self.userCfg[configType].has_option(section,option): - return self.userCfg[configType].Get(section, option, type=type) + return self.userCfg[configType].Get(section, option, + type=type, raw=raw) elif self.defaultCfg[configType].has_option(section,option): - return self.defaultCfg[configType].Get(section, option, type=type) + return self.defaultCfg[configType].Get(section, option, + type=type, raw=raw) else: #returning default, print warning if warn_on_default: warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n' From python-checkins at python.org Mon Feb 5 22:42:38 2007 From: python-checkins at python.org (brett.cannon) Date: Mon, 5 Feb 2007 22:42:38 +0100 (CET) Subject: [Python-checkins] r53636 - sandbox/trunk/import_in_py/controlled_importlib.py sandbox/trunk/import_in_py/test_controlled_importlib.py Message-ID: <20070205214238.C2CFB1E400B@bag.python.org> Author: brett.cannon Date: Mon Feb 5 22:42:38 2007 New Revision: 53636 Modified: sandbox/trunk/import_in_py/controlled_importlib.py sandbox/trunk/import_in_py/test_controlled_importlib.py Log: Add whitelisting support for extension modules. Modified: sandbox/trunk/import_in_py/controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/controlled_importlib.py Mon Feb 5 22:42:38 2007 @@ -58,6 +58,25 @@ pass +class WhitelistExtHandler(importlib.ExtensionFileHandler): + + """Add whitelisting to the extension module handler.""" + + def __init__(self, whitelist): + self._whitelist = frozenset(whitelist) + super(WhitelistExtHandler, self).__init__() + + def cannot_handle(self, name): + if name in self._whitelist: + return False + return True + + def handle_code(self, loader, mod_name, extension_path, package=None): + if mod_name in self._whitelist: + return super(WhitelistExtHandler, self).handle_code(loder, mod_name, + extension_path, package) + raise ImportError("not allowed to load module") + class ControlledImport(importlib.Import): Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/test_controlled_importlib.py Mon Feb 5 22:42:38 2007 @@ -1,7 +1,9 @@ import controlled_importlib +import importlib import mock_importlib from contextlib import contextmanager, nested +import os import StringIO import sys import unittest @@ -108,6 +110,55 @@ self.failUnlessRaises(ImportError, imp_load.load_module, blacklist) +class ExtensionHelper(unittest.TestCase): + + whitelist = 'time' + blacklist = 'datetime' + + def setUp(self): + self.imp_load = controlled_importlib.WhitelistExtHandler([self.whitelist]) + + +class WhitelistExtensionsTests(ExtensionHelper): + + """Test the whitelisting of extension modules.""" + + def test_cannot_handle(self): + # Should return False for modules on the whitelist, True otherwise. + self.failUnless(not self.imp_load.cannot_handle(self.whitelist)) + self.failUnless(self.imp_load.cannot_handle(self.blacklist)) + + def handle_code(self): + # Should raise ImportError if the module is not whitelisted, otherwise + # return the module. + module = self.imp_load.handle_code(None, self.whitelist, + self.imp_load.handles[0]) + self.failUnlessEqual(module.__name__, self.whitelist) + self.failUnlessRaises(ImportError, self.imp_load.handle_code, None, + self.blacklist, self.imp_load.handles[0]) + + +class FileSystemImporterTests(ExtensionHelper): + + """Make sure that the filesystem importer respects what the handler's + cannot_handle method says.""" + + def test_find_module(self): + # Make sure that when the handler is used in a filesystem importer that + # whitelisting is still respected for find_module. + for entry in sys.path: + blacklist_filename = self.blacklist + self.imp_load.handles[0] + blacklist_path = os.path.join(entry, blacklist_filename) + if os.path.exists(blacklist_path): + sys_entry = entry + break + else: + raise test_support.TestSkipped("sys.path empty") + importer = importlib.FileSystemImporter(sys_entry, self.imp_load) + self.failUnless(importer.find_module(self.whitelist)) + self.failUnless(importer.find_module(self.blacklist) is None) + + @contextmanager def mutate_sys_modules(module, name): """Temporarily mutate sys.modules with a new module.""" @@ -242,6 +293,8 @@ test_support.run_unittest(WhitelistTests, WhitelistBuiltinTests, WhitelistFrozenTests, + WhitelistExtensionsTests, + FileSystemImporterTests, ControlledImportMethodTests, ControlledImportUsageTests) From python-checkins at python.org Mon Feb 5 23:01:59 2007 From: python-checkins at python.org (collin.winter) Date: Mon, 5 Feb 2007 23:01:59 +0100 (CET) Subject: [Python-checkins] r53637 - peps/trunk/pep-0000.txt peps/trunk/pep-3109.txt Message-ID: <20070205220159.5AEB81E401C@bag.python.org> Author: collin.winter Date: Mon Feb 5 23:01:58 2007 New Revision: 53637 Added: peps/trunk/pep-3109.txt (contents, props changed) Modified: peps/trunk/pep-0000.txt Log: Add PEP 3109: Raising Exceptions in Python 3000 Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Mon Feb 5 23:01:58 2007 @@ -107,6 +107,7 @@ S 3106 Revamping dict.keys(), .values() and .items() GvR S 3107 Function Annotations Winter, Lownds I 3108 Standard Library Reorganization Cannon + I 3109 Raising Exceptions in Python 3000 Winter Finished PEPs (done, implemented in Subversion) @@ -447,6 +448,7 @@ S 3106 Revamping dict.keys(), .values() and .items() GvR S 3107 Function Annotations Winter, Lownds I 3108 Standard Library Reorganization Cannon + I 3109 Raising Exceptions in Python 3000 Winter Key Added: peps/trunk/pep-3109.txt ============================================================================== --- (empty file) +++ peps/trunk/pep-3109.txt Mon Feb 5 23:01:58 2007 @@ -0,0 +1,286 @@ +PEP: 3109 +Title: Raising Exceptions in Python 3000 +Version: $Revision$ +Last-Modified: $Date$ +Author: Collin Winter +Status: Draft +Type: Standards Track +Content-Type: text/x-rst +Created: 19-Jan-2006 +Python-Version: 3.0 +Post-History: + + +Abstract +======== + +This PEP introduces changes to Python's mechanisms for raising +exceptions intended to reduce both line noise and the size of the +language. + + +Rationale +========= + +One of Python's guiding maxims is "there should be one -- and +preferably only one -- obvious way to do it" [#zen]_. Python 2.x's +``raise`` statement violates this principle, permitting multiple +ways of expressing the same thought. For example, these statements +are equivalent: :: + + raise E, V + + raise E(V) + +There is a third form of the ``raise`` statement, allowing arbitrary +tracebacks to be attached to an exception [#grammar]_: :: + + raise E, V, T + +where T is a traceback. As specified in PEP 344 [#pep344]_, +exception objects in Python 3.x will possess a ``__traceback__`` +attribute, admitting this translation of the three-expression +``raise`` statement: :: + + raise E, V, T + +is translated to :: + + e = E(V) + e.__traceback__ = T + raise e + +Using these translations, we can reduce the ``raise`` statement from +four forms to two: + +1. ``raise`` (with no arguments) is used to re-raise the active + exception in an ``except`` suite. + +2. ``raise EXCEPTION`` is used to raise a new exception. This form has + two sub-variants: ``EXCEPTION`` may be an exception class or an + instance of an exception class; valid exception classes are + BaseException and its subclasses [#pep352]_. If ``EXCEPTION`` + is a subclass, it will be called with no arguments to obtain + an exception instance. + + To raise anything else is an error. + +There is a further, more tangible benefit to be obtained through this +consolidation, as noted by A.M. Kuchling [#amk-line-noise]_. :: + + PEP 8 doesn't express any preference between the + two forms of raise statements: + raise ValueError, 'blah' + raise ValueError("blah") + + I like the second form better, because if the exception arguments + are long or include string formatting, you don't need to use line + continuation characters because of the containing parens. + +The BDFL has concurred [#guido-declaration]_ and endorsed the +consolidation of the several ``raise`` forms. + + +Grammar Changes +=============== + +In Python 3, the grammar for ``raise`` statements will change +from [#grammar]_ :: + + raise_stmt: 'raise' [test [',' test [',' test]]] + +to :: + + raise_stmt: 'raise' [test] + + +Changes to Builtin Types +======================== + +Because of its relation to exception raising, the signature for the +``throw()`` method on generator objects will change, dropping the +optional second and third parameters. The signature thus changes +from [#throw-sig]_ :: + + generator.throw(E, [V, [T]]) + +to :: + + generator.throw(EXCEPTION) + +Where ``EXCEPTION`` is either a subclass of ``BaseException`` or an +instance of a subclass of ``BaseException``. + + +Semantic Changes +================ + +In Python 2, the following ``raise`` statement is legal :: + + raise ((E1, (E2, E3)), E4), V + +The interpreter will take the tuple's first element as the exception +type (recursively), making the above fully equivalent to :: + + raise E1, V + +As of Python 3.0, support for raising tuples like this will be +dropped. This change will bring ``raise`` statements into line with +the ``throw()`` method on generator objects, which already disallows +this. + + +Compatibility Issues +==================== + +All two- and three-expression ``raise`` statements will require +modification, as will all two- and three-expression ``throw()`` calls +on generators. Fortunately, the translation from Python 2.x to +Python 3.x in this case is simple and can be handled mechanically +by Guido van Rossum's 2to3 utility [#2to3]_ using the ``raise`` and +``throw`` fixers ([#raise-fixer]_, [#throw-fixer]_). + +The following translations will be performed: + +1. Zero- and one-expression ``raise`` statements will be left + intact. + +2. Two-expression ``raise`` statements will be converted from :: + + raise E, V + + to :: + + raise E(V) + + Two-expression ``throw()`` calls will be converted from :: + + generator.throw(E, V) + + to :: + + generator.throw(E(V)) + + See point #5 for a caveat to this transformation. + +3. Three-expression ``raise`` statements will be converted from :: + + raise E, V, T + + to :: + + e = E(V) + e.__traceback__ = T + raise e + + Three-expression ``throw()`` calls will be converted from :: + + generator.throw(E, V, T) + + to :: + + e = E(V) + e.__traceback__ = T + generator.throw(e) + + See point #5 for a caveat to this transformation. + +4. Two- and three-expression ``raise`` statements where ``E`` is a + tuple literal can be converted automatically using ``2to3``'s + ``raise`` fixer. ``raise`` statements where ``E`` is a non-literal + tuple, e.g., the result of a function call, will need to be + converted manually. + +5. Two- and three-expression ``raise`` statements where ``E`` is an + exception class and ``V`` is an exception instance will need + special attention. These cases break down into two camps: + + 1. ``raise E, V`` as a long-hand version of the zero-argument + ``raise`` statement. As an example, assuming F is a subclass + of E :: + + try: + something() + except F as V: + raise F(V) + except E as V: + handle(V) + + This would be better expressed as :: + + try: + something() + except F: + raise + except E as V: + handle(V) + + 2. ``raise E, V`` as a way of "casting" an exception to another + class. Taking an example from + distutils.compiler.unixcompiler :: + + try: + self.spawn(pp_args) + except DistutilsExecError as msg: + raise CompileError(msg) + + This would be better expressed as :: + + try: + self.spawn(pp_args) + except DistutilsExecError as msg: + raise CompileError from msg + + Using the ``raise ... from ...`` syntax introduced in + PEP 344. + + +References +========== + +.. [#zen] + http://www.python.org/dev/peps/pep-0020/ + +.. [#grammar] + http://www.python.org/doc/current/ref/raise.html + +.. [#throw-sig] + http://www.python.org/dev/peps/pep-0342/ + +.. [#pep344] + http://www.python.org/dev/peps/pep-0344/ + +.. [#pep352] + http://www.python.org/dev/peps/pep-0352/ + +.. [#amk-line-noise] + http://mail.python.org/pipermail/python-dev/2005-August/055187.html + +.. [#guido-declaration] + http://mail.python.org/pipermail/python-dev/2005-August/055190.html + +.. [#2to3] + http://svn.python.org/view/sandbox/trunk/2to3/ + +.. [#raise-fixer] + http://svn.python.org/view/sandbox/trunk/2to3/fixes/fix_raise.py + +.. [#throw-fixer] + http://svn.python.org/view/sandbox/trunk/2to3/fixes/fix_throw.py + + +Copyright +========= + +This document has been placed in the public domain. + + + +.. + Local Variables: + mode: indented-text + indent-tabs-mode: nil + sentence-end-double-space: t + fill-column: 70 + coding: utf-8 + End: From python-checkins at python.org Mon Feb 5 23:05:47 2007 From: python-checkins at python.org (collin.winter) Date: Mon, 5 Feb 2007 23:05:47 +0100 (CET) Subject: [Python-checkins] r53638 - peps/trunk/pep-0000.txt peps/trunk/pep-3110.txt Message-ID: <20070205220547.B14C71E401C@bag.python.org> Author: collin.winter Date: Mon Feb 5 23:05:46 2007 New Revision: 53638 Added: peps/trunk/pep-3110.txt (contents, props changed) Modified: peps/trunk/pep-0000.txt Log: Add PEP 3110: Catching Exceptions in Python 3000 Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Mon Feb 5 23:05:46 2007 @@ -108,6 +108,7 @@ S 3107 Function Annotations Winter, Lownds I 3108 Standard Library Reorganization Cannon I 3109 Raising Exceptions in Python 3000 Winter + I 3110 Catching Exceptions in Python 3000 Winter Finished PEPs (done, implemented in Subversion) @@ -449,6 +450,7 @@ S 3107 Function Annotations Winter, Lownds I 3108 Standard Library Reorganization Cannon I 3109 Raising Exceptions in Python 3000 Winter + I 3110 Catching Exceptions in Python 3000 Winter Key Added: peps/trunk/pep-3110.txt ============================================================================== --- (empty file) +++ peps/trunk/pep-3110.txt Mon Feb 5 23:05:46 2007 @@ -0,0 +1,287 @@ +PEP: 3110 +Title: Catching Exceptions in Python 3000 +Version: $Revision$ +Last-Modified: $Date$ +Author: Collin Winter +Status: Draft +Type: Standards Track +Content-Type: text/x-rst +Created: 16-Jan-2006 +Python-Version: 3.0 +Post-History: + + +Abstract +======== + +This PEP introduces changes intended to help eliminate ambiguities +in Python's grammar, simplify exception classes, simplify garbage +collection for exceptions and reduce the size of the language in +Python 3.0. + + +Rationale +========= + +1. ``except`` clauses in Python 2.x present a syntactic ambiguity + where the parser cannot differentiate whether :: + + except , : + + should be interpreted as :: + + except , : + + or :: + + except , : + + Python 2 opts for the latter semantic, at the cost of requiring the + former to be parenthesized, like so :: + + except (, ): + +2. As specified in PEP 352 [#pep352]_, the ability to treat exceptions + as tuples will be removed, meaning this code will no longer work :: + + except os.error, (errno, errstr): + + Because the automatic unpacking will no longer be possible, it is + desirable to remove the ability to use tuples as ``except`` targets. + +3. As specified in PEP 344 [#pep344]_, exception instances in Python 3 + will possess a ``__traceback__`` attribute. The Open Issues section + of that PEP includes a paragraph on garbage collection difficulties + caused by this attribute, namely a "exception -> traceback -> + stack frame -> exception" reference cycle, whereby all locals are + kept in scope until the next GC run. This PEP intends to resolve + this issue by adding a cleanup semantic to ``except`` clauses in + Python 3 whereby the target name is deleted at the end of the + ``except`` suite. + +4. In the spirit of "there should be one -- and preferably only one + -- obvious way to do it" [#zen]_, it is desirable to consolidate + duplicate functionality. To this end, the ``exc_value``, + ``exc_type`` and ``exc_traceback`` attributes of the ``sys`` + module [#sys-module]_ will be removed in favor of + ``sys.exc_info()``, which provides the same information. These + attributes are already listed in PEP 3100 [#pep3100]_ as targeted + for removal. + + +Grammar Changes +=============== + +In Python 3, the grammar for ``except`` statements will change +from [#grammar]_ :: + + except_clause: 'except' [test [',' test]] + +to :: + + except_clause: 'except' [test ['as' NAME]] + +The use of ``as`` in place of the comma token means that :: + + except AttributeError, os.error: + +can be clearly understood as a tuple of exception classes. This new +syntax was first proposed by Greg Ewing [#firstproposal]_ and +endorsed ([#firstproposal]_, [#renaming]_) by the BDFL. + +Further, the restriction of the token following ``as`` from ``test`` +to ``NAME`` means that only valid identifiers can be used as +``except`` targets. + + +Semantic Changes +================ + +In order to resolve the garbage collection issue related to PEP 344, +``except`` statements in Python 3 will generate additional bytecode to +delete the target, thus eliminating the reference cycle. +The source-to-source translation, as suggested by Phillip J. Eby +[#except-translation]_, is :: + + try: + try_body + except E as N: + except_body + ... + +gets translated to (in Python 2.5 terms) :: + + try: + try_body + except E, N: + try: + except_body + finally: + N = None + del N + ... + +An implementation has already been checked into the p3yk branch +[#translation-checkin]_. + + +Compatibility Issues +==================== + +Nearly all ``except`` clauses will need to be changed. ``except`` +clauses with identifier targets will be converted from :: + + except E, N: + +to :: + + except E as N: + +``except`` clauses with non-tuple, non-identifier targets +(e.g., ``a.b.c[d]``) will need to be converted from :: + + except E, T: + +to :: + + except E as t: + T = t + +Both of these cases can be handled by Guido van Rossum's ``2to3`` +utility [#2to3]_ using the ``except`` fixer [#exceptfixer]_. + +``except`` clauses with tuple targets will need to be converted +manually, on a case-by-case basis. These changes will usually need +to be accompanied by changes to the exception classes themselves. +While these changes generally cannot be automated, the ``2to3`` +utility is able to point out cases where the target of an ``except`` +clause is a tuple, simplifying conversion. + +Situations where it is necessary to keep an exception instance around +past the end of the ``except`` suite can be easily translated like so +:: + + try: + ... + except E as N: + ... + ... + +becomes :: + + try: + ... + except E as N: + n = N + ... + ... + +This way, when ``N`` is deleted at the end of the block, ``n`` will +persist and can be used as normal. + +Lastly, all uses of the ``sys`` module's ``exc_type``, ``exc_value`` +and ``exc_traceback`` attributes will need to be removed. They can be +replaced with ``sys.exc_info()[0]``, ``sys.exc_info()[1]`` and +``sys.exc_info()[2]`` respectively, a transformation that can be +performed by ``2to3``'s ``sysexcattrs`` fixer. + + +Open Issues +=========== + +"except" Statements in Python 2.x +----------------------------------- + +It has been proposed that the grammar for ``except`` statements be +changed to accommodate both Python 2's ``,`` and Python 3's ``as`` +between the statement's type and target portions. The grammar +would thus change from :: + + except_clause: 'except' [test [',' test]] + +to :: + + except_clause: 'except' [test [('as' | ',') test]] + +It has not been decided whether the proposed end-of-suite cleanup +semantic for ``except`` statements should be included in the 2.x +series. + + +Replacing or Dropping "sys.exc_info()" +-------------------------------------- + +The idea of dropping ``sys.exc_info()`` or replacing it with a +``sys.exception`` attribute or a ``sys.get_exception()`` function +has been raised several times on python-3000 ([#drop-excinfo]_, +[#replace-excinfo]_) and mentioned in PEP 344's "Open Issues" section. + +While a ``2to3`` fixer to replace calls to ``sys.exc_info()`` +and some attribute accesses would be trivial, it would be far more +difficult for static analysis to find and fix functions that expect +the values from ``sys.exc_info()`` as arguments. Similarly, this does +not address the need to rewrite the documentation for all APIs that +are defined in terms of ``sys.exc_info()``. + + +References +========== + +.. [#pep352] + http://www.python.org/dev/peps/pep-0352/ + +.. [#zen] + http://www.python.org/dev/peps/pep-0020/ + +.. [#sys-module] + http://docs.python.org/lib/module-sys.html + +.. [#pep3100] + http://www.python.org/dev/peps/pep-3100/ + +.. [#pep344] + http://www.python.org/dev/peps/pep-0344/ + +.. [#firstproposal] + http://mail.python.org/pipermail/python-dev/2006-March/062449.html + +.. [#renaming] + http://mail.python.org/pipermail/python-dev/2006-March/062640.html + +.. [#grammar] + http://www.python.org/doc/current/ref/try.html + +.. [#except-translation] + http://mail.python.org/pipermail/python-3000/2007-January/005395.html + +.. [#translation-checkin] + http://svn.python.org/view?rev=53342&view=rev + +.. [#2to3] + http://svn.python.org/view/sandbox/trunk/2to3/ + +.. [#exceptfixer] + http://svn.python.org/view/sandbox/trunk/2to3/fixes/fix_except.py + +.. [#drop-excinfo] + http://mail.python.org/pipermail/python-3000/2007-January/005385.html + +.. [#replace-excinfo] + http://mail.python.org/pipermail/python-3000/2007-January/005604.html + + +Copyright +========= + +This document has been placed in the public domain. + + + +.. + Local Variables: + mode: indented-text + indent-tabs-mode: nil + sentence-end-double-space: t + fill-column: 70 + coding: utf-8 + End: From python-checkins at python.org Mon Feb 5 23:16:36 2007 From: python-checkins at python.org (collin.winter) Date: Mon, 5 Feb 2007 23:16:36 +0100 (CET) Subject: [Python-checkins] r53639 - peps/trunk/pep-0000.txt Message-ID: <20070205221636.796181E4015@bag.python.org> Author: collin.winter Date: Mon Feb 5 23:16:35 2007 New Revision: 53639 Modified: peps/trunk/pep-0000.txt Log: 3110 and 3109 are standards track, not informational, PEPs Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Mon Feb 5 23:16:35 2007 @@ -107,8 +107,8 @@ S 3106 Revamping dict.keys(), .values() and .items() GvR S 3107 Function Annotations Winter, Lownds I 3108 Standard Library Reorganization Cannon - I 3109 Raising Exceptions in Python 3000 Winter - I 3110 Catching Exceptions in Python 3000 Winter + S 3109 Raising Exceptions in Python 3000 Winter + S 3110 Catching Exceptions in Python 3000 Winter Finished PEPs (done, implemented in Subversion) @@ -449,8 +449,8 @@ S 3106 Revamping dict.keys(), .values() and .items() GvR S 3107 Function Annotations Winter, Lownds I 3108 Standard Library Reorganization Cannon - I 3109 Raising Exceptions in Python 3000 Winter - I 3110 Catching Exceptions in Python 3000 Winter + S 3109 Raising Exceptions in Python 3000 Winter + S 3110 Catching Exceptions in Python 3000 Winter Key From python-checkins at python.org Mon Feb 5 23:20:32 2007 From: python-checkins at python.org (brett.cannon) Date: Mon, 5 Feb 2007 23:20:32 +0100 (CET) Subject: [Python-checkins] r53640 - sandbox/trunk/import_in_py/test_controlled_importlib.py Message-ID: <20070205222032.7DC7B1E4016@bag.python.org> Author: brett.cannon Date: Mon Feb 5 23:20:31 2007 New Revision: 53640 Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py Log: Fix up previous extension module whitelisting and add testing in ControlledImport integration tests. Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/test_controlled_importlib.py Mon Feb 5 23:20:31 2007 @@ -118,6 +118,15 @@ def setUp(self): self.imp_load = controlled_importlib.WhitelistExtHandler([self.whitelist]) + def find_module(self, module): + for entry in sys.path: + module_filename= module + self.imp_load.handles[0] + module_path= os.path.join(entry, module_filename) + if os.path.exists(module_path): + return module_path + else: + raise test_support.TestSkipped("sys.path empty") + class WhitelistExtensionsTests(ExtensionHelper): @@ -128,14 +137,15 @@ self.failUnless(not self.imp_load.cannot_handle(self.whitelist)) self.failUnless(self.imp_load.cannot_handle(self.blacklist)) - def handle_code(self): + def test_handle_code(self): # Should raise ImportError if the module is not whitelisted, otherwise # return the module. - module = self.imp_load.handle_code(None, self.whitelist, - self.imp_load.handles[0]) + whitelist_path = self.find_module(self.whitelist) + module = self.imp_load.handle_code(None, self.whitelist, whitelist_path) self.failUnlessEqual(module.__name__, self.whitelist) + blacklist_path = self.find_module(self.blacklist) self.failUnlessRaises(ImportError, self.imp_load.handle_code, None, - self.blacklist, self.imp_load.handles[0]) + self.blacklist, blacklist_path) class FileSystemImporterTests(ExtensionHelper): @@ -146,14 +156,8 @@ def test_find_module(self): # Make sure that when the handler is used in a filesystem importer that # whitelisting is still respected for find_module. - for entry in sys.path: - blacklist_filename = self.blacklist + self.imp_load.handles[0] - blacklist_path = os.path.join(entry, blacklist_filename) - if os.path.exists(blacklist_path): - sys_entry = entry - break - else: - raise test_support.TestSkipped("sys.path empty") + blacklist_path = self.find_module(self.blacklist) + sys_entry = os.path.split(blacklist_path)[0] importer = importlib.FileSystemImporter(sys_entry, self.imp_load) self.failUnless(importer.find_module(self.whitelist)) self.failUnless(importer.find_module(self.blacklist) is None) @@ -257,8 +261,14 @@ self.failUnlessRaises(ImportError, import_, blacklisted, level=0) def test_extension_whitelisting(self): - # XXX - pass + whitelist = 'time' + blacklist = 'datetime' + with remove_from_sys_modules(whitelist, blacklist): + import_ = controlled_importlib.ControlledImport([], [], [whitelist]) + module = import_(whitelist, level=0) + self.failUnlessEqual(module.__name__, whitelist) + self.failUnlessRaises(ImportError, import_, blacklist, level=0) + def test_pyc_blocking(self): # XXX From python-checkins at python.org Tue Feb 6 00:02:17 2007 From: python-checkins at python.org (kurt.kaiser) Date: Tue, 6 Feb 2007 00:02:17 +0100 (CET) Subject: [Python-checkins] r53641 - python/trunk/Lib/idlelib/CallTips.py python/trunk/Lib/idlelib/NEWS.txt Message-ID: <20070205230217.0F0371E400D@bag.python.org> Author: kurt.kaiser Date: Tue Feb 6 00:02:16 2007 New Revision: 53641 Modified: python/trunk/Lib/idlelib/CallTips.py python/trunk/Lib/idlelib/NEWS.txt Log: 1. Calltips now 'handle' tuples in the argument list (display '' :) Suggested solution by Christos Georgiou, Bug 791968. 2. Clean up tests, were not failing when they should have been. 4. Remove some camelcase and an unneeded try/except block. Modified: python/trunk/Lib/idlelib/CallTips.py ============================================================================== --- python/trunk/Lib/idlelib/CallTips.py (original) +++ python/trunk/Lib/idlelib/CallTips.py Tue Feb 6 00:02:16 2007 @@ -3,7 +3,9 @@ Call Tips are floating windows which display function, class, and method parameter and docstring information when you type an opening parenthesis, and which disappear when you type a closing parenthesis. + """ +import re import sys import types @@ -89,6 +91,8 @@ two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. + To find methods, fetch_tip must be fed a fully qualified name. + """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt @@ -108,7 +112,7 @@ namespace.update(__main__.__dict__) try: return eval(name, namespace) - except: + except NameError: return None def _find_constructor(class_ob): @@ -124,39 +128,37 @@ def get_arg_text(ob): """Get a string describing the arguments for the given object""" - argText = "" + arg_text = "" if ob is not None: - argOffset = 0 + arg_offset = 0 if type(ob) in (types.ClassType, types.TypeType): # Look for the highest __init__ in the class chain. fob = _find_constructor(ob) if fob is None: fob = lambda: None else: - argOffset = 1 + arg_offset = 1 elif type(ob)==types.MethodType: # bit of a hack for methods - turn it into a function # but we drop the "self" param. fob = ob.im_func - argOffset = 1 + arg_offset = 1 else: fob = ob - # Try and build one for Python defined functions + # Try to build one for Python defined functions if type(fob) in [types.FunctionType, types.LambdaType]: - try: - realArgs = fob.func_code.co_varnames[argOffset:fob.func_code.co_argcount] - defaults = fob.func_defaults or [] - defaults = list(map(lambda name: "=%s" % repr(name), defaults)) - defaults = [""] * (len(realArgs)-len(defaults)) + defaults - items = map(lambda arg, dflt: arg+dflt, realArgs, defaults) - if fob.func_code.co_flags & 0x4: - items.append("...") - if fob.func_code.co_flags & 0x8: - items.append("***") - argText = ", ".join(items) - argText = "(%s)" % argText - except: - pass + argcount = fob.func_code.co_argcount + real_args = fob.func_code.co_varnames[arg_offset:argcount] + defaults = fob.func_defaults or [] + defaults = list(map(lambda name: "=%s" % repr(name), defaults)) + defaults = [""] * (len(real_args) - len(defaults)) + defaults + items = map(lambda arg, dflt: arg + dflt, real_args, defaults) + if fob.func_code.co_flags & 0x4: + items.append("...") + if fob.func_code.co_flags & 0x8: + items.append("***") + arg_text = ", ".join(items) + arg_text = "(%s)" % re.sub("\.\d+", "", arg_text) # See if we can use the docstring doc = getattr(ob, "__doc__", "") if doc: @@ -164,10 +166,10 @@ pos = doc.find("\n") if pos < 0 or pos > 70: pos = 70 - if argText: - argText += "\n" - argText += doc[:pos] - return argText + if arg_text: + arg_text += "\n" + arg_text += doc[:pos] + return arg_text ################################################# # @@ -181,16 +183,18 @@ def t4(*args): "(...)" def t5(a, *args): "(a, ...)" def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)" + def t7((a, b), c, (d, e)): "(, c, )" - class TC: - "(a=None, ...)" - def __init__(self, a=None, *b): "(a=None, ...)" + class TC(object): + "(ai=None, ...)" + def __init__(self, ai=None, *b): "(ai=None, ...)" def t1(self): "()" - def t2(self, a, b=None): "(a, b=None)" - def t3(self, a, *args): "(a, ...)" + def t2(self, ai, b=None): "(ai, b=None)" + def t3(self, ai, *args): "(ai, ...)" def t4(self, *args): "(...)" - def t5(self, a, *args): "(a, ...)" - def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)" + def t5(self, ai, *args): "(ai, ...)" + def t6(self, ai, b=None, *args, **kw): "(ai, b=None, ..., ***)" + def t7(self, (ai, b), c, (d, e)): "(, c, )" def test(tests): ct = CallTips() @@ -198,15 +202,20 @@ for t in tests: expected = t.__doc__ + "\n" + t.__doc__ name = t.__name__ - arg_text = ct.fetch_tip(name) + # exercise fetch_tip(), not just get_arg_text() + try: + qualified_name = "%s.%s" % (t.im_class.__name__, name) + except AttributeError: + qualified_name = name + arg_text = ct.fetch_tip(qualified_name) if arg_text != expected: failed.append(t) - print "%s - expected %s, but got %s" % (t, expected, - get_arg_text(entity)) + fmt = "%s - expected %s, but got %s" + print fmt % (t.__name__, expected, get_arg_text(t)) print "%d of %d tests failed" % (len(failed), len(tests)) tc = TC() - tests = (t1, t2, t3, t4, t5, t6, - TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6) + tests = (t1, t2, t3, t4, t5, t6, t7, + TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6, tc.t7) test(tests) Modified: python/trunk/Lib/idlelib/NEWS.txt ============================================================================== --- python/trunk/Lib/idlelib/NEWS.txt (original) +++ python/trunk/Lib/idlelib/NEWS.txt Tue Feb 6 00:02:16 2007 @@ -3,6 +3,9 @@ *Release date: XX-XXX-200X* +- Calltips now 'handle' tuples in the argument list (display '' :) + Suggested solution by Christos Georgiou, Bug 791968. + - Add 'raw' support to configHandler. Patch 1650174 Tal Einat. - Avoid hang when encountering a duplicate in a completion list. Bug 1571112. From python-checkins at python.org Tue Feb 6 00:45:30 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 6 Feb 2007 00:45:30 +0100 (CET) Subject: [Python-checkins] r53642 - sandbox/trunk/import_in_py/controlled_importlib.py sandbox/trunk/import_in_py/test_controlled_importlib.py Message-ID: <20070205234530.6E5DF1E400E@bag.python.org> Author: brett.cannon Date: Tue Feb 6 00:45:29 2007 New Revision: 53642 Modified: sandbox/trunk/import_in_py/controlled_importlib.py sandbox/trunk/import_in_py/test_controlled_importlib.py Log: Add support for importing any .py file but blocking all .pyc files. That means that an entry on sys.path_hooks is now added by ControlledImport.__init__. Also added tests to make sure that __loader__ attributes are not exposed on the modules. Modified: sandbox/trunk/import_in_py/controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/controlled_importlib.py Tue Feb 6 00:45:29 2007 @@ -73,7 +73,7 @@ def handle_code(self, loader, mod_name, extension_path, package=None): if mod_name in self._whitelist: - return super(WhitelistExtHandler, self).handle_code(loder, mod_name, + return super(WhitelistExtHandler, self).handle_code(loader, mod_name, extension_path, package) raise ImportError("not allowed to load module") @@ -96,9 +96,12 @@ sys.meta_path.append(WhitelistBuiltin(safe_builtins)) sys.meta_path.append(WhitelistFrozen(safe_frozen)) # Whitelist extension modules on sys.path. - # XXX + ext_handler = WhitelistExtHandler(safe_extensions) # Allow all .py files but not .pyc files on sys.path. - # XXX + py_handler = importlib.PyPycHandler(bytecode_handles=()) + # Put .py and extension handlers into a path_hooks factory. + fs_factory = importlib.FileSystemFactory(ext_handler, py_handler) + sys.path_hooks.append(fs_factory) def module_from_cache(self, name): """Override so that any module name starting with a dot raises Modified: sandbox/trunk/import_in_py/test_controlled_importlib.py ============================================================================== --- sandbox/trunk/import_in_py/test_controlled_importlib.py (original) +++ sandbox/trunk/import_in_py/test_controlled_importlib.py Tue Feb 6 00:45:29 2007 @@ -1,6 +1,7 @@ import controlled_importlib import importlib import mock_importlib +import test_importlib from contextlib import contextmanager, nested import os @@ -228,9 +229,13 @@ self.failUnless(not hasattr(stripped_module, '__loader__')) -class ControlledImportUsageTests(unittest.TestCase): +class ControlledImportUsageTests(test_importlib.TestPyPycPackages): """Make sure that usage of ControlledImport works properly.""" + + def setUp(self): + """Create .py and .pyc files for testing purposes.""" + super(ControlledImportUsageTests, self).setUp(faked_names=False) def test_block_dot_modules(self): # Modules with a leading dot should not be imported. @@ -271,18 +276,50 @@ def test_pyc_blocking(self): - # XXX - pass + # Importing of a .pyc file should fail. Also, no .pyc should be + # generated. + with remove_from_sys_modules(self.module_name): + import_ = controlled_importlib.ControlledImport() + os.unlink(self.py_path) + assert os.path.exists(self.pyc_path) + self.failUnlessRaises(ImportError, import_, self.module_name, + level=0) def test_py(self): - # XXX try importing something with the same name as a built-in that is - # not whitelisted. - pass + # Should be able to import a .py module. + with remove_from_sys_modules(self.module_name): + os.unlink(self.pyc_path) + import_ = controlled_importlib.ControlledImport() + self.failUnless(import_(self.module_name, level=0)) + + def test_no_pyc_creation(self): + # No .pyc file should be created by importing a .py file. + with remove_from_sys_modules(self.module_name): + os.unlink(self.pyc_path) + assert os.path.exists(self.py_path) + assert not os.path.exists(self.pyc_path) + import_ = controlled_importlib.ControlledImport() + module = import_(self.module_name, level=0) + self.failUnless(module) + self.failUnless(not os.path.exists(self.pyc_path)) def test_no_loader_attribute(self): # No __loader__ attribute should be exposed on any module or package. - # XXX check both modules, packages, and submodules. - pass + # Purposefully skipped the sub-package to make sure that implicit + # imports of dependencies does not leave __loader__ on by importing a + # module in the sub-package. + module_names = [self.top_level_module_name, self.pkg_name, + self.pkg_module_name, self.sub_pkg_module_name] + assert self.sub_pkg_name not in module_names + with remove_from_sys_modules(*module_names): + import_ = controlled_importlib.ControlledImport() + for module_name in module_names: + module = import_(module_name, level=0) + self.failUnless(not hasattr(sys.modules[module_name], + '__loader__')) + else: + self.failUnless(not hasattr(sys.modules[self.sub_pkg_name], + '__loader__')) def test_relative_import(self): # A relative import within a package should not be able to circumvent From buildbot at python.org Tue Feb 6 00:54:17 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 05 Feb 2007 23:54:17 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 trunk Message-ID: <20070205235417.918BC1E400B@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%2520trunk/builds/1381 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket sincerely, -The Buildbot From python-checkins at python.org Tue Feb 6 03:39:18 2007 From: python-checkins at python.org (collin.winter) Date: Tue, 6 Feb 2007 03:39:18 +0100 (CET) Subject: [Python-checkins] r53643 - peps/trunk/pep-3107.txt Message-ID: <20070206023918.870BC1E400B@bag.python.org> Author: collin.winter Date: Tue Feb 6 03:39:18 2007 New Revision: 53643 Modified: peps/trunk/pep-3107.txt Log: Mention that a reference implementation has been checked in Modified: peps/trunk/pep-3107.txt ============================================================================== --- peps/trunk/pep-3107.txt (original) +++ peps/trunk/pep-3107.txt Tue Feb 6 03:39:18 2007 @@ -236,8 +236,8 @@ Implementation ============== -A sample implementation for the syntax changes has been provided -[#implementation]_ by Tony Lownds. +A reference implementation has been checked into the p3yk branch +as revision 53170 [#implementation]_. Rejected Proposals @@ -297,7 +297,7 @@ http://mail.python.org/pipermail/python-3000/2006-June/002438.html .. [#implementation] - http://python.org/sf/1607548 + http://svn.python.org/view?rev=53170&view=rev .. [#grammar] http://www.python.org/doc/current/ref/function.html From python-checkins at python.org Tue Feb 6 04:21:41 2007 From: python-checkins at python.org (kurt.kaiser) Date: Tue, 6 Feb 2007 04:21:41 +0100 (CET) Subject: [Python-checkins] r53644 - python/trunk/Lib/idlelib/PyShell.py Message-ID: <20070206032141.1852A1E400B@bag.python.org> Author: kurt.kaiser Date: Tue Feb 6 04:21:40 2007 New Revision: 53644 Modified: python/trunk/Lib/idlelib/PyShell.py Log: Clean up ModifiedInterpreter.runcode() structure Modified: python/trunk/Lib/idlelib/PyShell.py ============================================================================== --- python/trunk/Lib/idlelib/PyShell.py (original) +++ python/trunk/Lib/idlelib/PyShell.py Tue Feb 6 04:21:40 2007 @@ -706,35 +706,37 @@ debugger = self.debugger try: self.tkconsole.beginexecuting() - try: - if not debugger and self.rpcclt is not None: - self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", - (code,), {}) - elif debugger: - debugger.run(code, self.locals) - else: - exec code in self.locals - except SystemExit: - if not self.tkconsole.closing: - if tkMessageBox.askyesno( - "Exit?", - "Do you want to exit altogether?", - default="yes", - master=self.tkconsole.text): - raise - else: - self.showtraceback() - else: + if not debugger and self.rpcclt is not None: + self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", + (code,), {}) + elif debugger: + debugger.run(code, self.locals) + else: + exec code in self.locals + except SystemExit: + if not self.tkconsole.closing: + if tkMessageBox.askyesno( + "Exit?", + "Do you want to exit altogether?", + default="yes", + master=self.tkconsole.text): raise - except: - if use_subprocess: - # When run w/o subprocess, both user and IDLE errors - # are printed here; skip message in that case. - print >> self.tkconsole.stderr, \ - "IDLE internal error in runcode()" + else: + self.showtraceback() + else: + raise + except: + if use_subprocess: + print >>self.tkconsole.stderr, \ + "IDLE internal error in runcode()" self.showtraceback() - if use_subprocess: - self.tkconsole.endexecuting() + self.tkconsole.endexecuting() + else: + if self.tkconsole.canceled: + self.tkconsole.canceled = False + print >>self.tkconsole.stderr, "KeyboardInterrupt" + else: + self.showtraceback() finally: if not use_subprocess: try: From buildbot at python.org Tue Feb 6 04:59:20 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 06 Feb 2007 03:59:20 +0000 Subject: [Python-checkins] buildbot warnings in ppc Debian unstable trunk Message-ID: <20070206035920.BE5841E400B@bag.python.org> The Buildbot has detected a new failure of ppc Debian unstable trunk. Full details are available at: http://www.python.org/dev/buildbot/all/ppc%2520Debian%2520unstable%2520trunk/builds/44 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_bsddb3 Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 378, in writerThread self.doWrite(d, name, x, min(stop, x+step)) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 366, in doWrite txn.abort() DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery -- PANIC: DB_NOTFOUND: No matching key/data pair found') Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 426, in readerThread rec = c.next() DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery') Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 378, in writerThread self.doWrite(d, name, x, min(stop, x+step)) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 358, in doWrite d.put(key, self.makeData(key), txn) DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery -- PANIC: fatal region error detected; run recovery') Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 426, in readerThread rec = c.next() DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery -- PANIC: fatal region error detected; run recovery') Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 426, in readerThread rec = c.next() DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery') Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 426, in readerThread rec = c.next() DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery') Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 426, in readerThread rec = c.next() DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery -- PANIC: fatal region error detected; run recovery') Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 378, in writerThread self.doWrite(d, name, x, min(stop, x+step)) File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 358, in doWrite d.put(key, self.makeData(key), txn) DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery -- PANIC: fatal region error detected; run recovery') ====================================================================== ERROR: test03_ThreadedTransactions (bsddb.test.test_thread.BTreeThreadedTransactions) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 73, in tearDown self.d.close() DBRunRecoveryError: (-30974, 'DB_RUNRECOVERY: Fatal error, run database recovery -- PANIC: fatal region error detected; run recovery') ====================================================================== ERROR: test03_ThreadedTransactions (bsddb.test.test_thread.HashThreadedTransactions) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 64, in setUp self.env.open(homeDir, self.envflags | db.DB_CREATE) DBNoSuchFileError: (2, 'No such file or directory -- /tmp/db_home/__db.001: unable to find environment') ====================================================================== ERROR: test03_ThreadedTransactions (bsddb.test.test_thread.BTreeThreadedNoWaitTransactions) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 64, in setUp self.env.open(homeDir, self.envflags | db.DB_CREATE) DBNoSuchFileError: (2, 'No such file or directory -- /tmp/db_home/__db.001: unable to find environment') ====================================================================== ERROR: test03_ThreadedTransactions (bsddb.test.test_thread.HashThreadedNoWaitTransactions) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/bsddb/test/test_thread.py", line 64, in setUp self.env.open(homeDir, self.envflags | db.DB_CREATE) DBNoSuchFileError: (2, 'No such file or directory -- /tmp/db_home/__db.001: unable to find environment') make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Tue Feb 6 05:01:00 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 06 Feb 2007 04:01:00 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian trunk Message-ID: <20070206040100.A997B1E400B@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%2520trunk/builds/44 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_bsddb3 make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Tue Feb 6 13:55:27 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 6 Feb 2007 13:55:27 +0100 (CET) Subject: [Python-checkins] r53645 - sandbox/trunk/setuptools/pydoc.py Message-ID: <20070206125527.3CB601E400C@bag.python.org> Author: phillip.eby Date: Tue Feb 6 13:55:26 2007 New Revision: 53645 Modified: sandbox/trunk/setuptools/pydoc.py Log: Match Python 2.5 pydoc Modified: sandbox/trunk/setuptools/pydoc.py ============================================================================== --- sandbox/trunk/setuptools/pydoc.py (original) +++ sandbox/trunk/setuptools/pydoc.py Tue Feb 6 13:55:26 2007 @@ -321,6 +321,8 @@ # identifies something in a way that pydoc itself has issues handling; # think 'super' and how it is a descriptor (which raises the exception # by lacking a __name__ attribute) and an instance. + if inspect.isgetsetdescriptor(object): return self.docdata(*args) + if inspect.ismemberdescriptor(object): return self.docdata(*args) try: if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) @@ -336,7 +338,7 @@ name and ' ' + repr(name), type(object).__name__) raise TypeError, message - docmodule = docclass = docroutine = docother = fail + docmodule = docclass = docroutine = docother = docproperty = docdata = fail def getdocloc(self, object): """Return the location of module docs or None""" @@ -918,6 +920,10 @@ lhs = name and '%s = ' % name or '' return lhs + self.repr(object) + def docdata(self, object, name=None, mod=None, cl=None): + """Produce html documentation for a data descriptor.""" + return self._docdescriptor(name, object, mod) + def index(self, dir, shadowed=None): """Generate an HTML index for a directory of modules.""" modpkgs = [] @@ -1271,6 +1277,10 @@ """Produce text documentation for a property.""" return self._docdescriptor(name, object, mod) + def docdata(self, object, name=None, mod=None, cl=None): + """Produce text documentation for a data descriptor.""" + return self._docdescriptor(name, object, mod) + def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None): """Produce text documentation for a data object.""" repr = self.repr(object) @@ -1400,6 +1410,14 @@ return 'module ' + thing.__name__ if inspect.isbuiltin(thing): return 'built-in function ' + thing.__name__ + if inspect.isgetsetdescriptor(thing): + return 'getset descriptor %s.%s.%s' % ( + thing.__objclass__.__module__, thing.__objclass__.__name__, + thing.__name__) + if inspect.ismemberdescriptor(thing): + return 'member descriptor %s.%s.%s' % ( + thing.__objclass__.__module__, thing.__objclass__.__name__, + thing.__name__) if inspect.isclass(thing): return 'class ' + thing.__name__ if inspect.isfunction(thing): @@ -1456,6 +1474,8 @@ 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 the passed object is a piece of data or an instance, # document its available methods instead of its value. From python-checkins at python.org Tue Feb 6 16:37:51 2007 From: python-checkins at python.org (peter.astrand) Date: Tue, 6 Feb 2007 16:37:51 +0100 (CET) Subject: [Python-checkins] r53646 - in python/trunk: Lib/subprocess.py Misc/NEWS Message-ID: <20070206153751.7979E1E400F@bag.python.org> Author: peter.astrand Date: Tue Feb 6 16:37:50 2007 New Revision: 53646 Modified: python/trunk/Lib/subprocess.py python/trunk/Misc/NEWS Log: Applied patch 1124861.3.patch to solve bug #1124861: Automatically create pipes on Windows, if GetStdHandle fails. Will backport. Modified: python/trunk/Lib/subprocess.py ============================================================================== --- python/trunk/Lib/subprocess.py (original) +++ python/trunk/Lib/subprocess.py Tue Feb 6 16:37:50 2007 @@ -592,6 +592,22 @@ c2pread, c2pwrite, errread, errwrite) + # On Windows, you cannot just redirect one or two handles: You + # either have to redirect all three or none. If the subprocess + # user has only redirected one or two handles, we are + # automatically creating PIPEs for the rest. We should close + # these after the process is started. See bug #1124861. + if mswindows: + if stdin is None and p2cwrite is not None: + os.close(p2cwrite) + p2cwrite = None + if stdout is None and c2pread is not None: + os.close(c2pread) + c2pread = None + if stderr is None and errread is not None: + os.close(errread) + errread = None + if p2cwrite is not None: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) if c2pread is not None: @@ -668,7 +684,9 @@ if stdin is None: p2cread = GetStdHandle(STD_INPUT_HANDLE) - elif stdin == PIPE: + if p2cread is not None: + pass + elif stdin is None or stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) # Detach and turn into fd p2cwrite = p2cwrite.Detach() @@ -682,7 +700,9 @@ if stdout is None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) - elif stdout == PIPE: + if c2pwrite is not None: + pass + elif stdout is None or stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) # Detach and turn into fd c2pread = c2pread.Detach() @@ -696,7 +716,9 @@ if stderr is None: errwrite = GetStdHandle(STD_ERROR_HANDLE) - elif stderr == PIPE: + if errwrite is not None: + pass + elif stderr is None or stderr == PIPE: errread, errwrite = CreatePipe(None, 0) # Detach and turn into fd errread = errread.Detach() Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue Feb 6 16:37:50 2007 @@ -126,6 +126,9 @@ Library ------- +- Bug #1124861: Automatically create pipes if GetStdHandle fails in + subprocess. + - Patch #1634778: add missing encoding aliases for iso8859_15 and iso8859_16. From python-checkins at python.org Tue Feb 6 16:41:47 2007 From: python-checkins at python.org (peter.astrand) Date: Tue, 6 Feb 2007 16:41:47 +0100 (CET) Subject: [Python-checkins] r53647 - in python/branches/release25-maint: Lib/subprocess.py Misc/NEWS Message-ID: <20070206154147.E1D541E4016@bag.python.org> Author: peter.astrand Date: Tue Feb 6 16:41:46 2007 New Revision: 53647 Modified: python/branches/release25-maint/Lib/subprocess.py python/branches/release25-maint/Misc/NEWS Log: Applied patch 1124861.3.patch to solve bug #1124861: Automatically create pipes on Windows, if GetStdHandle fails. Backport from rev 53646. Modified: python/branches/release25-maint/Lib/subprocess.py ============================================================================== --- python/branches/release25-maint/Lib/subprocess.py (original) +++ python/branches/release25-maint/Lib/subprocess.py Tue Feb 6 16:41:46 2007 @@ -592,6 +592,22 @@ c2pread, c2pwrite, errread, errwrite) + # On Windows, you cannot just redirect one or two handles: You + # either have to redirect all three or none. If the subprocess + # user has only redirected one or two handles, we are + # automatically creating PIPEs for the rest. We should close + # these after the process is started. See bug #1124861. + if mswindows: + if stdin is None and p2cwrite is not None: + os.close(p2cwrite) + p2cwrite = None + if stdout is None and c2pread is not None: + os.close(c2pread) + c2pread = None + if stderr is None and errread is not None: + os.close(errread) + errread = None + if p2cwrite: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) if c2pread: @@ -668,7 +684,9 @@ if stdin is None: p2cread = GetStdHandle(STD_INPUT_HANDLE) - elif stdin == PIPE: + if p2cread is not None: + pass + elif stdin is None or stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) # Detach and turn into fd p2cwrite = p2cwrite.Detach() @@ -682,7 +700,9 @@ if stdout is None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) - elif stdout == PIPE: + if c2pwrite is not None: + pass + elif stdout is None or stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) # Detach and turn into fd c2pread = c2pread.Detach() @@ -696,7 +716,9 @@ if stderr is None: errwrite = GetStdHandle(STD_ERROR_HANDLE) - elif stderr == PIPE: + if errwrite is not None: + pass + elif stderr is None or stderr == PIPE: errread, errwrite = CreatePipe(None, 0) # Detach and turn into fd errread = errread.Detach() Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Tue Feb 6 16:41:46 2007 @@ -157,6 +157,9 @@ Library ------- +- Bug #1124861: Automatically create pipes if GetStdHandle fails in + subprocess. + - Patch #783050: the pty.fork() function now closes the slave fd correctly. From buildbot at python.org Tue Feb 6 18:11:02 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 06 Feb 2007 17:11:02 +0000 Subject: [Python-checkins] buildbot warnings in hppa Ubuntu dapper 2.5 Message-ID: <20070206171102.942651E400F@bag.python.org> The Buildbot has detected a new failure of hppa Ubuntu dapper 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/hppa%2520Ubuntu%2520dapper%25202.5/builds/24 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: peter.astrand Build had warnings: warnings test Excerpt from the test logfile: make: *** [buildbottest] Killed sincerely, -The Buildbot From python-checkins at python.org Tue Feb 6 19:38:15 2007 From: python-checkins at python.org (lars.gustaebel) Date: Tue, 6 Feb 2007 19:38:15 +0100 (CET) Subject: [Python-checkins] r53648 - in python/trunk: Doc/lib/libtarfile.tex Lib/tarfile.py Lib/test/test_tarfile.py Misc/NEWS Message-ID: <20070206183815.8D91D1E400F@bag.python.org> Author: lars.gustaebel Date: Tue Feb 6 19:38:13 2007 New Revision: 53648 Modified: python/trunk/Doc/lib/libtarfile.tex python/trunk/Lib/tarfile.py python/trunk/Lib/test/test_tarfile.py python/trunk/Misc/NEWS Log: Patch #1652681: create nonexistent files in append mode and allow appending to empty files. Modified: python/trunk/Doc/lib/libtarfile.tex ============================================================================== --- python/trunk/Doc/lib/libtarfile.tex (original) +++ python/trunk/Doc/lib/libtarfile.tex Tue Feb 6 19:38:13 2007 @@ -36,7 +36,8 @@ \lineii{'r:'}{Open for reading exclusively without compression.} \lineii{'r:gz'}{Open for reading with gzip compression.} \lineii{'r:bz2'}{Open for reading with bzip2 compression.} - \lineii{'a' or 'a:'}{Open for appending with no compression.} + \lineii{'a' or 'a:'}{Open for appending with no compression. The file + is created if it does not exist.} \lineii{'w' or 'w:'}{Open for uncompressed writing.} \lineii{'w:gz'}{Open for gzip compressed writing.} \lineii{'w:bz2'}{Open for bzip2 compressed writing.} Modified: python/trunk/Lib/tarfile.py ============================================================================== --- python/trunk/Lib/tarfile.py (original) +++ python/trunk/Lib/tarfile.py Tue Feb 6 19:38:13 2007 @@ -1060,6 +1060,10 @@ self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode] if not fileobj: + if self._mode == "a" and not os.path.exists(self.name): + # Create nonexistent files in append mode. + self._mode = "w" + self.mode = "wb" fileobj = file(self.name, self.mode) self._extfileobj = False else: @@ -1093,7 +1097,8 @@ self.fileobj.seek(0) break if tarinfo is None: - self.fileobj.seek(- BLOCKSIZE, 1) + if self.offset > 0: + self.fileobj.seek(- BLOCKSIZE, 1) break if self._mode in "aw": @@ -1120,7 +1125,7 @@ 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression - 'a' or 'a:' open for appending + 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression Modified: python/trunk/Lib/test/test_tarfile.py ============================================================================== --- python/trunk/Lib/test/test_tarfile.py (original) +++ python/trunk/Lib/test/test_tarfile.py Tue Feb 6 19:38:13 2007 @@ -305,6 +305,61 @@ self.assertEqual(self.dst.getnames(), [], "added the archive to itself") +class AppendTest(unittest.TestCase): + # Test append mode (cp. patch #1652681). + + def setUp(self): + self.tarname = tmpname() + if os.path.exists(self.tarname): + os.remove(self.tarname) + + def _add_testfile(self, fileobj=None): + tar = tarfile.open(self.tarname, "a", fileobj=fileobj) + tar.addfile(tarfile.TarInfo("bar")) + tar.close() + + def _create_testtar(self): + src = tarfile.open(tarname()) + t = src.getmember("0-REGTYPE") + t.name = "foo" + f = src.extractfile(t) + tar = tarfile.open(self.tarname, "w") + tar.addfile(t, f) + tar.close() + + def _test(self, names=["bar"], fileobj=None): + tar = tarfile.open(self.tarname, fileobj=fileobj) + self.assert_(tar.getnames() == names) + + def test_non_existing(self): + self._add_testfile() + self._test() + + def test_empty(self): + open(self.tarname, "w").close() + self._add_testfile() + self._test() + + def test_empty_fileobj(self): + fobj = StringIO.StringIO() + self._add_testfile(fobj) + fobj.seek(0) + self._test(fileobj=fobj) + + def test_fileobj(self): + self._create_testtar() + data = open(self.tarname).read() + fobj = StringIO.StringIO(data) + self._add_testfile(fobj) + fobj.seek(0) + self._test(names=["foo", "bar"], fileobj=fobj) + + def test_existing(self): + self._create_testtar() + self._add_testfile() + self._test(names=["foo", "bar"]) + + class Write100Test(BaseTest): # The name field in a tar header stores strings of at most 100 chars. # If a string is shorter than 100 chars it has to be padded with '\0', @@ -711,6 +766,7 @@ ReadAsteriskTest, ReadStreamAsteriskTest, WriteTest, + AppendTest, Write100Test, WriteSize0Test, WriteStreamTest, Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue Feb 6 19:38:13 2007 @@ -126,6 +126,9 @@ Library ------- +- Patch #1652681: tarfile.py: create nonexistent files in append mode and + allow appending to empty files. + - Bug #1124861: Automatically create pipes if GetStdHandle fails in subprocess. From buildbot at python.org Tue Feb 6 20:06:21 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 06 Feb 2007 19:06:21 +0000 Subject: [Python-checkins] buildbot warnings in x86 W2k trunk Message-ID: <20070206190621.C83B61E400F@bag.python.org> The Buildbot has detected a new failure of x86 W2k trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520W2k%2520trunk/builds/63 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: lars.gustaebel Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_tarfile ====================================================================== ERROR: test_fileobj (test.test_tarfile.AppendTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\trentm\data\buildbot\python-slave\trunk.mick-windows\build\lib\test\test_tarfile.py", line 355, in test_fileobj self._test(names=["foo", "bar"], fileobj=fobj) File "C:\trentm\data\buildbot\python-slave\trunk.mick-windows\build\lib\test\test_tarfile.py", line 331, in _test tar = tarfile.open(self.tarname, fileobj=fileobj) File "C:\trentm\data\buildbot\python-slave\trunk.mick-windows\build\lib\tarfile.py", line 1157, in open raise ReadError("file could not be opened successfully") ReadError: file could not be opened successfully sincerely, -The Buildbot From python-checkins at python.org Tue Feb 6 20:09:44 2007 From: python-checkins at python.org (kurt.kaiser) Date: Tue, 6 Feb 2007 20:09:44 +0100 (CET) Subject: [Python-checkins] r53649 - python/trunk/Lib/idlelib/CodeContext.py Message-ID: <20070206190944.C6C6D1E4013@bag.python.org> Author: kurt.kaiser Date: Tue Feb 6 20:09:43 2007 New Revision: 53649 Modified: python/trunk/Lib/idlelib/CodeContext.py Log: Updated patch (CodeContext.061217.patch) to [ 1362975 ] CodeContext - Improved text indentation Tal Einat 16Dec06 Modified: python/trunk/Lib/idlelib/CodeContext.py ============================================================================== --- python/trunk/Lib/idlelib/CodeContext.py (original) +++ python/trunk/Lib/idlelib/CodeContext.py Tue Feb 6 20:09:43 2007 @@ -10,6 +10,7 @@ """ import Tkinter +from Tkconstants import TOP, LEFT, X, W, SUNKEN from configHandler import idleConf import re from sys import maxint as INFINITY @@ -24,7 +25,6 @@ class CodeContext: menudefs = [('options', [('!Code Conte_xt', '<>')])] - context_depth = idleConf.GetOption("extensions", "CodeContext", "numlines", type="int", default=3) bgcolor = idleConf.GetOption("extensions", "CodeContext", @@ -54,66 +54,33 @@ def toggle_code_context_event(self, event=None): if not self.label: - # The following code attempts to figure out the required border - # width and vertical padding required for the CodeContext widget - # to be perfectly aligned with the text in the main Text widget. - # This is done by retrieving the appropriate attributes from the - # editwin.text and editwin.text_frame widgets. + # Calculate the border width and horizontal padding required to + # align the context with the text in the main Text widget. # # All values are passed through int(str()), since some - # values may be pixel objects, which can't simply be added added - # to ints. - # - # This code is considered somewhat unstable since it relies on - # some of Tk's inner workings. However its effect is merely - # cosmetic; failure will only cause the CodeContext text to be - # somewhat misaligned with the text in the main Text widget. - # - # To avoid possible errors, all references to the inner workings - # of Tk are executed inside try/except blocks. - - widgets_for_width_calc = self.editwin.text, self.editwin.text_frame - - # calculate the required vertical padding + # values may be pixel objects, which can't simply be added to ints. + widgets = self.editwin.text, self.editwin.text_frame + # Calculate the required vertical padding padx = 0 - for widget in widgets_for_width_calc: - try: - # retrieve the "padx" attribte from widget's pack info - padx += int(str( widget.pack_info()['padx'] )) - except: - pass - try: - # retrieve the widget's "padx" attribte - padx += int(str( widget.cget('padx') )) - except: - pass - - # calculate the required border width - border_width = 0 - for widget in widgets_for_width_calc: - try: - # retrieve the widget's "border" attribte - border_width += int(str( widget.cget('border') )) - except: - pass - + for widget in widgets: + padx += int(str( widget.pack_info()['padx'] )) + padx += int(str( widget.cget('padx') )) + # Calculate the required border width + border = 0 + for widget in widgets: + border += int(str( widget.cget('border') )) self.label = Tkinter.Label(self.editwin.top, text="\n" * (self.context_depth - 1), - anchor="w", justify="left", + anchor=W, justify=LEFT, font=self.textfont, bg=self.bgcolor, fg=self.fgcolor, width=1, #don't request more than we get - padx=padx, #line up with text widget - border=border_width, #match border width - relief="sunken", - ) - - # CodeContext's label widget is packed before and above the - # text_frame widget, thus ensuring that it will appear directly - # above it. - self.label.pack(side="top", fill="x", expand=False, + padx=padx, border=border, + relief=SUNKEN) + # Pack the label widget before and above the text_frame widget, + # thus ensuring that it will appear directly above text_frame + self.label.pack(side=TOP, fill=X, expand=False, before=self.editwin.text_frame) - else: self.label.destroy() self.label = None @@ -190,7 +157,6 @@ stopindent) self.info.extend(lines) self.topvisible = new_topvisible - # empty lines in context pane: context_strings = [""] * max(0, self.context_depth - len(self.info)) # followed by the context hint lines: From python-checkins at python.org Tue Feb 6 20:21:19 2007 From: python-checkins at python.org (kurt.kaiser) Date: Tue, 6 Feb 2007 20:21:19 +0100 (CET) Subject: [Python-checkins] r53650 - python/trunk/Lib/idlelib/IOBinding.py Message-ID: <20070206192119.C72131E400F@bag.python.org> Author: kurt.kaiser Date: Tue Feb 6 20:21:19 2007 New Revision: 53650 Modified: python/trunk/Lib/idlelib/IOBinding.py Log: narrow exception per [ 1540849 ] except too broad Modified: python/trunk/Lib/idlelib/IOBinding.py ============================================================================== --- python/trunk/Lib/idlelib/IOBinding.py (original) +++ python/trunk/Lib/idlelib/IOBinding.py Tue Feb 6 20:21:19 2007 @@ -209,7 +209,7 @@ # gets set to "not modified" at every new prompt. try: interp = self.editwin.interp - except: + except AttributeError: interp = None if not self.filename and self.get_saved() and not interp: self.editwin.flist.open(filename, self.loadfile) From buildbot at python.org Tue Feb 6 20:42:31 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 06 Feb 2007 19:42:31 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian trunk Message-ID: <20070206194231.303771E400F@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%2520trunk/builds/47 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: make: *** [buildbottest] Segmentation fault sincerely, -The Buildbot From buildbot at python.org Tue Feb 6 20:47:34 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 06 Feb 2007 19:47:34 +0000 Subject: [Python-checkins] buildbot warnings in ppc Debian unstable trunk Message-ID: <20070206194734.C33901E4010@bag.python.org> The Buildbot has detected a new failure of ppc Debian unstable trunk. Full details are available at: http://www.python.org/dev/buildbot/all/ppc%2520Debian%2520unstable%2520trunk/builds/47 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_bsddb3 make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Tue Feb 6 22:33:24 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 06 Feb 2007 21:33:24 +0000 Subject: [Python-checkins] buildbot warnings in hppa Ubuntu dapper trunk Message-ID: <20070206213325.014131E400F@bag.python.org> The Buildbot has detected a new failure of hppa Ubuntu dapper trunk. Full details are available at: http://www.python.org/dev/buildbot/all/hppa%2520Ubuntu%2520dapper%2520trunk/builds/60 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From python-checkins at python.org Wed Feb 7 04:39:42 2007 From: python-checkins at python.org (kurt.kaiser) Date: Wed, 7 Feb 2007 04:39:42 +0100 (CET) Subject: [Python-checkins] r53653 - python/trunk/Lib/idlelib/AutoCompleteWindow.py python/trunk/Lib/idlelib/NEWS.txt Message-ID: <20070207033942.7AADD1E4010@bag.python.org> Author: kurt.kaiser Date: Wed Feb 7 04:39:41 2007 New Revision: 53653 Modified: python/trunk/Lib/idlelib/AutoCompleteWindow.py python/trunk/Lib/idlelib/NEWS.txt Log: [ 1621265 ] Auto-completion list placement Move AC window below input line unless not enough space, then put it above. Patch: Tal Einat Modified: python/trunk/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/trunk/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/trunk/Lib/idlelib/AutoCompleteWindow.py Wed Feb 7 04:39:41 2007 @@ -215,13 +215,22 @@ if not self.is_active(): return # Position the completion list window + text = self.widget + text.see(self.startindex) + x, y, cx, cy = text.bbox(self.startindex) acw = self.autocompletewindow - self.widget.see(self.startindex) - x, y, cx, cy = self.widget.bbox(self.startindex) - acw.wm_geometry("+%d+%d" % (x + self.widget.winfo_rootx(), - y + self.widget.winfo_rooty() \ - -acw.winfo_height())) - + acw_width, acw_height = acw.winfo_width(), acw.winfo_height() + text_width, text_height = text.winfo_width(), text.winfo_height() + new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width)) + new_y = text.winfo_rooty() + y + if (text_height - (y + cy) >= acw_height # enough height below + or y < acw_height): # not enough height above + # place acw below current line + new_y += cy + else: + # place acw above current line + new_y -= acw_height + acw.wm_geometry("+%d+%d" % (new_x, new_y)) def hide_event(self, event): if not self.is_active(): Modified: python/trunk/Lib/idlelib/NEWS.txt ============================================================================== --- python/trunk/Lib/idlelib/NEWS.txt (original) +++ python/trunk/Lib/idlelib/NEWS.txt Wed Feb 7 04:39:41 2007 @@ -3,6 +3,9 @@ *Release date: XX-XXX-200X* +- AutoCompleteWindow moved below input line, will move above if there + isn't enough space. Patch 1621265 Tal Einat + - Calltips now 'handle' tuples in the argument list (display '' :) Suggested solution by Christos Georgiou, Bug 791968. From buildbot at python.org Wed Feb 7 05:32:55 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 04:32:55 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 trunk Message-ID: <20070207043255.DFBD21E4010@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%2520trunk/builds/1386 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_signal test_socket sincerely, -The Buildbot From python-checkins at python.org Wed Feb 7 09:07:13 2007 From: python-checkins at python.org (kurt.kaiser) Date: Wed, 7 Feb 2007 09:07:13 +0100 (CET) Subject: [Python-checkins] r53654 - python/trunk/Lib/idlelib/CallTips.py Message-ID: <20070207080713.D0F6C1E4010@bag.python.org> Author: kurt.kaiser Date: Wed Feb 7 09:07:13 2007 New Revision: 53654 Modified: python/trunk/Lib/idlelib/CallTips.py Log: Handle AttributeError during calltip lookup Modified: python/trunk/Lib/idlelib/CallTips.py ============================================================================== --- python/trunk/Lib/idlelib/CallTips.py (original) +++ python/trunk/Lib/idlelib/CallTips.py Wed Feb 7 09:07:13 2007 @@ -112,7 +112,7 @@ namespace.update(__main__.__dict__) try: return eval(name, namespace) - except NameError: + except (NameError, AttributeError): return None def _find_constructor(class_ob): From buildbot at python.org Wed Feb 7 09:27:08 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 08:27:08 +0000 Subject: [Python-checkins] buildbot warnings in hppa Ubuntu dapper trunk Message-ID: <20070207082708.6FCB31E4010@bag.python.org> The Buildbot has detected a new failure of hppa Ubuntu dapper trunk. Full details are available at: http://www.python.org/dev/buildbot/all/hppa%2520Ubuntu%2520dapper%2520trunk/builds/62 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: make: *** [buildbottest] Killed sincerely, -The Buildbot From buildbot at python.org Wed Feb 7 10:06:28 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 09:06:28 +0000 Subject: [Python-checkins] buildbot failure in x86 gentoo 2.5 Message-ID: <20070207090628.74B0C1E4006@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/209 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Colten': Jacoby Build Source Stamp: [branch Israel] Sheldon Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Wed Feb 7 10:06:36 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 09:06:36 +0000 Subject: [Python-checkins] buildbot failure in sparc solaris10 gcc 2.5 Message-ID: <20070207090636.D5FAD1E4006@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%25202.5/builds/202 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Darien': Dontae Build Source Stamp: [branch Anderson] Jaylen Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Wed Feb 7 10:12:46 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 09:12:46 +0000 Subject: [Python-checkins] buildbot failure in amd64 gentoo 2.5 Message-ID: <20070207091246.E1A861E4006@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%25202.5/builds/212 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Brant': Daren Build Source Stamp: [branch Brock] Tyshawn Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Wed Feb 7 10:17:07 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 09:17:07 +0000 Subject: [Python-checkins] buildbot failure in x86 OpenBSD 2.5 Message-ID: <20070207091707.A79621E4006@bag.python.org> The Buildbot has detected a new failure of x86 OpenBSD 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520OpenBSD%25202.5/builds/191 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Jaylin': Maximus Build Source Stamp: [branch Stephen] Ricardo Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Wed Feb 7 12:57:25 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 11:57:25 +0000 Subject: [Python-checkins] buildbot failure in g4 osx.4 2.5 Message-ID: <20070207115726.07DC61E4010@bag.python.org> The Buildbot has detected a new failure of g4 osx.4 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/g4%2520osx.4%25202.5/builds/199 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Elvis': Jabari Build Source Stamp: [branch Milton] Josef Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From python-checkins at python.org Wed Feb 7 21:01:29 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 7 Feb 2007 21:01:29 +0100 (CET) Subject: [Python-checkins] r53655 - in python/branches/release25-maint: Lib/test/test_dict.py Objects/dictobject.c Message-ID: <20070207200129.B2D161E4013@bag.python.org> Author: raymond.hettinger Date: Wed Feb 7 21:01:28 2007 New Revision: 53655 Modified: python/branches/release25-maint/Lib/test/test_dict.py python/branches/release25-maint/Objects/dictobject.c Log: SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses Modified: python/branches/release25-maint/Lib/test/test_dict.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_dict.py (original) +++ python/branches/release25-maint/Lib/test/test_dict.py Wed Feb 7 21:01:28 2007 @@ -189,6 +189,14 @@ self.assertRaises(ValueError, {}.update, [(1, 2, 3)]) + # SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses + class KeyUpperDict(dict): + def __getitem__(self, key): + return key.upper() + d.clear() + d.update(KeyUpperDict.fromkeys('abc')) + self.assertEqual(d, {'a':'A', 'b':'B', 'c':'C'}) + def test_fromkeys(self): self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = {} Modified: python/branches/release25-maint/Objects/dictobject.c ============================================================================== --- python/branches/release25-maint/Objects/dictobject.c (original) +++ python/branches/release25-maint/Objects/dictobject.c Wed Feb 7 21:01:28 2007 @@ -1306,7 +1306,7 @@ return -1; } mp = (dictobject*)a; - if (PyDict_Check(b)) { + if (PyDict_CheckExact(b)) { other = (dictobject*)b; if (other == mp || other->ma_used == 0) /* a.update(a) or a.update({}); nothing to do */ From python-checkins at python.org Wed Feb 7 21:08:56 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 7 Feb 2007 21:08:56 +0100 (CET) Subject: [Python-checkins] r53656 - in python/trunk: Lib/test/test_dict.py Objects/dictobject.c Message-ID: <20070207200856.B31AA1E4013@bag.python.org> Author: raymond.hettinger Date: Wed Feb 7 21:08:22 2007 New Revision: 53656 Modified: python/trunk/Lib/test/test_dict.py python/trunk/Objects/dictobject.c Log: SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses Modified: python/trunk/Lib/test/test_dict.py ============================================================================== --- python/trunk/Lib/test/test_dict.py (original) +++ python/trunk/Lib/test/test_dict.py Wed Feb 7 21:08:22 2007 @@ -189,6 +189,14 @@ self.assertRaises(ValueError, {}.update, [(1, 2, 3)]) + # SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses + class KeyUpperDict(dict): + def __getitem__(self, key): + return key.upper() + d.clear() + d.update(KeyUpperDict.fromkeys('abc')) + self.assertEqual(d, {'a':'A', 'b':'B', 'c':'C'}) + def test_fromkeys(self): self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = {} Modified: python/trunk/Objects/dictobject.c ============================================================================== --- python/trunk/Objects/dictobject.c (original) +++ python/trunk/Objects/dictobject.c Wed Feb 7 21:08:22 2007 @@ -1306,7 +1306,7 @@ return -1; } mp = (dictobject*)a; - if (PyDict_Check(b)) { + if (PyDict_CheckExact(b)) { other = (dictobject*)b; if (other == mp || other->ma_used == 0) /* a.update(a) or a.update({}); nothing to do */ From buildbot at python.org Wed Feb 7 21:39:42 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 20:39:42 +0000 Subject: [Python-checkins] buildbot warnings in x86 mvlgcc 2.5 Message-ID: <20070207203943.038E71E4005@bag.python.org> The Buildbot has detected a new failure of x86 mvlgcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520mvlgcc%25202.5/builds/106 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_urllib2net make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Wed Feb 7 21:48:18 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 20:48:18 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian 2.5 Message-ID: <20070207204819.0E5691E4033@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%25202.5/builds/17 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_urllib2net make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Wed Feb 7 22:03:05 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 21:03:05 +0000 Subject: [Python-checkins] buildbot warnings in sparc solaris10 gcc 2.5 Message-ID: <20070207210306.1CD421E4016@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%25202.5/builds/206 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_codecmaps_jp test_codecmaps_kr sincerely, -The Buildbot From python-checkins at python.org Wed Feb 7 22:03:25 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 7 Feb 2007 22:03:25 +0100 (CET) Subject: [Python-checkins] r53657 - python/branches/release25-maint/Doc/lib/libstdtypes.tex Message-ID: <20070207210325.906A21E4013@bag.python.org> Author: raymond.hettinger Date: Wed Feb 7 22:03:24 2007 New Revision: 53657 Modified: python/branches/release25-maint/Doc/lib/libstdtypes.tex Log: SF: 1397711 Set docs conflated immutable and hashable Modified: python/branches/release25-maint/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libstdtypes.tex (original) +++ python/branches/release25-maint/Doc/lib/libstdtypes.tex Wed Feb 7 22:03:24 2007 @@ -1224,7 +1224,7 @@ \label{types-set}} \obindex{set} -A \dfn{set} object is an unordered collection of immutable values. +A \dfn{set} object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. From python-checkins at python.org Wed Feb 7 22:04:21 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 7 Feb 2007 22:04:21 +0100 (CET) Subject: [Python-checkins] r53658 - python/trunk/Doc/lib/libstdtypes.tex Message-ID: <20070207210421.18DEA1E401E@bag.python.org> Author: raymond.hettinger Date: Wed Feb 7 22:04:20 2007 New Revision: 53658 Modified: python/trunk/Doc/lib/libstdtypes.tex Log: SF: 1397711 Set docs conflated immutable and hashable Modified: python/trunk/Doc/lib/libstdtypes.tex ============================================================================== --- python/trunk/Doc/lib/libstdtypes.tex (original) +++ python/trunk/Doc/lib/libstdtypes.tex Wed Feb 7 22:04:20 2007 @@ -1224,7 +1224,7 @@ \label{types-set}} \obindex{set} -A \dfn{set} object is an unordered collection of immutable values. +A \dfn{set} object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. From buildbot at python.org Wed Feb 7 22:20:51 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 21:20:51 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) 2.5 Message-ID: <20070207212051.BEE431E4037@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%25202.5/builds/153 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildbot/Buildbot/2.5.baxter-ubuntu/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (3.24533) is more than 2 seconds more than expected (0.001) sincerely, -The Buildbot From python-checkins at python.org Wed Feb 7 22:40:51 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 7 Feb 2007 22:40:51 +0100 (CET) Subject: [Python-checkins] r53659 - in python/branches/release25-maint: Lib/test/test_defaultdict.py Misc/NEWS Modules/collectionsmodule.c Message-ID: <20070207214051.490D31E4027@bag.python.org> Author: raymond.hettinger Date: Wed Feb 7 22:40:49 2007 New Revision: 53659 Modified: python/branches/release25-maint/Lib/test/test_defaultdict.py python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Modules/collectionsmodule.c Log: Check for a common user error with defaultdict(). Modified: python/branches/release25-maint/Lib/test/test_defaultdict.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_defaultdict.py (original) +++ python/branches/release25-maint/Lib/test/test_defaultdict.py Wed Feb 7 22:40:49 2007 @@ -47,6 +47,7 @@ self.assertEqual(err.args, (15,)) else: self.fail("d2[15] didn't raise KeyError") + self.assertRaises(TypeError, defaultdict, 1) def test_missing(self): d1 = defaultdict() @@ -60,10 +61,10 @@ self.assertEqual(repr(d1), "defaultdict(None, {})") d1[11] = 41 self.assertEqual(repr(d1), "defaultdict(None, {11: 41})") - d2 = defaultdict(0) - self.assertEqual(d2.default_factory, 0) + d2 = defaultdict(int) + self.assertEqual(d2.default_factory, int) d2[12] = 42 - self.assertEqual(repr(d2), "defaultdict(0, {12: 42})") + self.assertEqual(repr(d2), "defaultdict(, {12: 42})") def foo(): return 43 d3 = defaultdict(foo) self.assert_(d3.default_factory is foo) Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Wed Feb 7 22:40:49 2007 @@ -103,6 +103,8 @@ Extension Modules ----------------- +- collections.defaultdict() now verifies that the factory function is callable. + - Bug #1486663: don't reject keyword arguments for subclasses of builtin types. Modified: python/branches/release25-maint/Modules/collectionsmodule.c ============================================================================== --- python/branches/release25-maint/Modules/collectionsmodule.c (original) +++ python/branches/release25-maint/Modules/collectionsmodule.c Wed Feb 7 22:40:49 2007 @@ -1252,8 +1252,14 @@ newargs = PyTuple_New(0); else { Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n > 0) + if (n > 0) { newdefault = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(newdefault)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return -1; + } + } newargs = PySequence_GetSlice(args, 1, n); } if (newargs == NULL) From python-checkins at python.org Wed Feb 7 22:42:17 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 7 Feb 2007 22:42:17 +0100 (CET) Subject: [Python-checkins] r53660 - in python/trunk: Lib/test/test_defaultdict.py Modules/collectionsmodule.c Message-ID: <20070207214217.7E2911E4010@bag.python.org> Author: raymond.hettinger Date: Wed Feb 7 22:42:17 2007 New Revision: 53660 Modified: python/trunk/Lib/test/test_defaultdict.py python/trunk/Modules/collectionsmodule.c Log: Check for a common user error with defaultdict(). Modified: python/trunk/Lib/test/test_defaultdict.py ============================================================================== --- python/trunk/Lib/test/test_defaultdict.py (original) +++ python/trunk/Lib/test/test_defaultdict.py Wed Feb 7 22:42:17 2007 @@ -47,6 +47,7 @@ self.assertEqual(err.args, (15,)) else: self.fail("d2[15] didn't raise KeyError") + self.assertRaises(TypeError, defaultdict, 1) def test_missing(self): d1 = defaultdict() @@ -60,10 +61,10 @@ self.assertEqual(repr(d1), "defaultdict(None, {})") d1[11] = 41 self.assertEqual(repr(d1), "defaultdict(None, {11: 41})") - d2 = defaultdict(0) - self.assertEqual(d2.default_factory, 0) + d2 = defaultdict(int) + self.assertEqual(d2.default_factory, int) d2[12] = 42 - self.assertEqual(repr(d2), "defaultdict(0, {12: 42})") + self.assertEqual(repr(d2), "defaultdict(, {12: 42})") def foo(): return 43 d3 = defaultdict(foo) self.assert_(d3.default_factory is foo) Modified: python/trunk/Modules/collectionsmodule.c ============================================================================== --- python/trunk/Modules/collectionsmodule.c (original) +++ python/trunk/Modules/collectionsmodule.c Wed Feb 7 22:42:17 2007 @@ -1252,8 +1252,14 @@ newargs = PyTuple_New(0); else { Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n > 0) + if (n > 0) { newdefault = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(newdefault)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return -1; + } + } newargs = PySequence_GetSlice(args, 1, n); } if (newargs == NULL) From python-checkins at python.org Wed Feb 7 23:12:02 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 7 Feb 2007 23:12:02 +0100 (CET) Subject: [Python-checkins] r53661 - in python/branches/release25-maint: Lib/test/test_operator.py Misc/NEWS Objects/abstract.c Message-ID: <20070207221202.554041E4013@bag.python.org> Author: raymond.hettinger Date: Wed Feb 7 23:12:01 2007 New Revision: 53661 Modified: python/branches/release25-maint/Lib/test/test_operator.py python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Objects/abstract.c Log: Bug #1575169: operator.isSequenceType() now returns False for subclasses of dict. Modified: python/branches/release25-maint/Lib/test/test_operator.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_operator.py (original) +++ python/branches/release25-maint/Lib/test/test_operator.py Wed Feb 7 23:12:01 2007 @@ -215,6 +215,8 @@ self.failUnless(operator.isSequenceType(xrange(10))) self.failUnless(operator.isSequenceType('yeahbuddy')) self.failIf(operator.isSequenceType(3)) + class Dict(dict): pass + self.failIf(operator.isSequenceType(Dict())) def test_lshift(self): self.failUnlessRaises(TypeError, operator.lshift) Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Wed Feb 7 23:12:01 2007 @@ -103,6 +103,8 @@ Extension Modules ----------------- +- Bug #1575169: operator.isSequenceType() now returns False for subclasses of dict. + - collections.defaultdict() now verifies that the factory function is callable. - Bug #1486663: don't reject keyword arguments for subclasses of builtin Modified: python/branches/release25-maint/Objects/abstract.c ============================================================================== --- python/branches/release25-maint/Objects/abstract.c (original) +++ python/branches/release25-maint/Objects/abstract.c Wed Feb 7 23:12:01 2007 @@ -1157,6 +1157,8 @@ { if (s && PyInstance_Check(s)) return PyObject_HasAttrString(s, "__getitem__"); + if (PyObject_IsInstance(s, &PyDict_Type)) + return 0; return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } From python-checkins at python.org Wed Feb 7 23:24:08 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 7 Feb 2007 23:24:08 +0100 (CET) Subject: [Python-checkins] r53662 - in python/trunk: Lib/test/test_operator.py Objects/abstract.c Message-ID: <20070207222408.84C0D1E4005@bag.python.org> Author: raymond.hettinger Date: Wed Feb 7 23:24:07 2007 New Revision: 53662 Modified: python/trunk/Lib/test/test_operator.py python/trunk/Objects/abstract.c Log: Bug #1575169: operator.isSequenceType() now returns False for subclasses of dict. Modified: python/trunk/Lib/test/test_operator.py ============================================================================== --- python/trunk/Lib/test/test_operator.py (original) +++ python/trunk/Lib/test/test_operator.py Wed Feb 7 23:24:07 2007 @@ -215,6 +215,8 @@ self.failUnless(operator.isSequenceType(xrange(10))) self.failUnless(operator.isSequenceType('yeahbuddy')) self.failIf(operator.isSequenceType(3)) + class Dict(dict): pass + self.failIf(operator.isSequenceType(Dict())) def test_lshift(self): self.failUnlessRaises(TypeError, operator.lshift) Modified: python/trunk/Objects/abstract.c ============================================================================== --- python/trunk/Objects/abstract.c (original) +++ python/trunk/Objects/abstract.c Wed Feb 7 23:24:07 2007 @@ -1157,6 +1157,8 @@ { if (s && PyInstance_Check(s)) return PyObject_HasAttrString(s, "__getitem__"); + if (PyObject_IsInstance(s, &PyDict_Type)) + return 0; return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } From python-checkins at python.org Thu Feb 8 00:48:15 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 8 Feb 2007 00:48:15 +0100 (CET) Subject: [Python-checkins] r53663 - python/branches/release25-maint/Objects/abstract.c Message-ID: <20070207234815.B3B1B1E4005@bag.python.org> Author: raymond.hettinger Date: Thu Feb 8 00:48:15 2007 New Revision: 53663 Modified: python/branches/release25-maint/Objects/abstract.c Log: Silence compiler warning Modified: python/branches/release25-maint/Objects/abstract.c ============================================================================== --- python/branches/release25-maint/Objects/abstract.c (original) +++ python/branches/release25-maint/Objects/abstract.c Thu Feb 8 00:48:15 2007 @@ -1157,7 +1157,7 @@ { if (s && PyInstance_Check(s)) return PyObject_HasAttrString(s, "__getitem__"); - if (PyObject_IsInstance(s, &PyDict_Type)) + if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type)) return 0; return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; From python-checkins at python.org Thu Feb 8 00:49:04 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 8 Feb 2007 00:49:04 +0100 (CET) Subject: [Python-checkins] r53664 - python/trunk/Objects/abstract.c Message-ID: <20070207234904.2EC6D1E4005@bag.python.org> Author: raymond.hettinger Date: Thu Feb 8 00:49:03 2007 New Revision: 53664 Modified: python/trunk/Objects/abstract.c Log: Silence compiler warning Modified: python/trunk/Objects/abstract.c ============================================================================== --- python/trunk/Objects/abstract.c (original) +++ python/trunk/Objects/abstract.c Thu Feb 8 00:49:03 2007 @@ -1157,7 +1157,7 @@ { if (s && PyInstance_Check(s)) return PyObject_HasAttrString(s, "__getitem__"); - if (PyObject_IsInstance(s, &PyDict_Type)) + if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type)) return 0; return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; From buildbot at python.org Thu Feb 8 00:54:02 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 07 Feb 2007 23:54:02 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) trunk Message-ID: <20070207235402.D0D631E4005@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%2520trunk/builds/1169 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings failed slave lost sincerely, -The Buildbot From python-checkins at python.org Thu Feb 8 00:57:06 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 8 Feb 2007 00:57:06 +0100 (CET) Subject: [Python-checkins] r53665 - in python/branches/release25-maint: Lib/test/test_itertools.py Misc/NEWS Modules/itertoolsmodule.c Objects/enumobject.c Message-ID: <20070207235706.806DD1E4005@bag.python.org> Author: raymond.hettinger Date: Thu Feb 8 00:57:05 2007 New Revision: 53665 Modified: python/branches/release25-maint/Lib/test/test_itertools.py python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Modules/itertoolsmodule.c python/branches/release25-maint/Objects/enumobject.c Log: Do not let overflows in enumerate() and count() pass silently. Modified: python/branches/release25-maint/Lib/test/test_itertools.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_itertools.py (original) +++ python/branches/release25-maint/Lib/test/test_itertools.py Thu Feb 8 00:57:05 2007 @@ -52,8 +52,7 @@ self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)]) self.assertRaises(TypeError, count, 2, 3) self.assertRaises(TypeError, count, 'a') - c = count(sys.maxint-2) # verify that rollover doesn't crash - c.next(); c.next(); c.next(); c.next(); c.next() + self.assertRaises(OverflowError, list, islice(count(sys.maxint-5), 10)) c = count(3) self.assertEqual(repr(c), 'count(3)') c.next() Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Thu Feb 8 00:57:05 2007 @@ -12,6 +12,8 @@ Core and builtins ----------------- +- SF #151204: enumerate() now raises an Overflow error at sys.maxint items. + - Bug #1377858: Fix the segfaulting of the interpreter when an object created a weakref on itself during a __del__ call for new-style classes (classic classes still have the bug). @@ -103,6 +105,8 @@ Extension Modules ----------------- +- operator.count() now raises an OverflowError when the count reaches sys.maxint. + - Bug #1575169: operator.isSequenceType() now returns False for subclasses of dict. - collections.defaultdict() now verifies that the factory function is callable. Modified: python/branches/release25-maint/Modules/itertoolsmodule.c ============================================================================== --- python/branches/release25-maint/Modules/itertoolsmodule.c (original) +++ python/branches/release25-maint/Modules/itertoolsmodule.c Thu Feb 8 00:57:05 2007 @@ -2073,6 +2073,11 @@ static PyObject * count_next(countobject *lz) { + if (lz->cnt == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot count beyond LONG_MAX"); + return NULL; + } return PyInt_FromSsize_t(lz->cnt++); } Modified: python/branches/release25-maint/Objects/enumobject.c ============================================================================== --- python/branches/release25-maint/Objects/enumobject.c (original) +++ python/branches/release25-maint/Objects/enumobject.c Thu Feb 8 00:57:05 2007 @@ -62,6 +62,12 @@ PyObject *result = en->en_result; PyObject *it = en->en_sit; + if (en->en_index == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "enumerate() is limited to LONG_MAX items"); + return NULL; + } + next_item = (*it->ob_type->tp_iternext)(it); if (next_item == NULL) return NULL; From python-checkins at python.org Thu Feb 8 01:07:33 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 8 Feb 2007 01:07:33 +0100 (CET) Subject: [Python-checkins] r53666 - in python/trunk: Lib/test/test_itertools.py Modules/itertoolsmodule.c Objects/enumobject.c Message-ID: <20070208000733.C0CDD1E4005@bag.python.org> Author: raymond.hettinger Date: Thu Feb 8 01:07:32 2007 New Revision: 53666 Modified: python/trunk/Lib/test/test_itertools.py python/trunk/Modules/itertoolsmodule.c python/trunk/Objects/enumobject.c Log: Do not let overflows in enumerate() and count() pass silently. Modified: python/trunk/Lib/test/test_itertools.py ============================================================================== --- python/trunk/Lib/test/test_itertools.py (original) +++ python/trunk/Lib/test/test_itertools.py Thu Feb 8 01:07:32 2007 @@ -52,8 +52,7 @@ self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)]) self.assertRaises(TypeError, count, 2, 3) self.assertRaises(TypeError, count, 'a') - c = count(sys.maxint-2) # verify that rollover doesn't crash - c.next(); c.next(); c.next(); c.next(); c.next() + self.assertRaises(OverflowError, list, islice(count(sys.maxint-5), 10)) c = count(3) self.assertEqual(repr(c), 'count(3)') c.next() Modified: python/trunk/Modules/itertoolsmodule.c ============================================================================== --- python/trunk/Modules/itertoolsmodule.c (original) +++ python/trunk/Modules/itertoolsmodule.c Thu Feb 8 01:07:32 2007 @@ -2073,6 +2073,11 @@ static PyObject * count_next(countobject *lz) { + if (lz->cnt == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot count beyond LONG_MAX"); + return NULL; + } return PyInt_FromSsize_t(lz->cnt++); } Modified: python/trunk/Objects/enumobject.c ============================================================================== --- python/trunk/Objects/enumobject.c (original) +++ python/trunk/Objects/enumobject.c Thu Feb 8 01:07:32 2007 @@ -62,6 +62,12 @@ PyObject *result = en->en_result; PyObject *it = en->en_sit; + if (en->en_index == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "enumerate() is limited to LONG_MAX items"); + return NULL; + } + next_item = (*it->ob_type->tp_iternext)(it); if (next_item == NULL) return NULL; From python-checkins at python.org Thu Feb 8 01:49:52 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 8 Feb 2007 01:49:52 +0100 (CET) Subject: [Python-checkins] r53667 - python/branches/release25-maint/Objects/setobject.c Message-ID: <20070208004952.7D2AE1E4005@bag.python.org> Author: raymond.hettinger Date: Thu Feb 8 01:49:51 2007 New Revision: 53667 Modified: python/branches/release25-maint/Objects/setobject.c Log: Bypass set specific optimizations for set and frozenset subclasses. Modified: python/branches/release25-maint/Objects/setobject.c ============================================================================== --- python/branches/release25-maint/Objects/setobject.c (original) +++ python/branches/release25-maint/Objects/setobject.c Thu Feb 8 01:49:51 2007 @@ -912,7 +912,7 @@ { PyObject *key, *it; - if (PyAnySet_Check(other)) + if (PyAnySet_CheckExact(other)) return set_merge(so, other); if (PyDict_CheckExact(other)) { @@ -1190,7 +1190,7 @@ if (result == NULL) return NULL; - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_ssize_t pos = 0; setentry *entry; @@ -1314,7 +1314,7 @@ if ((PyObject *)so == other) return set_clear_internal(so); - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { setentry *entry; Py_ssize_t pos = 0; @@ -1363,7 +1363,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { + if (!PyAnySet_CheckExact(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1472,7 +1472,7 @@ Py_RETURN_NONE; } - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_INCREF(other); otherset = (PySetObject *)other; } else { @@ -1555,7 +1555,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { PyObject *tmp, *result; tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) @@ -1584,7 +1584,7 @@ { PyObject *tmp, *result; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) return NULL; From python-checkins at python.org Thu Feb 8 01:50:40 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 8 Feb 2007 01:50:40 +0100 (CET) Subject: [Python-checkins] r53668 - python/trunk/Objects/setobject.c Message-ID: <20070208005040.257761E4032@bag.python.org> Author: raymond.hettinger Date: Thu Feb 8 01:50:39 2007 New Revision: 53668 Modified: python/trunk/Objects/setobject.c Log: Bypass set specific optimizations for set and frozenset subclasses. Modified: python/trunk/Objects/setobject.c ============================================================================== --- python/trunk/Objects/setobject.c (original) +++ python/trunk/Objects/setobject.c Thu Feb 8 01:50:39 2007 @@ -912,7 +912,7 @@ { PyObject *key, *it; - if (PyAnySet_Check(other)) + if (PyAnySet_CheckExact(other)) return set_merge(so, other); if (PyDict_CheckExact(other)) { @@ -1190,7 +1190,7 @@ if (result == NULL) return NULL; - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_ssize_t pos = 0; setentry *entry; @@ -1314,7 +1314,7 @@ if ((PyObject *)so == other) return set_clear_internal(so); - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { setentry *entry; Py_ssize_t pos = 0; @@ -1363,7 +1363,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { + if (!PyAnySet_CheckExact(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1472,7 +1472,7 @@ Py_RETURN_NONE; } - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_INCREF(other); otherset = (PySetObject *)other; } else { @@ -1555,7 +1555,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { PyObject *tmp, *result; tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) @@ -1584,7 +1584,7 @@ { PyObject *tmp, *result; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) return NULL; From buildbot at python.org Thu Feb 8 02:10:12 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 08 Feb 2007 01:10:12 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) 2.5 Message-ID: <20070208011012.3A8331E4005@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%25202.5/builds/155 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildbot/Buildbot/2.5.baxter-ubuntu/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (3.73337) is more than 2 seconds more than expected (0.001) sincerely, -The Buildbot From python-checkins at python.org Thu Feb 8 02:37:18 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 8 Feb 2007 02:37:18 +0100 (CET) Subject: [Python-checkins] r53669 - python/branches/release25-maint/Lib/decimal.py Message-ID: <20070208013718.D11141E4005@bag.python.org> Author: raymond.hettinger Date: Thu Feb 8 02:37:18 2007 New Revision: 53669 Modified: python/branches/release25-maint/Lib/decimal.py Log: Fix docstring bug Modified: python/branches/release25-maint/Lib/decimal.py ============================================================================== --- python/branches/release25-maint/Lib/decimal.py (original) +++ python/branches/release25-maint/Lib/decimal.py Thu Feb 8 02:37:18 2007 @@ -487,7 +487,7 @@ 28 >>> with localcontext(): ... ctx = getcontext() - ... ctx.prec() += 2 + ... ctx.prec += 2 ... print ctx.prec ... 30 From python-checkins at python.org Thu Feb 8 02:42:36 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 8 Feb 2007 02:42:36 +0100 (CET) Subject: [Python-checkins] r53670 - python/trunk/Lib/decimal.py Message-ID: <20070208014236.7E7F61E4005@bag.python.org> Author: raymond.hettinger Date: Thu Feb 8 02:42:35 2007 New Revision: 53670 Modified: python/trunk/Lib/decimal.py Log: Fix docstring bug Modified: python/trunk/Lib/decimal.py ============================================================================== --- python/trunk/Lib/decimal.py (original) +++ python/trunk/Lib/decimal.py Thu Feb 8 02:42:35 2007 @@ -487,7 +487,7 @@ 28 >>> with localcontext(): ... ctx = getcontext() - ... ctx.prec() += 2 + ... ctx.prec += 2 ... print ctx.prec ... 30 From buildbot at python.org Thu Feb 8 04:03:51 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 08 Feb 2007 03:03:51 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 2.5 Message-ID: <20070208030352.044DA1E4005@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%25202.5/builds/163 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket ====================================================================== FAIL: testInterruptedTimeout (test.test_socket.TCPTimeoutTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/net/ringneck/scratch1/nnorwitz/python/2.5.norwitz-tru64/build/Lib/test/test_socket.py", line 872, in testInterruptedTimeout self.fail("got Alarm in wrong place") AssertionError: got Alarm in wrong place sincerely, -The Buildbot From buildbot at python.org Thu Feb 8 04:10:05 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 08 Feb 2007 03:10:05 +0000 Subject: [Python-checkins] buildbot warnings in S-390 Debian trunk Message-ID: <20070208031005.99D771E4005@bag.python.org> The Buildbot has detected a new failure of S-390 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/S-390%2520Debian%2520trunk/builds/655 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_urllibnet make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Thu Feb 8 04:12:26 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 08 Feb 2007 03:12:26 +0000 Subject: [Python-checkins] buildbot warnings in hppa Ubuntu dapper trunk Message-ID: <20070208031226.96E151E4005@bag.python.org> The Buildbot has detected a new failure of hppa Ubuntu dapper trunk. Full details are available at: http://www.python.org/dev/buildbot/all/hppa%2520Ubuntu%2520dapper%2520trunk/builds/65 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Thu Feb 8 05:08:43 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 08 Feb 2007 04:08:43 +0000 Subject: [Python-checkins] buildbot warnings in sparc solaris10 gcc trunk Message-ID: <20070208040843.7C54B1E4005@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc trunk. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%2520trunk/builds/1745 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socketserver Traceback (most recent call last): File "/opt/users/buildbot/slave/trunk.loewis-sun/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/opt/users/buildbot/slave/trunk.loewis-sun/build/Lib/test/test_socketserver.py", line 81, in run svr = svrcls(self.__addr, self.__hdlrcls) File "/opt/users/buildbot/slave/trunk.loewis-sun/build/Lib/SocketServer.py", line 330, in __init__ self.server_bind() File "/opt/users/buildbot/slave/trunk.loewis-sun/build/Lib/SocketServer.py", line 341, in server_bind self.socket.bind(self.server_address) File "", line 1, in bind error: (125, 'Address already in use') Traceback (most recent call last): File "/opt/users/buildbot/slave/trunk.loewis-sun/build/Lib/threading.py", line 473, in __bootstrap (self.getName(), _format_exc())) File "/opt/users/buildbot/slave/trunk.loewis-sun/build/Lib/traceback.py", line 236, in format_exc return ''.join(format_exception(etype, value, tb, limit)) File "/opt/users/buildbot/slave/trunk.loewis-sun/build/Lib/traceback.py", line 142, in format_exception list = list + format_tb(tb, limit) File "/opt/users/buildbot/slave/trunk.loewis-sun/build/Lib/traceback.py", line 76, in format_tb return format_list(extract_tb(tb, limit)) File "/opt/users/buildbot/slave/trunk.loewis-sun/build/Lib/traceback.py", line 101, in extract_tb line = linecache.getline(filename, lineno, f.f_globals) AttributeError: 'NoneType' object has no attribute 'getline' sincerely, -The Buildbot From python-checkins at python.org Thu Feb 8 10:13:38 2007 From: python-checkins at python.org (martin.v.loewis) Date: Thu, 8 Feb 2007 10:13:38 +0100 (CET) Subject: [Python-checkins] r53671 - in python/trunk: Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c Message-ID: <20070208091338.0B8EB1E4005@bag.python.org> Author: martin.v.loewis Date: Thu Feb 8 10:13:36 2007 New Revision: 53671 Modified: python/trunk/Lib/test/test_datetime.py python/trunk/Misc/NEWS python/trunk/Modules/datetimemodule.c Log: Bug #1653736: Complain about keyword arguments to time.isoformat. Will backport to 2.5. Modified: python/trunk/Lib/test/test_datetime.py ============================================================================== --- python/trunk/Lib/test/test_datetime.py (original) +++ python/trunk/Lib/test/test_datetime.py Thu Feb 8 10:13:36 2007 @@ -1740,6 +1740,11 @@ self.assertEqual(t.isoformat(), "00:00:00.100000") self.assertEqual(t.isoformat(), str(t)) + def test_1653736(self): + # verify it doesn't accept extra keyword arguments + t = self.theclass(second=1) + self.assertRaises(TypeError, t.isoformat, foo=3) + def test_strftime(self): t = self.theclass(1, 2, 3, 4) self.assertEqual(t.strftime('%H %M %S'), "01 02 03") Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu Feb 8 10:13:36 2007 @@ -347,6 +347,8 @@ Extension Modules ----------------- +- Bug #1653736: Complain about keyword arguments to time.isoformat. + - Bug #1486663: don't reject keyword arguments for subclasses of builtin types. Modified: python/trunk/Modules/datetimemodule.c ============================================================================== --- python/trunk/Modules/datetimemodule.c (original) +++ python/trunk/Modules/datetimemodule.c Thu Feb 8 10:13:36 2007 @@ -3167,7 +3167,7 @@ } static PyObject * -time_isoformat(PyDateTime_Time *self) +time_isoformat(PyDateTime_Time *self, PyObject *unused) { char buf[100]; PyObject *result; @@ -3411,7 +3411,7 @@ static PyMethodDef time_methods[] = { - {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, + {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" "[+HH:MM].")}, From python-checkins at python.org Thu Feb 8 10:13:52 2007 From: python-checkins at python.org (martin.v.loewis) Date: Thu, 8 Feb 2007 10:13:52 +0100 (CET) Subject: [Python-checkins] r53672 - in python/branches/release25-maint: Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c Message-ID: <20070208091352.8FC4B1E4005@bag.python.org> Author: martin.v.loewis Date: Thu Feb 8 10:13:51 2007 New Revision: 53672 Modified: python/branches/release25-maint/Lib/test/test_datetime.py python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Modules/datetimemodule.c Log: Bug #1653736: Complain about keyword arguments to time.isoformat. Modified: python/branches/release25-maint/Lib/test/test_datetime.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_datetime.py (original) +++ python/branches/release25-maint/Lib/test/test_datetime.py Thu Feb 8 10:13:51 2007 @@ -1740,6 +1740,11 @@ self.assertEqual(t.isoformat(), "00:00:00.100000") self.assertEqual(t.isoformat(), str(t)) + def test_1653736(self): + # verify it doesn't accept extra keyword arguments + t = self.theclass(second=1) + self.assertRaises(TypeError, t.isoformat, foo=3) + def test_strftime(self): t = self.theclass(1, 2, 3, 4) self.assertEqual(t.strftime('%H %M %S'), "01 02 03") Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Thu Feb 8 10:13:51 2007 @@ -105,6 +105,8 @@ Extension Modules ----------------- +- Bug #1653736: Complain about keyword arguments to time.isoformat. + - operator.count() now raises an OverflowError when the count reaches sys.maxint. - Bug #1575169: operator.isSequenceType() now returns False for subclasses of dict. Modified: python/branches/release25-maint/Modules/datetimemodule.c ============================================================================== --- python/branches/release25-maint/Modules/datetimemodule.c (original) +++ python/branches/release25-maint/Modules/datetimemodule.c Thu Feb 8 10:13:51 2007 @@ -3167,7 +3167,7 @@ } static PyObject * -time_isoformat(PyDateTime_Time *self) +time_isoformat(PyDateTime_Time *self, PyObject *unused) { char buf[100]; PyObject *result; @@ -3411,7 +3411,7 @@ static PyMethodDef time_methods[] = { - {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, + {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" "[+HH:MM].")}, From nnorwitz at gmail.com Thu Feb 8 11:23:05 2007 From: nnorwitz at gmail.com (Neal Norwitz) Date: Thu, 8 Feb 2007 05:23:05 -0500 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20070208102305.GA8084@python.psfb.org> test_cmd_line leaked [17, 0, -17] references test_softspace leaked [0, 90, 0] references From buildbot at python.org Thu Feb 8 11:36:05 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 08 Feb 2007 10:36:05 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) trunk Message-ID: <20070208103605.5FF841E401A@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%2520trunk/builds/1172 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_timeout test_urllibnet ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (3.20527) is more than 2 seconds more than expected (0.001) sincerely, -The Buildbot From buildbot at python.org Thu Feb 8 12:18:54 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 08 Feb 2007 11:18:54 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 2.5 Message-ID: <20070208111854.6B9811E4005@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%25202.5/builds/165 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_signal test_socket sincerely, -The Buildbot From buildbot at python.org Thu Feb 8 13:52:47 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 08 Feb 2007 12:52:47 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) 2.5 Message-ID: <20070208125247.512501E4007@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%25202.5/builds/157 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildbot/Buildbot/2.5.baxter-ubuntu/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (3.5533) is more than 2 seconds more than expected (0.001) sincerely, -The Buildbot From python-checkins at python.org Thu Feb 8 21:08:16 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 8 Feb 2007 21:08:16 +0100 (CET) Subject: [Python-checkins] r53673 - sandbox/trunk/setuptools/pkg_resources.py Message-ID: <20070208200816.D88EB1E4007@bag.python.org> Author: phillip.eby Date: Thu Feb 8 21:08:16 2007 New Revision: 53673 Modified: sandbox/trunk/setuptools/pkg_resources.py Log: Ensure extracted libraries have correct permissions on Posix systems (e.g. Cygwin, which is where I found the problem.) Modified: sandbox/trunk/setuptools/pkg_resources.py ============================================================================== --- sandbox/trunk/setuptools/pkg_resources.py (original) +++ sandbox/trunk/setuptools/pkg_resources.py Thu Feb 8 21:08:16 2007 @@ -883,6 +883,23 @@ return target_path + + + + + + + + + + + + + + + + + def postprocess(self, tempname, filename): """Perform any platform-specific postprocessing of `tempname` @@ -897,7 +914,31 @@ is the name it will be renamed to by the caller after this routine returns. """ - # XXX + + if os.name == 'posix': + # Make the resource executable + mode = ((os.stat(tempname).st_mode) | 0555) & 07777 + os.chmod(tempname, mode) + + + + + + + + + + + + + + + + + + + + def set_extraction_path(self, path): From python-checkins at python.org Thu Feb 8 21:11:22 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 8 Feb 2007 21:11:22 +0100 (CET) Subject: [Python-checkins] r53674 - sandbox/branches/setuptools-0.6/pkg_resources.py sandbox/branches/setuptools-0.6/pkg_resources.txt Message-ID: <20070208201122.BF4791E4007@bag.python.org> Author: phillip.eby Date: Thu Feb 8 21:11:22 2007 New Revision: 53674 Modified: sandbox/branches/setuptools-0.6/pkg_resources.py sandbox/branches/setuptools-0.6/pkg_resources.txt Log: Fix extracted C extensions not having executable permissions under Cygwin. (backport from trunk) Modified: sandbox/branches/setuptools-0.6/pkg_resources.py ============================================================================== --- sandbox/branches/setuptools-0.6/pkg_resources.py (original) +++ sandbox/branches/setuptools-0.6/pkg_resources.py Thu Feb 8 21:11:22 2007 @@ -883,6 +883,23 @@ return target_path + + + + + + + + + + + + + + + + + def postprocess(self, tempname, filename): """Perform any platform-specific postprocessing of `tempname` @@ -897,7 +914,31 @@ is the name it will be renamed to by the caller after this routine returns. """ - # XXX + + if os.name == 'posix': + # Make the resource executable + mode = ((os.stat(tempname).st_mode) | 0555) & 07777 + os.chmod(tempname, mode) + + + + + + + + + + + + + + + + + + + + def set_extraction_path(self, path): Modified: sandbox/branches/setuptools-0.6/pkg_resources.txt ============================================================================== --- sandbox/branches/setuptools-0.6/pkg_resources.txt (original) +++ sandbox/branches/setuptools-0.6/pkg_resources.txt Thu Feb 8 21:11:22 2007 @@ -1692,6 +1692,9 @@ Release Notes/Change History ---------------------------- +0.6c6 + * Fix extracted C extensions not having executable permissions under Cygwin. + 0.6c4 * Fix "dev" versions being considered newer than release candidates. From python-checkins at python.org Thu Feb 8 23:32:36 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 8 Feb 2007 23:32:36 +0100 (CET) Subject: [Python-checkins] r53675 - sandbox/trunk/2to3/fixes/find_pattern.py Message-ID: <20070208223236.290561E4012@bag.python.org> Author: guido.van.rossum Date: Thu Feb 8 23:32:35 2007 New Revision: 53675 Added: sandbox/trunk/2to3/fixes/find_pattern.py (contents, props changed) Log: Helper script by Collin Winter. Added: sandbox/trunk/2to3/fixes/find_pattern.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/find_pattern.py Thu Feb 8 23:32:35 2007 @@ -0,0 +1,98 @@ +#!/usr/bin/env python2.5 + +"""A script that makes determining PATTERN for a new fixer much, much easier. + +Figuring out exactly what PATTERN I want for a given fixer class is +getting tedious. This script will step through each possible subtree +for a given string, allowing you to select which one you want. It will +then try to figure out an appropriate pattern to match that tree. This +pattern will require some editing (it will be overly restrictive) but +should provide a solid base to work with and handle the tricky parts. + +Usage: + + python find_pattern.py "g.throw(E, V, T)" + +This will step through each subtree in the parse. To reject a +candidate subtree, hit enter; to accept a candidate, hit "y" and +enter. The pattern will be spit out to stdout. + +For example, the above will yield a succession of possible snippets, +skipping all leaf-only trees. I accept + +'g.throw(E, V, T)' + +This causes find_pattern to spit out + +power< 'g' trailer< '.' 'throw' > + trailer< '(' arglist< 'E' ',' 'V' ',' 'T' > ')' > > + + +Some minor tweaks later, I'm left with + +power< any trailer< '.' 'throw' > + trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' > > + + +which is exactly what I was after. + +Larger snippets can be placed in a file (as opposed to a command-line +arg) and processed with the -f option. +""" + +__author__ = "Collin Winter " + +# Python imports +import optparse +import sys +from StringIO import StringIO + +# Local imports +import pytree +from pgen2 import driver +from pygram import python_symbols, python_grammar + +driver = driver.Driver(python_grammar, convert=pytree.convert) + +def main(args): + parser = optparse.OptionParser(usage="find_pattern.py [options] [string]") + parser.add_option("-f", "--file", action="store", + help="Read a code snippet from the specified file") + + # Parse command line arguments + options, args = parser.parse_args(args) + if options.file: + tree = driver.parse_file(options.file) + elif len(args) > 1: + tree = driver.parse_stream(StringIO(args[1] + "\n")) + else: + print >>sys.stderr, "You must specify an input file or an input string" + return 1 + + examine_tree(tree) + return 0 + +def examine_tree(tree): + for node in tree.post_order(): + if isinstance(node, pytree.Leaf): + continue + print repr(str(node)) + verdict = raw_input() + if verdict.strip(): + print find_pattern(node) + return + +def find_pattern(node): + if isinstance(node, pytree.Leaf): + return repr(node.value) + + return find_symbol(node.type) + \ + "< " + " ".join(find_pattern(n) for n in node.children) + " >" + +def find_symbol(sym): + for n, v in python_symbols.__dict__.items(): + if v == sym: + return n + +if __name__ == "__main__": + sys.exit(main(sys.argv)) From python-checkins at python.org Thu Feb 8 23:35:32 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 8 Feb 2007 23:35:32 +0100 (CET) Subject: [Python-checkins] r53676 - in sandbox/trunk/2to3: find_pattern.py fixes/find_pattern.py Message-ID: <20070208223532.2720F1E401A@bag.python.org> Author: guido.van.rossum Date: Thu Feb 8 23:35:31 2007 New Revision: 53676 Added: sandbox/trunk/2to3/find_pattern.py (contents, props changed) Removed: sandbox/trunk/2to3/fixes/find_pattern.py Log: Move find_pattern.py to where it belongs. [Blush.] Added: sandbox/trunk/2to3/find_pattern.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/find_pattern.py Thu Feb 8 23:35:31 2007 @@ -0,0 +1,97 @@ +#!/usr/bin/env python2.5 + +"""Script that makes determining PATTERN for a new fix much easier. + +Figuring out exactly what PATTERN I want for a given fixer class is +getting tedious. This script will step through each possible subtree +for a given string, allowing you to select which one you want. It will +then try to figure out an appropriate pattern to match that tree. This +pattern will require some editing (it will be overly restrictive) but +should provide a solid base to work with and handle the tricky parts. + +Usage: + + python find_pattern.py "g.throw(E, V, T)" + +This will step through each subtree in the parse. To reject a +candidate subtree, hit enter; to accept a candidate, hit "y" and +enter. The pattern will be spit out to stdout. + +For example, the above will yield a succession of possible snippets, +skipping all leaf-only trees. I accept + +'g.throw(E, V, T)' + +This causes find_pattern to spit out + +power< 'g' trailer< '.' 'throw' > + trailer< '(' arglist< 'E' ',' 'V' ',' 'T' > ')' > > + + +Some minor tweaks later, I'm left with + +power< any trailer< '.' 'throw' > + trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' > > + +which is exactly what I was after. + +Larger snippets can be placed in a file (as opposed to a command-line +arg) and processed with the -f option. +""" + +__author__ = "Collin Winter " + +# Python imports +import optparse +import sys +from StringIO import StringIO + +# Local imports +import pytree +from pgen2 import driver +from pygram import python_symbols, python_grammar + +driver = driver.Driver(python_grammar, convert=pytree.convert) + +def main(args): + parser = optparse.OptionParser(usage="find_pattern.py [options] [string]") + parser.add_option("-f", "--file", action="store", + help="Read a code snippet from the specified file") + + # Parse command line arguments + options, args = parser.parse_args(args) + if options.file: + tree = driver.parse_file(options.file) + elif len(args) > 1: + tree = driver.parse_stream(StringIO(args[1] + "\n")) + else: + print >>sys.stderr, "You must specify an input file or an input string" + return 1 + + examine_tree(tree) + return 0 + +def examine_tree(tree): + for node in tree.post_order(): + if isinstance(node, pytree.Leaf): + continue + print repr(str(node)) + verdict = raw_input() + if verdict.strip(): + print find_pattern(node) + return + +def find_pattern(node): + if isinstance(node, pytree.Leaf): + return repr(node.value) + + return find_symbol(node.type) + \ + "< " + " ".join(find_pattern(n) for n in node.children) + " >" + +def find_symbol(sym): + for n, v in python_symbols.__dict__.items(): + if v == sym: + return n + +if __name__ == "__main__": + sys.exit(main(sys.argv)) Deleted: /sandbox/trunk/2to3/fixes/find_pattern.py ============================================================================== --- /sandbox/trunk/2to3/fixes/find_pattern.py Thu Feb 8 23:35:31 2007 +++ (empty file) @@ -1,98 +0,0 @@ -#!/usr/bin/env python2.5 - -"""A script that makes determining PATTERN for a new fixer much, much easier. - -Figuring out exactly what PATTERN I want for a given fixer class is -getting tedious. This script will step through each possible subtree -for a given string, allowing you to select which one you want. It will -then try to figure out an appropriate pattern to match that tree. This -pattern will require some editing (it will be overly restrictive) but -should provide a solid base to work with and handle the tricky parts. - -Usage: - - python find_pattern.py "g.throw(E, V, T)" - -This will step through each subtree in the parse. To reject a -candidate subtree, hit enter; to accept a candidate, hit "y" and -enter. The pattern will be spit out to stdout. - -For example, the above will yield a succession of possible snippets, -skipping all leaf-only trees. I accept - -'g.throw(E, V, T)' - -This causes find_pattern to spit out - -power< 'g' trailer< '.' 'throw' > - trailer< '(' arglist< 'E' ',' 'V' ',' 'T' > ')' > > - - -Some minor tweaks later, I'm left with - -power< any trailer< '.' 'throw' > - trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' > > - - -which is exactly what I was after. - -Larger snippets can be placed in a file (as opposed to a command-line -arg) and processed with the -f option. -""" - -__author__ = "Collin Winter " - -# Python imports -import optparse -import sys -from StringIO import StringIO - -# Local imports -import pytree -from pgen2 import driver -from pygram import python_symbols, python_grammar - -driver = driver.Driver(python_grammar, convert=pytree.convert) - -def main(args): - parser = optparse.OptionParser(usage="find_pattern.py [options] [string]") - parser.add_option("-f", "--file", action="store", - help="Read a code snippet from the specified file") - - # Parse command line arguments - options, args = parser.parse_args(args) - if options.file: - tree = driver.parse_file(options.file) - elif len(args) > 1: - tree = driver.parse_stream(StringIO(args[1] + "\n")) - else: - print >>sys.stderr, "You must specify an input file or an input string" - return 1 - - examine_tree(tree) - return 0 - -def examine_tree(tree): - for node in tree.post_order(): - if isinstance(node, pytree.Leaf): - continue - print repr(str(node)) - verdict = raw_input() - if verdict.strip(): - print find_pattern(node) - return - -def find_pattern(node): - if isinstance(node, pytree.Leaf): - return repr(node.value) - - return find_symbol(node.type) + \ - "< " + " ".join(find_pattern(n) for n in node.children) + " >" - -def find_symbol(sym): - for n, v in python_symbols.__dict__.items(): - if v == sym: - return n - -if __name__ == "__main__": - sys.exit(main(sys.argv)) From python-checkins at python.org Thu Feb 8 23:42:36 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 8 Feb 2007 23:42:36 +0100 (CET) Subject: [Python-checkins] r53677 - in sandbox/trunk/2to3: example.py fixer_tests.py fixes/basefix.py fixes/fix_apply.py fixes/fix_except.py fixes/fix_exec.py fixes/fix_has_key.py fixes/fix_intern.py fixes/fix_long.py fixes/fix_print.py fixes/fix_raise.py fixes/fix_repr.py fixes/fix_sysexcinfo.py fixes/fix_throw.py fixes/macros.py pytree.py refactor.py Message-ID: <20070208224236.B638D1E4008@bag.python.org> Author: guido.van.rossum Date: Thu Feb 8 23:42:35 2007 New Revision: 53677 Added: sandbox/trunk/2to3/fixes/fix_sysexcinfo.py (contents, props changed) sandbox/trunk/2to3/fixes/fix_throw.py (contents, props changed) sandbox/trunk/2to3/fixes/macros.py (contents, props changed) Modified: sandbox/trunk/2to3/example.py sandbox/trunk/2to3/fixer_tests.py sandbox/trunk/2to3/fixes/basefix.py sandbox/trunk/2to3/fixes/fix_apply.py sandbox/trunk/2to3/fixes/fix_except.py sandbox/trunk/2to3/fixes/fix_exec.py sandbox/trunk/2to3/fixes/fix_has_key.py sandbox/trunk/2to3/fixes/fix_intern.py sandbox/trunk/2to3/fixes/fix_long.py sandbox/trunk/2to3/fixes/fix_print.py sandbox/trunk/2to3/fixes/fix_raise.py sandbox/trunk/2to3/fixes/fix_repr.py sandbox/trunk/2to3/pytree.py sandbox/trunk/2to3/refactor.py Log: Lots of new stuff by Collin Winter: - macros.patch is a new version of the earlier macros.patch. - better_raise.patch allows 2to3 to convert three-argument raise statements. This depends on macros.patch. - fix_throw.patch converts two- and three-argument generator.throw() calls much like fix_raise does. - fix_sysexcinfo.patch adds a fixer that warns on usage of sys.exc_{info,type,value,traceback}. Right now I see some test failures; I'll ask Collin to address these. Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Thu Feb 8 23:42:35 2007 @@ -165,7 +165,7 @@ except Exception, (f, e): pass except ImportError, e: - pass + print e.args # try: pass @@ -208,7 +208,7 @@ pass except (Exception, SystemExit): pass - + def raise_examples(): raise Exception, 5 # @@ -223,10 +223,14 @@ raise Exception(5, 6) # # These should produce a warning + # TODO: convert "raise E, V, T" to + # "e = E(V); e.__traceback__ = T; raise e;" # raise Exception, 5, 6 # raise Exception,5,6 + # + raise Exception, (5, 6, 7), 6 def long_examples(): x = long(x) @@ -238,6 +242,6 @@ a = 12 b = 0x12 c = 3.14 - - + + # This is the last line. Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Thu Feb 8 23:42:35 2007 @@ -11,14 +11,18 @@ import refactor +# We wrap the RefactoringTool's fixer objects so we can intercept +# the call to set_filename() and so modify the fixers' logging objects. +# This allows us to make sure that certain code chunks produce certain +# warnings. class Fixer(object): def __init__(self, fixer, handler): self.fixer = fixer self.handler = handler - + def __getattr__(self, attr): return getattr(self.fixer, attr) - + def set_filename(self, filename): self.fixer.set_filename(filename) self.fixer.logger.addHandler(self.handler) @@ -27,30 +31,29 @@ def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) - + self.verbose = False class FixerTestCase(unittest.TestCase): def setUp(self): options = Options(fix=[self.fixer]) self.refactor = refactor.RefactoringTool(options) - + self.logging_stream = StringIO() sh = logging.StreamHandler(self.logging_stream) sh.setFormatter(logging.Formatter("%(message)s")) self.refactor.fixers = [Fixer(f, sh) for f in self.refactor.fixers] - + def check(self, before, after): before += "\n" after += "\n" refactored = self.refactor_stream("", StringIO(before)) self.failUnlessEqual(after, refactored) - + def warns(self, before, after, message): self.check(before, after) - - self.logging_stream.seek(0) - self.failUnless(message in '\n'.join(self.logging_stream)) + + self.failUnless(message in self.logging_stream.getvalue()) def refactor_stream(self, stream_name, stream): try: @@ -70,158 +73,158 @@ def test_1(self): b = """if x <> y: pass""" - + a = """if x != y: pass""" self.check(b, a) - + def test_2(self): b = """if x<>y: pass""" - + a = """if x!=y: pass""" self.check(b, a) - + def test_3(self): b = """if x<>y<>z: pass""" - + a = """if x!=y!=z: pass""" self.check(b, a) - + class Test_has_key(FixerTestCase): fixer = "has_key" - + def test_1(self): b = """x = d.has_key("x") or d.has_key("y")""" a = """x = "x" in d or "y" in d""" self.check(b, a) - + def test_2(self): b = """x = a.b.c.d.has_key("x") ** 3""" a = """x = ("x" in a.b.c.d) ** 3""" self.check(b, a) - + def test_3(self): b = """x = a.b.has_key(1 + 2).__repr__()""" a = """x = (1 + 2 in a.b).__repr__()""" self.check(b, a) - + def test_4(self): b = """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4""" a = """x = (1 + 2 in a.b).__repr__() ** -3 ** 4""" self.check(b, a) - + def test_5(self): b = """x = a.has_key(f or g)""" a = """x = (f or g) in a""" self.check(b, a) - + def test_6(self): b = """x = a + b.has_key(c)""" a = """x = a + (c in b)""" self.check(b, a) - + def test_7(self): b = """x = a.has_key(lambda: 12)""" a = """x = (lambda: 12) in a""" self.check(b, a) - + def test_8(self): b = """x = a.has_key(a for a in b)""" a = """x = (a for a in b) in a""" self.check(b, a) - + def test_9(self): b = """if not a.has_key(b): pass""" a = """if b not in a: pass""" self.check(b, a) - + def test_10(self): b = """if not a.has_key(b).__repr__(): pass""" a = """if not (b in a).__repr__(): pass""" self.check(b, a) - + def test_11(self): b = """if not a.has_key(b) ** 2: pass""" a = """if not (b in a) ** 2: pass""" self.check(b, a) - + class Test_apply(FixerTestCase): fixer = "apply" - + def test_1(self): b = """x = apply(f, g + h)""" a = """x = f(*g + h)""" self.check(b, a) - + def test_2(self): b = """y = apply(f, g, h)""" a = """y = f(*g, **h)""" self.check(b, a) - + def test_3(self): b = """z = apply(fs[0], g or h, h or g)""" a = """z = fs[0](*g or h, **h or g)""" self.check(b, a) - + def test_4(self): b = """apply(f, (x, y) + t)""" a = """f(*(x, y) + t)""" self.check(b, a) - + def test_5(self): b = """apply(f, args,)""" a = """f(*args)""" self.check(b, a) - + def test_6(self): b = """apply(f, args, kwds,)""" a = """f(*args, **kwds)""" self.check(b, a) - + # Test that complex functions are parenthesized - + def test_7(self): b = """x = apply(f+g, args)""" a = """x = (f+g)(*args)""" self.check(b, a) - + def test_8(self): b = """x = apply(f*g, args)""" a = """x = (f*g)(*args)""" self.check(b, a) - + def test_9(self): b = """x = apply(f**g, args)""" a = """x = (f**g)(*args)""" self.check(b, a) - + # But dotted names etc. not - + def test_10(self): b = """x = apply(f.g, args)""" a = """x = f.g(*args)""" self.check(b, a) - + def test_11(self): b = """x = apply(f[x], args)""" a = """x = f[x](*args)""" self.check(b, a) - + def test_12(self): b = """x = apply(f(), args)""" a = """x = f()(*args)""" self.check(b, a) - + # Extreme case def test_13(self): b = """x = apply(a.b.c.d.e.f, args, kwds)""" a = """x = a.b.c.d.e.f(*args, **kwds)""" self.check(b, a) - + # XXX Comments in weird places still get lost def test_14(self): b = """apply( # foo @@ -229,49 +232,49 @@ args)""" a = """f(*args)""" self.check(b, a) - + # These should *not* be touched - + def test_15(self): b = """apply()""" a = """apply()""" self.check(b, a) - + def test_16(self): b = """apply(f)""" a = """apply(f)""" self.check(b, a) - + def test_17(self): b = """apply(f,)""" a = """apply(f,)""" self.check(b, a) - + def test_18(self): b = """apply(f, args, kwds, extras)""" a = """apply(f, args, kwds, extras)""" self.check(b, a) - + def test_19(self): b = """apply(f, *args, **kwds)""" a = """apply(f, *args, **kwds)""" self.check(b, a) - + def test_20(self): b = """apply(f, *args)""" a = """apply(f, *args)""" self.check(b, a) - + def test_21(self): b = """apply(func=f, args=args, kwds=kwds)""" a = """apply(func=f, args=args, kwds=kwds)""" self.check(b, a) - + def test_22(self): b = """apply(f, args=args, kwds=kwds)""" a = """apply(f, args=args, kwds=kwds)""" self.check(b, a) - + def test_23(self): b = """apply(f, args, kwds=kwds)""" a = """apply(f, args, kwds=kwds)""" @@ -280,106 +283,106 @@ class Test_intern(FixerTestCase): fixer = "intern" - + def test_1(self): b = """x = intern(a)""" a = """x = sys.intern(a)""" self.check(b, a) - + def test_2(self): b = """y = intern("b" # test )""" a = """y = sys.intern("b" # test )""" self.check(b, a) - + def test_3(self): b = """z = intern(a+b+c.d,)""" a = """z = sys.intern(a+b+c.d,)""" self.check(b, a) - + def test_4(self): b = """intern("y%s" % 5).replace("y", "")""" a = """sys.intern("y%s" % 5).replace("y", "")""" self.check(b, a) - + # These should not be refactored - + def test_5(self): b = """intern(a=1)""" a = """intern(a=1)""" self.check(b, a) - + def test_6(self): b = """intern(f, g)""" a = """intern(f, g)""" self.check(b, a) - + def test_7(self): b = """intern(*h)""" a = """intern(*h)""" self.check(b, a) - + def test_8(self): b = """intern(**i)""" a = """intern(**i)""" self.check(b, a) - + class Test_print(FixerTestCase): fixer = "print" - + def test_1(self): b = """print 1, 1+1, 1+1+1""" a = """Print(1, 1+1, 1+1+1)""" self.check(b, a) - + def test_2(self): b = """print 1, 2""" a = """Print(1, 2)""" self.check(b, a) - + def test_3(self): b = """print""" a = """Print()""" self.check(b, a) - + # trailing commas - + def test_4(self): b = """print 1, 2, 3,""" a = """Print(1, 2, 3, end=' ')""" self.check(b, a) - + def test_5(self): b = """print 1, 2,""" a = """Print(1, 2, end=' ')""" self.check(b, a) - + def test_6(self): b = """print 1,""" a = """Print(1, end=' ')""" self.check(b, a) - + # >> stuff - + # no trailing comma def test_7(self): b = """print >>sys.stderr, 1, 2, 3""" a = """Print(1, 2, 3, file=sys.stderr)""" self.check(b, a) - + # trailing comma def test_8(self): b = """print >>sys.stderr, 1, 2,""" a = """Print(1, 2, end=' ', file=sys.stderr)""" self.check(b, a) - + # no trailing comma def test_9(self): b = """print >>sys.stderr, 1+1""" a = """Print(1+1, file=sys.stderr)""" self.check(b, a) - + # spaces before sys.stderr def test_10(self): b = """print >> sys.stderr""" @@ -389,49 +392,49 @@ class Test_exec(FixerTestCase): fixer = "exec" - + def test_1(self): b = """exec code""" a = """exec(code)""" self.check(b, a) - + def test_2(self): b = """exec code in ns""" a = """exec(code, ns)""" self.check(b, a) - + def test_3(self): b = """exec code in ns1, ns2""" a = """exec(code, ns1, ns2)""" self.check(b, a) - + def test_4(self): b = """exec (a.b()) in ns""" a = """exec((a.b()), ns)""" self.check(b, a) - + def test_5(self): b = """exec a.b() + c in ns""" a = """exec(a.b() + c, ns)""" self.check(b, a) - + # These should not be touched - + def test_6(self): b = """exec(code)""" a = """exec(code)""" self.check(b, a) - + def test_7(self): b = """exec (code)""" a = """exec (code)""" self.check(b, a) - + def test_8(self): b = """exec(code, ns)""" a = """exec(code, ns)""" self.check(b, a) - + def test_9(self): b = """exec(code, ns1, ns2)""" a = """exec(code, ns1, ns2)""" @@ -440,40 +443,40 @@ class Test_repr(FixerTestCase): fixer = "repr" - + def test_1(self): b = """x = `1 + 2`""" a = """x = repr(1 + 2)""" self.check(b, a) - + def test_2(self): b = """y = `x`""" a = """y = repr(x)""" self.check(b, a) - + def test_3(self): b = """z = `y`.__repr__()""" a = """z = repr(y).__repr__()""" self.check(b, a) - + def test_4(self): b = """x = `1, 2, 3`""" a = """x = repr((1, 2, 3))""" self.check(b, a) - + def test_5(self): b = """x = `1 + `2``""" a = """x = repr(1 + repr(2))""" self.check(b, a) - + def test_6(self): b = """x = `1, 2 + `3, 4``""" a = """x = repr((1, 2 + repr((3, 4))))""" self.check(b, a) - + class Test_except(): fixer = "except" - + def test_1(self): b = """ try: @@ -482,7 +485,7 @@ pass except ImportError, e: pass""" - + a = """ try: pass @@ -491,42 +494,42 @@ except ImportError as e: pass""" self.check(b, a) - + def test_2(self): b = """ try: pass except (RuntimeError, ImportError), e: pass""" - + a = """ try: pass except (RuntimeError, ImportError) as e: pass""" self.check(b, a) - + def test_3(self): b = """ try: pass except Exception, (a, b): pass""" - + a = """ try: pass except Exception as (a, b): pass""" self.check(b, a) - + def test_4(self): b = """ try: pass except Exception, d[5]: pass""" - + a = """ try: pass @@ -534,14 +537,14 @@ d[5] = xxx_todo_changeme pass""" self.check(b, a) - + def test_5(self): b = """ try: pass except Exception, a.foo: pass""" - + a = """ try: pass @@ -549,14 +552,14 @@ a.foo = xxx_todo_changeme1 pass""" self.check(b, a) - + def test_6(self): b = """ try: pass except Exception, a().foo: pass""" - + a = """ try: pass @@ -564,9 +567,9 @@ a().foo = xxx_todo_changeme2 pass""" self.check(b, a) - + # These should not be touched: - + def test_7(self): b = """ try: @@ -580,7 +583,7 @@ except: pass""" self.check(b, a) - + def test_8(self): b = """ try: @@ -594,7 +597,7 @@ except Exception: pass""" self.check(b, a) - + def test_9(self): b = """ try: @@ -609,94 +612,303 @@ pass""" self.check(b, a) - + class Test_raise(FixerTestCase): fixer = "raise" - + def test_1(self): b = """raise Exception, 5""" a = """raise Exception(5)""" self.check(b, a) - + def test_2(self): b = """raise Exception,5""" a = """raise Exception(5)""" self.check(b, a) - + def test_3(self): b = """raise Exception, (5, 6, 7)""" a = """raise Exception((5, 6, 7))""" self.check(b, a) - + # These should not be touched - + def test_4(self): b = """raise Exception""" a = """raise Exception""" self.check(b, a) - + def test_5(self): b = """raise Exception(5, 6)""" a = """raise Exception(5, 6)""" self.check(b, a) - - # These should produce a warning - + + # These should result in traceback-assignment + + def test_tb_1(self): + b = """def foo(): + raise Exception, 5, 6""" + a = """def foo(): + xxx_todo_changeme = Exception(5) + xxx_todo_changeme.__traceback__ = 6 + raise xxx_todo_changeme""" + self.check(b, a) + + def test_tb_2(self): + b = """def foo(): + a = 5 + raise Exception, 5, 6 + b = 6""" + a = """def foo(): + a = 5 + xxx_todo_changeme1 = Exception(5) + xxx_todo_changeme1.__traceback__ = 6 + raise xxx_todo_changeme1 + b = 6""" + self.check(b, a) + + def test_tb_3(self): + b = """def foo(): + raise Exception,5,6""" + a = """def foo(): + xxx_todo_changeme2 = Exception(5) + xxx_todo_changeme2.__traceback__ = 6 + raise xxx_todo_changeme2""" + self.check(b, a) + + def test_tb_4(self): + b = """def foo(): + a = 5 + raise Exception,5,6 + b = 6""" + a = """def foo(): + a = 5 + xxx_todo_changeme3 = Exception(5) + xxx_todo_changeme3.__traceback__ = 6 + raise xxx_todo_changeme3 + b = 6""" + self.check(b, a) + + def test_tb_5(self): + b = """def foo(): + raise Exception, (5, 6, 7), 6""" + a = """def foo(): + xxx_todo_changeme4 = Exception((5, 6, 7)) + xxx_todo_changeme4.__traceback__ = 6 + raise xxx_todo_changeme4""" + self.check(b, a) + + def test_tb_6(self): + b = """def foo(): + a = 5 + raise Exception, (5, 6, 7), 6 + b = 6""" + a = """def foo(): + a = 5 + xxx_todo_changeme5 = Exception((5, 6, 7)) + xxx_todo_changeme5.__traceback__ = 6 + raise xxx_todo_changeme5 + b = 6""" + self.check(b, a) + + +class Test_throw(FixerTestCase): + fixer = "throw" + + def test_1(self): + b = """g.throw(Exception, 5)""" + a = """g.throw(Exception(5))""" + self.check(b, a) + + def test_2(self): + b = """g.throw(Exception,5)""" + a = """g.throw(Exception(5))""" + self.check(b, a) + + def test_3(self): + b = """g.throw(Exception, (5, 6, 7))""" + a = """g.throw(Exception((5, 6, 7)))""" + self.check(b, a) + + def test_4(self): + b = """5 + g.throw(Exception, 5)""" + a = """5 + g.throw(Exception(5))""" + self.check(b, a) + + # These should not be touched + + def test_5(self): + b = """g.throw(Exception)""" + a = """g.throw(Exception)""" + self.check(b, a) + def test_6(self): - b = """raise Exception, 5, 6""" - a = """raise Exception, 5, 6""" - self.warns(b, a, "raise will not support providing a traceback") - + b = """g.throw(Exception(5, 6))""" + a = """g.throw(Exception(5, 6))""" + self.check(b, a) + def test_7(self): - b = """raise Exception,5,6""" - a = """raise Exception,5,6""" - self.warns(b, a, "raise will not support providing a traceback") - + b = """5 + g.throw(Exception(5, 6))""" + a = """5 + g.throw(Exception(5, 6))""" + self.check(b, a) + + # These should result in traceback-assignment + + def test_tb_1(self): + b = """def foo(): + g.throw(Exception, 5, 6)""" + a = """def foo(): + xxx_todo_changeme6 = Exception(5) + xxx_todo_changeme6.__traceback__ = 6 + g.throw(xxx_todo_changeme6)""" + self.check(b, a) + + def test_tb_2(self): + b = """def foo(): + a = 5 + g.throw(Exception, 5, 6) + b = 6""" + a = """def foo(): + a = 5 + xxx_todo_changeme7 = Exception(5) + xxx_todo_changeme7.__traceback__ = 6 + g.throw(xxx_todo_changeme7) + b = 6""" + self.check(b, a) + + def test_tb_3(self): + b = """def foo(): + g.throw(Exception,5,6)""" + a = """def foo(): + xxx_todo_changeme8 = Exception(5) + xxx_todo_changeme8.__traceback__ = 6 + g.throw(xxx_todo_changeme8)""" + self.check(b, a) + + def test_tb_4(self): + b = """def foo(): + a = 5 + g.throw(Exception,5,6) + b = 6""" + a = """def foo(): + a = 5 + xxx_todo_changeme9 = Exception(5) + xxx_todo_changeme9.__traceback__ = 6 + g.throw(xxx_todo_changeme9) + b = 6""" + self.check(b, a) + + def test_tb_5(self): + b = """def foo(): + g.throw(Exception, (5, 6, 7), 6)""" + a = """def foo(): + xxx_todo_changeme10 = Exception((5, 6, 7)) + xxx_todo_changeme10.__traceback__ = 6 + g.throw(xxx_todo_changeme10)""" + self.check(b, a) + + def test_tb_6(self): + b = """def foo(): + a = 5 + g.throw(Exception, (5, 6, 7), 6) + b = 6""" + a = """def foo(): + a = 5 + xxx_todo_changeme11 = Exception((5, 6, 7)) + xxx_todo_changeme11.__traceback__ = 6 + g.throw(xxx_todo_changeme11) + b = 6""" + self.check(b, a) + + def test_tb_7(self): + b = """def foo(): + a + g.throw(Exception, 5, 6)""" + a = """def foo(): + xxx_todo_changeme12 = Exception(5) + xxx_todo_changeme12.__traceback__ = 6 + a + g.throw(xxx_todo_changeme12)""" + self.check(b, a) + + def test_tb_8(self): + b = """def foo(): + a = 5 + a + g.throw(Exception, 5, 6) + b = 6""" + a = """def foo(): + a = 5 + xxx_todo_changeme13 = Exception(5) + xxx_todo_changeme13.__traceback__ = 6 + a + g.throw(xxx_todo_changeme13) + b = 6""" + self.check(b, a) + + class Test_long(FixerTestCase): fixer = "long" - + def test_1(self): b = """x = long(x)""" a = """x = int(x)""" self.check(b, a) - + def test_2(self): b = """y = isinstance(x, long)""" a = """y = isinstance(x, int)""" self.check(b, a) - + def test_3(self): b = """z = type(x) in (int, long)""" a = """z = type(x) in (int, int)""" self.check(b, a) - + def test_4(self): b = """a = 12L""" a = """a = 12""" self.check(b, a) - + def test_5(self): b = """b = 0x12l""" a = """b = 0x12""" self.check(b, a) - + # These should not be touched - + def test_6(self): b = """a = 12""" a = """a = 12""" self.check(b, a) - + def test_7(self): b = """b = 0x12""" a = """b = 0x12""" self.check(b, a) - + def test_8(self): b = """c = 3.14""" a = """c = 3.14""" self.check(b, a) - + + +class Test_sysexcinfo(FixerTestCase): + fixer = "sysexcinfo" + + def test_1(self): + s = """sys.exc_info()""" + self.warns(s, s, "This function is going away") + + def test_2(self): + s = """if sys.exc_info()[1] == 1: + pass""" + + self.warns(s, s, "This function is going away") + + def test_3(self): + s = """f = sys.exc_info""" + self.warns(s, s, "This function is going away") + + def test_4(self): + s = """f = sys.exc_type + ":" + sys.exc_value""" + self.warns(s, s, "This attribute is going away") if __name__ == "__main__": import sys Modified: sandbox/trunk/2to3/fixes/basefix.py ============================================================================== --- sandbox/trunk/2to3/fixes/basefix.py (original) +++ sandbox/trunk/2to3/fixes/basefix.py Thu Feb 8 23:42:35 2007 @@ -86,6 +86,10 @@ return pygram.parenthesize(node) def new_name(self, template="xxx_todo_changeme"): + """Return a string suitable for use as an identifier + + The new name is guaranteed not to conflict with other identifiers. + """ name = template while name in self.used_names: name = template + str(numbers.next()) @@ -93,6 +97,12 @@ return name def cannot_convert(self, node, reason=None): + """Warn the user that a given chunk of code is not valid Python 3, + but that it cannot be converted automatically. + + First argument is the top-level node for the code in question. + Optional second argument is why it can't be converted. + """ lineno = node.get_lineno() for_output = node.clone() for_output.set_prefix("") Modified: sandbox/trunk/2to3/fixes/fix_apply.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_apply.py (original) +++ sandbox/trunk/2to3/fixes/fix_apply.py Thu Feb 8 23:42:35 2007 @@ -9,7 +9,7 @@ # Local imports import pytree from fixes import basefix - +from fixes.macros import Call, Comma class FixApply(basefix.BaseFix): @@ -49,17 +49,13 @@ kwds.set_prefix("") l_newargs = [pytree.Leaf(token.STAR, "*"), args] if kwds is not None: - l_newargs.extend([pytree.Leaf(token.COMMA, ","), + l_newargs.extend([Comma(), pytree.Leaf(token.DOUBLESTAR, "**"), kwds]) l_newargs[-2].set_prefix(" ") # that's the ** token # XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t) # can be translated into f(x, y, *t) instead of f(*(x, y) + t) - new = pytree.Node(syms.power, - (func, - pytree.Node(syms.trailer, - (pytree.Leaf(token.LPAR, "("), - pytree.Node(syms.arglist, l_newargs), - pytree.Leaf(token.RPAR, ")"))))) + #new = pytree.Node(syms.power, (func, ArgList(l_newargs))) + new = Call(func, l_newargs) new.set_prefix(prefix) return new Modified: sandbox/trunk/2to3/fixes/fix_except.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_except.py (original) +++ sandbox/trunk/2to3/fixes/fix_except.py Thu Feb 8 23:42:35 2007 @@ -7,6 +7,7 @@ # Local imports import pytree from fixes import basefix +from fixes.macros import Assign, Attr, Name def find_excepts(nodes): for i in range(len(nodes)): @@ -19,9 +20,6 @@ as_leaf = pytree.Leaf(token.NAME, "as") as_leaf.set_prefix(" ") -ass_leaf = pytree.Leaf(token.EQUAL, "=") -ass_leaf.set_prefix(" ") - tuple_reason = "exception unpacking is going away" class FixExcept(basefix.BaseFix): @@ -32,42 +30,44 @@ ['finally' ':' suite] | 'finally' ':' suite) > """ - + def transform(self, node): syms = self.syms results = self.match(node) assert results - + try_cleanup = [ch.clone() for ch in results['cleanup']] for except_clause, e_suite in find_excepts(try_cleanup): if len(except_clause.children) == 4: (E, comma, N) = except_clause.children[1:4] comma.replace(as_leaf.clone()) - if str(N).strip()[0] == '(': - # We're dealing with a tuple - self.cannot_convert(N, tuple_reason) - elif N.type != token.NAME: + if N.type != token.NAME: # Generate a new N for the except clause - new_N = pytree.Leaf(token.NAME, self.new_name()) + new_N = Name(self.new_name()) new_N.set_prefix(" ") target = N.clone() target.set_prefix("") N.replace(new_N) - + new_N = new_N.clone() + # Insert "old_N = new_N" as the first statement in - # the except body + # the except body. This loop skips leading whitespace + # and indents suite_stmts = list(e_suite.children) for i, stmt in enumerate(suite_stmts): if isinstance(stmt, pytree.Node): break - assign = pytree.Node(syms.atom, - [target, - ass_leaf.clone(), - new_N.clone()]) - - assign.parent = e_suite + + # The assignment is different if old_N is a tuple + # In that case, the assignment is old_N = new_N.message + if str(N).strip()[0] == '(': + assign = Assign(target, Attr(new_N, Name('message'))) + else: + assign = Assign(target, new_N) + + assign.parent = e_suite suite_stmts = suite_stmts[:i] + [assign] + suite_stmts e_suite.children = tuple(suite_stmts) - + children = [c.clone() for c in node.children[:3]] + try_cleanup return pytree.Node(node.type, children) Modified: sandbox/trunk/2to3/fixes/fix_exec.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_exec.py (original) +++ sandbox/trunk/2to3/fixes/fix_exec.py Thu Feb 8 23:42:35 2007 @@ -9,6 +9,7 @@ # Local imports import pytree from fixes import basefix +from fixes.macros import Comma, Name, Call class FixExec(basefix.BaseFix): @@ -29,14 +30,10 @@ args = [a.clone()] args[0].set_prefix("") if b is not None: - args.extend([pytree.Leaf(token.COMMA, ","), b.clone()]) + args.extend([Comma(), b.clone()]) if c is not None: - args.extend([pytree.Leaf(token.COMMA, ","), c.clone()]) - new = pytree.Node(syms.factor, - [pytree.Leaf(token.NAME, "exec"), - pytree.Node(syms.trailer, - [pytree.Leaf(token.LPAR, "("), - pytree.Node(syms.arglist, args), - pytree.Leaf(token.RPAR, ")")])]) + args.extend([Comma(), c.clone()]) + + new = Call(Name("exec"), args) new.set_prefix(node.get_prefix()) return new Modified: sandbox/trunk/2to3/fixes/fix_has_key.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_has_key.py (original) +++ sandbox/trunk/2to3/fixes/fix_has_key.py Thu Feb 8 23:42:35 2007 @@ -9,6 +9,7 @@ # Local imports import pytree from fixes import basefix +from fixes.macros import Name class FixHasKey(basefix.BaseFix): @@ -68,10 +69,10 @@ else: before = pytree.Node(syms.power, before) before.set_prefix(" ") - n_op = pytree.Leaf(token.NAME, "in") + n_op = Name("in") n_op.set_prefix(" ") if negation: - n_not = pytree.Leaf(token.NAME, "not") + n_not = Name("not") n_not.set_prefix(" ") n_op = pytree.Node(syms.comp_op, (n_not, n_op)) new = pytree.Node(syms.comparison, (arg, n_op, before)) Modified: sandbox/trunk/2to3/fixes/fix_intern.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_intern.py (original) +++ sandbox/trunk/2to3/fixes/fix_intern.py Thu Feb 8 23:42:35 2007 @@ -9,6 +9,7 @@ # Local imports import pytree from fixes import basefix +from fixes.macros import Name, Attr class FixIntern(basefix.BaseFix): @@ -36,14 +37,11 @@ if after: after = tuple(n.clone() for n in after) new = pytree.Node(syms.power, - (pytree.Leaf(token.NAME, "sys"), - pytree.Node(syms.trailer, - [pytree.Leaf(token.DOT, "."), - pytree.Leaf(token.NAME, "intern")]), - pytree.Node(syms.trailer, + Attr(Name("sys"), Name("intern")) + + (pytree.Node(syms.trailer, [results["lpar"].clone(), newarglist, - results["rpar"].clone()])) + results["rpar"].clone()]),) + after) new.set_prefix(node.get_prefix()) return new Modified: sandbox/trunk/2to3/fixes/fix_long.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_long.py (original) +++ sandbox/trunk/2to3/fixes/fix_long.py Thu Feb 8 23:42:35 2007 @@ -12,6 +12,7 @@ # Local imports import pytree from fixes import basefix +from fixes.macros import Name class FixLong(basefix.BaseFix): @@ -20,8 +21,8 @@ (long_type = 'long' | number = NUMBER) """ - static_long = pytree.Leaf(token.NAME, "long") - static_int = pytree.Leaf(token.NAME, "int") + static_long = Name("long") + static_int = Name("int") def transform(self, node): results = self.match(node) Modified: sandbox/trunk/2to3/fixes/fix_print.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_print.py (original) +++ sandbox/trunk/2to3/fixes/fix_print.py Thu Feb 8 23:42:35 2007 @@ -16,6 +16,7 @@ # Local imports import pytree from fixes import basefix +from fixes.macros import Name, Call, Comma class FixPrint(basefix.BaseFix): @@ -36,19 +37,15 @@ results = self.match(node) assert results - if node == pytree.Leaf(token.NAME, "print"): + if node == Name("print"): # Special-case print all by itself - new = pytree.Node(syms.power, - (pytree.Leaf(token.NAME, "Print"), - pytree.Node(syms.trailer, - (pytree.Leaf(token.LPAR, "("), - pytree.Leaf(token.RPAR, ")"))))) + new = Call(Name("Print"), []) new.set_prefix(node.get_prefix()) return new - assert node.children[0] == pytree.Leaf(token.NAME, "print") + assert node.children[0] == Name("print") args = node.children[1:] sep = end = file = None - if args and args[-1] == pytree.Leaf(token.COMMA, ","): + if args and args[-1] == Comma(): args = args[:-1] end = " " if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"): @@ -56,7 +53,6 @@ file = args[1].clone() args = args[3:] # Strip a possible comma after the file expression # Now synthesize a Print(args, sep=..., end=..., file=...) node. - n_print = pytree.Leaf(token.NAME, "Print") # XXX -> "print" l_args = [arg.clone() for arg in args] if l_args: l_args[0].set_prefix("") @@ -69,15 +65,7 @@ pytree.Leaf(token.STRING, repr(end))) if file is not None: self.add_kwarg(l_args, "file", file) - if l_args: - n_arglist = pytree.Node(syms.arglist, l_args) - else: - n_arglist = None - l_args = [pytree.Leaf(token.LPAR, "("), pytree.Leaf(token.RPAR, ")")] - if n_arglist: - l_args.insert(1, n_arglist) - n_trailer = pytree.Node(syms.trailer, l_args) - n_stmt = pytree.Node(syms.power, (n_print, n_trailer)) + n_stmt = Call(Name("Print"), l_args) n_stmt.set_prefix(node.get_prefix()) return n_stmt @@ -85,10 +73,10 @@ # XXX All this prefix-setting may lose comments (though rarely) n_expr.set_prefix("") n_argument = pytree.Node(self.syms.argument, - (pytree.Leaf(token.NAME, s_kwd), + (Name(s_kwd), pytree.Leaf(token.EQUAL, "="), n_expr)) if l_nodes: - l_nodes.append(pytree.Leaf(token.COMMA, ",")) + l_nodes.append(Comma()) n_argument.set_prefix(" ") l_nodes.append(n_argument) Modified: sandbox/trunk/2to3/fixes/fix_raise.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_raise.py (original) +++ sandbox/trunk/2to3/fixes/fix_raise.py Thu Feb 8 23:42:35 2007 @@ -1,4 +1,4 @@ -"""Fixer for 'raise E, a1, a2, ...'""" +"""Fixer for 'raise E, V, T'""" # Author: Collin Winter # Python imports @@ -7,35 +7,57 @@ # Local imports import pytree from fixes import basefix - -reason = "Python 3's raise will not support providing a traceback" +from fixes.macros import Name, Call, Assign, Newline, Attr class FixRaise(basefix.BaseFix): PATTERN = """ - raise_stmt< 'raise' exc=any ',' a1=any [',' a2=any] > + raise_stmt< 'raise' exc=any ',' val=any [',' tb=any] > """ def transform(self, node): syms = self.syms results = self.match(node) assert results - + exc = results["exc"].clone() - args = [results["a1"].clone()] + args = [results["val"].clone()] args[0].set_prefix("") - - arg2 = results.get("a2") - if arg2 is not None: - self.cannot_convert(node, reason) - return node - - new = pytree.Node(syms.raise_stmt, - [pytree.Leaf(token.NAME, "raise"), - exc, - pytree.Node(syms.trailer, - [pytree.Leaf(token.LPAR, "("), - pytree.Node(syms.arglist, args), - pytree.Leaf(token.RPAR, ")")])]) - new.set_prefix(node.get_prefix()) - return new + + if "tb" in results: + tb = results["tb"].clone() + name = Name(self.new_name()) + children = list(node.parent.parent.children) + i = children.index(node.parent) + indent = children[1].value + + # Instance the exception + build_e = pytree.Node(syms.simple_stmt, + [Assign(name.clone(), Call(exc, args)), + Newline()]) + build_e.parent = node.parent.parent + if node.get_prefix(): + # Over-indents otherwise + build_e.set_prefix(indent) + + # Assign the traceback + set_tb = pytree.Node(syms.simple_stmt, + [Assign(Attr(name.clone(), + Name("__traceback__")), tb), + Newline()]) + set_tb.set_prefix(indent) + set_tb.parent = node.parent.parent + + # Insert into the suite + children[i:i] = [build_e, set_tb] + node.parent.parent.children = tuple(children) + + name.set_prefix(" ") + new = pytree.Node(syms.simple_stmt, [Name("raise"), name]) + new.set_prefix(indent) + return new + else: + new = pytree.Node(syms.raise_stmt, + [Name("raise"), Call(exc, args)]) + new.set_prefix(node.get_prefix()) + return new Modified: sandbox/trunk/2to3/fixes/fix_repr.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_repr.py (original) +++ sandbox/trunk/2to3/fixes/fix_repr.py Thu Feb 8 23:42:35 2007 @@ -9,6 +9,7 @@ # Local imports import pytree from fixes import basefix +from fixes.macros import Call, Name class FixRepr(basefix.BaseFix): @@ -23,11 +24,6 @@ expr = results["expr"].clone() if expr.type == self.syms.testlist1: expr = self.parenthesize(expr) - new = pytree.Node(self.syms.power, - (pytree.Leaf(token.NAME, "repr"), - pytree.Node(self.syms.trailer, - (pytree.Leaf(token.LPAR, "("), - expr, - pytree.Leaf(token.RPAR, ")"))))) + new = Call(Name("repr"), [expr]) new.set_prefix(node.get_prefix()) return new Added: sandbox/trunk/2to3/fixes/fix_sysexcinfo.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/fix_sysexcinfo.py Thu Feb 8 23:42:35 2007 @@ -0,0 +1,32 @@ +"""Fixer/warner for sys.exc_{info,value,type,traceback}""" +# Author: Collin Winter + +# Python imports +import token + +# Local imports +from pytree import Leaf +from fixes import basefix + + +class FixSysexcinfo(basefix.BaseFix): + + PATTERN = """ + power< 'sys' trailer< '.' attr='exc_info'> any* > + | + power< 'sys' + trailer< '.' attr=('exc_value' | 'exc_traceback' | 'exc_type')> + any* > + """ + + def transform(self, node): + results = self.match(node) + assert results + attr = results['attr'] + + if isinstance(attr, Leaf) and attr.value == 'exc_info': + self.cannot_convert(node, + "This function is going away in Python 3") + else: + self.cannot_convert(node, + "This attribute is going away in Python 3") Added: sandbox/trunk/2to3/fixes/fix_throw.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/fix_throw.py Thu Feb 8 23:42:35 2007 @@ -0,0 +1,80 @@ +"""Fixer for generator.throw(E, V, T)""" +# Author: Collin Winter + +# Python imports +import token + +# Local imports +import pytree +from fixes import basefix +from fixes.macros import Name, Call, Assign, Newline, Attr + +class FixThrow(basefix.BaseFix): + + PATTERN = """ + power< any trailer< '.' 'throw' > + trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' > + > + """ + + def transform(self, node): + syms = self.syms + results = self.match(node) + assert results + + throw_args = results["args"] + exc = results["exc"].clone() + args = [results["val"].clone()] + args[0].set_prefix("") + + if "tb" in results: + tb = results["tb"].clone() + name = Name(self.new_name()) + suite = find_parent_suite(node) + stmts = list(suite.children) + node_stmt = find_stmt(stmts, node) + i = stmts.index(node_stmt) + indent = stmts[1].value + + # Instance the exception + build_e = pytree.Node(syms.simple_stmt, + [Assign(name.clone(), Call(exc, args)), + Newline()]) + build_e.parent = node.parent.parent + if node_stmt.get_prefix(): + # Over-indents otherwise + build_e.set_prefix(indent) + + # Assign the traceback + tb.set_prefix(" ") + set_tb = pytree.Node(syms.simple_stmt, + [Assign(Attr(name.clone(), + Name("__traceback__")), tb), + Newline()]) + set_tb.set_prefix(indent) + set_tb.parent = node.parent.parent + + # Insert into the suite + stmts[i:i] = [build_e, set_tb] + suite.children = tuple(stmts) + + throw_args.replace(name) + if not node_stmt.get_prefix(): + node_stmt.set_prefix(indent) + # No return + else: + throw_args.replace(Call(exc, args)) + # No return + + +def find_parent_suite(node): + parent = node.parent + while parent: + if len(parent.children) > 2 and parent.children[0].value == "\n": + return parent + parent = parent.parent + +def find_stmt(stmts, node): + while node not in stmts: + node = node.parent + return node Added: sandbox/trunk/2to3/fixes/macros.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/macros.py Thu Feb 8 23:42:35 2007 @@ -0,0 +1,57 @@ +"""Abstract away often-used node construction routines.""" +# Author: Collin Winter + +# Python imports +import token + +# Local imports +from pytree import Leaf, Node +from pygram import python_symbols as syms + + +### Constant nodes +ass_leaf = Leaf(token.EQUAL, "=") +ass_leaf.set_prefix(" ") + +comma_leaf = Leaf(token.COMMA, ",") +lparen_leaf = Leaf(token.LPAR, "(") +rparen_leaf = Leaf(token.RPAR, ")") + +def Assign(target, source): + """Build an assignment statement""" + if not isinstance(target, tuple): + target = (target,) + if not isinstance(source, tuple): + source.set_prefix(" ") + source = (source,) + + return Node(syms.atom, target + (ass_leaf.clone(),) + source) + +def Name(name): + """Return a NAME leaf""" + return Leaf(token.NAME, name) + +def Attr(obj, attr): + """A node tuple for obj.attr""" + return (obj, + Node(syms.trailer, [Leaf(token.DOT, '.'), + attr])) + +def Comma(): + """A comma leaf""" + return comma_leaf.clone() + +def ArgList(args, lparen=lparen_leaf, rparen=rparen_leaf): + """A parenthesised argument list, used by Call()""" + return Node(syms.trailer, + [lparen.clone(), + Node(syms.arglist, args), + rparen.clone()]) + +def Call(func_name, args): + """A function call""" + return Node(syms.power, [func_name, ArgList(args)]) + +def Newline(): + """A newline literal""" + return Leaf(token.NEWLINE, "\n") Modified: sandbox/trunk/2to3/pytree.py ============================================================================== --- sandbox/trunk/2to3/pytree.py (original) +++ sandbox/trunk/2to3/pytree.py Thu Feb 8 23:42:35 2007 @@ -115,8 +115,9 @@ if new is not None: new.parent = self.parent self.parent = None - + def get_lineno(self): + """Returns the line number which generated the invocant node.""" node = self while not isinstance(node, Leaf): if not node.children: Modified: sandbox/trunk/2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/refactor.py (original) +++ sandbox/trunk/2to3/refactor.py Thu Feb 8 23:42:35 2007 @@ -24,6 +24,7 @@ import patcomp from pgen2 import driver import fixes +import fixes.macros import pygram logging.basicConfig(format='%(name)s: %(message)s', level=logging.INFO) From python-checkins at python.org Thu Feb 8 23:46:51 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 8 Feb 2007 23:46:51 +0100 (CET) Subject: [Python-checkins] r53678 - sandbox/trunk/2to3/fixes/fix_throw.py Message-ID: <20070208224651.2317F1E4008@bag.python.org> Author: guido.van.rossum Date: Thu Feb 8 23:46:50 2007 New Revision: 53678 Modified: sandbox/trunk/2to3/fixes/fix_throw.py Log: Fix unit test failure caused by improper indentation in PATTERN (introduced by my folding a long line). Modified: sandbox/trunk/2to3/fixes/fix_throw.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_throw.py (original) +++ sandbox/trunk/2to3/fixes/fix_throw.py Thu Feb 8 23:46:50 2007 @@ -14,7 +14,7 @@ PATTERN = """ power< any trailer< '.' 'throw' > trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' > - > + > """ def transform(self, node): From python-checkins at python.org Thu Feb 8 23:58:19 2007 From: python-checkins at python.org (kurt.kaiser) Date: Thu, 8 Feb 2007 23:58:19 +0100 (CET) Subject: [Python-checkins] r53679 - python/trunk/Lib/idlelib/AutoCompleteWindow.py python/trunk/Lib/idlelib/NEWS.txt python/trunk/Lib/idlelib/help.txt Message-ID: <20070208225819.546331E4009@bag.python.org> Author: kurt.kaiser Date: Thu Feb 8 23:58:18 2007 New Revision: 53679 Modified: python/trunk/Lib/idlelib/AutoCompleteWindow.py python/trunk/Lib/idlelib/NEWS.txt python/trunk/Lib/idlelib/help.txt Log: Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented; mouse and cursor selection in ACWindow implemented; double Tab inserts current selection and closes ACW (similar to double-click and Return); scroll wheel now works in ACW. Added AutoComplete instructions to IDLE Help. Modified: python/trunk/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/trunk/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/trunk/Lib/idlelib/AutoCompleteWindow.py Thu Feb 8 23:58:18 2007 @@ -10,13 +10,14 @@ KEYPRESS_VIRTUAL_EVENT_NAME = "<>" # We need to bind event beyond so that the function will be called # before the default specific IDLE function -KEYPRESS_SEQUENCES = ("", "", "", - "", "", "", "") +KEYPRESS_SEQUENCES = ("", "", "", "", + "", "", "", "", + "", "") KEYRELEASE_VIRTUAL_EVENT_NAME = "<>" KEYRELEASE_SEQUENCE = "" -LISTUPDATE_SEQUENCE = "" +LISTUPDATE_SEQUENCE = "" WINCONFIG_SEQUENCE = "" -DOUBLECLICK_SEQUENCE = "" +DOUBLECLICK_SEQUENCE = "" class AutoCompleteWindow: @@ -49,6 +50,8 @@ # event ids self.hideid = self.keypressid = self.listupdateid = self.winconfigid \ = self.keyreleaseid = self.doubleclickid = None + # Flag set if last keypress was a tab + self.lastkey_was_tab = False def _change_start(self, newstart): i = 0 @@ -118,11 +121,6 @@ i = 0 while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]: i += 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) @@ -206,7 +204,7 @@ self.keyrelease_event) self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE) self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, - self.listupdate_event) + self.listselect_event) self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event) self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, self.doubleclick_event) @@ -237,11 +235,12 @@ return self.hide_window() - def listupdate_event(self, event): + def listselect_event(self, event): if not self.is_active(): return self.userwantswindow = True - self._selection_changed() + cursel = int(self.listbox.curselection()[0]) + self._change_start(self.completions[cursel]) def doubleclick_event(self, event): # Put the selected completion in the text, and close the list @@ -257,7 +256,8 @@ state = event.mc_state else: state = 0 - + if keysym != "Tab": + self.lastkey_was_tab = False if (len(keysym) == 1 or keysym in ("underscore", "BackSpace") or (self.mode==AutoComplete.COMPLETE_FILES and keysym in ("period", "minus"))) \ @@ -339,13 +339,21 @@ self.listbox.select_clear(cursel) self.listbox.select_set(newsel) self._selection_changed() + self._change_start(self.completions[newsel]) return "break" elif (keysym == "Tab" and not state): - # The user wants a completion, but it is handled by AutoComplete - # (not AutoCompleteWindow), so ignore. - self.userwantswindow = True - return + if self.lastkey_was_tab: + # two tabs in a row; insert current selection and close acw + cursel = int(self.listbox.curselection()[0]) + self._change_start(self.completions[cursel]) + self.hide_window() + return "break" + else: + # first tab; let AutoComplete handle the completion + self.userwantswindow = True + self.lastkey_was_tab = True + return elif reduce(lambda x, y: x or y, [keysym.find(s) != -1 for s in ("Shift", "Control", "Alt", Modified: python/trunk/Lib/idlelib/NEWS.txt ============================================================================== --- python/trunk/Lib/idlelib/NEWS.txt (original) +++ python/trunk/Lib/idlelib/NEWS.txt Thu Feb 8 23:58:18 2007 @@ -3,6 +3,11 @@ *Release date: XX-XXX-200X* +- Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented; + mouse and cursor selection in ACWindow implemented; double Tab inserts + current selection and closes ACW (similar to double-click and Return); scroll + wheel now works in ACW. Added AutoComplete instructions to IDLE Help. + - AutoCompleteWindow moved below input line, will move above if there isn't enough space. Patch 1621265 Tal Einat Modified: python/trunk/Lib/idlelib/help.txt ============================================================================== --- python/trunk/Lib/idlelib/help.txt (original) +++ python/trunk/Lib/idlelib/help.txt Thu Feb 8 23:58:18 2007 @@ -44,6 +44,10 @@ Find in Files... -- Open a search dialog box for searching files Replace... -- Open a search-and-replace dialog box Go to Line -- Ask for a line number and show that line + Show Calltip -- Open a small window with function param hints + Show Completions -- Open a scroll window allowing selection keywords + and attributes. (see '*TIPS*', below) + Show Parens -- Highlight the surrounding parenthesis Expand Word -- Expand the word you have typed to match another word in the same buffer; repeat to get a different expansion @@ -91,6 +95,7 @@ Code Context -- Open a pane at the top of the edit window which shows the block context of the section of code which is scrolling off the top or the window. + (Not present in Shell window.) Windows Menu: @@ -138,8 +143,11 @@ Control-left/right Arrow moves by words in a strange but useful way. Home/End go to begin/end of line. Control-Home/End go to begin/end of file. - Some useful Emacs bindings (Control-a, Control-e, Control-k, etc.) - are inherited from Tcl/Tk. + Some useful Emacs bindings are inherited from Tcl/Tk: + Control-a beginning of line + Control-e end of line + Control-k kill line (but doesn't put it in clipboard) + Control-l center window around the insertion point Standard Windows bindings may work on that platform. Keybindings are selected in the Settings Dialog, look there. @@ -155,6 +163,52 @@ See also the indent/dedent region commands in the edit menu. +Completions: + + Completions are supplied for functions, classes, and attributes of + classes, both built-in and user-defined. Completions are also provided + for filenames. + + The AutoCompleteWindow (ACW) will open after a predefined delay + (default is two seconds) after a '.' or (in a string) an os.sep is + typed. If after one of those characters (plus zero or more other + characters) you type a Tab the ACW will open immediately if a possible + continuation is found. + + If there is only one possible completion for the characters entered, a + Tab will supply that completion without opening the ACW. + + 'Show Completions' will force open a completions window. In an empty + string, this will contain the files in the current directory. On a + blank line, it will contain the built-in and user-defined functions and + classes in the current name spaces, plus any modules imported. If some + characters have been entered, the ACW will attempt to be more specific. + + If string of characters is typed, the ACW selection will jump to the + entry most closely matching those characters. Entering a Tab will cause + the longest non-ambiguous match to be entered in the Edit window or + Shell. Two Tabs in a row will supply the current ACW selection, as + will Return or a double click. Cursor keys, Page Up/Down, mouse + selection, and the scrollwheel all operate on the ACW. + + 'Hidden' attributes can be accessed by typing the beginning of hidden + name after a '.'. e.g. '_'. This allows access to modules with + '__all__' set, or to class-private attributes. + + Completions and the 'Expand Word' facility can save a lot of typing! + + Completions are currently limited to those in the namespaces. Names in + an Edit window which are not via __main__ or sys.modules will not be + found. Run the module once with your imports to correct this + situation. Note that IDLE itself places quite a few modules in + sys.modules, so much can be found by default, e.g. the re module. + + If you don't like the ACW popping up unbidden, simply make the delay + longer or disable the extension. OTOH, you could make the delay zero. + + You could also switch off the CallTips extension. (We will be adding + a delay to the call tip window.) + Python Shell window: Control-c interrupts executing command. @@ -165,7 +219,7 @@ Alt-p retrieves previous command matching what you have typed. Alt-n retrieves next. - (These are Control-p, Control-n on the Mac) + (These are Control-p, Control-n on the Mac) Return while cursor is on a previous command retrieves that command. Expand word is also useful to reduce typing. @@ -196,7 +250,7 @@ be changed using the Settings dialog. Command line usage: - + Enter idle -h at the command prompt to get a usage message. Running without a subprocess: @@ -211,3 +265,18 @@ re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. + +Extensions: + + IDLE contains an extension facility. See the beginning of + config-extensions.def in the idlelib directory for further information. + The default extensions are currently: + + FormatParagraph + AutoExpand + ZoomHeight + ScriptBinding + CallTips + ParenMatch + AutoComplete + CodeContext From buildbot at python.org Fri Feb 9 00:22:28 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 08 Feb 2007 23:22:28 +0000 Subject: [Python-checkins] buildbot warnings in amd64 gentoo trunk Message-ID: <20070208232228.E3BA71E4009@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo trunk. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%2520trunk/builds/1824 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Fri Feb 9 00:54:16 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 00:54:16 +0100 (CET) Subject: [Python-checkins] r53680 - sandbox/trunk/2to3/fixer_tests.py Message-ID: <20070208235416.5CF951E4009@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 00:54:15 2007 New Revision: 53680 Modified: sandbox/trunk/2to3/fixer_tests.py (contents, props changed) Log: Make fixer_tests.py executable, adding a #! line. Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Fri Feb 9 00:54:15 2007 @@ -1,3 +1,4 @@ +#!/usr/bin/env python2.5 """ Test suite for the fixer modules """ # Author: Collin Winter From buildbot at python.org Fri Feb 9 01:20:07 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 09 Feb 2007 00:20:07 +0000 Subject: [Python-checkins] buildbot warnings in hppa Ubuntu dapper trunk Message-ID: <20070209002008.0C2CB1E4021@bag.python.org> The Buildbot has detected a new failure of hppa Ubuntu dapper trunk. Full details are available at: http://www.python.org/dev/buildbot/all/hppa%2520Ubuntu%2520dapper%2520trunk/builds/68 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: kurt.kaiser Build had warnings: warnings test Excerpt from the test logfile: make: *** [buildbottest] Killed sincerely, -The Buildbot From python-checkins at python.org Fri Feb 9 02:27:50 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 02:27:50 +0100 (CET) Subject: [Python-checkins] r53681 - in sandbox/trunk/2to3: example.py fixes/fix_dict.py Message-ID: <20070209012750.2F6C11E4009@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 02:27:49 2007 New Revision: 53681 Added: sandbox/trunk/2to3/fixes/fix_dict.py (contents, props changed) Modified: sandbox/trunk/2to3/example.py Log: Work checkpoint: convert d.keys(), d.iterkeys() etc. Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Fri Feb 9 02:27:49 2007 @@ -243,5 +243,36 @@ b = 0x12 c = 3.14 +def dict_examples(): + # + # Plain method calls + # + print d.keys() + print d.items() + print d.values() + # + # Plain method calls in special contexts + # + print list(e.keys()) + print sorted(e.keys()) + print iter(e.keys()) + for i in e.keys(): print i + # + # Iterator method calls + # + print d.iterkeys() + print d.iteritems() + print d.itervalues() + # + # Iterator method calls in special contexts + # + print list(e.iterkeys()) + print sorted(e.iterkeys()) + print iter(e.iterkeys()) + for i in e.iterkeys(): print i + # + # This should be left unchanged but trigger a warning: + # + print d.keys()[0] # This is the last line. Added: sandbox/trunk/2to3/fixes/fix_dict.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/fix_dict.py Fri Feb 9 02:27:49 2007 @@ -0,0 +1,90 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. + +"""Fixer for dict methods. + +d.keys() -> list(d.keys()) +d.items() -> list(d.items()) +d.values() -> list(d.values()) + +d.iterkeys() -> iter(d.keys()) +d.iteritems() -> iter(d.items()) +d.itervalues() -> iter(d.values()) + +Except in certain very specific contexts: the iter() can be dropped +when the context is list(), sorted(), iter() or for...in; the list() +can be dropped when the context is list() or sorted() (but not iter() +or for...in!). + +Note: iter(d.keys()) could be written as iter(d) but since the +original d.iterkeys() was also redundant we don't fix this. And there +are (rare) contexts where it makes a difference (e.g. when passing it +as an argument to a function that introspects the argument). +""" + +# Python imports +import token + +# Local imports +import pytree +import patcomp +from fixes import basefix +from fixes import macros + +class FixDict(basefix.BaseFix): + + PATTERN = """ + power< prefix=any+ + trailer< '.' method=('keys'|'items'|'values'| + 'iterkeys'|'iteritems'|'itervalues') > + trailer< '(' ')' > + tail=any* + > + """ + + def transform(self, node): + results = self.match(node) + prefix = results["prefix"] + method = results["method"][0].value # Extract method name + tail = results["tail"] + if tail: + return self.cannot_convert(node, + "stuff after .[iter]keys() etc. unsupported") + syms = self.syms + isiter = method.startswith("iter") + if isiter: + method = method[4:] + assert method in ("keys", "items", "values"), repr(method) + prefix = [n.clone() for n in prefix] + new = pytree.Node(syms.power, + prefix + [pytree.Node(syms.trailer, + [pytree.Leaf(token.DOT, '.'), + macros.Name(method)]), + pytree.Node(syms.trailer, + [macros.lparen_leaf.clone(), + macros.rparen_leaf.clone()])]) + if not self.in_special_context(node, isiter): + new.set_prefix("") + new = macros.Call(macros.Name(isiter and "iter" or "list"), [new]) + new.set_prefix(node.get_prefix()) + return new + + P1 = "trailer< '(' node=any ')' >" + p1 = patcomp.PatternCompiler().compile_pattern(P1) + + P2 = "power< func=NAME trailer< '(' node=any ')' > any* >" + p2 = patcomp.PatternCompiler().compile_pattern(P2) + + def in_special_context(self, node, isiter): + results = {} + if not (self.p1.match(node.parent, results) and + results["node"] is node): + return False + results = {} + if not (self.p2.match(node.parent.parent, results) and + results["node"] is node): + return False + if isiter: + return results["func"].value == ("iter", "list", "sorted") + else: + return results["func"].value in ("list", "sorted") + # XXX TODO: for...in context. From python-checkins at python.org Fri Feb 9 05:10:51 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 05:10:51 +0100 (CET) Subject: [Python-checkins] r53682 - in sandbox/trunk/2to3: example.py fixes/fix_dict.py Message-ID: <20070209041051.1D9F71E4009@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 05:10:50 2007 New Revision: 53682 Modified: sandbox/trunk/2to3/example.py sandbox/trunk/2to3/fixes/fix_dict.py Log: Refactor the context checking a bit. Add support for special contexts 'for...in'. Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Fri Feb 9 05:10:50 2007 @@ -253,26 +253,35 @@ # # Plain method calls in special contexts # - print list(e.keys()) - print sorted(e.keys()) print iter(e.keys()) for i in e.keys(): print i + [i for i in e.keys()] + (i for i in e.keys()) # # Iterator method calls # - print d.iterkeys() - print d.iteritems() - print d.itervalues() + print f.iterkeys() + print f.iteritems() + print f.itervalues() # # Iterator method calls in special contexts # - print list(e.iterkeys()) - print sorted(e.iterkeys()) - print iter(e.iterkeys()) - for i in e.iterkeys(): print i + print list(g.iterkeys()) + print sorted(g.iterkeys()) + print iter(g.iterkeys()) + for i in g.iterkeys(): print i + [i for i in g.iterkeys()] + (i for i in g.iterkeys()) + +def dict_negative_examples(): + # + # These should all remain unchanged: + # + print list(h.keys()) + print sorted(h.keys()) # - # This should be left unchanged but trigger a warning: + # This should be left unchanged and trigger a warning: # - print d.keys()[0] + print h.keys()[0] # This is the last line. Modified: sandbox/trunk/2to3/fixes/fix_dict.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_dict.py (original) +++ sandbox/trunk/2to3/fixes/fix_dict.py Fri Feb 9 05:10:50 2007 @@ -68,23 +68,29 @@ new.set_prefix(node.get_prefix()) return new - P1 = "trailer< '(' node=any ')' >" + P1 = "power< func=NAME trailer< '(' node=any ')' > any* >" p1 = patcomp.PatternCompiler().compile_pattern(P1) - P2 = "power< func=NAME trailer< '(' node=any ')' > any* >" + P2 = """for_stmt< 'for' any 'in' node=any ':' any* > + | list_for< 'for' any 'in' node=any any* > + | gen_for< 'for' any 'in' node=any any* > + """ p2 = patcomp.PatternCompiler().compile_pattern(P2) def in_special_context(self, node, isiter): - results = {} - if not (self.p1.match(node.parent, results) and - results["node"] is node): + if node.parent is None: return False results = {} - if not (self.p2.match(node.parent.parent, results) and - results["node"] is node): + if (node.parent.parent is not None and + self.p1.match(node.parent.parent, results) and + results["node"] is node): + if isiter: + # iter(d.iterkeys()) -> iter(d.keys()), etc. + return results["func"].value in ("iter", "list", "sorted") + else: + # list(d.keys()) -> list(d.keys()), etc. + return results["func"].value in ("list", "sorted") + if not isiter: return False - if isiter: - return results["func"].value == ("iter", "list", "sorted") - else: - return results["func"].value in ("list", "sorted") - # XXX TODO: for...in context. + # for ... in d.iterkeys() -> for ... in d.keys(), etc. + return self.p2.match(node.parent, results) and results["node"] is node From python-checkins at python.org Fri Feb 9 05:41:13 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 05:41:13 +0100 (CET) Subject: [Python-checkins] r53683 - sandbox/trunk/2to3/fixer_tests.py Message-ID: <20070209044113.0549F1E4009@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 05:41:12 2007 New Revision: 53683 Modified: sandbox/trunk/2to3/fixer_tests.py Log: Unit tests for dict fixer. Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Fri Feb 9 05:41:12 2007 @@ -911,6 +911,116 @@ s = """f = sys.exc_type + ":" + sys.exc_value""" self.warns(s, s, "This attribute is going away") + +class Test_dict(FixerTestCase): + fixer = "dict" + + def test_01(self): + b = "d.keys()" + a = "list(d.keys())" + self.check(b, a) + + def test_01a(self): + b = "a[0].foo().keys()" + a = "list(a[0].foo().keys())" + self.check(b, a) + + def test_02(self): + b = "d.items()" + a = "list(d.items())" + self.check(b, a) + + def test_03(self): + b = "d.values()" + a = "list(d.values())" + self.check(b, a) + + def test_04(self): + b = "d.iterkeys()" + a = "iter(d.keys())" + self.check(b, a) + + def test_05(self): + b = "d.iteritems()" + a = "iter(d.items())" + self.check(b, a) + + def test_06(self): + b = "d.itervalues()" + a = "iter(d.values())" + self.check(b, a) + + def test_07(self): + b = "list(d.keys())" + a = b + self.check(b, a) + + def test_08(self): + b = "sorted(d.keys())" + a = b + self.check(b, a) + + def test_09(self): + b = "iter(d.keys())" + a = "iter(list(d.keys()))" + self.check(b, a) + + def test_10(self): + b = "foo(d.keys())" + a = "foo(list(d.keys()))" + self.check(b, a) + + def test_11(self): + b = "for i in d.keys(): print i" + a = "for i in list(d.keys()): print i" + self.check(b, a) + + def test_12(self): + b = "for i in d.iterkeys(): print i" + a = "for i in d.keys(): print i" + self.check(b, a) + + def test_13(self): + b = "[i for i in d.keys()]" + a = "[i for i in list(d.keys())]" + self.check(b, a) + + def test_14(self): + b = "[i for i in d.iterkeys()]" + a = "[i for i in d.keys()]" + self.check(b, a) + + def test_15(self): + b = "(i for i in d.keys())" + a = "(i for i in list(d.keys()))" + self.check(b, a) + + def test_16(self): + b = "(i for i in d.iterkeys())" + a = "(i for i in d.keys())" + self.check(b, a) + + def test_17(self): + b = "iter(d.iterkeys())" + a = "iter(d.keys())" + self.check(b, a) + + def test_18(self): + b = "list(d.iterkeys())" + a = "list(d.keys())" + self.check(b, a) + + def test_19(self): + b = "sorted(d.iterkeys())" + a = "sorted(d.keys())" + self.check(b, a) + + def test_20(self): + b = "foo(d.iterkeys())" + a = "foo(iter(d.keys()))" + self.check(b, a) + + if __name__ == "__main__": import sys if not sys.argv[1:]: From python-checkins at python.org Fri Feb 9 05:55:42 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 05:55:42 +0100 (CET) Subject: [Python-checkins] r53684 - sandbox/trunk/2to3/fixes/fix_print.py Message-ID: <20070209045542.428E51E4009@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 05:55:41 2007 New Revision: 53684 Modified: sandbox/trunk/2to3/fixes/fix_print.py Log: Use print() instead of Print(). Modified: sandbox/trunk/2to3/fixes/fix_print.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_print.py (original) +++ sandbox/trunk/2to3/fixes/fix_print.py Fri Feb 9 05:55:41 2007 @@ -4,10 +4,10 @@ """Fixer for print. Change: - 'print' into 'Print()' - 'print ...' into 'Print(...)' - 'print ... ,' into 'Print(..., end=" ")' - 'print >>x, ...' into 'Print(..., file=x)' + 'print' into 'print()' + 'print ...' into 'print(...)' + 'print ... ,' into 'print(..., end=" ")' + 'print >>x, ...' into 'print(..., file=x)' """ # Python imports @@ -39,7 +39,7 @@ if node == Name("print"): # Special-case print all by itself - new = Call(Name("Print"), []) + new = Call(Name("print"), []) new.set_prefix(node.get_prefix()) return new assert node.children[0] == Name("print") @@ -52,7 +52,7 @@ assert len(args) >= 2 file = args[1].clone() args = args[3:] # Strip a possible comma after the file expression - # Now synthesize a Print(args, sep=..., end=..., file=...) node. + # Now synthesize a print(args, sep=..., end=..., file=...) node. l_args = [arg.clone() for arg in args] if l_args: l_args[0].set_prefix("") @@ -65,7 +65,7 @@ pytree.Leaf(token.STRING, repr(end))) if file is not None: self.add_kwarg(l_args, "file", file) - n_stmt = Call(Name("Print"), l_args) + n_stmt = Call(Name("print"), l_args) n_stmt.set_prefix(node.get_prefix()) return n_stmt From python-checkins at python.org Fri Feb 9 06:41:38 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 06:41:38 +0100 (CET) Subject: [Python-checkins] r53687 - peps/trunk/pep-3100.txt Message-ID: <20070209054138.164711E4014@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 06:41:37 2007 New Revision: 53687 Modified: peps/trunk/pep-3100.txt Log: Mark print conversion as mostly done. Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Fri Feb 9 06:41:37 2007 @@ -67,7 +67,7 @@ * ``exec`` as a statement is not worth it -- make it a function [done] * (Maybe) add optional declarations for static typing [#pep3107]_ [10]_ * Support only new-style classes; classic classes will be gone [1]_ [done] -* Replace ``print`` by a function [14]_ [#pep3105]_ +* Replace ``print`` by a function [14]_ [#pep3105]_ [mostly done] * Use ``except E1, E2, E3 as err:`` if you want the error variable. [3]_ * ``None`` becomes a keyword [4]_ (What about ``True``, ``False``?) * ``...`` to become a general expression element [16]_ [done] From python-checkins at python.org Fri Feb 9 13:19:33 2007 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 9 Feb 2007 13:19:33 +0100 (CET) Subject: [Python-checkins] r53689 - in python/trunk: Misc/NEWS Objects/typeobject.c Message-ID: <20070209121933.AB1DF1E400A@bag.python.org> Author: martin.v.loewis Date: Fri Feb 9 13:19:32 2007 New Revision: 53689 Modified: python/trunk/Misc/NEWS python/trunk/Objects/typeobject.c Log: Bug #1653736: Properly discard third argument to slot_nb_inplace_power. Will backport. Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri Feb 9 13:19:32 2007 @@ -12,6 +12,8 @@ Core and builtins ----------------- +- Bug #1653736: Properly discard third argument to slot_nb_inplace_power. + - PEP 352: Raising a string exception now triggers a TypeError. Attempting to catch a string exception raises DeprecationWarning. Modified: python/trunk/Objects/typeobject.c ============================================================================== --- python/trunk/Objects/typeobject.c (original) +++ python/trunk/Objects/typeobject.c Fri Feb 9 13:19:32 2007 @@ -4427,7 +4427,13 @@ SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O") SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O") SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O") -SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O") +/* Can't use SLOT1 here, because nb_inplace_power is ternary */ +static PyObject * +slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) +{ + static PyObject *cache_str; + return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); +} SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O") SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O") SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O") From python-checkins at python.org Fri Feb 9 13:19:47 2007 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 9 Feb 2007 13:19:47 +0100 (CET) Subject: [Python-checkins] r53690 - in python/branches/release25-maint: Misc/NEWS Objects/typeobject.c Message-ID: <20070209121947.22E2D1E400A@bag.python.org> Author: martin.v.loewis Date: Fri Feb 9 13:19:46 2007 New Revision: 53690 Modified: python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Objects/typeobject.c Log: Bug #1653736: Properly discard third argument to slot_nb_inplace_power. Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Fri Feb 9 13:19:46 2007 @@ -12,6 +12,8 @@ Core and builtins ----------------- +- Bug #1653736: Properly discard third argument to slot_nb_inplace_power. + - SF #151204: enumerate() now raises an Overflow error at sys.maxint items. - Bug #1377858: Fix the segfaulting of the interpreter when an object created Modified: python/branches/release25-maint/Objects/typeobject.c ============================================================================== --- python/branches/release25-maint/Objects/typeobject.c (original) +++ python/branches/release25-maint/Objects/typeobject.c Fri Feb 9 13:19:46 2007 @@ -4427,7 +4427,13 @@ SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O") SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O") SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O") -SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O") +/* Can't use SLOT1 here, because nb_inplace_power is ternary */ +static PyObject * +slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) +{ + static PyObject *cache_str; + return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); +} SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O") SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O") SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O") From python-checkins at python.org Fri Feb 9 13:36:49 2007 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 9 Feb 2007 13:36:49 +0100 (CET) Subject: [Python-checkins] r53691 - in python/trunk: Lib/distutils/command/build_ext.py Misc/NEWS Message-ID: <20070209123649.E28321E400A@bag.python.org> Author: martin.v.loewis Date: Fri Feb 9 13:36:48 2007 New Revision: 53691 Modified: python/trunk/Lib/distutils/command/build_ext.py python/trunk/Misc/NEWS Log: Bug #1600860: Search for shared python library in LIBDIR, not lib/python/config, on "linux" and "gnu" systems. Will backport. Modified: python/trunk/Lib/distutils/command/build_ext.py ============================================================================== --- python/trunk/Lib/distutils/command/build_ext.py (original) +++ python/trunk/Lib/distutils/command/build_ext.py Fri Feb 9 13:36:48 2007 @@ -185,9 +185,7 @@ # for extensions under Cygwin and AtheOS Python's library directory must be # appended to library_dirs - if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos' or \ - ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')) and - sysconfig.get_config_var('Py_ENABLE_SHARED')): + if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos': if string.find(sys.executable, sys.exec_prefix) != -1: # building third party extensions self.library_dirs.append(os.path.join(sys.prefix, "lib", @@ -197,6 +195,17 @@ # building python standard extensions self.library_dirs.append('.') + # for extensions under Linux with a shared Python library, + # Python's library directory must be appended to library_dirs + if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \ + and sysconfig.get_config_var('Py_ENABLE_SHARED'): + if string.find(sys.executable, sys.exec_prefix) != -1: + # building third party extensions + self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) + else: + # building python standard extensions + self.library_dirs.append('.') + # The argument parsing will result in self.define being a string, but # it has to be a list of 2-tuples. All the preprocessor symbols # specified by the 'define' option will be set to '1'. Multiple Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri Feb 9 13:36:48 2007 @@ -128,6 +128,9 @@ Library ------- +- Bug #1600860: Search for shared python library in LIBDIR, not lib/python/config, + on "linux" and "gnu" systems. + - Patch #1652681: tarfile.py: create nonexistent files in append mode and allow appending to empty files. From python-checkins at python.org Fri Feb 9 13:37:13 2007 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 9 Feb 2007 13:37:13 +0100 (CET) Subject: [Python-checkins] r53692 - in python/branches/release25-maint: Lib/distutils/command/build_ext.py Misc/NEWS Message-ID: <20070209123713.A0A1E1E400A@bag.python.org> Author: martin.v.loewis Date: Fri Feb 9 13:37:12 2007 New Revision: 53692 Modified: python/branches/release25-maint/Lib/distutils/command/build_ext.py python/branches/release25-maint/Misc/NEWS Log: Bug #1600860: Search for shared python library in LIBDIR, not lib/python/config, on "linux" and "gnu" systems. Modified: python/branches/release25-maint/Lib/distutils/command/build_ext.py ============================================================================== --- python/branches/release25-maint/Lib/distutils/command/build_ext.py (original) +++ python/branches/release25-maint/Lib/distutils/command/build_ext.py Fri Feb 9 13:37:12 2007 @@ -185,9 +185,7 @@ # for extensions under Cygwin and AtheOS Python's library directory must be # appended to library_dirs - if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos' or \ - ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')) and - sysconfig.get_config_var('Py_ENABLE_SHARED')): + if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos': if string.find(sys.executable, sys.exec_prefix) != -1: # building third party extensions self.library_dirs.append(os.path.join(sys.prefix, "lib", @@ -197,6 +195,17 @@ # building python standard extensions self.library_dirs.append('.') + # for extensions under Linux with a shared Python library, + # Python's library directory must be appended to library_dirs + if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \ + and sysconfig.get_config_var('Py_ENABLE_SHARED'): + if string.find(sys.executable, sys.exec_prefix) != -1: + # building third party extensions + self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) + else: + # building python standard extensions + self.library_dirs.append('.') + # The argument parsing will result in self.define being a string, but # it has to be a list of 2-tuples. All the preprocessor symbols # specified by the 'define' option will be set to '1'. Multiple Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Fri Feb 9 13:37:12 2007 @@ -169,6 +169,9 @@ Library ------- +- Bug #1600860: Search for shared python library in LIBDIR, not lib/python/config, + on "linux" and "gnu" systems. + - Bug #1124861: Automatically create pipes if GetStdHandle fails in subprocess. From python-checkins at python.org Fri Feb 9 13:58:50 2007 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 9 Feb 2007 13:58:50 +0100 (CET) Subject: [Python-checkins] r53693 - python/trunk/Doc/lib/emailgenerator.tex Message-ID: <20070209125850.B26F21E400A@bag.python.org> Author: martin.v.loewis Date: Fri Feb 9 13:58:49 2007 New Revision: 53693 Modified: python/trunk/Doc/lib/emailgenerator.tex Log: Update broken link. Will backport to 2.5. Modified: python/trunk/Doc/lib/emailgenerator.tex ============================================================================== --- python/trunk/Doc/lib/emailgenerator.tex (original) +++ python/trunk/Doc/lib/emailgenerator.tex Fri Feb 9 13:58:49 2007 @@ -33,7 +33,7 @@ line. This is the only guaranteed portable way to avoid having such lines be mistaken for a \UNIX{} mailbox format envelope header separator (see \ulink{WHY THE CONTENT-LENGTH FORMAT IS BAD} -{http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html} +{http://www.jwz.org/doc/content-length.html} for details). \var{mangle_from_} defaults to \code{True}, but you might want to set this to \code{False} if you are not writing \UNIX{} mailbox format files. From python-checkins at python.org Fri Feb 9 13:59:28 2007 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 9 Feb 2007 13:59:28 +0100 (CET) Subject: [Python-checkins] r53694 - python/branches/release25-maint/Doc/lib/emailgenerator.tex Message-ID: <20070209125928.3F0CF1E400A@bag.python.org> Author: martin.v.loewis Date: Fri Feb 9 13:59:27 2007 New Revision: 53694 Modified: python/branches/release25-maint/Doc/lib/emailgenerator.tex Log: Update broken link. Modified: python/branches/release25-maint/Doc/lib/emailgenerator.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/emailgenerator.tex (original) +++ python/branches/release25-maint/Doc/lib/emailgenerator.tex Fri Feb 9 13:59:27 2007 @@ -33,7 +33,7 @@ line. This is the only guaranteed portable way to avoid having such lines be mistaken for a \UNIX{} mailbox format envelope header separator (see \ulink{WHY THE CONTENT-LENGTH FORMAT IS BAD} -{http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html} +{http://www.jwz.org/doc/content-length.html} for details). \var{mangle_from_} defaults to \code{True}, but you might want to set this to \code{False} if you are not writing \UNIX{} mailbox format files. From buildbot at python.org Fri Feb 9 14:12:03 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 09 Feb 2007 13:12:03 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 trunk Message-ID: <20070209131203.E514A1E400A@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%2520trunk/builds/1394 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket ====================================================================== FAIL: testInterruptedTimeout (test.test_socket.TCPTimeoutTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/net/ringneck/scratch1/nnorwitz/python/trunk.norwitz-tru64/build/Lib/test/test_socket.py", line 886, in testInterruptedTimeout self.fail("got Alarm in wrong place") AssertionError: got Alarm in wrong place sincerely, -The Buildbot From buildbot at python.org Fri Feb 9 14:38:46 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 09 Feb 2007 13:38:46 +0000 Subject: [Python-checkins] buildbot warnings in x86 gentoo 2.5 Message-ID: <20070209133846.65E191E400A@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/221 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: Traceback (most recent call last): File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/test/test_socketserver.py", line 81, in run svr = svrcls(self.__addr, self.__hdlrcls) File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/SocketServer.py", line 330, in __init__ self.server_bind() File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/SocketServer.py", line 341, in server_bind self.socket.bind(self.server_address) File "", line 1, in bind error: (98, 'Address already in use') 1 test failed: test_socketserver make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Fri Feb 9 15:04:16 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 09 Feb 2007 14:04:16 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian trunk Message-ID: <20070209140416.7CCFE1E4010@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%2520trunk/builds/59 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_ctypes make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Fri Feb 9 15:50:40 2007 From: python-checkins at python.org (collin.winter) Date: Fri, 9 Feb 2007 15:50:40 +0100 (CET) Subject: [Python-checkins] r53695 - peps/trunk/pep-3109.txt Message-ID: <20070209145040.DC1CF1E4010@bag.python.org> Author: collin.winter Date: Fri Feb 9 15:50:40 2007 New Revision: 53695 Modified: peps/trunk/pep-3109.txt Log: Fix off-by-one indentation error Modified: peps/trunk/pep-3109.txt ============================================================================== --- peps/trunk/pep-3109.txt (original) +++ peps/trunk/pep-3109.txt Fri Feb 9 15:50:40 2007 @@ -215,24 +215,24 @@ except E as V: handle(V) - 2. ``raise E, V`` as a way of "casting" an exception to another - class. Taking an example from - distutils.compiler.unixcompiler :: - - try: - self.spawn(pp_args) - except DistutilsExecError as msg: - raise CompileError(msg) - - This would be better expressed as :: - - try: - self.spawn(pp_args) - except DistutilsExecError as msg: - raise CompileError from msg - - Using the ``raise ... from ...`` syntax introduced in - PEP 344. + 2. ``raise E, V`` as a way of "casting" an exception to another + class. Taking an example from + distutils.compiler.unixcompiler :: + + try: + self.spawn(pp_args) + except DistutilsExecError as msg: + raise CompileError(msg) + + This would be better expressed as :: + + try: + self.spawn(pp_args) + except DistutilsExecError as msg: + raise CompileError from msg + + Using the ``raise ... from ...`` syntax introduced in + PEP 344. References From buildbot at python.org Fri Feb 9 17:10:24 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 09 Feb 2007 16:10:24 +0000 Subject: [Python-checkins] buildbot warnings in x86 cygwin 2.5 Message-ID: <20070209161024.D87AD1E4010@bag.python.org> The Buildbot has detected a new failure of x86 cygwin 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520cygwin%25202.5/builds/8 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: andrew.kuchling,brett.cannon,fred.drake,georg.brandl,martin.v.loewis,peter.astrand,raymond.hettinger,thomas.heller Build had warnings: warnings failed slave lost sincerely, -The Buildbot From python-checkins at python.org Fri Feb 9 17:25:05 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 17:25:05 +0100 (CET) Subject: [Python-checkins] r53696 - sandbox/trunk/2to3/refactor.py Message-ID: <20070209162505.8CFD01E4010@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 17:25:05 2007 New Revision: 53696 Modified: sandbox/trunk/2to3/refactor.py Log: Make a log message about modified files unambiguous. Modified: sandbox/trunk/2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/refactor.py (original) +++ sandbox/trunk/2to3/refactor.py Fri Feb 9 17:25:05 2007 @@ -262,10 +262,14 @@ self.log_message("Wrote changes to %s", filename) def summarize(self): + if self.options.write: + were = "were" + else: + were = "should be" if not self.files: - self.log_message("No files were (or should be) modified.") + self.log_message("No files %s modified.", were) else: - self.log_message("Files that were (or should be) modified:") + self.log_message("Files that %s modified:", were) for file in self.files: self.log_message(file) if self.errors: From buildbot at python.org Fri Feb 9 18:19:52 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 09 Feb 2007 17:19:52 +0000 Subject: [Python-checkins] buildbot warnings in hppa Ubuntu dapper 2.5 Message-ID: <20070209171952.3E06D1E4010@bag.python.org> The Buildbot has detected a new failure of hppa Ubuntu dapper 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/hppa%2520Ubuntu%2520dapper%25202.5/builds/31 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: make: *** [buildbottest] Killed sincerely, -The Buildbot From python-checkins at python.org Fri Feb 9 19:48:42 2007 From: python-checkins at python.org (georg.brandl) Date: Fri, 9 Feb 2007 19:48:42 +0100 (CET) Subject: [Python-checkins] r53697 - python/trunk/Doc/lib/libprofile.tex Message-ID: <20070209184842.1BAEF1E4012@bag.python.org> Author: georg.brandl Date: Fri Feb 9 19:48:41 2007 New Revision: 53697 Modified: python/trunk/Doc/lib/libprofile.tex Log: Bug #1656078: typo in in profile docs. Modified: python/trunk/Doc/lib/libprofile.tex ============================================================================== --- python/trunk/Doc/lib/libprofile.tex (original) +++ python/trunk/Doc/lib/libprofile.tex Fri Feb 9 19:48:41 2007 @@ -319,7 +319,7 @@ \begin{funcdesc}{run}{command\optional{, filename}} -This function takes a single argument that has can be passed to the +This function takes a single argument that can be passed to the \keyword{exec} statement, and an optional file name. In all cases this routine attempts to \keyword{exec} its first argument, and gather profiling statistics from the execution. If no file name is present, then this From python-checkins at python.org Fri Feb 9 19:48:45 2007 From: python-checkins at python.org (georg.brandl) Date: Fri, 9 Feb 2007 19:48:45 +0100 (CET) Subject: [Python-checkins] r53698 - python/branches/release25-maint/Doc/lib/libprofile.tex Message-ID: <20070209184845.1ACFD1E4012@bag.python.org> Author: georg.brandl Date: Fri Feb 9 19:48:44 2007 New Revision: 53698 Modified: python/branches/release25-maint/Doc/lib/libprofile.tex Log: Bug #1656078: typo in in profile docs. (backport from rev. 53697) Modified: python/branches/release25-maint/Doc/lib/libprofile.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libprofile.tex (original) +++ python/branches/release25-maint/Doc/lib/libprofile.tex Fri Feb 9 19:48:44 2007 @@ -319,7 +319,7 @@ \begin{funcdesc}{run}{command\optional{, filename}} -This function takes a single argument that has can be passed to the +This function takes a single argument that can be passed to the \keyword{exec} statement, and an optional file name. In all cases this routine attempts to \keyword{exec} its first argument, and gather profiling statistics from the execution. If no file name is present, then this From python-checkins at python.org Fri Feb 9 21:00:13 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 21:00:13 +0100 (CET) Subject: [Python-checkins] r53699 - sandbox/trunk/2to3/example.py sandbox/trunk/2to3/refactor.py Message-ID: <20070209200013.D5C801E401C@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 21:00:11 2007 New Revision: 53699 Modified: sandbox/trunk/2to3/example.py sandbox/trunk/2to3/refactor.py Log: Add a new option to fix doctests. For now, you must choose to either fix doctests or the regular source code; you can't fix both at once. Also, it doesn't really parse docstrings; it just looks for lines starting with >>> anywhere in the input file(s). Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Fri Feb 9 21:00:11 2007 @@ -1,6 +1,33 @@ #!/usr/bin/python # comment indented by tab -"""Docstring.""" + +"""Docstring. + +Here are some doctest exampes: + +>>> print 42 +42 + + >>> d = {1: 1, 2: 2, 2: 2} + >>> d.keys().sort() + >>> print d + {1: 1, 2: 2} + + >>> for i in d.keys(): + ... print i, d[i] + +And a tricky one: + +>>> class X(Structure): +... _fields_ = [("x", c_int), ("y", c_int), ("array", c_char_p * 5)] +... +>>> x = X() +>>> print x._objects +None +>>> + +""" + import sys def ne_examples(): Modified: sandbox/trunk/2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/refactor.py (original) +++ sandbox/trunk/2to3/refactor.py Fri Feb 9 21:00:11 2007 @@ -26,9 +26,11 @@ import fixes import fixes.macros import pygram +import tokenize logging.basicConfig(format='%(name)s: %(message)s', level=logging.INFO) + def main(args=None): """Main program. @@ -39,13 +41,16 @@ """ # Set up option parser parser = optparse.OptionParser(usage="refactor.py [options] file|dir ...") + parser.add_option("-d", "--doctests_only", action="store_true", + help="Fix up doctests only") parser.add_option("-f", "--fix", action="append", default=[], help="Each FIX specifies a transformation; default all") parser.add_option("-l", "--list-fixes", action="store_true", help="List available transformations (fixes/fix_*.py)") parser.add_option("-v", "--verbose", action="store_true", help="More verbose logging") - parser.add_option("-w", "--write", action="store_true") + parser.add_option("-w", "--write", action="store_true", + help="Write back modified files") # Parse command line arguments options, args = parser.parse_args(args) @@ -92,7 +97,7 @@ The argument is an optparse.Values instance. """ self.options = options - self.errors = 0 + self.errors = [] self.logger = logging.getLogger("RefactoringTool") self.driver = driver.Driver(pygram.python_grammar, convert=pytree.convert, @@ -133,7 +138,7 @@ def log_error(self, msg, *args, **kwds): """Increments error count and log a message.""" - self.errors += 1 + self.errors.append((msg, args, kwds)) self.logger.error(msg, *args, **kwds) def log_message(self, msg, *args): @@ -177,23 +182,35 @@ self.log_error("Can't open %s: %s", filename, err) return try: - try: - tree = self.driver.parse_file(filename) - except Exception, err: - self.log_error("Can't parse %s: %s: %s", - filename, err.__class__.__name__, err) - return + if self.options.doctests_only: + input = f.read() + else: + try: + tree = self.driver.parse_file(filename) + except Exception, err: + self.log_error("Can't parse %s: %s: %s", + filename, err.__class__.__name__, err) + return + finally: + f.close() + if self.options.doctests_only: + if self.options.verbose: + self.log_message("Refactoring doctests in %s", filename) + output = self.refactor_docstring(input, filename) + if output != input: + self.write_file(output, filename, input) + elif self.options.verbose: + self.log_message("No doctest changes in %s", filename) + else: if self.options.verbose: self.log_message("Refactoring %s", filename) if self.refactor_tree(tree, filename): - self.write_tree(tree, filename) + self.write_file(str(tree), filename) elif self.options.verbose: self.log_message("No changes in %s", filename) - finally: - f.close() def refactor_tree(self, tree, filename): - """Refactors a parse tree.""" + """Refactors a parse tree (modifying the tree in place).""" for fixer in self.fixers: fixer.set_filename(filename) fixer.used_names = tree.used_names @@ -207,26 +224,26 @@ changes += 1 return changes - def write_tree(self, tree, filename): - """Writes a (presumably modified) tree to a file. + def write_file(self, new_text, filename, old_text=None): + """Writes a string to a file. If there are no changes, this is a no-op. - Otherwise, it first shows a unified diff between the old file - and the tree, and then rewrites the file, but the latter is + Otherwise, it first shows a unified diff between the old text + and the new text, and then rewrites the file; the latter is only done if the write option is set. """ self.files.append(filename) - try: - f = open(filename, "r") - except IOError, err: - self.log_error("Can't read %s: %s", filename, err) - return - try: - old_text = f.read() - finally: - f.close() - new_text = str(tree) + if old_text is None: + try: + f = open(filename, "r") + except IOError, err: + self.log_error("Can't read %s: %s", filename, err) + return + try: + old_text = f.read() + finally: + f.close() if old_text == new_text: if self.options.verbose: self.log_message("No changes to %s", filename) @@ -261,11 +278,86 @@ if self.options.verbose: self.log_message("Wrote changes to %s", filename) + PS1 = ">>> " + PS2 = "... " + + def refactor_docstring(self, input, filename): + """Refactors a docstring, looking for doctests. + + This returns a modified version of the input string. It looks + for doctests, which start with a ">>>" prompt, and may be + continued with "..." prompts, as long as the "..." is indented + the same as the ">>>". + + (Unfortunately we can't use the doctest module's parser, + since, like most parsers, it is not geared towards preserving + the original source.) + """ + result = [] + block = None + block_lineno = None + indent = None + lineno = 0 + for line in input.splitlines(True): + lineno += 1 + if line.lstrip().startswith(self.PS1): + if block is not None: + result.extend(self.refactor_doctest(block, block_lineno, + indent, filename)) + block_lineno = lineno + block = [line] + i = line.find(self.PS1) + indent = line[:i] + elif (indent is not None and + (line.startswith(indent + self.PS2) or + line == indent + self.PS2.rstrip() + "\n")): + block.append(line) + else: + if block is not None: + result.extend(self.refactor_doctest(block, block_lineno, + indent, filename)) + block = None + indent = None + result.append(line) + if block is not None: + result.extend(self.refactor_doctest(block, block_lineno, + indent, filename)) + return "".join(result) + + def refactor_doctest(self, block, lineno, indent, filename): + """Refactors one doctest. + + A doctest is given as a block of lines, the first of which starts + with ">>>" (possibly indented), while the remaining lines start + with "..." (identically indented). + + """ + try: + tree = self.parse_block(block, lineno, indent) + except Exception, err: + if self.options.verbose: + for line in block: + self.log_message("Source: %s", line.rstrip("\n")) + self.log_error("Can't parse docstring in %s line %s: %s: %s", + filename, lineno, err.__class__.__name__, err) + return block + if self.refactor_tree(tree, filename): + new = str(tree).splitlines(True) + # Undo the adjustment of the line numbers in wrap_toks() below. + clipped, new = new[:lineno-1], new[lineno-1:] + assert clipped == ["\n"] * (lineno-1), clipped + if not new[-1].endswith("\n"): + new[-1] += "\n" + block = [indent + self.PS1 + new.pop(0)] + if new: + block += [indent + self.PS2 + line for line in new] + return block + def summarize(self): if self.options.write: were = "were" else: - were = "should be" + were = "need to be" if not self.files: self.log_message("No files %s modified.", were) else: @@ -273,13 +365,57 @@ for file in self.files: self.log_message(file) if self.errors: - if self.errors == 1: - self.log_message("There was 1 error") + if len(self.errors) == 1: + self.log_message("There was 1 error:") + else: + self.log_message("There were %d errors:", len(self.errors)) + for msg, args, kwds in self.errors: + self.log_message(msg, *args, **kwds) + + def parse_block(self, block, lineno, indent): + """Parses a block into a tree. + + This is necessary to get correct line number / offset information + in the parser diagnostics and embedded into the parse tree. + """ + return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + + def wrap_toks(self, block, lineno, indent): + """Wraps a tokenize stream to systematically modify start/end.""" + tokens = tokenize.generate_tokens(self.gen_lines(block, indent).next) + for type, value, (line0, col0), (line1, col1), line_text in tokens: + line0 += lineno - 1 + line1 += lineno - 1 + # Don't bother updating the columns; this is too complicated + # since line_text would also have to be updated and it would + # still break for tokens spanning lines. Let the user guess + # that the column numbers for doctests are relative to the + # end of the prompt string (PS1 or PS2). + yield type, value, (line0, col0), (line1, col1), line_text + + + def gen_lines(self, block, indent): + """Generates lines as expected by tokenize from a list of lines. + + This strips the first len(indent + self.PS1) characters off each line. + """ + prefix1 = indent + self.PS1 + prefix2 = indent + self.PS2 + prefix = prefix1 + for line in block: + if line.startswith(prefix): + yield line[len(prefix):] + elif line == prefix.rstrip() + "\n": + yield "\n" else: - self.log_message("There were %d errors", self.errors) + raise AssertionError("line=%r, prefix=%r" % (line, prefix)) + prefix = prefix2 + while True: + yield "" def diff_texts(a, b, filename): + """Prints a unified diff of two strings.""" a = a.splitlines() b = b.splitlines() for line in difflib.unified_diff(a, b, filename, filename, From python-checkins at python.org Fri Feb 9 21:02:27 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 21:02:27 +0100 (CET) Subject: [Python-checkins] r53700 - sandbox/trunk/2to3/fixer_tests.py Message-ID: <20070209200227.0AC4D1E4028@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 21:02:26 2007 New Revision: 53700 Modified: sandbox/trunk/2to3/fixer_tests.py Log: Fix unit tests that broke when I changed print() to Print(). Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Fri Feb 9 21:02:26 2007 @@ -334,34 +334,34 @@ def test_1(self): b = """print 1, 1+1, 1+1+1""" - a = """Print(1, 1+1, 1+1+1)""" + a = """print(1, 1+1, 1+1+1)""" self.check(b, a) def test_2(self): b = """print 1, 2""" - a = """Print(1, 2)""" + a = """print(1, 2)""" self.check(b, a) def test_3(self): b = """print""" - a = """Print()""" + a = """print()""" self.check(b, a) # trailing commas def test_4(self): b = """print 1, 2, 3,""" - a = """Print(1, 2, 3, end=' ')""" + a = """print(1, 2, 3, end=' ')""" self.check(b, a) def test_5(self): b = """print 1, 2,""" - a = """Print(1, 2, end=' ')""" + a = """print(1, 2, end=' ')""" self.check(b, a) def test_6(self): b = """print 1,""" - a = """Print(1, end=' ')""" + a = """print(1, end=' ')""" self.check(b, a) # >> stuff @@ -369,25 +369,25 @@ # no trailing comma def test_7(self): b = """print >>sys.stderr, 1, 2, 3""" - a = """Print(1, 2, 3, file=sys.stderr)""" + a = """print(1, 2, 3, file=sys.stderr)""" self.check(b, a) # trailing comma def test_8(self): b = """print >>sys.stderr, 1, 2,""" - a = """Print(1, 2, end=' ', file=sys.stderr)""" + a = """print(1, 2, end=' ', file=sys.stderr)""" self.check(b, a) # no trailing comma def test_9(self): b = """print >>sys.stderr, 1+1""" - a = """Print(1+1, file=sys.stderr)""" + a = """print(1+1, file=sys.stderr)""" self.check(b, a) # spaces before sys.stderr def test_10(self): b = """print >> sys.stderr""" - a = """Print(file=sys.stderr)""" + a = """print(file=sys.stderr)""" self.check(b, a) From python-checkins at python.org Sat Feb 10 00:52:38 2007 From: python-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 00:52:38 +0100 (CET) Subject: [Python-checkins] r53720 - peps/trunk/pep-3100.txt Message-ID: <20070209235238.77D931E4012@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 00:52:38 2007 New Revision: 53720 Modified: peps/trunk/pep-3100.txt Log: Mark print() as done, period. Note that softspace is gone too. Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Sat Feb 10 00:52:38 2007 @@ -67,7 +67,8 @@ * ``exec`` as a statement is not worth it -- make it a function [done] * (Maybe) add optional declarations for static typing [#pep3107]_ [10]_ * Support only new-style classes; classic classes will be gone [1]_ [done] -* Replace ``print`` by a function [14]_ [#pep3105]_ [mostly done] +* Replace ``print`` by a function [14]_ [#pep3105]_ [done] +* The ``softspace`` attribute of files goes away. [done] * Use ``except E1, E2, E3 as err:`` if you want the error variable. [3]_ * ``None`` becomes a keyword [4]_ (What about ``True``, ``False``?) * ``...`` to become a general expression element [16]_ [done] From python-checkins at python.org Sat Feb 10 02:17:30 2007 From: python-checkins at python.org (collin.winter) Date: Sat, 10 Feb 2007 02:17:30 +0100 (CET) Subject: [Python-checkins] r53722 - peps/trunk/pep-3100.txt Message-ID: <20070210011730.2E32F1E4012@bag.python.org> Author: collin.winter Date: Sat Feb 10 02:17:29 2007 New Revision: 53722 Modified: peps/trunk/pep-3100.txt Log: Add sys.exc_clear for removal Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Sat Feb 10 02:17:29 2007 @@ -218,6 +218,8 @@ * ``sys.exc_type``, ``sys.exc_values``, ``sys.exc_traceback``: not thread-safe; use ``sys.exc_info()`` or an attribute of the exception [2]_ [11]_ [#sys-module]_ +* ``sys.exc_clear``: Python 3's except statements provide the same + functionality [24]_ [#pep3110]_ [#sys-module]_ * ``array.read``, ``array.write`` [#array-module]_ * ``operator.isCallable`` : ``callable()`` built-in is being removed [#operator-module]_ @@ -312,6 +314,9 @@ .. [23] python-3000 email ("__nonzero__ vs. __bool__") http://mail.python.org/pipermail/python-3000/2006-November/004524.html + +.. [24] python-3000 email ("Pre-peps on raise and except changes") + http://mail.python.org/pipermail/python-3000/2007-February/005672.html .. [#sys-module] Python docs (sys -- System-specific parameters and functions) http://docs.python.org/lib/module-sys.html @@ -363,6 +368,9 @@ .. [#pep3107] PEP 3107 (Function Annotations) http://www.python.org/dev/peps/pep-3107 + +.. [#pep3110] PEP 3110 (Catching Exceptions in Python 3000) + http://www.python.org/dev/peps/pep-3110/#semantic-changes Copyright From buildbot at python.org Sat Feb 10 19:42:19 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 10 Feb 2007 18:42:19 +0000 Subject: [Python-checkins] buildbot failure in g4 osx.4 2.5 Message-ID: <20070210184219.C6E141E4003@bag.python.org> The Buildbot has detected a new failure of g4 osx.4 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/g4%2520osx.4%25202.5/builds/210 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Dominick': Gannon Build Source Stamp: [branch Hugo] Silas Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sat Feb 10 19:42:43 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 10 Feb 2007 18:42:43 +0000 Subject: [Python-checkins] buildbot failure in sparc solaris10 gcc 2.5 Message-ID: <20070210184243.77EEE1E4003@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%25202.5/builds/215 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Ezra': Erik Build Source Stamp: [branch Nathan] Kendell Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sat Feb 10 19:45:11 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 10 Feb 2007 18:45:11 +0000 Subject: [Python-checkins] buildbot failure in x86 gentoo 2.5 Message-ID: <20070210184511.4EF161E4003@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/222 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Omari': Teddy Build Source Stamp: [branch Zechariah] Shaun Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sat Feb 10 19:47:46 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 10 Feb 2007 18:47:46 +0000 Subject: [Python-checkins] buildbot failure in x86 XP 2.5 Message-ID: <20070210184751.28BA91E4003@bag.python.org> The Buildbot has detected a new failure of x86 XP 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%25202.5/builds/111 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Peyton': Isiah Build Source Stamp: [branch Darien] Addison Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sat Feb 10 19:53:42 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 10 Feb 2007 18:53:42 +0000 Subject: [Python-checkins] buildbot failure in amd64 gentoo 2.5 Message-ID: <20070210185342.2C7BC1E4003@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%25202.5/builds/224 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'London': Donta Build Source Stamp: [branch Michel] Dana Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From python-checkins at python.org Sat Feb 10 20:38:59 2007 From: python-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 20:38:59 +0100 (CET) Subject: [Python-checkins] r53725 - sandbox/trunk/2to3/refactor.py Message-ID: <20070210193859.B53A01E4004@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 20:38:59 2007 New Revision: 53725 Modified: sandbox/trunk/2to3/refactor.py Log: Add -p option which assumes print() is a function, not a keyword. Modified: sandbox/trunk/2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/refactor.py (original) +++ sandbox/trunk/2to3/refactor.py Sat Feb 10 20:38:59 2007 @@ -47,6 +47,8 @@ help="Each FIX specifies a transformation; default all") parser.add_option("-l", "--list-fixes", action="store_true", help="List available transformations (fixes/fix_*.py)") + parser.add_option("-p", "--print-function", action="store_true", + help="Modify the grammar so that print() is a function") parser.add_option("-v", "--verbose", action="store_true", help="More verbose logging") parser.add_option("-w", "--write", action="store_true", @@ -99,6 +101,8 @@ self.options = options self.errors = [] self.logger = logging.getLogger("RefactoringTool") + if self.options.print_function: + del pygram.python_grammar.keywords["print"] self.driver = driver.Driver(pygram.python_grammar, convert=pytree.convert, logger=self.logger) From python-checkins at python.org Sat Feb 10 22:23:31 2007 From: python-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 22:23:31 +0100 (CET) Subject: [Python-checkins] r53726 - sandbox/trunk/2to3/fixer_tests.py Message-ID: <20070210212331.C9E831E4004@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 22:23:30 2007 New Revision: 53726 Modified: sandbox/trunk/2to3/fixer_tests.py Log: Need to set options.print_function to make the tests pass now. Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Sat Feb 10 22:23:30 2007 @@ -37,7 +37,7 @@ class FixerTestCase(unittest.TestCase): def setUp(self): - options = Options(fix=[self.fixer]) + options = Options(fix=[self.fixer], print_function=False) self.refactor = refactor.RefactoringTool(options) self.logging_stream = StringIO() From buildbot at python.org Sun Feb 11 00:46:14 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 10 Feb 2007 23:46:14 +0000 Subject: [Python-checkins] buildbot failure in x86 OpenBSD 2.5 Message-ID: <20070210234614.355A61E4004@bag.python.org> The Buildbot has detected a new failure of x86 OpenBSD 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520OpenBSD%25202.5/builds/203 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Destin': Rasheed Build Source Stamp: [branch Tucker] Shane Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From python-checkins at python.org Sun Feb 11 00:52:29 2007 From: python-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 00:52:29 +0100 (CET) Subject: [Python-checkins] r53728 - sandbox/trunk/2to3/fixes/fix_dict2.py Message-ID: <20070210235229.F24501E4027@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 00:52:29 2007 New Revision: 53728 Added: sandbox/trunk/2to3/fixes/fix_dict2.py (contents, props changed) Log: Add a much simpler dict refactorer, which is less safe but more practical. Added: sandbox/trunk/2to3/fixes/fix_dict2.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/fix_dict2.py Sun Feb 11 00:52:29 2007 @@ -0,0 +1,36 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. + +"""Fixer for dict methods, take 2. + +This is less correct but more pragmatic. + +.iterkeys -> .keys +.iteritems -> .items +.itervalues -> .values +""" + +# Python imports +import token + +# Local imports +import pytree +from fixes import basefix +from fixes import macros + +class FixDict2(basefix.BaseFix): + + PATTERN = """ + trailer< '.' method=('iterkeys'|'iteritems'|'itervalues') > + """ + + def transform(self, node): + results = self.match(node) + method = results["method"][0].value # Extract method name + assert method.startswith("iter") + newmethod = method[4:] + new = pytree.Node(self.syms.trailer, + [pytree.Leaf(token.DOT, '.'), + macros.Name(newmethod)]) + new.set_prefix(node.get_prefix()) + new.children[1].set_prefix(node.children[1].get_prefix()) + return new From python-checkins at python.org Sun Feb 11 01:18:47 2007 From: python-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 01:18:47 +0100 (CET) Subject: [Python-checkins] r53729 - in sandbox/trunk/2to3: Grammar.txt pgen2/grammar.py refactor.py tokenize.py Message-ID: <20070211001847.6FB3F1E4004@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 01:18:46 2007 New Revision: 53729 Modified: sandbox/trunk/2to3/Grammar.txt sandbox/trunk/2to3/pgen2/grammar.py sandbox/trunk/2to3/refactor.py sandbox/trunk/2to3/tokenize.py Log: Tweaks to the grammar and tokenizer to support parsing Py3k source code. This has become necessary now that I'm converting the stdelib one fix at a time. Modified: sandbox/trunk/2to3/Grammar.txt ============================================================================== --- sandbox/trunk/2to3/Grammar.txt (original) +++ sandbox/trunk/2to3/Grammar.txt Sun Feb 11 01:18:46 2007 @@ -33,13 +33,20 @@ decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE decorators: decorator+ -funcdef: [decorators] 'def' NAME parameters ':' suite -parameters: '(' [varargslist] ')' -varargslist: ((fpdef ['=' test] ',')* - ('*' NAME [',' '**' NAME] | '**' NAME) | - fpdef ['=' test] (',' fpdef ['=' test])* [',']) -fpdef: NAME | '(' fplist ')' -fplist: fpdef (',' fpdef)* [','] +funcdef: [decorators] 'def' NAME parameters ['->' test] ':' suite +parameters: '(' [typedargslist] ')' +typedargslist: ((tfpdef ['=' test] ',')* + ('*' [tname] (',' tname ['=' test])* [',' '**' tname] | '**' tname) + | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) +tname: NAME [':' test] +tfpdef: tname | '(' tfplist ')' +tfplist: tfpdef (',' tfpdef)* [','] +varargslist: ((vfpdef ['=' test] ',')* + ('*' [vname] (',' vname ['=' test])* [',' '**' vname] | '**' vname) + | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) +vname: NAME +vfpdef: vname | '(' vfplist ')' +vfplist: vfpdef (',' vfpdef)* [','] stmt: simple_stmt | compound_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE @@ -113,19 +120,19 @@ power: atom trailer* ['**' factor] atom: ('(' [yield_expr|testlist_gexp] ')' | '[' [listmaker] ']' | - '{' [dictmaker] '}' | + '{' [dictsetmaker] '}' | '`' testlist1 '`' | - NAME | NUMBER | STRING+) + NAME | NUMBER | STRING+ | '.' '.' '.') listmaker: test ( list_for | (',' test)* [','] ) testlist_gexp: test ( gen_for | (',' test)* [','] ) lambdef: 'lambda' [varargslist] ':' test trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] -subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] +subscript: test | [test] ':' [test] [sliceop] sliceop: ':' [test] exprlist: expr (',' expr)* [','] testlist: test (',' test)* [','] -dictmaker: test ':' test (',' test ':' test)* [','] +dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [',']) classdef: 'class' NAME ['(' [testlist] ')'] ':' suite Modified: sandbox/trunk/2to3/pgen2/grammar.py ============================================================================== --- sandbox/trunk/2to3/pgen2/grammar.py (original) +++ sandbox/trunk/2to3/pgen2/grammar.py Sun Feb 11 01:18:46 2007 @@ -158,6 +158,7 @@ **= DOUBLESTAREQUAL // DOUBLESLASH //= DOUBLESLASHEQUAL +-> RARROW """ opmap = {} Modified: sandbox/trunk/2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/refactor.py (original) +++ sandbox/trunk/2to3/refactor.py Sun Feb 11 01:18:46 2007 @@ -20,13 +20,13 @@ import logging # Local imports +import tokenize import pytree import patcomp from pgen2 import driver import fixes import fixes.macros import pygram -import tokenize logging.basicConfig(format='%(name)s: %(message)s', level=logging.INFO) Modified: sandbox/trunk/2to3/tokenize.py ============================================================================== --- sandbox/trunk/2to3/tokenize.py (original) +++ sandbox/trunk/2to3/tokenize.py Sun Feb 11 01:18:46 2007 @@ -36,13 +36,17 @@ __all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize", "generate_tokens", "NL", "untokenize"] del x -del token COMMENT = N_TOKENS tok_name[COMMENT] = 'COMMENT' NL = N_TOKENS + 1 tok_name[NL] = 'NL' -N_TOKENS += 2 +RARROW = N_TOKENS + 2 +token.RARROW = RARROW +tok_name[RARROW] = 'RARROW' +N_TOKENS += 3 + +del token def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' @@ -81,7 +85,7 @@ # longest operators first (e.g., if = came before ==, == would get # recognized as two instances of =). Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", - r"//=?", + r"//=?", r"->", r"[+\-*/%&|^=<>]=?", r"~") From python-checkins at python.org Sun Feb 11 01:35:37 2007 From: python-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 01:35:37 +0100 (CET) Subject: [Python-checkins] r53730 - in sandbox/trunk/2to3: example.py fixes/fix_xrange.py Message-ID: <20070211003537.645A51E4004@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 01:35:36 2007 New Revision: 53730 Added: sandbox/trunk/2to3/fixes/fix_xrange.py (contents, props changed) Modified: sandbox/trunk/2to3/example.py Log: Add a converter that turns xrange() calls into range() calls. (Still waiting for Neal to implement the new range() :-). Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Sun Feb 11 01:35:36 2007 @@ -311,4 +311,9 @@ # print h.keys()[0] +def xrange_examples(): + for i in xrange(100): print i + for i in xrange(0, 100): print i + for i in xrange(0, 100, 10): print i + # This is the last line. Added: sandbox/trunk/2to3/fixes/fix_xrange.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/fix_xrange.py Sun Feb 11 01:35:36 2007 @@ -0,0 +1,28 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. + +"""Fixer that changes xrange(...) into range(...).""" + +# Python imports +import token + +# Local imports +import pytree +from fixes import basefix +from fixes import macros + +class FixXrange(basefix.BaseFix): + + PATTERN = """ + power< + 'xrange' + args=trailer< '(' [any] ')' > + > + """ + + def transform(self, node): + results = self.match(node) + args = results["args"] + new = pytree.Node(self.syms.power, + [macros.Name("range"), args.clone()]) + new.set_prefix(node.get_prefix()) + return new From python-checkins at python.org Sun Feb 11 06:36:01 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 11 Feb 2007 06:36:01 +0100 (CET) Subject: [Python-checkins] r53731 - python/trunk/Parser/Python.asdl Message-ID: <20070211053601.A06771E401F@bag.python.org> Author: brett.cannon Date: Sun Feb 11 06:36:00 2007 New Revision: 53731 Modified: python/trunk/Parser/Python.asdl Log: Change a very minor inconsistency (that is purely cosmetic) in the AST definition. Modified: python/trunk/Parser/Python.asdl ============================================================================== --- python/trunk/Parser/Python.asdl (original) +++ python/trunk/Parser/Python.asdl Sun Feb 11 06:36:00 2007 @@ -75,7 +75,7 @@ | Subscript(expr value, slice slice, expr_context ctx) | Name(identifier id, expr_context ctx) | List(expr* elts, expr_context ctx) - | Tuple(expr *elts, expr_context ctx) + | Tuple(expr* elts, expr_context ctx) -- col_offset is the byte offset in the utf8 string the parser uses attributes (int lineno, int col_offset) From python-checkins at python.org Sun Feb 11 08:03:45 2007 From: python-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 08:03:45 +0100 (CET) Subject: [Python-checkins] r53733 - in sandbox/trunk/2to3: example.py fixer_tests.py fixes/fix_dict.py Message-ID: <20070211070345.1B3111E4008@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 08:03:43 2007 New Revision: 53733 Modified: sandbox/trunk/2to3/example.py sandbox/trunk/2to3/fixer_tests.py sandbox/trunk/2to3/fixes/fix_dict.py Log: Make the dict fixer handle a "tail", e.g. d.keys()[0]. Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Sun Feb 11 08:03:43 2007 @@ -299,6 +299,13 @@ for i in g.iterkeys(): print i [i for i in g.iterkeys()] (i for i in g.iterkeys()) + # + # Examples with a "tail"; these are never "special" + # + print h.iterkeys().next() + print h.keys()[0] + print list(h.iterkeys().next()) + for x in h.keys()[0]: print x def dict_negative_examples(): # @@ -306,10 +313,6 @@ # print list(h.keys()) print sorted(h.keys()) - # - # This should be left unchanged and trigger a warning: - # - print h.keys()[0] def xrange_examples(): for i in xrange(100): print i Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Sun Feb 11 08:03:43 2007 @@ -1020,6 +1020,27 @@ a = "foo(iter(d.keys()))" self.check(b, a) + def test_21(self): + b = "print h.iterkeys().next()" + a = "print iter(h.keys()).next()" + self.check(b, a) + + def test_22(self): + b = "print h.keys()[0]" + a = "print list(h.keys())[0]" + self.check(b, a) + + def test_23(self): + b = "print list(h.iterkeys().next())" + a = "print list(iter(h.keys()).next())" + self.check(b, a) + + def test_24(self): + b = "for x in h.keys()[0]: print x" + a = "for x in list(h.keys())[0]: print x" + self.check(b, a) + + if __name__ == "__main__": import sys Modified: sandbox/trunk/2to3/fixes/fix_dict.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_dict.py (original) +++ sandbox/trunk/2to3/fixes/fix_dict.py Sun Feb 11 08:03:43 2007 @@ -33,7 +33,7 @@ class FixDict(basefix.BaseFix): PATTERN = """ - power< prefix=any+ + power< head=any+ trailer< '.' method=('keys'|'items'|'values'| 'iterkeys'|'iteritems'|'itervalues') > trailer< '(' ')' > @@ -43,28 +43,29 @@ def transform(self, node): results = self.match(node) - prefix = results["prefix"] + head = results["head"] method = results["method"][0].value # Extract method name tail = results["tail"] - if tail: - return self.cannot_convert(node, - "stuff after .[iter]keys() etc. unsupported") syms = self.syms isiter = method.startswith("iter") if isiter: method = method[4:] assert method in ("keys", "items", "values"), repr(method) - prefix = [n.clone() for n in prefix] - new = pytree.Node(syms.power, - prefix + [pytree.Node(syms.trailer, - [pytree.Leaf(token.DOT, '.'), - macros.Name(method)]), - pytree.Node(syms.trailer, - [macros.lparen_leaf.clone(), - macros.rparen_leaf.clone()])]) - if not self.in_special_context(node, isiter): + head = [n.clone() for n in head] + tail = [n.clone() for n in tail] + special = not tail and self.in_special_context(node, isiter) + args = head + [pytree.Node(syms.trailer, + [pytree.Leaf(token.DOT, '.'), + macros.Name(method)]), + pytree.Node(syms.trailer, + [macros.lparen_leaf.clone(), + macros.rparen_leaf.clone()])] + new = pytree.Node(syms.power, args) + if not special: new.set_prefix("") new = macros.Call(macros.Name(isiter and "iter" or "list"), [new]) + if tail: + new = pytree.Node(syms.power, [new] + tail) new.set_prefix(node.get_prefix()) return new From buildbot at python.org Sun Feb 11 08:30:07 2007 From: buildbot at python.org (buildbot at python.org) Date: Sun, 11 Feb 2007 07:30:07 +0000 Subject: [Python-checkins] buildbot warnings in ia64 Ubuntu trunk trunk Message-ID: <20070211073008.2D7C71E4008@bag.python.org> The Buildbot has detected a new failure of ia64 Ubuntu trunk trunk. Full details are available at: http://www.python.org/dev/buildbot/all/ia64%2520Ubuntu%2520trunk%2520trunk/builds/381 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: brett.cannon,georg.brandl,martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Sun Feb 11 08:40:33 2007 From: buildbot at python.org (buildbot at python.org) Date: Sun, 11 Feb 2007 07:40:33 +0000 Subject: [Python-checkins] buildbot warnings in x86 cygwin trunk Message-ID: <20070211074033.5A44E1E4008@bag.python.org> The Buildbot has detected a new failure of x86 cygwin trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520cygwin%2520trunk/builds/14 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: brett.cannon,georg.brandl,martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From python-checkins at python.org Sun Feb 11 19:24:38 2007 From: python-checkins at python.org (skip.montanaro) Date: Sun, 11 Feb 2007 19:24:38 +0100 (CET) Subject: [Python-checkins] r53735 - in python/trunk: Lib/trace.py Misc/NEWS Message-ID: <20070211182438.CC7ED1E400C@bag.python.org> Author: skip.montanaro Date: Sun Feb 11 19:24:37 2007 New Revision: 53735 Modified: python/trunk/Lib/trace.py python/trunk/Misc/NEWS Log: fix trace.py --ignore-dir Modified: python/trunk/Lib/trace.py ============================================================================== --- python/trunk/Lib/trace.py (original) +++ python/trunk/Lib/trace.py Sun Feb 11 19:24:37 2007 @@ -587,7 +587,7 @@ """ if why == 'call': code = frame.f_code - filename = code.co_filename + filename = frame.f_globals.get('__file__', None) if filename: # XXX modname() doesn't work right for packages, so # the ignore support won't work right for packages Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun Feb 11 19:24:37 2007 @@ -128,6 +128,9 @@ Library ------- +- Patch 1571379: Make trace's --ignore-dir facility work in the face of + relative directory names. + - Bug #1600860: Search for shared python library in LIBDIR, not lib/python/config, on "linux" and "gnu" systems. From python-checkins at python.org Sun Feb 11 19:37:55 2007 From: python-checkins at python.org (skip.montanaro) Date: Sun, 11 Feb 2007 19:37:55 +0100 (CET) Subject: [Python-checkins] r53736 - in python/branches/release24-maint: Lib/trace.py Misc/NEWS Message-ID: <20070211183755.008DD1E400C@bag.python.org> Author: skip.montanaro Date: Sun Feb 11 19:37:54 2007 New Revision: 53736 Modified: python/branches/release24-maint/Lib/trace.py python/branches/release24-maint/Misc/NEWS Log: backport: fix trace.py --ignore-dir Modified: python/branches/release24-maint/Lib/trace.py ============================================================================== --- python/branches/release24-maint/Lib/trace.py (original) +++ python/branches/release24-maint/Lib/trace.py Sun Feb 11 19:37:54 2007 @@ -583,7 +583,7 @@ """ if why == 'call': code = frame.f_code - filename = code.co_filename + filename = frame.f_globals.get('__file__', None) if filename: # XXX modname() doesn't work right for packages, so # the ignore support won't work right for packages Modified: python/branches/release24-maint/Misc/NEWS ============================================================================== --- python/branches/release24-maint/Misc/NEWS (original) +++ python/branches/release24-maint/Misc/NEWS Sun Feb 11 19:37:54 2007 @@ -192,6 +192,9 @@ Library ------- +- Patch 1571379: Make trace's --ignore-dir facility work in the face of + relative directory names. + - Bug #1545341: The 'classifier' keyword argument to the Distutils setup() function now accepts tuples as well as lists. From python-checkins at python.org Sun Feb 11 19:41:56 2007 From: python-checkins at python.org (skip.montanaro) Date: Sun, 11 Feb 2007 19:41:56 +0100 (CET) Subject: [Python-checkins] r53737 - in python/branches/release25-maint: Lib/trace.py Misc/NEWS Message-ID: <20070211184156.AF2311E400C@bag.python.org> Author: skip.montanaro Date: Sun Feb 11 19:41:56 2007 New Revision: 53737 Modified: python/branches/release25-maint/Lib/trace.py python/branches/release25-maint/Misc/NEWS Log: backport: fix trace.py --ignore-dir Modified: python/branches/release25-maint/Lib/trace.py ============================================================================== --- python/branches/release25-maint/Lib/trace.py (original) +++ python/branches/release25-maint/Lib/trace.py Sun Feb 11 19:41:56 2007 @@ -587,7 +587,7 @@ """ if why == 'call': code = frame.f_code - filename = code.co_filename + filename = frame.f_globals.get('__file__', None) if filename: # XXX modname() doesn't work right for packages, so # the ignore support won't work right for packages Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Sun Feb 11 19:41:56 2007 @@ -169,6 +169,9 @@ Library ------- +- Patch 1571379: Make trace's --ignore-dir facility work in the face of + relative directory names. + - Bug #1600860: Search for shared python library in LIBDIR, not lib/python/config, on "linux" and "gnu" systems. From python-checkins at python.org Sun Feb 11 20:44:42 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 11 Feb 2007 20:44:42 +0100 (CET) Subject: [Python-checkins] r53741 - python/trunk/Python/Python-ast.c Message-ID: <20070211194442.4233C1E400C@bag.python.org> Author: brett.cannon Date: Sun Feb 11 20:44:41 2007 New Revision: 53741 Modified: python/trunk/Python/Python-ast.c Log: Check in changed Python-ast.c from a cosmetic change to Python.asdl (in r53731). Modified: python/trunk/Python/Python-ast.c ============================================================================== --- python/trunk/Python/Python-ast.c (original) +++ python/trunk/Python/Python-ast.c Sun Feb 11 20:44:41 2007 @@ -3048,7 +3048,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__", "43614") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53731") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) From buildbot at python.org Sun Feb 11 20:53:50 2007 From: buildbot at python.org (buildbot at python.org) Date: Sun, 11 Feb 2007 19:53:50 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) trunk Message-ID: <20070211195350.847A61E400C@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%2520trunk/builds/1177 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: skip.montanaro Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_timeout test_urllib2net ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (2.74149) is more than 2 seconds more than expected (0.001) sincerely, -The Buildbot From buildbot at python.org Sun Feb 11 22:14:05 2007 From: buildbot at python.org (buildbot at python.org) Date: Sun, 11 Feb 2007 21:14:05 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) 2.5 Message-ID: <20070211211405.D1E941E400C@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%25202.5/builds/160 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: georg.brandl,martin.v.loewis,skip.montanaro Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_timeout test_urllibnet ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildbot/Buildbot/2.5.baxter-ubuntu/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (2.36012) is more than 2 seconds more than expected (0.001) sincerely, -The Buildbot From python-checkins at python.org Mon Feb 12 00:50:58 2007 From: python-checkins at python.org (david.goodger) Date: Mon, 12 Feb 2007 00:50:58 +0100 (CET) Subject: [Python-checkins] r53744 - peps/trunk/pep-0000.txt peps/trunk/pep-0363.txt Message-ID: <20070211235058.C060F1E400C@bag.python.org> Author: david.goodger Date: Mon Feb 12 00:50:57 2007 New Revision: 53744 Added: peps/trunk/pep-0363.txt (contents, props changed) Modified: peps/trunk/pep-0000.txt Log: added PEP 363 "Syntax For Dynamic Attribute Access" by Ben North Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Mon Feb 12 00:50:57 2007 @@ -98,6 +98,7 @@ S 355 Path - Object oriented filesystem paths Lindqvist S 358 The "bytes" Object Schemenauer S 362 Function Signature Object Cannon, Seo + S 363 Syntax For Dynamic Attribute Access North S 754 IEEE 754 Floating Point Special Values Warnes S 3101 Advanced String Formatting Talin S 3102 Keyword-Only Arguments Talin @@ -434,6 +435,7 @@ I 360 Externally Maintained Packages Cannon I 361 Python 2.6 Release Schedule Norwitz, et al S 362 Function Signature Object Cannon, Seo + S 363 Syntax For Dynamic Attribute Access North SR 666 Reject Foolish Indentation Creighton S 754 IEEE 754 Floating Point Special Values Warnes P 3000 Python 3000 GvR @@ -530,6 +532,7 @@ Meyer, Mike mwm at mired.org Montanaro, Skip skip at pobox.com Moore, Paul gustav at morpheus.demon.co.uk + North, Ben ben at redfrontdoor.org Norwitz, Neal nnorwitz at gmail.com Oliphant, Travis oliphant at ee.byu.edu Pedroni, Samuele pedronis at python.org Added: peps/trunk/pep-0363.txt ============================================================================== --- (empty file) +++ peps/trunk/pep-0363.txt Mon Feb 12 00:50:57 2007 @@ -0,0 +1,272 @@ +PEP: 363 +Title: Syntax For Dynamic Attribute Access +Version: $Revision$ +Last-Modified: $Date$ +Author: Ben North +Status: Draft +Type: Standards Track +Content-Type: text/plain +Created: 29-Jan-2007 +Post-History: + + +Abstract + + Dynamic attribute access is currently possible using the "getattr" + and "setattr" builtins. The present PEP suggests a new syntax to + make such access easier, allowing the coder for example to write + + x.('foo_%d' % n) += 1 + + z = y.('foo_%d' % n).('bar_%s' % s) + + instead of + + attr_name = 'foo_%d' % n + setattr(x, attr_name, getattr(x, attr_name) + 1) + + z = getattr(getattr(y, 'foo_%d' % n), 'bar_%s' % s) + + +Note + + I wrote this patch mostly to advance my own understanding of and + experiment with the python language, but I've written it up in the + style of a PEP in case it might be a useful idea. + + +Rationale + + Dictionary access and indexing both have a friendly invocation + syntax: instead of x.__getitem__(12) the coder can write x[12]. + This also allows the use of subscripted elements in an augmented + assignment, as in "x[12] += 1". The present proposal brings this + ease-of-use to dynamic attribute access too. + + Attribute access is currently possible in two ways: + + * When the attribute name is known at code-writing time, the + ".NAME" trailer can be used, as in + + x.foo = 42 + y.bar += 100 + + * When the attribute name is computed dynamically at run-time, the + "getattr" and "setattr" builtins must be used: + + x = getattr(y, 'foo_%d' % n) + setattr(z, 'bar_%s' % s, 99) + + The "getattr" builtin also allows the coder to specify a default + value to be returned in the event that the object does not have + an attribute of the given name: + + x = getattr(y, 'foo_%d' % n, 0) + + This PEP describes a new syntax for dynamic attribute access --- + "x.(expr)" --- with examples given in the Abstract above. The new + syntax also allows the provision of a default value in the "get" + case, as in: + + x = y.('foo_%d' % n, None) + + This 2-argument form of dynamic attribute access is not permitted as + the target of an (augmented or normal) assignment. Also, this part + of the new syntax was not as well received [6] in initial + discussions on python-ideas, and I agree that it does not fit so + cleanly. I'm happy to prepare a revised PEP/patch without the + 2-argument form if the consensus is that this would be preferred. + + Finally, the new syntax can be used with the "del" statement, as in + + del x.(attr_name) + + +Impact On Existing Code + + The proposed new syntax is not currently valid, so no existing + well-formed programs have their meaning altered by this proposal. + + Across all "*.py" files in the 2.5 distribution, there are around + 600 uses of "getattr", "setattr" or "delattr". They break down as + follows (figures have some room for error because they were + arrived at by partially-manual inspection): + + c.300 uses of plain "getattr(x, attr_name)", which could be + replaced with the new syntax; + + c.150 uses of the 3-argument form, i.e., with the default + value; these could be replaced with the 2-argument form + of the new syntax (the cases break down into c.125 cases + where the attribute name is a literal string, and c.25 + where it's only known at run-time); + + c.5 uses of the 2-argument form with a literal string + attribute name, which I think could be replaced with the + standard "x.attribute" syntax; + + c.120 uses of setattr, of which 15 use getattr to find the + new value; all could be replaced with the new syntax, + the 15 where getattr is also involved would show a + particular increase in clarity; + + c.5 uses which would have to stay as "getattr" because they + are calls of a variable named "getattr" whose default + value is the builtin "getattr"; + + c.5 uses of the 2-argument form, inside a try/except block + which catches AttributeError and uses a default value + instead; these could use 2-argument form of the new + syntax; + + c.10 uses of "delattr", which could use the new syntax. + + As examples, the line + + setattr(self, attr, change_root(self.root, getattr(self, attr))) + + from Lib/distutils/command/install.py could be rewritten + + self.(attr) = change_root(self.root, self.(attr)) + + and the line + + setattr(self, method_name, getattr(self.metadata, method_name)) + + from Lib/distutils/dist.py could be rewritten + + self.(method_name) = self.metadata.(method_name) + + +Performance Impact + + Initial pystone measurements are inconclusive, but suggest there may + be a performance penalty of around 1% in the pystones score with the + patched version. One suggestion is that this is because the longer + main loop in ceval.c hurts the cache behaviour, but this has not + been confirmed. (Maybe a tool like valgrind [2] could help here?) + + On the other hand, measurements suggest a speed-up of around 40--45% + for dynamic attribute access. + + +Discussion To Date + + Initial posting of this PEP in draft form was to python-ideas on + 20070209 [4], and the response was generally positive: + + I've thought of the same syntax. I think you should submit this + to the PEP editor and argue on Python-dev for its inclusion in + Python 2.6 -- there's no benefit that I see of waiting until + 3.0. --- Guido van Rossum [5] + + Wow! I have to say this is a compelling idea. The syntax is a + bit foreign looking, but [...] I feel like I could learn to like + it anyway. --- Greg Falcon [6] + + I look forward to seeing this in Python 2.6. --- Josiah + Carlson, further down the thread [8] + + with Greg Falcon expressing the reservations about the 2-argument + form already noted above, and Josiah Carlson raising a query about + performance: + + My only concern with your propsed change is your draft + implementation. [...] Specifically, your changes [...] may + negatively affect general Python performance. --- Josiah + Carlson [7] + + Some initial measurements (see above) suggest the performance + penalty is small, and Josiah Carlson said of such cost that it + "isn't really substantial". [8] + + +Questions To Be Resolved + + * Whether to allow the 2-argument form for default arguments. + + * Whether the performance impact is real; whether it is acceptable; + whether alternative implementations might improve this aspect. + + +Alternative Syntax For The New Feature + + Other syntaxes could be used, for example braces are currently + invalid in a "trailer", so could be used here, giving + + x{'foo_%d' % n} += 1 + + My personal preference is for the + + x.('foo_%d' % n) += 1 + + syntax though: the presence of the dot shows there is attribute + access going on; the parentheses have an analogous meaning to the + mathematical "work this out first" meaning. This is also the + syntax used in the language Matlab [1] for dynamic "field" access + (where "field" is the Matlab term analogous to Python's + "attribute"). + + Discussions on python-ideas (see above) made no comment on the brace + alternative, and the .() notation was well-enough received, so the + brace alternative should be considered rejected, I think. + + +Error Cases + + Only strings are permitted as attribute names, so for instance the + following error is produced: + + >>> x.(99) = 8 + Traceback (most recent call last): + File "", line 1, in + TypeError: attribute name must be string, not 'int' + + This is handled by the existing PyObject_GetAttr function. + + +Draft Implementation + + A draft implementation adds a new alternative to the "trailer" + clause in Grammar/Grammar; a new AST type, "DynamicAttribute" in + Python.asdl, with accompanying changes to symtable.c, ast.c, and + compile.c, and three new opcodes (load/store/del) with + accompanying changes to opcode.h and ceval.c. The patch consists + of c.180 additional lines in the core code, and c.100 additional + lines of tests. It is available as sourceforge patch #1657573 [3]. + + +References + + [1] Using Dynamic Field Names :: Data Types (MATLAB Programming) + http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f2-41859.html + + [2] Valgrind: "suite of tools for debugging and profiling Linux programs" + http://www.valgrind.org/ + + [3] Sourceforge patch #1657573 + http://sourceforge.net/tracker/index.php?func=detail&aid=1657573&group_id=5470&atid=305470 + + [4] http://mail.python.org/pipermail/python-ideas/2007-February/000210.html + + [5] http://mail.python.org/pipermail/python-ideas/2007-February/000211.html + + [6] http://mail.python.org/pipermail/python-ideas/2007-February/000212.html + + [7] http://mail.python.org/pipermail/python-ideas/2007-February/000213.html + + [8] http://mail.python.org/pipermail/python-ideas/2007-February/000227.html + + +Copyright + + This document has been placed in the public domain. + + +Local Variables: +mode: indented-text +indent-tabs-mode: nil +sentence-end-double-space: t +fill-column: 70 +coding: utf-8 +End: From python-checkins at python.org Mon Feb 12 01:00:19 2007 From: python-checkins at python.org (collin.winter) Date: Mon, 12 Feb 2007 01:00:19 +0100 (CET) Subject: [Python-checkins] r53745 - sandbox/trunk/2to3/fixer_tests.py Message-ID: <20070212000019.CA8531E4017@bag.python.org> Author: collin.winter Date: Mon Feb 12 01:00:19 2007 New Revision: 53745 Modified: sandbox/trunk/2to3/fixer_tests.py Log: Make Test_except actually run; fix related transformation errors Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Mon Feb 12 01:00:19 2007 @@ -4,6 +4,7 @@ # Python imports from StringIO import StringIO +import re import unittest import logging @@ -11,6 +12,15 @@ import pytree import refactor +skip_whitespace = re.compile(r"""\S""") + +def reformat(string): + indent = re.search(skip_whitespace, string).start() + if indent == 0: + code = string + else: + code = "\n".join(line[indent-1:] for line in string.split("\n")[1:]) + return code + "\n\n" # We wrap the RefactoringTool's fixer objects so we can intercept # the call to set_filename() and so modify the fixers' logging objects. @@ -46,8 +56,8 @@ self.refactor.fixers = [Fixer(f, sh) for f in self.refactor.fixers] def check(self, before, after): - before += "\n" - after += "\n" + before = reformat(before) + after = reformat(after) refactored = self.refactor_stream("", StringIO(before)) self.failUnlessEqual(after, refactored) @@ -475,25 +485,28 @@ a = """x = repr((1, 2 + repr((3, 4))))""" self.check(b, a) -class Test_except(): +class Test_except(FixerTestCase): fixer = "except" def test_1(self): b = """ - try: - pass - except Exception, (f, e): - pass - except ImportError, e: - pass""" + def foo(): + try: + pass + except Exception, (f, e): + pass + except ImportError, e: + pass""" a = """ - try: - pass - except Exception as (f, e): - pass - except ImportError as e: - pass""" + def foo(): + try: + pass + except Exception as xxx_todo_changeme: + (f, e) = xxx_todo_changeme.message + pass + except ImportError as e: + pass""" self.check(b, a) def test_2(self): @@ -520,7 +533,8 @@ a = """ try: pass - except Exception as (a, b): + except Exception as xxx_todo_changeme1: + (a, b) = xxx_todo_changeme1.message pass""" self.check(b, a) @@ -534,8 +548,8 @@ a = """ try: pass - except Exception as xxx_todo_changeme: - d[5] = xxx_todo_changeme + except Exception as xxx_todo_changeme2: + d[5] = xxx_todo_changeme2 pass""" self.check(b, a) @@ -549,8 +563,8 @@ a = """ try: pass - except Exception as xxx_todo_changeme1: - a.foo = xxx_todo_changeme1 + except Exception as xxx_todo_changeme3: + a.foo = xxx_todo_changeme3 pass""" self.check(b, a) @@ -564,8 +578,8 @@ a = """ try: pass - except Exception as xxx_todo_changeme2: - a().foo = xxx_todo_changeme2 + except Exception as xxx_todo_changeme4: + a().foo = xxx_todo_changeme4 pass""" self.check(b, a) @@ -650,9 +664,9 @@ b = """def foo(): raise Exception, 5, 6""" a = """def foo(): - xxx_todo_changeme = Exception(5) - xxx_todo_changeme.__traceback__ = 6 - raise xxx_todo_changeme""" + xxx_todo_changeme5 = Exception(5) + xxx_todo_changeme5.__traceback__ = 6 + raise xxx_todo_changeme5""" self.check(b, a) def test_tb_2(self): @@ -662,9 +676,9 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme1 = Exception(5) - xxx_todo_changeme1.__traceback__ = 6 - raise xxx_todo_changeme1 + xxx_todo_changeme6 = Exception(5) + xxx_todo_changeme6.__traceback__ = 6 + raise xxx_todo_changeme6 b = 6""" self.check(b, a) @@ -672,9 +686,9 @@ b = """def foo(): raise Exception,5,6""" a = """def foo(): - xxx_todo_changeme2 = Exception(5) - xxx_todo_changeme2.__traceback__ = 6 - raise xxx_todo_changeme2""" + xxx_todo_changeme7 = Exception(5) + xxx_todo_changeme7.__traceback__ = 6 + raise xxx_todo_changeme7""" self.check(b, a) def test_tb_4(self): @@ -684,9 +698,9 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme3 = Exception(5) - xxx_todo_changeme3.__traceback__ = 6 - raise xxx_todo_changeme3 + xxx_todo_changeme8 = Exception(5) + xxx_todo_changeme8.__traceback__ = 6 + raise xxx_todo_changeme8 b = 6""" self.check(b, a) @@ -694,9 +708,9 @@ b = """def foo(): raise Exception, (5, 6, 7), 6""" a = """def foo(): - xxx_todo_changeme4 = Exception((5, 6, 7)) - xxx_todo_changeme4.__traceback__ = 6 - raise xxx_todo_changeme4""" + xxx_todo_changeme9 = Exception((5, 6, 7)) + xxx_todo_changeme9.__traceback__ = 6 + raise xxx_todo_changeme9""" self.check(b, a) def test_tb_6(self): @@ -706,9 +720,9 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme5 = Exception((5, 6, 7)) - xxx_todo_changeme5.__traceback__ = 6 - raise xxx_todo_changeme5 + xxx_todo_changeme10 = Exception((5, 6, 7)) + xxx_todo_changeme10.__traceback__ = 6 + raise xxx_todo_changeme10 b = 6""" self.check(b, a) @@ -759,9 +773,9 @@ b = """def foo(): g.throw(Exception, 5, 6)""" a = """def foo(): - xxx_todo_changeme6 = Exception(5) - xxx_todo_changeme6.__traceback__ = 6 - g.throw(xxx_todo_changeme6)""" + xxx_todo_changeme11 = Exception(5) + xxx_todo_changeme11.__traceback__ = 6 + g.throw(xxx_todo_changeme11)""" self.check(b, a) def test_tb_2(self): @@ -771,9 +785,9 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme7 = Exception(5) - xxx_todo_changeme7.__traceback__ = 6 - g.throw(xxx_todo_changeme7) + xxx_todo_changeme12 = Exception(5) + xxx_todo_changeme12.__traceback__ = 6 + g.throw(xxx_todo_changeme12) b = 6""" self.check(b, a) @@ -781,9 +795,9 @@ b = """def foo(): g.throw(Exception,5,6)""" a = """def foo(): - xxx_todo_changeme8 = Exception(5) - xxx_todo_changeme8.__traceback__ = 6 - g.throw(xxx_todo_changeme8)""" + xxx_todo_changeme13 = Exception(5) + xxx_todo_changeme13.__traceback__ = 6 + g.throw(xxx_todo_changeme13)""" self.check(b, a) def test_tb_4(self): @@ -793,9 +807,9 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme9 = Exception(5) - xxx_todo_changeme9.__traceback__ = 6 - g.throw(xxx_todo_changeme9) + xxx_todo_changeme14 = Exception(5) + xxx_todo_changeme14.__traceback__ = 6 + g.throw(xxx_todo_changeme14) b = 6""" self.check(b, a) @@ -803,9 +817,9 @@ b = """def foo(): g.throw(Exception, (5, 6, 7), 6)""" a = """def foo(): - xxx_todo_changeme10 = Exception((5, 6, 7)) - xxx_todo_changeme10.__traceback__ = 6 - g.throw(xxx_todo_changeme10)""" + xxx_todo_changeme15 = Exception((5, 6, 7)) + xxx_todo_changeme15.__traceback__ = 6 + g.throw(xxx_todo_changeme15)""" self.check(b, a) def test_tb_6(self): @@ -815,9 +829,9 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme11 = Exception((5, 6, 7)) - xxx_todo_changeme11.__traceback__ = 6 - g.throw(xxx_todo_changeme11) + xxx_todo_changeme16 = Exception((5, 6, 7)) + xxx_todo_changeme16.__traceback__ = 6 + g.throw(xxx_todo_changeme16) b = 6""" self.check(b, a) @@ -825,9 +839,9 @@ b = """def foo(): a + g.throw(Exception, 5, 6)""" a = """def foo(): - xxx_todo_changeme12 = Exception(5) - xxx_todo_changeme12.__traceback__ = 6 - a + g.throw(xxx_todo_changeme12)""" + xxx_todo_changeme17 = Exception(5) + xxx_todo_changeme17.__traceback__ = 6 + a + g.throw(xxx_todo_changeme17)""" self.check(b, a) def test_tb_8(self): @@ -837,9 +851,9 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme13 = Exception(5) - xxx_todo_changeme13.__traceback__ = 6 - a + g.throw(xxx_todo_changeme13) + xxx_todo_changeme18 = Exception(5) + xxx_todo_changeme18.__traceback__ = 6 + a + g.throw(xxx_todo_changeme18) b = 6""" self.check(b, a) From python-checkins at python.org Mon Feb 12 04:00:06 2007 From: python-checkins at python.org (brett.cannon) Date: Mon, 12 Feb 2007 04:00:06 +0100 (CET) Subject: [Python-checkins] r53750 - peps/trunk/pep-0339.txt Message-ID: <20070212030006.9239C1E4004@bag.python.org> Author: brett.cannon Date: Mon Feb 12 04:00:05 2007 New Revision: 53750 Modified: peps/trunk/pep-0339.txt Log: Mention how Python/Python-ast.c must be committed separately after every change to the grammar as its __version__ value is set to the AST grammar's revision number. Modified: peps/trunk/pep-0339.txt ============================================================================== --- peps/trunk/pep-0339.txt (original) +++ peps/trunk/pep-0339.txt Mon Feb 12 04:00:05 2007 @@ -443,7 +443,9 @@ Creates C structs corresponding to the ASDL types. Also contains code for marshaling AST nodes (core ASDL types have marshaling code in asdl.c). "File automatically generated by - Parser/asdl_c.py". + Parser/asdl_c.py". This file must be committed separately + after every grammar change is committed since the __version__ + value is set to the latest grammar change revision number. - asdl.c Contains code to handle the ASDL sequence type. Also has code From python-checkins at python.org Mon Feb 12 04:51:03 2007 From: python-checkins at python.org (brett.cannon) Date: Mon, 12 Feb 2007 04:51:03 +0100 (CET) Subject: [Python-checkins] r53751 - in python/trunk: Include/Python-ast.h Parser/asdl_c.py Python/Python-ast.c Message-ID: <20070212035103.F36DE1E4004@bag.python.org> Author: brett.cannon Date: Mon Feb 12 04:51:02 2007 New Revision: 53751 Modified: python/trunk/Include/Python-ast.h python/trunk/Parser/asdl_c.py python/trunk/Python/Python-ast.c Log: Modify Parser/asdl_c.py so that the __version__ number for Python/Python-ast.c is specified at the top of the file. Also add a note that Python/Python-ast.c needs to be committed separately after a change to the AST grammar to capture the revision number of the change (which is what __version__ is set to). Modified: python/trunk/Include/Python-ast.h ============================================================================== --- python/trunk/Include/Python-ast.h (original) +++ python/trunk/Include/Python-ast.h Mon Feb 12 04:51:02 2007 @@ -1,4 +1,4 @@ -/* File automatically generated by Parser/asdl_c.py */ +/* File automatically generated by Parser/asdl_c.py. */ #include "asdl.h" Modified: python/trunk/Parser/asdl_c.py ============================================================================== --- python/trunk/Parser/asdl_c.py (original) +++ python/trunk/Parser/asdl_c.py Mon Feb 12 04:51:02 2007 @@ -525,6 +525,9 @@ (cons.name, cons.name), 1) self.emit("if (!%s_singleton) return 0;" % cons.name, 1) +def parse_version(mod): + return mod.version.value[12:-3] + class ASTModuleVisitor(PickleVisitor): def visitModule(self, mod): @@ -540,7 +543,8 @@ self.emit('if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)', 1) self.emit("return;", 2) # Value of version: "$Revision$" - self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)' % mod.version.value[12:-3], 1) + self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)' + % parse_version(mod), 1) self.emit("return;", 2) for dfn in mod.dfns: self.visit(dfn) @@ -721,11 +725,23 @@ v.visit(object) v.emit("", 0) +common_msg = "/* File automatically generated by %s. */\n" + +c_file_msg = """ +/* + __version__ %s. + + This module must be committed separately after each AST grammar change; + The __version__ number is set to the revision number of the commit + containing the grammar change. +*/ +""" + def main(srcfile): argv0 = sys.argv[0] components = argv0.split(os.sep) argv0 = os.sep.join(components[-2:]) - auto_gen_msg = '/* File automatically generated by %s */\n' % argv0 + auto_gen_msg = common_msg % argv0 mod = asdl.parse(srcfile) if not asdl.check(mod): sys.exit(1) @@ -746,6 +762,7 @@ p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") f = open(p, "wb") print >> f, auto_gen_msg + print >> f, c_file_msg % parse_version(mod) print >> f, '#include "Python.h"' print >> f, '#include "%s-ast.h"' % mod.name print >> f Modified: python/trunk/Python/Python-ast.c ============================================================================== --- python/trunk/Python/Python-ast.c (original) +++ python/trunk/Python/Python-ast.c Mon Feb 12 04:51:02 2007 @@ -1,4 +1,13 @@ -/* File automatically generated by Parser/asdl_c.py */ +/* File automatically generated by Parser/asdl_c.py. */ + + +/* + __version__ 53731. + + This module must be committed separately after each AST grammar change; + The __version__ number is set to the revision number of the commit + containing the grammar change. +*/ #include "Python.h" #include "Python-ast.h" From python-checkins at python.org Mon Feb 12 10:25:54 2007 From: python-checkins at python.org (lars.gustaebel) Date: Mon, 12 Feb 2007 10:25:54 +0100 (CET) Subject: [Python-checkins] r53752 - python/trunk/Doc/lib/libtarfile.tex Message-ID: <20070212092554.720F81E4015@bag.python.org> Author: lars.gustaebel Date: Mon Feb 12 10:25:53 2007 New Revision: 53752 Modified: python/trunk/Doc/lib/libtarfile.tex Log: Bug #1656581: Point out that external file objects are supposed to be at position 0. Modified: python/trunk/Doc/lib/libtarfile.tex ============================================================================== --- python/trunk/Doc/lib/libtarfile.tex (original) +++ python/trunk/Doc/lib/libtarfile.tex Mon Feb 12 10:25:53 2007 @@ -49,8 +49,8 @@ avoid this. If a compression method is not supported, \exception{CompressionError} is raised. - If \var{fileobj} is specified, it is used as an alternative to - a file object opened for \var{name}. + If \var{fileobj} is specified, it is used as an alternative to a file + object opened for \var{name}. It is supposed to be at position 0. For special purposes, there is a second format for \var{mode}: \code{'filemode|[compression]'}. \function{open()} will return a @@ -161,6 +161,7 @@ If \var{fileobj} is given, it is used for reading or writing data. If it can be determined, \var{mode} is overridden by \var{fileobj}'s mode. + \var{fileobj} will be used from position 0. \begin{notice} \var{fileobj} is not closed, when \class{TarFile} is closed. \end{notice} From python-checkins at python.org Mon Feb 12 10:27:10 2007 From: python-checkins at python.org (lars.gustaebel) Date: Mon, 12 Feb 2007 10:27:10 +0100 (CET) Subject: [Python-checkins] r53753 - python/branches/release25-maint/Doc/lib/libtarfile.tex Message-ID: <20070212092710.E2E1D1E4004@bag.python.org> Author: lars.gustaebel Date: Mon Feb 12 10:27:10 2007 New Revision: 53753 Modified: python/branches/release25-maint/Doc/lib/libtarfile.tex Log: Bug #1656581: Point out that external file objects are supposed to be at position 0. (backport from rev. 53752) Modified: python/branches/release25-maint/Doc/lib/libtarfile.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libtarfile.tex (original) +++ python/branches/release25-maint/Doc/lib/libtarfile.tex Mon Feb 12 10:27:10 2007 @@ -48,8 +48,8 @@ avoid this. If a compression method is not supported, \exception{CompressionError} is raised. - If \var{fileobj} is specified, it is used as an alternative to - a file object opened for \var{name}. + If \var{fileobj} is specified, it is used as an alternative to a file + object opened for \var{name}. It is supposed to be at position 0. For special purposes, there is a second format for \var{mode}: \code{'filemode|[compression]'}. \function{open()} will return a @@ -155,6 +155,7 @@ If \var{fileobj} is given, it is used for reading or writing data. If it can be determined, \var{mode} is overridden by \var{fileobj}'s mode. + \var{fileobj} will be used from position 0. \begin{notice} \var{fileobj} is not closed, when \class{TarFile} is closed. \end{notice} From python-checkins at python.org Mon Feb 12 13:21:11 2007 From: python-checkins at python.org (martin.v.loewis) Date: Mon, 12 Feb 2007 13:21:11 +0100 (CET) Subject: [Python-checkins] r53754 - in python/trunk: Lib/test/test_sax.py Lib/xml/sax/saxutils.py Misc/NEWS Message-ID: <20070212122111.805291E400D@bag.python.org> Author: martin.v.loewis Date: Mon Feb 12 13:21:10 2007 New Revision: 53754 Modified: python/trunk/Lib/test/test_sax.py python/trunk/Lib/xml/sax/saxutils.py python/trunk/Misc/NEWS Log: Patch 1463026: Support default namespace in XMLGenerator. Fixes #847665. Will backport. Modified: python/trunk/Lib/test/test_sax.py ============================================================================== --- python/trunk/Lib/test/test_sax.py (original) +++ python/trunk/Lib/test/test_sax.py Mon Feb 12 13:21:10 2007 @@ -216,7 +216,44 @@ ('' % ns_uri) -# ===== XMLFilterBase +def test_1463026_1(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS((None, 'a'), 'a') + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_2(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping(None, 'qux') + gen.startElementNS(('qux', 'a'), 'a', {}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping(None) + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_3(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping('my', 'qux') + gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping('my') + gen.endDocument() + + return result.getvalue() == start+'' + +# ===== Xmlfilterbase def test_filter_basic(): result = StringIO() Modified: python/trunk/Lib/xml/sax/saxutils.py ============================================================================== --- python/trunk/Lib/xml/sax/saxutils.py (original) +++ python/trunk/Lib/xml/sax/saxutils.py Mon Feb 12 13:21:10 2007 @@ -100,6 +100,17 @@ else: self._out.write(text.encode(self._encoding, _error_handling)) + def _qname(self, name): + """Builds a qualified name from a (ns_url, localname) pair""" + if name[0]: + # The name is in a non-empty namespace + prefix = self._current_context[name[0]] + if prefix: + # If it is not the default namespace, prepend the prefix + return prefix + ":" + name[1] + # Return the unqualified name + return name[1] + # ContentHandler methods def startDocument(self): @@ -125,29 +136,21 @@ self._write('' % name) def startElementNS(self, name, qname, attrs): - if name[0] is None: - # if the name was not namespace-scoped, use the unqualified part - name = name[1] - else: - # else try to restore the original prefix from the namespace - name = self._current_context[name[0]] + ":" + name[1] - self._write('<' + name) + self._write('<' + self._qname(name)) - for pair in self._undeclared_ns_maps: - self._write(' xmlns:%s="%s"' % pair) + for prefix, uri in self._undeclared_ns_maps: + if prefix: + self._out.write(' xmlns:%s="%s"' % (prefix, uri)) + else: + self._out.write(' xmlns="%s"' % uri) self._undeclared_ns_maps = [] for (name, value) in attrs.items(): - name = self._current_context[name[0]] + ":" + name[1] - self._write(' %s=%s' % (name, quoteattr(value))) + self._write(' %s=%s' % (self._qname(name), quoteattr(value))) self._write('>') def endElementNS(self, name, qname): - if name[0] is None: - name = name[1] - else: - name = self._current_context[name[0]] + ":" + name[1] - self._write('' % name) + self._write('' % self._qname(name)) def characters(self, content): self._write(escape(content)) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon Feb 12 13:21:10 2007 @@ -128,6 +128,8 @@ Library ------- +- Patch 1463026: Support default namespace in XMLGenerator. + - Patch 1571379: Make trace's --ignore-dir facility work in the face of relative directory names. From python-checkins at python.org Mon Feb 12 13:21:42 2007 From: python-checkins at python.org (martin.v.loewis) Date: Mon, 12 Feb 2007 13:21:42 +0100 (CET) Subject: [Python-checkins] r53755 - in python/branches/release25-maint: Lib/test/test_sax.py Lib/xml/sax/saxutils.py Misc/NEWS Message-ID: <20070212122142.A97B31E4004@bag.python.org> Author: martin.v.loewis Date: Mon Feb 12 13:21:41 2007 New Revision: 53755 Modified: python/branches/release25-maint/Lib/test/test_sax.py python/branches/release25-maint/Lib/xml/sax/saxutils.py python/branches/release25-maint/Misc/NEWS Log: Patch 1463026: Support default namespace in XMLGenerator. Fixes #847665. Modified: python/branches/release25-maint/Lib/test/test_sax.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_sax.py (original) +++ python/branches/release25-maint/Lib/test/test_sax.py Mon Feb 12 13:21:41 2007 @@ -216,7 +216,44 @@ ('' % ns_uri) -# ===== XMLFilterBase +def test_1463026_1(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS((None, 'a'), 'a') + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_2(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping(None, 'qux') + gen.startElementNS(('qux', 'a'), 'a', {}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping(None) + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_3(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping('my', 'qux') + gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping('my') + gen.endDocument() + + return result.getvalue() == start+'' + +# ===== Xmlfilterbase def test_filter_basic(): result = StringIO() Modified: python/branches/release25-maint/Lib/xml/sax/saxutils.py ============================================================================== --- python/branches/release25-maint/Lib/xml/sax/saxutils.py (original) +++ python/branches/release25-maint/Lib/xml/sax/saxutils.py Mon Feb 12 13:21:41 2007 @@ -100,6 +100,17 @@ else: self._out.write(text.encode(self._encoding, _error_handling)) + def _qname(self, name): + """Builds a qualified name from a (ns_url, localname) pair""" + if name[0]: + # The name is in a non-empty namespace + prefix = self._current_context[name[0]] + if prefix: + # If it is not the default namespace, prepend the prefix + return prefix + ":" + name[1] + # Return the unqualified name + return name[1] + # ContentHandler methods def startDocument(self): @@ -125,29 +136,21 @@ self._write('' % name) def startElementNS(self, name, qname, attrs): - if name[0] is None: - # if the name was not namespace-scoped, use the unqualified part - name = name[1] - else: - # else try to restore the original prefix from the namespace - name = self._current_context[name[0]] + ":" + name[1] - self._write('<' + name) + self._write('<' + self._qname(name)) - for pair in self._undeclared_ns_maps: - self._write(' xmlns:%s="%s"' % pair) + for prefix, uri in self._undeclared_ns_maps: + if prefix: + self._out.write(' xmlns:%s="%s"' % (prefix, uri)) + else: + self._out.write(' xmlns="%s"' % uri) self._undeclared_ns_maps = [] for (name, value) in attrs.items(): - name = self._current_context[name[0]] + ":" + name[1] - self._write(' %s=%s' % (name, quoteattr(value))) + self._write(' %s=%s' % (self._qname(name), quoteattr(value))) self._write('>') def endElementNS(self, name, qname): - if name[0] is None: - name = name[1] - else: - name = self._current_context[name[0]] + ":" + name[1] - self._write('' % name) + self._write('' % self._qname(name)) def characters(self, content): self._write(escape(content)) Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Mon Feb 12 13:21:41 2007 @@ -169,6 +169,8 @@ Library ------- +- Patch 1463026: Support default namespace in XMLGenerator. + - Patch 1571379: Make trace's --ignore-dir facility work in the face of relative directory names. From buildbot at python.org Mon Feb 12 14:39:50 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 12 Feb 2007 13:39:50 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) trunk Message-ID: <20070212133951.0FA451E4006@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%2520trunk/builds/1180 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: lars.gustaebel,martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: Traceback (most recent call last): File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30995, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') 1 test failed: test_timeout sincerely, -The Buildbot From buildbot at python.org Mon Feb 12 15:00:06 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 12 Feb 2007 14:00:06 +0000 Subject: [Python-checkins] buildbot warnings in ia64 Ubuntu trunk 2.5 Message-ID: <20070212140006.7D6331E4006@bag.python.org> The Buildbot has detected a new failure of ia64 Ubuntu trunk 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/ia64%2520Ubuntu%2520trunk%25202.5/builds/192 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: lars.gustaebel,martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_ctypes make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Mon Feb 12 17:22:30 2007 From: python-checkins at python.org (collin.winter) Date: Mon, 12 Feb 2007 17:22:30 +0100 (CET) Subject: [Python-checkins] r53756 - in sandbox/trunk/2to3: fixer_tests.py fixes/fix_raise.py fixes/macros.py Message-ID: <20070212162230.2304B1E4006@bag.python.org> Author: collin.winter Date: Mon Feb 12 17:22:29 2007 New Revision: 53756 Modified: sandbox/trunk/2to3/fixer_tests.py sandbox/trunk/2to3/fixes/fix_raise.py sandbox/trunk/2to3/fixes/macros.py Log: Make fix_raise smarter about dealing with parenthesized expressions Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Mon Feb 12 17:22:29 2007 @@ -643,20 +643,37 @@ def test_3(self): b = """raise Exception, (5, 6, 7)""" - a = """raise Exception((5, 6, 7))""" + a = """raise Exception(5, 6, 7)""" self.check(b, a) - - # These should not be touched - + def test_4(self): - b = """raise Exception""" - a = """raise Exception""" + b = """raise E, (5, 6) % (a, b)""" + a = """raise E((5, 6) % (a, b))""" self.check(b, a) - + def test_5(self): - b = """raise Exception(5, 6)""" - a = """raise Exception(5, 6)""" + b = """raise (((E1, E2), E3), E4), V""" + a = """raise E1(V)""" + self.check(b, a) + + def test_6(self): + b = """raise (E1, (E2, E3), E4), V""" + a = """raise E1(V)""" self.check(b, a) + + # These should produce a warning + + def test_warn_1(self): + s = """raise 'foo'""" + self.warns(s, s, "Python 3 does not support string exceptions") + + def test_warn_2(self): + s = """raise "foo", 5""" + self.warns(s, s, "Python 3 does not support string exceptions") + + def test_warn_3(self): + s = """raise "foo", 5, 6""" + self.warns(s, s, "Python 3 does not support string exceptions") # These should result in traceback-assignment @@ -708,7 +725,7 @@ b = """def foo(): raise Exception, (5, 6, 7), 6""" a = """def foo(): - xxx_todo_changeme9 = Exception((5, 6, 7)) + xxx_todo_changeme9 = Exception(5, 6, 7) xxx_todo_changeme9.__traceback__ = 6 raise xxx_todo_changeme9""" self.check(b, a) @@ -720,7 +737,7 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme10 = Exception((5, 6, 7)) + xxx_todo_changeme10 = Exception(5, 6, 7) xxx_todo_changeme10.__traceback__ = 6 raise xxx_todo_changeme10 b = 6""" Modified: sandbox/trunk/2to3/fixes/fix_raise.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_raise.py (original) +++ sandbox/trunk/2to3/fixes/fix_raise.py Mon Feb 12 17:22:29 2007 @@ -7,22 +7,48 @@ # Local imports import pytree from fixes import basefix -from fixes.macros import Name, Call, Assign, Newline, Attr +from fixes.macros import Name, Call, Assign, Newline, Attr, is_tuple class FixRaise(basefix.BaseFix): PATTERN = """ - raise_stmt< 'raise' exc=any ',' val=any [',' tb=any] > + raise_stmt< 'raise' exc=any [',' val=any [',' tb=any]] > """ def transform(self, node): syms = self.syms results = self.match(node) assert results - + exc = results["exc"].clone() - args = [results["val"].clone()] - args[0].set_prefix("") + if exc.type is token.STRING: + self.cannot_convert(node, "Python 3 does not support string exceptions") + return + + # Python 2 supports + # raise ((((E1, E2), E3), E4), E5), V + # as a synonym for + # raise E1, V + # Since Python 3 will not support this, we recurse down any tuple + # literals, always taking the first element. + while is_tuple(exc): + # exc.children[1:-1] is the unparenthesized tuple + # exc.children[1].children[0] is the first element of the tuple + exc = exc.children[1].children[0].clone() + exc.set_prefix(" ") + + if "val" not in results: + # One-argument raise + new = pytree.Node(syms.raise_stmt, [Name("raise"), exc]) + new.set_prefix(node.get_prefix()) + return new + + val = results["val"].clone() + if is_tuple(val): + args = [c.clone() for c in val.children[1:-1]] + else: + val.set_prefix("") + args = [val] if "tb" in results: tb = results["tb"].clone() @@ -42,8 +68,7 @@ # Assign the traceback set_tb = pytree.Node(syms.simple_stmt, - [Assign(Attr(name.clone(), - Name("__traceback__")), tb), + [Assign(Attr(name.clone(), Name("__traceback__")), tb), Newline()]) set_tb.set_prefix(indent) set_tb.parent = node.parent.parent @@ -57,7 +82,6 @@ new.set_prefix(indent) return new else: - new = pytree.Node(syms.raise_stmt, - [Name("raise"), Call(exc, args)]) + new = pytree.Node(syms.raise_stmt, [Name("raise"), Call(exc, args)]) new.set_prefix(node.get_prefix()) return new Modified: sandbox/trunk/2to3/fixes/macros.py ============================================================================== --- sandbox/trunk/2to3/fixes/macros.py (original) +++ sandbox/trunk/2to3/fixes/macros.py Mon Feb 12 17:22:29 2007 @@ -55,3 +55,13 @@ def Newline(): """A newline literal""" return Leaf(token.NEWLINE, "\n") + +def is_tuple(node): + """Does the node represent a tuple literal?""" + + return (isinstance(node, Node) + and len(node.children) > 1 + and isinstance(node.children[0], Leaf) + and isinstance(node.children[-1], Leaf) + and node.children[0].value == "(" + and node.children[-1].value == ")") From python-checkins at python.org Mon Feb 12 17:23:25 2007 From: python-checkins at python.org (armin.rigo) Date: Mon, 12 Feb 2007 17:23:25 +0100 (CET) Subject: [Python-checkins] r53757 - python/trunk/Lib/test/test_descr.py Message-ID: <20070212162325.150241E4006@bag.python.org> Author: armin.rigo Date: Mon Feb 12 17:23:24 2007 New Revision: 53757 Modified: python/trunk/Lib/test/test_descr.py Log: Fix the line to what is my guess at the original author's meaning. (The line has no effect anyway, but is present because it's customary call the base class __init__). Modified: python/trunk/Lib/test/test_descr.py ============================================================================== --- python/trunk/Lib/test/test_descr.py (original) +++ python/trunk/Lib/test/test_descr.py Mon Feb 12 17:23:24 2007 @@ -2226,7 +2226,7 @@ __slots__ = ['prec'] def __init__(self, value=0.0, prec=12): self.prec = int(prec) - float.__init__(value) + float.__init__(self, value) def __repr__(self): return "%.*g" % (self.prec, self) vereq(repr(precfloat(1.1)), "1.1") From buildbot at python.org Mon Feb 12 17:47:38 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 12 Feb 2007 16:47:38 +0000 Subject: [Python-checkins] buildbot warnings in x86 gentoo trunk Message-ID: <20070212164738.8D3E71E4006@bag.python.org> The Buildbot has detected a new failure of x86 gentoo trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%2520trunk/builds/1914 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: armin.rigo Build had warnings: warnings test Excerpt from the test logfile: Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 260, in writerThread self.assertEqual(data, self.makeData(key)) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/unittest.py", line 334, in failUnlessEqual (msg or '%r != %r' % (first, second)) AssertionError: None != '1001-1001-1001-1001-1001' Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 260, in writerThread self.assertEqual(data, self.makeData(key)) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/unittest.py", line 334, in failUnlessEqual (msg or '%r != %r' % (first, second)) AssertionError: None != '2000-2000-2000-2000-2000' Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 260, in writerThread self.assertEqual(data, self.makeData(key)) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/unittest.py", line 334, in failUnlessEqual (msg or '%r != %r' % (first, second)) AssertionError: None != '0002-0002-0002-0002-0002' 1 test failed: test_urllib2net make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Mon Feb 12 20:14:36 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 12 Feb 2007 19:14:36 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP-2 trunk Message-ID: <20070212191436.80A1E1E4006@bag.python.org> The Buildbot has detected a new failure of x86 XP-2 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP-2%2520trunk/builds/955 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: andrew.kuchling,armin.rigo,brett.cannon,georg.brandl,kurt.kaiser,lars.gustaebel,martin.v.loewis,peter.astrand,raymond.hettinger,skip.montanaro,tim.peters Build had warnings: warnings failed slave lost sincerely, -The Buildbot From buildbot at python.org Mon Feb 12 21:12:13 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 12 Feb 2007 20:12:13 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP-2 trunk Message-ID: <20070212201213.4BF4E1E400D@bag.python.org> The Buildbot has detected a new failure of x86 XP-2 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP-2%2520trunk/builds/958 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'tim': lost connection Build Source Stamp: [branch trunk] HEAD Blamelist: Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_socket_ssl test_tarfile ====================================================================== ERROR: test_fileobj (test.test_tarfile.AppendTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Code\bb_slave\trunk.peters-windows\build\lib\test\test_tarfile.py", line 355, in test_fileobj self._test(names=["foo", "bar"], fileobj=fobj) File "C:\Code\bb_slave\trunk.peters-windows\build\lib\test\test_tarfile.py", line 331, in _test tar = tarfile.open(self.tarname, fileobj=fileobj) File "C:\Code\bb_slave\trunk.peters-windows\build\lib\tarfile.py", line 1157, in open raise ReadError("file could not be opened successfully") ReadError: file could not be opened successfully sincerely, -The Buildbot From python-checkins at python.org Tue Feb 13 00:59:47 2007 From: python-checkins at python.org (collin.winter) Date: Tue, 13 Feb 2007 00:59:47 +0100 (CET) Subject: [Python-checkins] r53758 - in sandbox/trunk/2to3: fixes/fix_apply.py fixes/fix_dict.py fixes/fix_dict2.py fixes/fix_except.py fixes/fix_exec.py fixes/fix_has_key.py fixes/fix_intern.py fixes/fix_long.py fixes/fix_ne.py fixes/fix_print.py fixes/fix_raise.py fixes/fix_repr.py fixes/fix_sysexcinfo.py fixes/fix_throw.py fixes/fix_xrange.py fixes/macros.py patcomp.py pgen2/conv.py pgen2/driver.py pgen2/grammar.py pgen2/parse.py pgen2/pgen.py pgen2/token.py pgen2/tokenize.py pygram.py refactor.py tokenize.py Message-ID: <20070212235947.A3CCC1E400D@bag.python.org> Author: collin.winter Date: Tue Feb 13 00:59:44 2007 New Revision: 53758 Added: sandbox/trunk/2to3/pgen2/token.py (contents, props changed) sandbox/trunk/2to3/pgen2/tokenize.py - copied, changed from r53757, sandbox/trunk/2to3/tokenize.py Removed: sandbox/trunk/2to3/tokenize.py Modified: sandbox/trunk/2to3/fixes/fix_apply.py sandbox/trunk/2to3/fixes/fix_dict.py sandbox/trunk/2to3/fixes/fix_dict2.py sandbox/trunk/2to3/fixes/fix_except.py sandbox/trunk/2to3/fixes/fix_exec.py sandbox/trunk/2to3/fixes/fix_has_key.py sandbox/trunk/2to3/fixes/fix_intern.py sandbox/trunk/2to3/fixes/fix_long.py sandbox/trunk/2to3/fixes/fix_ne.py sandbox/trunk/2to3/fixes/fix_print.py sandbox/trunk/2to3/fixes/fix_raise.py sandbox/trunk/2to3/fixes/fix_repr.py sandbox/trunk/2to3/fixes/fix_sysexcinfo.py sandbox/trunk/2to3/fixes/fix_throw.py sandbox/trunk/2to3/fixes/fix_xrange.py sandbox/trunk/2to3/fixes/macros.py sandbox/trunk/2to3/patcomp.py sandbox/trunk/2to3/pgen2/conv.py sandbox/trunk/2to3/pgen2/driver.py sandbox/trunk/2to3/pgen2/grammar.py sandbox/trunk/2to3/pgen2/parse.py sandbox/trunk/2to3/pgen2/pgen.py sandbox/trunk/2to3/pygram.py sandbox/trunk/2to3/refactor.py Log: Move token and tokenize into pgen2 Modified: sandbox/trunk/2to3/fixes/fix_apply.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_apply.py (original) +++ sandbox/trunk/2to3/fixes/fix_apply.py Tue Feb 13 00:59:44 2007 @@ -3,11 +3,9 @@ """Fixer for apply().""" -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Call, Comma Modified: sandbox/trunk/2to3/fixes/fix_dict.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_dict.py (original) +++ sandbox/trunk/2to3/fixes/fix_dict.py Tue Feb 13 00:59:44 2007 @@ -21,12 +21,10 @@ as an argument to a function that introspects the argument). """ -# Python imports -import token - # Local imports import pytree import patcomp +from pgen2 import token from fixes import basefix from fixes import macros Modified: sandbox/trunk/2to3/fixes/fix_dict2.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_dict2.py (original) +++ sandbox/trunk/2to3/fixes/fix_dict2.py Tue Feb 13 00:59:44 2007 @@ -9,11 +9,9 @@ .itervalues -> .values """ -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes import macros Modified: sandbox/trunk/2to3/fixes/fix_except.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_except.py (original) +++ sandbox/trunk/2to3/fixes/fix_except.py Tue Feb 13 00:59:44 2007 @@ -1,11 +1,9 @@ """Fixer for except statements with named exceptions.""" # Author: Collin Winter -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Assign, Attr, Name Modified: sandbox/trunk/2to3/fixes/fix_exec.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_exec.py (original) +++ sandbox/trunk/2to3/fixes/fix_exec.py Tue Feb 13 00:59:44 2007 @@ -3,11 +3,9 @@ """Fixer for exec.""" -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Comma, Name, Call Modified: sandbox/trunk/2to3/fixes/fix_has_key.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_has_key.py (original) +++ sandbox/trunk/2to3/fixes/fix_has_key.py Tue Feb 13 00:59:44 2007 @@ -3,11 +3,9 @@ """Fixer for has_key().""" -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Name Modified: sandbox/trunk/2to3/fixes/fix_intern.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_intern.py (original) +++ sandbox/trunk/2to3/fixes/fix_intern.py Tue Feb 13 00:59:44 2007 @@ -3,11 +3,9 @@ """Fixer for intern().""" -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Name, Attr Modified: sandbox/trunk/2to3/fixes/fix_long.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_long.py (original) +++ sandbox/trunk/2to3/fixes/fix_long.py Tue Feb 13 00:59:44 2007 @@ -6,11 +6,9 @@ This also strips the trailing 'L' or 'l' from long loterals. """ -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Name Modified: sandbox/trunk/2to3/fixes/fix_ne.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_ne.py (original) +++ sandbox/trunk/2to3/fixes/fix_ne.py Tue Feb 13 00:59:44 2007 @@ -6,11 +6,9 @@ This is so simple that we don't need the pattern compiler. """ -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix Modified: sandbox/trunk/2to3/fixes/fix_print.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_print.py (original) +++ sandbox/trunk/2to3/fixes/fix_print.py Tue Feb 13 00:59:44 2007 @@ -10,11 +10,9 @@ 'print >>x, ...' into 'print(..., file=x)' """ -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Name, Call, Comma Modified: sandbox/trunk/2to3/fixes/fix_raise.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_raise.py (original) +++ sandbox/trunk/2to3/fixes/fix_raise.py Tue Feb 13 00:59:44 2007 @@ -1,11 +1,9 @@ """Fixer for 'raise E, V, T'""" # Author: Collin Winter -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Name, Call, Assign, Newline, Attr, is_tuple Modified: sandbox/trunk/2to3/fixes/fix_repr.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_repr.py (original) +++ sandbox/trunk/2to3/fixes/fix_repr.py Tue Feb 13 00:59:44 2007 @@ -3,11 +3,9 @@ """Fixer that transforms `xyzzy` into repr(xyzzy).""" -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Call, Name Modified: sandbox/trunk/2to3/fixes/fix_sysexcinfo.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_sysexcinfo.py (original) +++ sandbox/trunk/2to3/fixes/fix_sysexcinfo.py Tue Feb 13 00:59:44 2007 @@ -1,10 +1,8 @@ """Fixer/warner for sys.exc_{info,value,type,traceback}""" # Author: Collin Winter -# Python imports -import token - # Local imports +from pgen2 import token from pytree import Leaf from fixes import basefix Modified: sandbox/trunk/2to3/fixes/fix_throw.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_throw.py (original) +++ sandbox/trunk/2to3/fixes/fix_throw.py Tue Feb 13 00:59:44 2007 @@ -1,11 +1,9 @@ """Fixer for generator.throw(E, V, T)""" # Author: Collin Winter -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes.macros import Name, Call, Assign, Newline, Attr Modified: sandbox/trunk/2to3/fixes/fix_xrange.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_xrange.py (original) +++ sandbox/trunk/2to3/fixes/fix_xrange.py Tue Feb 13 00:59:44 2007 @@ -2,11 +2,9 @@ """Fixer that changes xrange(...) into range(...).""" -# Python imports -import token - # Local imports import pytree +from pgen2 import token from fixes import basefix from fixes import macros Modified: sandbox/trunk/2to3/fixes/macros.py ============================================================================== --- sandbox/trunk/2to3/fixes/macros.py (original) +++ sandbox/trunk/2to3/fixes/macros.py Tue Feb 13 00:59:44 2007 @@ -1,10 +1,8 @@ """Abstract away often-used node construction routines.""" # Author: Collin Winter -# Python imports -import token - # Local imports +from pgen2 import token from pytree import Leaf, Node from pygram import python_symbols as syms Modified: sandbox/trunk/2to3/patcomp.py ============================================================================== --- sandbox/trunk/2to3/patcomp.py (original) +++ sandbox/trunk/2to3/patcomp.py Tue Feb 13 00:59:44 2007 @@ -12,12 +12,12 @@ # Python imports import os -import token -import tokenize # Fairly local imports from pgen2 import driver from pgen2 import literals +from pgen2 import token +from pgen2 import tokenize # Really local imports import pytree Modified: sandbox/trunk/2to3/pgen2/conv.py ============================================================================== --- sandbox/trunk/2to3/pgen2/conv.py (original) +++ sandbox/trunk/2to3/pgen2/conv.py Tue Feb 13 00:59:44 2007 @@ -28,9 +28,10 @@ # Python imports import re -import token -from pgen2 import grammar +# Local imports +from pgen2 import grammar, token + class Converter(grammar.Grammar): """Grammar subclass that reads classic pgen output files. Modified: sandbox/trunk/2to3/pgen2/driver.py ============================================================================== --- sandbox/trunk/2to3/pgen2/driver.py (original) +++ sandbox/trunk/2to3/pgen2/driver.py Tue Feb 13 00:59:44 2007 @@ -17,13 +17,10 @@ # Python imports import os -import token import logging -import tokenize # Pgen imports -from pgen2 import parse -from pgen2 import grammar +from pgen2 import grammar, parse, token, tokenize class Driver(object): Modified: sandbox/trunk/2to3/pgen2/grammar.py ============================================================================== --- sandbox/trunk/2to3/pgen2/grammar.py (original) +++ sandbox/trunk/2to3/pgen2/grammar.py Tue Feb 13 00:59:44 2007 @@ -13,9 +13,12 @@ """ # Python imports -import token, tokenize import cPickle as pickle +# Local imports +from pgen2 import token, tokenize + + class Grammar(object): """Pgen parsing tables tables conversion class. Modified: sandbox/trunk/2to3/pgen2/parse.py ============================================================================== --- sandbox/trunk/2to3/pgen2/parse.py (original) +++ sandbox/trunk/2to3/pgen2/parse.py Tue Feb 13 00:59:44 2007 @@ -10,8 +10,8 @@ """ -# Python imports -import token +# Local imports +from pgen2 import token class ParseError(Exception): """Exception to signal the parser is stuck.""" Modified: sandbox/trunk/2to3/pgen2/pgen.py ============================================================================== --- sandbox/trunk/2to3/pgen2/pgen.py (original) +++ sandbox/trunk/2to3/pgen2/pgen.py Tue Feb 13 00:59:44 2007 @@ -1,12 +1,8 @@ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. -# Python imports -import token -import tokenize - # Pgen imports -from pgen2 import grammar +from pgen2 import grammar, token, tokenize class PgenGrammar(grammar.Grammar): pass Added: sandbox/trunk/2to3/pgen2/token.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/pgen2/token.py Tue Feb 13 00:59:44 2007 @@ -0,0 +1,82 @@ +#! /usr/bin/env python + +"""Token constants (from "token.h").""" + +# Taken from Python (r53757) and modified to include some tokens +# originally monkeypatched in by pgen2.tokenize + +#--start constants-- +ENDMARKER = 0 +NAME = 1 +NUMBER = 2 +STRING = 3 +NEWLINE = 4 +INDENT = 5 +DEDENT = 6 +LPAR = 7 +RPAR = 8 +LSQB = 9 +RSQB = 10 +COLON = 11 +COMMA = 12 +SEMI = 13 +PLUS = 14 +MINUS = 15 +STAR = 16 +SLASH = 17 +VBAR = 18 +AMPER = 19 +LESS = 20 +GREATER = 21 +EQUAL = 22 +DOT = 23 +PERCENT = 24 +BACKQUOTE = 25 +LBRACE = 26 +RBRACE = 27 +EQEQUAL = 28 +NOTEQUAL = 29 +LESSEQUAL = 30 +GREATEREQUAL = 31 +TILDE = 32 +CIRCUMFLEX = 33 +LEFTSHIFT = 34 +RIGHTSHIFT = 35 +DOUBLESTAR = 36 +PLUSEQUAL = 37 +MINEQUAL = 38 +STAREQUAL = 39 +SLASHEQUAL = 40 +PERCENTEQUAL = 41 +AMPEREQUAL = 42 +VBAREQUAL = 43 +CIRCUMFLEXEQUAL = 44 +LEFTSHIFTEQUAL = 45 +RIGHTSHIFTEQUAL = 46 +DOUBLESTAREQUAL = 47 +DOUBLESLASH = 48 +DOUBLESLASHEQUAL = 49 +AT = 50 +OP = 51 +COMMENT = 52 +NL = 53 +RARROW = 54 +ERRORTOKEN = 55 +N_TOKENS = 56 +NT_OFFSET = 256 +#--end constants-- + +tok_name = {} +for _name, _value in globals().items(): + if type(_value) is type(0): + tok_name[_value] = _name + + +def ISTERMINAL(x): + return x < NT_OFFSET + +def ISNONTERMINAL(x): + return x >= NT_OFFSET + +def ISEOF(x): + return x == ENDMARKER Copied: sandbox/trunk/2to3/pgen2/tokenize.py (from r53757, sandbox/trunk/2to3/tokenize.py) ============================================================================== --- sandbox/trunk/2to3/tokenize.py (original) +++ sandbox/trunk/2to3/pgen2/tokenize.py Tue Feb 13 00:59:44 2007 @@ -30,23 +30,12 @@ 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro' import string, re -from token import * +from pgen2.token import * -import token -__all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize", - "generate_tokens", "NL", "untokenize"] -del x - -COMMENT = N_TOKENS -tok_name[COMMENT] = 'COMMENT' -NL = N_TOKENS + 1 -tok_name[NL] = 'NL' -RARROW = N_TOKENS + 2 -token.RARROW = RARROW -tok_name[RARROW] = 'RARROW' -N_TOKENS += 3 - -del token +from pgen2 import token +__all__ = [x for x in dir(token) if x[0] != '_'] + ["tokenize", + "generate_tokens", "untokenize"] +del x, token def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' Modified: sandbox/trunk/2to3/pygram.py ============================================================================== --- sandbox/trunk/2to3/pygram.py (original) +++ sandbox/trunk/2to3/pygram.py Tue Feb 13 00:59:44 2007 @@ -5,10 +5,10 @@ # Python imports import os -import token # Local imports import pytree +from pgen2 import token from pgen2 import driver # The grammar file Modified: sandbox/trunk/2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/refactor.py (original) +++ sandbox/trunk/2to3/refactor.py Tue Feb 13 00:59:44 2007 @@ -20,10 +20,10 @@ import logging # Local imports -import tokenize import pytree import patcomp from pgen2 import driver +from pgen2 import tokenize import fixes import fixes.macros import pygram Deleted: /sandbox/trunk/2to3/tokenize.py ============================================================================== --- /sandbox/trunk/2to3/tokenize.py Tue Feb 13 00:59:44 2007 +++ (empty file) @@ -1,399 +0,0 @@ -# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. -# All rights reserved. - -"""Tokenization help for Python programs. - -generate_tokens(readline) is a generator that breaks a stream of -text into Python tokens. It accepts a readline-like method which is called -repeatedly to get the next line of input (or "" for EOF). It generates -5-tuples with these members: - - the token type (see token.py) - the token (a string) - the starting (row, column) indices of the token (a 2-tuple of ints) - the ending (row, column) indices of the token (a 2-tuple of ints) - the original line (string) - -It is designed to match the working of the Python tokenizer exactly, except -that it produces COMMENT tokens for comments and gives type OP for all -operators - -Older entry points - tokenize_loop(readline, tokeneater) - tokenize(readline, tokeneater=printtoken) -are the same, except instead of generating tokens, tokeneater is a callback -function to which the 5 fields described above are passed as 5 arguments, -each time a new token is found.""" - -__author__ = 'Ka-Ping Yee ' -__credits__ = \ - 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro' - -import string, re -from token import * - -import token -__all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize", - "generate_tokens", "NL", "untokenize"] -del x - -COMMENT = N_TOKENS -tok_name[COMMENT] = 'COMMENT' -NL = N_TOKENS + 1 -tok_name[NL] = 'NL' -RARROW = N_TOKENS + 2 -token.RARROW = RARROW -tok_name[RARROW] = 'RARROW' -N_TOKENS += 3 - -del token - -def group(*choices): return '(' + '|'.join(choices) + ')' -def any(*choices): return group(*choices) + '*' -def maybe(*choices): return group(*choices) + '?' - -Whitespace = r'[ \f\t]*' -Comment = r'#[^\r\n]*' -Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment) -Name = r'[a-zA-Z_]\w*' - -Hexnumber = r'0[xX][\da-fA-F]*[lL]?' -Octnumber = r'0[0-7]*[lL]?' -Decnumber = r'[1-9]\d*[lL]?' -Intnumber = group(Hexnumber, Octnumber, Decnumber) -Exponent = r'[eE][-+]?\d+' -Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent) -Expfloat = r'\d+' + Exponent -Floatnumber = group(Pointfloat, Expfloat) -Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]') -Number = group(Imagnumber, Floatnumber, Intnumber) - -# Tail end of ' string. -Single = r"[^'\\]*(?:\\.[^'\\]*)*'" -# Tail end of " string. -Double = r'[^"\\]*(?:\\.[^"\\]*)*"' -# Tail end of ''' string. -Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" -# Tail end of """ string. -Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' -Triple = group("[uU]?[rR]?'''", '[uU]?[rR]?"""') -# Single-line ' or " string. -String = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'", - r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"') - -# Because of leftmost-then-longest match semantics, be sure to put the -# longest operators first (e.g., if = came before ==, == would get -# recognized as two instances of =). -Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", - r"//=?", r"->", - r"[+\-*/%&|^=<>]=?", - r"~") - -Bracket = '[][(){}]' -Special = group(r'\r?\n', r'[:;.,`@]') -Funny = group(Operator, Bracket, Special) - -PlainToken = group(Number, Funny, String, Name) -Token = Ignore + PlainToken - -# First (or only) line of ' or " string. -ContStr = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" + - group("'", r'\\\r?\n'), - r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' + - group('"', r'\\\r?\n')) -PseudoExtras = group(r'\\\r?\n', Comment, Triple) -PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name) - -tokenprog, pseudoprog, single3prog, double3prog = map( - re.compile, (Token, PseudoToken, Single3, Double3)) -endprogs = {"'": re.compile(Single), '"': re.compile(Double), - "'''": single3prog, '"""': double3prog, - "r'''": single3prog, 'r"""': double3prog, - "u'''": single3prog, 'u"""': double3prog, - "ur'''": single3prog, 'ur"""': double3prog, - "R'''": single3prog, 'R"""': double3prog, - "U'''": single3prog, 'U"""': double3prog, - "uR'''": single3prog, 'uR"""': double3prog, - "Ur'''": single3prog, 'Ur"""': double3prog, - "UR'''": single3prog, 'UR"""': double3prog, - 'r': None, 'R': None, 'u': None, 'U': None} - -triple_quoted = {} -for t in ("'''", '"""', - "r'''", 'r"""', "R'''", 'R"""', - "u'''", 'u"""', "U'''", 'U"""', - "ur'''", 'ur"""', "Ur'''", 'Ur"""', - "uR'''", 'uR"""', "UR'''", 'UR"""'): - triple_quoted[t] = t -single_quoted = {} -for t in ("'", '"', - "r'", 'r"', "R'", 'R"', - "u'", 'u"', "U'", 'U"', - "ur'", 'ur"', "Ur'", 'Ur"', - "uR'", 'uR"', "UR'", 'UR"' ): - single_quoted[t] = t - -tabsize = 8 - -class TokenError(Exception): pass - -class StopTokenizing(Exception): pass - -def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing - print "%d,%d-%d,%d:\t%s\t%s" % \ - (srow, scol, erow, ecol, tok_name[type], repr(token)) - -def tokenize(readline, tokeneater=printtoken): - """ - The tokenize() function accepts two parameters: one representing the - input stream, and one providing an output mechanism for tokenize(). - - The first parameter, readline, must be a callable object which provides - the same interface as the readline() method of built-in file objects. - Each call to the function should return one line of input as a string. - - The second parameter, tokeneater, must also be a callable object. It is - called once for each token, with five arguments, corresponding to the - tuples generated by generate_tokens(). - """ - try: - tokenize_loop(readline, tokeneater) - except StopTokenizing: - pass - -# backwards compatible interface -def tokenize_loop(readline, tokeneater): - for token_info in generate_tokens(readline): - tokeneater(*token_info) - -class Untokenizer: - - def __init__(self): - self.tokens = [] - self.prev_row = 1 - self.prev_col = 0 - - def add_whitespace(self, start): - row, col = start - assert row <= self.prev_row - col_offset = col - self.prev_col - if col_offset: - self.tokens.append(" " * col_offset) - - def untokenize(self, iterable): - for t in iterable: - if len(t) == 2: - self.compat(t, iterable) - break - tok_type, token, start, end, line = t - self.add_whitespace(start) - self.tokens.append(token) - self.prev_row, self.prev_col = end - if tok_type in (NEWLINE, NL): - self.prev_row += 1 - self.prev_col = 0 - return "".join(self.tokens) - - def compat(self, token, iterable): - startline = False - indents = [] - toks_append = self.tokens.append - toknum, tokval = token - if toknum in (NAME, NUMBER): - tokval += ' ' - if toknum in (NEWLINE, NL): - startline = True - for tok in iterable: - toknum, tokval = tok[:2] - - if toknum in (NAME, NUMBER): - tokval += ' ' - - if toknum == INDENT: - indents.append(tokval) - continue - elif toknum == DEDENT: - indents.pop() - continue - elif toknum in (NEWLINE, NL): - startline = True - elif startline and indents: - toks_append(indents[-1]) - startline = False - toks_append(tokval) - -def untokenize(iterable): - """Transform tokens back into Python source code. - - Each element returned by the iterable must be a token sequence - with at least two elements, a token number and token value. If - only two tokens are passed, the resulting output is poor. - - Round-trip invariant for full input: - Untokenized source will match input source exactly - - Round-trip invariant for limited intput: - # Output text will tokenize the back to the input - t1 = [tok[:2] for tok in generate_tokens(f.readline)] - newcode = untokenize(t1) - readline = iter(newcode.splitlines(1)).next - t2 = [tok[:2] for tokin generate_tokens(readline)] - assert t1 == t2 - """ - ut = Untokenizer() - return ut.untokenize(iterable) - -def generate_tokens(readline): - """ - The generate_tokens() generator requires one argment, readline, which - must be a callable object which provides the same interface as the - readline() method of built-in file objects. Each call to the function - should return one line of input as a string. Alternately, readline - can be a callable function terminating with StopIteration: - readline = open(myfile).next # Example of alternate readline - - The generator produces 5-tuples with these members: the token type; the - token string; a 2-tuple (srow, scol) of ints specifying the row and - column where the token begins in the source; a 2-tuple (erow, ecol) of - ints specifying the row and column where the token ends in the source; - and the line on which the token was found. The line passed is the - logical line; continuation lines are included. - """ - lnum = parenlev = continued = 0 - namechars, numchars = string.ascii_letters + '_', '0123456789' - contstr, needcont = '', 0 - contline = None - indents = [0] - - while 1: # loop over lines in stream - try: - line = readline() - except StopIteration: - line = '' - lnum = lnum + 1 - pos, max = 0, len(line) - - if contstr: # continued string - if not line: - raise TokenError, ("EOF in multi-line string", strstart) - endmatch = endprog.match(line) - if endmatch: - pos = end = endmatch.end(0) - yield (STRING, contstr + line[:end], - strstart, (lnum, end), contline + line) - contstr, needcont = '', 0 - contline = None - elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': - yield (ERRORTOKEN, contstr + line, - strstart, (lnum, len(line)), contline) - contstr = '' - contline = None - continue - else: - contstr = contstr + line - contline = contline + line - continue - - elif parenlev == 0 and not continued: # new statement - if not line: break - column = 0 - while pos < max: # measure leading whitespace - if line[pos] == ' ': column = column + 1 - elif line[pos] == '\t': column = (column/tabsize + 1)*tabsize - elif line[pos] == '\f': column = 0 - else: break - pos = pos + 1 - if pos == max: break - - if line[pos] in '#\r\n': # skip comments or blank lines - if line[pos] == '#': - comment_token = line[pos:].rstrip('\r\n') - nl_pos = pos + len(comment_token) - yield (COMMENT, comment_token, - (lnum, pos), (lnum, pos + len(comment_token)), line) - yield (NL, line[nl_pos:], - (lnum, nl_pos), (lnum, len(line)), line) - else: - yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], - (lnum, pos), (lnum, len(line)), line) - continue - - if column > indents[-1]: # count indents or dedents - indents.append(column) - yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line) - while column < indents[-1]: - if column not in indents: - raise IndentationError( - "unindent does not match any outer indentation level", - ("", lnum, pos, line)) - indents = indents[:-1] - yield (DEDENT, '', (lnum, pos), (lnum, pos), line) - - else: # continued statement - if not line: - raise TokenError, ("EOF in multi-line statement", (lnum, 0)) - continued = 0 - - while pos < max: - pseudomatch = pseudoprog.match(line, pos) - if pseudomatch: # scan for tokens - start, end = pseudomatch.span(1) - spos, epos, pos = (lnum, start), (lnum, end), end - token, initial = line[start:end], line[start] - - if initial in numchars or \ - (initial == '.' and token != '.'): # ordinary number - yield (NUMBER, token, spos, epos, line) - elif initial in '\r\n': - yield (NL if parenlev > 0 else NEWLINE, - token, spos, epos, line) - elif initial == '#': - assert not token.endswith("\n") - yield (COMMENT, token, spos, epos, line) - elif token in triple_quoted: - endprog = endprogs[token] - endmatch = endprog.match(line, pos) - if endmatch: # all on one line - pos = endmatch.end(0) - token = line[start:pos] - yield (STRING, token, spos, (lnum, pos), line) - else: - strstart = (lnum, start) # multiple lines - contstr = line[start:] - contline = line - break - elif initial in single_quoted or \ - token[:2] in single_quoted or \ - token[:3] in single_quoted: - if token[-1] == '\n': # continued string - strstart = (lnum, start) - endprog = (endprogs[initial] or endprogs[token[1]] or - endprogs[token[2]]) - contstr, needcont = line[start:], 1 - contline = line - break - else: # ordinary string - yield (STRING, token, spos, epos, line) - elif initial in namechars: # ordinary name - yield (NAME, token, spos, epos, line) - elif initial == '\\': # continued stmt - # This yield is new; needed for better idempotency: - yield (NL, token, spos, (lnum, pos), line) - continued = 1 - else: - if initial in '([{': parenlev = parenlev + 1 - elif initial in ')]}': parenlev = parenlev - 1 - yield (OP, token, spos, epos, line) - else: - yield (ERRORTOKEN, line[pos], - (lnum, pos), (lnum, pos+1), line) - pos = pos + 1 - - for indent in indents[1:]: # pop remaining indent levels - yield (DEDENT, '', (lnum, 0), (lnum, 0), '') - yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '') - -if __name__ == '__main__': # testing - import sys - if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline) - else: tokenize(sys.stdin.readline) From python-checkins at python.org Tue Feb 13 07:25:50 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 13 Feb 2007 07:25:50 +0100 (CET) Subject: [Python-checkins] r53760 - python/branches/bcannon-sandboxing/BRANCH_NOTES Message-ID: <20070213062550.EFF521E4009@bag.python.org> Author: brett.cannon Date: Tue Feb 13 07:25:50 2007 New Revision: 53760 Added: python/branches/bcannon-sandboxing/BRANCH_NOTES (contents, props changed) Log: Add a file documenting some things about this branch. Added: python/branches/bcannon-sandboxing/BRANCH_NOTES ============================================================================== --- (empty file) +++ python/branches/bcannon-sandboxing/BRANCH_NOTES Tue Feb 13 07:25:50 2007 @@ -0,0 +1,24 @@ +======= +Purpose +======= +This branch is to try to track how memory is used throughout the interpreter. +The goal was to be able to ask questions like, "how many bytes are being used +by integers?" and the like. + +The hope was that people would be able to tell where all of their memory usage +was going. This could also help with finding reference leaks if a certain type +of object was taking up more memory than it was supposed to. + +====== +Status +====== +Tracking "leaks" a few bytes after every pressing of Enter at an interpreter +prompt. + +This branch was meant as a proof-of-concept of the idea. It was to work out +how one could track pymalloc and malloc usage. + +========== +References +========== +* PEP.txt in this branch. From python-checkins at python.org Tue Feb 13 07:29:09 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 13 Feb 2007 07:29:09 +0100 (CET) Subject: [Python-checkins] r53761 - python/branches/bcannon-objcap/BRANCH_NOTES Message-ID: <20070213062909.9645C1E4009@bag.python.org> Author: brett.cannon Date: Tue Feb 13 07:29:09 2007 New Revision: 53761 Added: python/branches/bcannon-objcap/BRANCH_NOTES (contents, props changed) Log: Doc to contain basic info about this branch. Added: python/branches/bcannon-objcap/BRANCH_NOTES ============================================================================== --- (empty file) +++ python/branches/bcannon-objcap/BRANCH_NOTES Tue Feb 13 07:29:09 2007 @@ -0,0 +1,17 @@ +======= +Purpose +======= +Attempt to develop some form of security model for Python. + +====== +Status +====== +Working on an interpreter-wide security model for Python. This is not a +replacement for rexec but should allow someone who embeds Python to be able to +execute Python code safely. + +========== +References +========== +* securing_python.txt +* http://docs.google.com/Doc?id=dg7fctr4_4d8tdbq From python-checkins at python.org Tue Feb 13 07:41:31 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 13 Feb 2007 07:41:31 +0100 (CET) Subject: [Python-checkins] r53762 - python/branches/pep302_phase2/BRANCH_NOTES Message-ID: <20070213064131.B7C941E4009@bag.python.org> Author: brett.cannon Date: Tue Feb 13 07:41:27 2007 New Revision: 53762 Added: python/branches/pep302_phase2/BRANCH_NOTES (contents, props changed) Log: Doc describing what this branch is for. Added: python/branches/pep302_phase2/BRANCH_NOTES ============================================================================== --- (empty file) +++ python/branches/pep302_phase2/BRANCH_NOTES Tue Feb 13 07:41:27 2007 @@ -0,0 +1,15 @@ +======= +Purpose +======= +Replace the C implementation of import with Python implementation. + +====== +Status +====== +Rewrite of import in Pure Python contained is in Python's sandbox under +import_in_py. + + +========== +References +========== From python-checkins at python.org Tue Feb 13 09:34:46 2007 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 13 Feb 2007 09:34:46 +0100 (CET) Subject: [Python-checkins] r53763 - in python/trunk: Lib/imputil.py Misc/NEWS Message-ID: <20070213083446.AA8FB1E400D@bag.python.org> Author: martin.v.loewis Date: Tue Feb 13 09:34:45 2007 New Revision: 53763 Modified: python/trunk/Lib/imputil.py python/trunk/Misc/NEWS Log: Patch #685268: Consider a package's __path__ in imputil. Will backport. Modified: python/trunk/Lib/imputil.py ============================================================================== --- python/trunk/Lib/imputil.py (original) +++ python/trunk/Lib/imputil.py Tue Feb 13 09:34:45 2007 @@ -552,6 +552,10 @@ # This method is only used when we look for a module within a package. assert parent + for submodule_path in parent.__path__: + code = self._import_pathname(_os_path_join(submodule_path, modname), fqname) + if code is not None: + return code return self._import_pathname(_os_path_join(parent.__pkgdir__, modname), fqname) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue Feb 13 09:34:45 2007 @@ -128,6 +128,8 @@ Library ------- +- Patch #685268: Consider a package's __path__ in imputil. + - Patch 1463026: Support default namespace in XMLGenerator. - Patch 1571379: Make trace's --ignore-dir facility work in the face of From python-checkins at python.org Tue Feb 13 09:35:02 2007 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 13 Feb 2007 09:35:02 +0100 (CET) Subject: [Python-checkins] r53764 - in python/branches/release25-maint: Lib/imputil.py Misc/NEWS Message-ID: <20070213083502.5BCC01E400D@bag.python.org> Author: martin.v.loewis Date: Tue Feb 13 09:35:01 2007 New Revision: 53764 Modified: python/branches/release25-maint/Lib/imputil.py python/branches/release25-maint/Misc/NEWS Log: Patch #685268: Consider a package's __path__ in imputil. Modified: python/branches/release25-maint/Lib/imputil.py ============================================================================== --- python/branches/release25-maint/Lib/imputil.py (original) +++ python/branches/release25-maint/Lib/imputil.py Tue Feb 13 09:35:01 2007 @@ -552,6 +552,10 @@ # This method is only used when we look for a module within a package. assert parent + for submodule_path in parent.__path__: + code = self._import_pathname(_os_path_join(submodule_path, modname), fqname) + if code is not None: + return code return self._import_pathname(_os_path_join(parent.__pkgdir__, modname), fqname) Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Tue Feb 13 09:35:01 2007 @@ -169,6 +169,8 @@ Library ------- +- Patch #685268: Consider a package's __path__ in imputil. + - Patch 1463026: Support default namespace in XMLGenerator. - Patch 1571379: Make trace's --ignore-dir facility work in the face of From python-checkins at python.org Tue Feb 13 10:49:40 2007 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 13 Feb 2007 10:49:40 +0100 (CET) Subject: [Python-checkins] r53765 - in python/trunk: Doc/lib/libzipfile.tex Lib/test/test_zipfile.py Lib/zipfile.py Misc/NEWS Message-ID: <20070213094940.540B31E400D@bag.python.org> Author: martin.v.loewis Date: Tue Feb 13 10:49:38 2007 New Revision: 53765 Modified: python/trunk/Doc/lib/libzipfile.tex python/trunk/Lib/test/test_zipfile.py python/trunk/Lib/zipfile.py python/trunk/Misc/NEWS Log: Patch #698833: Support file decryption in zipfile. Modified: python/trunk/Doc/lib/libzipfile.tex ============================================================================== --- python/trunk/Doc/lib/libzipfile.tex (original) +++ python/trunk/Doc/lib/libzipfile.tex Tue Feb 13 10:49:38 2007 @@ -17,8 +17,10 @@ {PKZIP Application Note}. This module does not currently handle ZIP files which have appended -comments, or multi-disk ZIP files. It can handle ZIP files that use the -ZIP64 extensions (that is ZIP files that are more than 4 GByte in size). +comments, or multi-disk ZIP files. It can handle ZIP files that use +the ZIP64 extensions (that is ZIP files that are more than 4 GByte in +size). It supports decryption of encrypted files in ZIP archives, but +it cannot currently create an encrypted file. The available attributes of this module are: @@ -138,9 +140,18 @@ Print a table of contents for the archive to \code{sys.stdout}. \end{methoddesc} -\begin{methoddesc}{read}{name} +\begin{methoddesc}{setpassword}{pwd} + Set \var{pwd} as default password to extract encrypted files. + \versionadded{2.6} +\end{methoddesc} + +\begin{methoddesc}{read}{name\optional{, pwd}} Return the bytes of the file in the archive. The archive must be - open for read or append. + open for read or append. \var{pwd} is the password used for encrypted + files and, if specified, it will override the default password set with + \method{setpassword()}. + + \versionchanged[\var{pwd} was added]{2.6} \end{methoddesc} \begin{methoddesc}{testzip}{} Modified: python/trunk/Lib/test/test_zipfile.py ============================================================================== --- python/trunk/Lib/test/test_zipfile.py (original) +++ python/trunk/Lib/test/test_zipfile.py Tue Feb 13 10:49:38 2007 @@ -349,8 +349,49 @@ # and report that the first file in the archive was corrupt. self.assertRaises(RuntimeError, zipf.testzip) + +class DecryptionTests(unittest.TestCase): + # This test checks that ZIP decryption works. Since the library does not + # support encryption at the moment, we use a pre-generated encrypted + # ZIP file + + data = ( + 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00' + '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y' + '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl' + 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00' + '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81' + '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00' + '\x00\x00L\x00\x00\x00\x00\x00' ) + + plain = 'zipfile.py encryption test' + + def setUp(self): + fp = open(TESTFN, "wb") + fp.write(self.data) + fp.close() + self.zip = zipfile.ZipFile(TESTFN, "r") + + def tearDown(self): + self.zip.close() + os.unlink(TESTFN) + + def testNoPassword(self): + # Reading the encrypted file without password + # must generate a RunTime exception + self.assertRaises(RuntimeError, self.zip.read, "test.txt") + + def testBadPassword(self): + self.zip.setpassword("perl") + self.assertRaises(RuntimeError, self.zip.read, "test.txt") + + def testGoodPassword(self): + self.zip.setpassword("python") + self.assertEquals(self.zip.read("test.txt"), self.plain) + def test_main(): - run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, PyZipFileTests) + run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, + PyZipFileTests, DecryptionTests) #run_unittest(TestZip64InSmallFiles) if __name__ == "__main__": Modified: python/trunk/Lib/zipfile.py ============================================================================== --- python/trunk/Lib/zipfile.py (original) +++ python/trunk/Lib/zipfile.py Tue Feb 13 10:49:38 2007 @@ -296,6 +296,65 @@ extra = extra[ln+4:] +class _ZipDecrypter: + """Class to handle decryption of files stored within a ZIP archive. + + ZIP supports a password-based form of encryption. Even though known + plaintext attacks have been found against it, it is still useful + for low-level securicy. + + Usage: + zd = _ZipDecrypter(mypwd) + plain_char = zd(cypher_char) + plain_text = map(zd, cypher_text) + """ + + def _GenerateCRCTable(): + """Generate a CRC-32 table. + + ZIP encryption uses the CRC32 one-byte primitive for scrambling some + internal keys. We noticed that a direct implementation is faster than + relying on binascii.crc32(). + """ + poly = 0xedb88320 + table = [0] * 256 + for i in range(256): + crc = i + for j in range(8): + if crc & 1: + crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly + else: + crc = ((crc >> 1) & 0x7FFFFFFF) + table[i] = crc + return table + crctable = _GenerateCRCTable() + + def _crc32(self, ch, crc): + """Compute the CRC32 primitive on one byte.""" + return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] + + def __init__(self, pwd): + self.key0 = 305419896 + self.key1 = 591751049 + self.key2 = 878082192 + for p in pwd: + self._UpdateKeys(p) + + def _UpdateKeys(self, c): + self.key0 = self._crc32(c, self.key0) + self.key1 = (self.key1 + (self.key0 & 255)) & 4294967295 + self.key1 = (self.key1 * 134775813 + 1) & 4294967295 + self.key2 = self._crc32(chr((self.key1 >> 24) & 255), self.key2) + + def __call__(self, c): + """Decrypt a single character.""" + c = ord(c) + k = self.key2 | 2 + c = c ^ (((k * (k^1)) >> 8) & 255) + c = chr(c) + self._UpdateKeys(c) + return c + class ZipFile: """ Class with methods to open, read, write, close, list zip files. @@ -330,6 +389,7 @@ self.filelist = [] # List of ZipInfo instances for archive self.compression = compression # Method of compression self.mode = key = mode.replace('b', '')[0] + self.pwd = None # Check if we were passed a file-like object if isinstance(file, basestring): @@ -461,7 +521,11 @@ """Return the instance of ZipInfo given 'name'.""" return self.NameToInfo[name] - def read(self, name): + def setpassword(self, pwd): + """Set default password for encrypted files.""" + self.pwd = pwd + + def read(self, name, pwd=None): """Return file bytes (as a string) for name.""" if self.mode not in ("r", "a"): raise RuntimeError, 'read() requires mode "r" or "a"' @@ -469,6 +533,13 @@ raise RuntimeError, \ "Attempt to read ZIP archive that was already closed" zinfo = self.getinfo(name) + is_encrypted = zinfo.flag_bits & 0x1 + if is_encrypted: + if not pwd: + pwd = self.pwd + if not pwd: + raise RuntimeError, "File %s is encrypted, " \ + "password required for extraction" % name filepos = self.fp.tell() self.fp.seek(zinfo.header_offset, 0) @@ -489,6 +560,18 @@ zinfo.orig_filename, fname) bytes = self.fp.read(zinfo.compress_size) + # Go with decryption + if is_encrypted: + zd = _ZipDecrypter(pwd) + # The first 12 bytes in the cypher stream is an encryption header + # used to strengthen the algorithm. The first 11 bytes are + # completely random, while the 12th contains the MSB of the CRC, + # and is used to check the correctness of the password. + h = map(zd, bytes[0:12]) + if ord(h[11]) != ((zinfo.CRC>>24)&255): + raise RuntimeError, "Bad password for file %s" % name + bytes = "".join(map(zd, bytes[12:])) + # Go with decompression self.fp.seek(filepos, 0) if zinfo.compress_type == ZIP_STORED: pass Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue Feb 13 10:49:38 2007 @@ -128,6 +128,8 @@ Library ------- +- Patch #698833: Support file decryption in zipfile. + - Patch #685268: Consider a package's __path__ in imputil. - Patch 1463026: Support default namespace in XMLGenerator. From python-checkins at python.org Tue Feb 13 11:10:40 2007 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 13 Feb 2007 11:10:40 +0100 (CET) Subject: [Python-checkins] r53766 - in python/trunk: Doc/lib/libzipfile.tex Lib/test/test_zipfile.py Lib/zipfile.py Misc/NEWS Message-ID: <20070213101040.E77081E4021@bag.python.org> Author: martin.v.loewis Date: Tue Feb 13 11:10:39 2007 New Revision: 53766 Modified: python/trunk/Doc/lib/libzipfile.tex python/trunk/Lib/test/test_zipfile.py python/trunk/Lib/zipfile.py python/trunk/Misc/NEWS Log: Patch #1517891: Make 'a' create the file if it doesn't exist. Fixes #1514451. Modified: python/trunk/Doc/lib/libzipfile.tex ============================================================================== --- python/trunk/Doc/lib/libzipfile.tex (original) +++ python/trunk/Doc/lib/libzipfile.tex Tue Feb 13 11:10:39 2007 @@ -101,6 +101,8 @@ \end{verbatim} also works, and at least \program{WinZip} can read such files. + If \var{mode} is \code{a} and the file does not exist at all, + it is created. \var{compression} is the ZIP compression method to use when writing the archive, and should be \constant{ZIP_STORED} or \constant{ZIP_DEFLATED}; unrecognized values will cause @@ -114,6 +116,9 @@ ZIP file would require ZIP64 extensions. ZIP64 extensions are disabled by default because the default \program{zip} and \program{unzip} commands on \UNIX{} (the InfoZIP utilities) don't support these extensions. + + \versionchanged[If the file does not exist, it is created if the + mode is 'a']{2.6} \end{classdesc} \begin{methoddesc}{close}{} Modified: python/trunk/Lib/test/test_zipfile.py ============================================================================== --- python/trunk/Lib/test/test_zipfile.py (original) +++ python/trunk/Lib/test/test_zipfile.py Tue Feb 13 11:10:39 2007 @@ -307,6 +307,28 @@ class OtherTests(unittest.TestCase): + def testCreateNonExistentFileForAppend(self): + if os.path.exists(TESTFN): + os.unlink(TESTFN) + + filename = 'testfile.txt' + content = 'hello, world. this is some content.' + + try: + zf = zipfile.ZipFile(TESTFN, 'a') + zf.writestr(filename, content) + zf.close() + except IOError, (errno, errmsg): + self.fail('Could not append data to a non-existent zip file.') + + self.assert_(os.path.exists(TESTFN)) + + zf = zipfile.ZipFile(TESTFN, 'r') + self.assertEqual(zf.read(filename), content) + zf.close() + + os.unlink(TESTFN) + def testCloseErroneousFile(self): # This test checks that the ZipFile constructor closes the file object # it opens if there's an error in the file. If it doesn't, the traceback Modified: python/trunk/Lib/zipfile.py ============================================================================== --- python/trunk/Lib/zipfile.py (original) +++ python/trunk/Lib/zipfile.py Tue Feb 13 11:10:39 2007 @@ -396,7 +396,14 @@ self._filePassed = 0 self.filename = file modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'} - self.fp = open(file, modeDict[mode]) + try: + self.fp = open(file, modeDict[mode]) + except IOError: + if mode == 'a': + mode = key = 'w' + self.fp = open(file, modeDict[mode]) + else: + raise else: self._filePassed = 1 self.fp = file Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue Feb 13 11:10:39 2007 @@ -128,6 +128,9 @@ Library ------- +- Patch #1517891: Mode 'a' for ZipFile now creates the file if it + doesn't exist. + - Patch #698833: Support file decryption in zipfile. - Patch #685268: Consider a package's __path__ in imputil. From buildbot at python.org Tue Feb 13 11:33:03 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 10:33:03 +0000 Subject: [Python-checkins] buildbot warnings in S-390 Debian 2.5 Message-ID: <20070213103303.858F91E400F@bag.python.org> The Buildbot has detected a new failure of S-390 Debian 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/S-390%2520Debian%25202.5/builds/179 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pybot/buildarea/2.5.klose-debian-s390/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (5.00805) is more than 2 seconds more than expected (0.001) make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Tue Feb 13 11:36:04 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 10:36:04 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian trunk Message-ID: <20070213103604.876061E400E@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%2520trunk/builds/67 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Tue Feb 13 12:32:24 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 11:32:24 +0000 Subject: [Python-checkins] buildbot warnings in S-390 Debian trunk Message-ID: <20070213113224.DA8971E400F@bag.python.org> The Buildbot has detected a new failure of S-390 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/S-390%2520Debian%2520trunk/builds/668 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-debian-s390/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (5.00804) is more than 2 seconds more than expected (0.001) make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Tue Feb 13 13:08:24 2007 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 13 Feb 2007 13:08:24 +0100 (CET) Subject: [Python-checkins] r53767 - python/trunk/Doc/lib/liblocale.tex Message-ID: <20070213120824.A11181E400F@bag.python.org> Author: martin.v.loewis Date: Tue Feb 13 13:08:24 2007 New Revision: 53767 Modified: python/trunk/Doc/lib/liblocale.tex Log: Bug #1658794: Remove extraneous 'this'. Will backport to 2.5. Modified: python/trunk/Doc/lib/liblocale.tex ============================================================================== --- python/trunk/Doc/lib/liblocale.tex (original) +++ python/trunk/Doc/lib/liblocale.tex Tue Feb 13 13:08:24 2007 @@ -481,7 +481,7 @@ locale settings. When a call to the \function{setlocale()} function changes the \constant{LC_CTYPE} settings, the variables \code{string.lowercase}, \code{string.uppercase} and -\code{string.letters} are recalculated. Note that this code that uses +\code{string.letters} are recalculated. Note that code that uses these variable through `\keyword{from} ... \keyword{import} ...', e.g.\ \code{from string import letters}, is not affected by subsequent \function{setlocale()} calls. From python-checkins at python.org Tue Feb 13 13:08:35 2007 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 13 Feb 2007 13:08:35 +0100 (CET) Subject: [Python-checkins] r53768 - python/branches/release25-maint/Doc/lib/liblocale.tex Message-ID: <20070213120835.17CFD1E400F@bag.python.org> Author: martin.v.loewis Date: Tue Feb 13 13:08:34 2007 New Revision: 53768 Modified: python/branches/release25-maint/Doc/lib/liblocale.tex Log: Bug #1658794: Remove extraneous 'this'. Modified: python/branches/release25-maint/Doc/lib/liblocale.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/liblocale.tex (original) +++ python/branches/release25-maint/Doc/lib/liblocale.tex Tue Feb 13 13:08:34 2007 @@ -481,7 +481,7 @@ locale settings. When a call to the \function{setlocale()} function changes the \constant{LC_CTYPE} settings, the variables \code{string.lowercase}, \code{string.uppercase} and -\code{string.letters} are recalculated. Note that this code that uses +\code{string.letters} are recalculated. Note that code that uses these variable through `\keyword{from} ... \keyword{import} ...', e.g.\ \code{from string import letters}, is not affected by subsequent \function{setlocale()} calls. From python-checkins at python.org Tue Feb 13 13:14:20 2007 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 13 Feb 2007 13:14:20 +0100 (CET) Subject: [Python-checkins] r53769 - in python/trunk: Misc/NEWS Modules/socketmodule.c Message-ID: <20070213121420.A50C91E400F@bag.python.org> Author: martin.v.loewis Date: Tue Feb 13 13:14:19 2007 New Revision: 53769 Modified: python/trunk/Misc/NEWS python/trunk/Modules/socketmodule.c Log: Patch #1657276: Make NETLINK_DNRTMSG conditional. Will backport. Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue Feb 13 13:14:19 2007 @@ -364,6 +364,8 @@ Extension Modules ----------------- +- Patch #1657276: Make NETLINK_DNRTMSG conditional. + - Bug #1653736: Complain about keyword arguments to time.isoformat. - Bug #1486663: don't reject keyword arguments for subclasses of builtin Modified: python/trunk/Modules/socketmodule.c ============================================================================== --- python/trunk/Modules/socketmodule.c (original) +++ python/trunk/Modules/socketmodule.c Tue Feb 13 13:14:19 2007 @@ -4383,7 +4383,9 @@ PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); #endif PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); +#ifdef NETLINK_DNRTMSG PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); +#endif #ifdef NETLINK_TAPBASE PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); #endif From python-checkins at python.org Tue Feb 13 13:14:30 2007 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 13 Feb 2007 13:14:30 +0100 (CET) Subject: [Python-checkins] r53770 - in python/branches/release25-maint: Misc/NEWS Modules/socketmodule.c Message-ID: <20070213121430.09D801E400F@bag.python.org> Author: martin.v.loewis Date: Tue Feb 13 13:14:29 2007 New Revision: 53770 Modified: python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Modules/socketmodule.c Log: Patch #1657276: Make NETLINK_DNRTMSG conditional. Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Tue Feb 13 13:14:29 2007 @@ -107,6 +107,8 @@ Extension Modules ----------------- +- Patch #1657276: Make NETLINK_DNRTMSG conditional. + - Bug #1653736: Complain about keyword arguments to time.isoformat. - operator.count() now raises an OverflowError when the count reaches sys.maxint. Modified: python/branches/release25-maint/Modules/socketmodule.c ============================================================================== --- python/branches/release25-maint/Modules/socketmodule.c (original) +++ python/branches/release25-maint/Modules/socketmodule.c Tue Feb 13 13:14:29 2007 @@ -4363,7 +4363,9 @@ PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); #endif PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); +#ifdef NETLINK_DNRTMSG PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); +#endif #ifdef NETLINK_TAPBASE PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); #endif From buildbot at python.org Tue Feb 13 15:53:04 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 14:53:04 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 trunk Message-ID: <20070213145304.3B96A1E400F@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%2520trunk/builds/1405 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket sincerely, -The Buildbot From buildbot at python.org Tue Feb 13 16:39:34 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 15:39:34 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) trunk Message-ID: <20070213153934.541721E400F@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%2520trunk/builds/1185 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout ====================================================================== FAIL: testConnectTimeout (test.test_timeout.TimeoutTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/test/test_timeout.py", line 128, in testConnectTimeout %(_delta, self.fuzz, _timeout)) AssertionError: timeout (3.38121) is more than 2 seconds more than expected (0.001) sincerely, -The Buildbot From python-checkins at python.org Tue Feb 13 17:09:25 2007 From: python-checkins at python.org (lars.gustaebel) Date: Tue, 13 Feb 2007 17:09:25 +0100 (CET) Subject: [Python-checkins] r53771 - in python/trunk: Lib/gzip.py Lib/test/test_gzip.py Misc/NEWS Message-ID: <20070213160925.86A031E400F@bag.python.org> Author: lars.gustaebel Date: Tue Feb 13 17:09:24 2007 New Revision: 53771 Modified: python/trunk/Lib/gzip.py python/trunk/Lib/test/test_gzip.py python/trunk/Misc/NEWS Log: Patch #1647484: Renamed GzipFile's filename attribute to name. The filename attribute is still accessible as a property that emits a DeprecationWarning. Modified: python/trunk/Lib/gzip.py ============================================================================== --- python/trunk/Lib/gzip.py (original) +++ python/trunk/Lib/gzip.py Tue Feb 13 17:09:24 2007 @@ -106,7 +106,7 @@ self._new_member = True self.extrabuf = "" self.extrasize = 0 - self.filename = filename + self.name = filename # Starts small, scales exponentially self.min_readsize = 100 @@ -127,14 +127,20 @@ if self.mode == WRITE: self._write_gzip_header() + @property + def filename(self): + import warnings + warnings.warn("use the name attribute", DeprecationWarning) + if self.mode == WRITE and self.name[-3:] != ".gz": + return self.name + ".gz" + return self.name + def __repr__(self): s = repr(self.fileobj) return '' def _init_write(self, filename): - if filename[-3:] != '.gz': - filename = filename + '.gz' - self.filename = filename + self.name = filename self.crc = zlib.crc32("") self.size = 0 self.writebuf = [] @@ -143,16 +149,15 @@ def _write_gzip_header(self): self.fileobj.write('\037\213') # magic header self.fileobj.write('\010') # compression method - fname = self.filename[:-3] flags = 0 - if fname: + if self.name: flags = FNAME self.fileobj.write(chr(flags)) write32u(self.fileobj, long(time.time())) self.fileobj.write('\002') self.fileobj.write('\377') - if fname: - self.fileobj.write(fname + '\000') + if self.name: + self.fileobj.write(self.name + '\000') def _init_read(self): self.crc = zlib.crc32("") Modified: python/trunk/Lib/test/test_gzip.py ============================================================================== --- python/trunk/Lib/test/test_gzip.py (original) +++ python/trunk/Lib/test/test_gzip.py Tue Feb 13 17:09:24 2007 @@ -153,6 +153,13 @@ self.assertEqual(f.myfileobj.mode, 'rb') f.close() + def test_1647484(self): + for mode in ('wb', 'rb'): + f = gzip.GzipFile(self.filename, mode) + self.assert_(hasattr(f, "name")) + self.assertEqual(f.name, self.filename) + f.close() + def test_main(verbose=None): test_support.run_unittest(TestGzip) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue Feb 13 17:09:24 2007 @@ -128,6 +128,8 @@ Library ------- +- Patch #1647484: Renamed GzipFile's filename attribute to name. + - Patch #1517891: Mode 'a' for ZipFile now creates the file if it doesn't exist. From python-checkins at python.org Tue Feb 13 17:24:00 2007 From: python-checkins at python.org (lars.gustaebel) Date: Tue, 13 Feb 2007 17:24:00 +0100 (CET) Subject: [Python-checkins] r53772 - python/trunk/Lib/gzip.py Message-ID: <20070213162400.ED07C1E400F@bag.python.org> Author: lars.gustaebel Date: Tue Feb 13 17:24:00 2007 New Revision: 53772 Modified: python/trunk/Lib/gzip.py Log: Strip the '.gz' extension from the filename that is written to the gzip header. Modified: python/trunk/Lib/gzip.py ============================================================================== --- python/trunk/Lib/gzip.py (original) +++ python/trunk/Lib/gzip.py Tue Feb 13 17:24:00 2007 @@ -149,15 +149,18 @@ def _write_gzip_header(self): self.fileobj.write('\037\213') # magic header self.fileobj.write('\010') # compression method + fname = self.name + if fname.endswith(".gz"): + fname = fname[:-3] flags = 0 - if self.name: + if fname: flags = FNAME self.fileobj.write(chr(flags)) write32u(self.fileobj, long(time.time())) self.fileobj.write('\002') self.fileobj.write('\377') - if self.name: - self.fileobj.write(self.name + '\000') + if fname: + self.fileobj.write(fname + '\000') def _init_read(self): self.crc = zlib.crc32("") From buildbot at python.org Tue Feb 13 18:18:12 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 17:18:12 +0000 Subject: [Python-checkins] buildbot failure in x86 gentoo 2.5 Message-ID: <20070213171812.74F3A1E4005@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/229 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Layne': Hamza Build Source Stamp: [branch Miles] Anibal Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Tue Feb 13 18:19:42 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 17:19:42 +0000 Subject: [Python-checkins] buildbot failure in amd64 gentoo 2.5 Message-ID: <20070213171942.B8E291E4005@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%25202.5/builds/231 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Terry': Royce Build Source Stamp: [branch Aldo] Arron Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Tue Feb 13 18:30:44 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 17:30:44 +0000 Subject: [Python-checkins] buildbot failure in sparc solaris10 gcc 2.5 Message-ID: <20070213173044.8CE3C1E4005@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%25202.5/builds/222 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Chaim': Jaime Build Source Stamp: [branch Gannon] Rey Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Tue Feb 13 18:33:00 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 17:33:00 +0000 Subject: [Python-checkins] buildbot failure in x86 OpenBSD 2.5 Message-ID: <20070213173300.D05951E4005@bag.python.org> The Buildbot has detected a new failure of x86 OpenBSD 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520OpenBSD%25202.5/builds/208 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Elian': Luc Build Source Stamp: [branch Allen] Dan Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Tue Feb 13 18:37:12 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 17:37:12 +0000 Subject: [Python-checkins] buildbot failure in g4 osx.4 2.5 Message-ID: <20070213173712.804D51E4005@bag.python.org> The Buildbot has detected a new failure of g4 osx.4 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/g4%2520osx.4%25202.5/builds/216 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Elliott': Rolando Build Source Stamp: [branch Destin] Jordy Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Tue Feb 13 23:02:28 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 13 Feb 2007 22:02:28 +0000 Subject: [Python-checkins] buildbot failure in x86 XP 2.5 Message-ID: <20070213220228.7A2951E4007@bag.python.org> The Buildbot has detected a new failure of x86 XP 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%25202.5/builds/115 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Weston': Kelly Build Source Stamp: [branch Neal] Brady Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From python-checkins at python.org Wed Feb 14 11:07:39 2007 From: python-checkins at python.org (martin.v.loewis) Date: Wed, 14 Feb 2007 11:07:39 +0100 (CET) Subject: [Python-checkins] r53774 - in python/trunk: Misc/NEWS Modules/socketmodule.c Modules/socketmodule.h Message-ID: <20070214100739.527271E4015@bag.python.org> Author: martin.v.loewis Date: Wed Feb 14 11:07:37 2007 New Revision: 53774 Modified: python/trunk/Misc/NEWS python/trunk/Modules/socketmodule.c python/trunk/Modules/socketmodule.h Log: Patch #1432399: Add HCI sockets. Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed Feb 14 11:07:37 2007 @@ -366,6 +366,8 @@ Extension Modules ----------------- +- Patch #1432399: Support the HCI protocol for bluetooth sockets + - Patch #1657276: Make NETLINK_DNRTMSG conditional. - Bug #1653736: Complain about keyword arguments to time.isoformat. Modified: python/trunk/Modules/socketmodule.c ============================================================================== --- python/trunk/Modules/socketmodule.c (original) +++ python/trunk/Modules/socketmodule.c Wed Feb 14 11:07:37 2007 @@ -362,20 +362,25 @@ #if defined(__FreeBSD__) #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM +#define BTPROTO_HCI BLUETOOTH_PROTO_HCI #define sockaddr_l2 sockaddr_l2cap #define sockaddr_rc sockaddr_rfcomm #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb) #elif defined(__NetBSD__) #define sockaddr_l2 sockaddr_bt #define sockaddr_rc sockaddr_bt +#define sockaddr_hci sockaddr_bt #define sockaddr_sco sockaddr_bt #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb) #else #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb) #endif #endif @@ -1119,6 +1124,14 @@ return ret; } + case BTPROTO_HCI: + { + struct sockaddr_hci *a = (struct sockaddr_hci *) addr; + PyObject *ret = NULL; + ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); + return ret; + } + #if !defined(__FreeBSD__) case BTPROTO_SCO: { @@ -1347,6 +1360,19 @@ *len_ret = sizeof *addr; return 1; } + case BTPROTO_HCI: + { + struct sockaddr_hci *addr = (struct sockaddr_hci *) _BT_SOCKADDR_MEMB(s, hci); + _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + *addr_ret = (struct sockaddr *) addr; + *len_ret = sizeof *addr; + return 1; + } #if !defined(__FreeBSD__) case BTPROTO_SCO: { @@ -1485,6 +1511,9 @@ case BTPROTO_RFCOMM: *len_ret = sizeof (struct sockaddr_rc); return 1; + case BTPROTO_HCI: + *len_ret = sizeof (struct sockaddr_hci); + return 1; #if !defined(__FreeBSD__) case BTPROTO_SCO: *len_ret = sizeof (struct sockaddr_sco); @@ -4430,6 +4459,11 @@ #ifdef USE_BLUETOOTH PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); + PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); + PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); + PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); + PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); + PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); #if !defined(__FreeBSD__) PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); #endif Modified: python/trunk/Modules/socketmodule.h ============================================================================== --- python/trunk/Modules/socketmodule.h (original) +++ python/trunk/Modules/socketmodule.h Wed Feb 14 11:07:37 2007 @@ -46,6 +46,7 @@ #include #include #include +#include #endif #ifdef HAVE_BLUETOOTH_H @@ -98,6 +99,7 @@ struct sockaddr_l2 bt_l2; struct sockaddr_rc bt_rc; struct sockaddr_sco bt_sco; + struct sockaddr_hci bt_hci; #endif #ifdef HAVE_NETPACKET_PACKET_H struct sockaddr_ll ll; From buildbot at python.org Wed Feb 14 11:49:23 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 14 Feb 2007 10:49:23 +0000 Subject: [Python-checkins] buildbot warnings in ppc Debian unstable trunk Message-ID: <20070214104923.9B57D1E4015@bag.python.org> The Buildbot has detected a new failure of ppc Debian unstable trunk. Full details are available at: http://www.python.org/dev/buildbot/all/ppc%2520Debian%2520unstable%2520trunk/builds/73 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 6 tests failed: test___all__ test_cookielib test_mimetools test_pickletools test_pyclbr test_site Traceback (most recent call last): File "./Lib/test/regrtest.py", line 1381, in main() File "./Lib/test/regrtest.py", line 416, in main e = _ExpectedSkips() File "./Lib/test/regrtest.py", line 1318, in __init__ from test import test_socket_ssl File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/test/test_socket_ssl.py", line 5, in import socket File "/home/pybot/buildarea/trunk.klose-debian-ppc/build/Lib/socket.py", line 45, in import _socket ImportError: No module named _socket make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Wed Feb 14 11:51:19 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 14 Feb 2007 10:51:19 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian trunk Message-ID: <20070214105119.51FC61E4015@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%2520trunk/builds/72 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 6 tests failed: test___all__ test_cookielib test_mimetools test_pickletools test_pyclbr test_site Traceback (most recent call last): File "./Lib/test/regrtest.py", line 1381, in main() File "./Lib/test/regrtest.py", line 416, in main e = _ExpectedSkips() File "./Lib/test/regrtest.py", line 1318, in __init__ from test import test_socket_ssl File "/home/pybot/buildarea64/trunk.klose-debian-ppc64/build/Lib/test/test_socket_ssl.py", line 5, in import socket File "/home/pybot/buildarea64/trunk.klose-debian-ppc64/build/Lib/socket.py", line 45, in import _socket ImportError: No module named _socket make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Wed Feb 14 12:02:13 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 14 Feb 2007 11:02:13 +0000 Subject: [Python-checkins] buildbot warnings in S-390 Debian trunk Message-ID: <20070214110213.C6BE71E4015@bag.python.org> The Buildbot has detected a new failure of S-390 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/S-390%2520Debian%2520trunk/builds/673 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 5 tests failed: test___all__ test_cookielib test_mimetools test_pickletools test_pyclbr Traceback (most recent call last): File "./Lib/test/regrtest.py", line 1381, in main() File "./Lib/test/regrtest.py", line 416, in main e = _ExpectedSkips() File "./Lib/test/regrtest.py", line 1318, in __init__ from test import test_socket_ssl File "/home/pybot/buildarea/trunk.klose-debian-s390/build/Lib/test/test_socket_ssl.py", line 5, in import socket File "/home/pybot/buildarea/trunk.klose-debian-s390/build/Lib/socket.py", line 45, in import _socket ImportError: No module named _socket make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Wed Feb 14 12:14:39 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 14 Feb 2007 11:14:39 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) trunk Message-ID: <20070214111439.82D211E4016@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%2520trunk/builds/1188 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: Traceback (most recent call last): File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30995, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') Traceback (most recent call last): File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30995, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') Traceback (most recent call last): File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30995, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') 6 tests failed: test___all__ test_cookielib test_mimetools test_pickletools test_pyclbr test_site Traceback (most recent call last): File "./Lib/test/regrtest.py", line 1381, in main() File "./Lib/test/regrtest.py", line 416, in main e = _ExpectedSkips() File "./Lib/test/regrtest.py", line 1318, in __init__ from test import test_socket_ssl File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/test/test_socket_ssl.py", line 5, in import socket File "/home/buildbot/Buildbot/trunk.baxter-ubuntu/build/Lib/socket.py", line 45, in import _socket ImportError: No module named _socket sincerely, -The Buildbot From python-checkins at python.org Wed Feb 14 12:30:08 2007 From: python-checkins at python.org (martin.v.loewis) Date: Wed, 14 Feb 2007 12:30:08 +0100 (CET) Subject: [Python-checkins] r53775 - python/trunk/Modules/socketmodule.c Message-ID: <20070214113008.44E871E4016@bag.python.org> Author: martin.v.loewis Date: Wed Feb 14 12:30:07 2007 New Revision: 53775 Modified: python/trunk/Modules/socketmodule.c Log: Update 1432399 to removal of _BT_SOCKADDR_MEMB. Modified: python/trunk/Modules/socketmodule.c ============================================================================== --- python/trunk/Modules/socketmodule.c (original) +++ python/trunk/Modules/socketmodule.c Wed Feb 14 12:30:07 2007 @@ -1362,14 +1362,13 @@ } case BTPROTO_HCI: { - struct sockaddr_hci *addr = (struct sockaddr_hci *) _BT_SOCKADDR_MEMB(s, hci); + struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { PyErr_SetString(socket_error, "getsockaddrarg: " "wrong format"); return 0; } - *addr_ret = (struct sockaddr *) addr; *len_ret = sizeof *addr; return 1; } From python-checkins at python.org Wed Feb 14 12:30:56 2007 From: python-checkins at python.org (martin.v.loewis) Date: Wed, 14 Feb 2007 12:30:56 +0100 (CET) Subject: [Python-checkins] r53776 - python/trunk/setup.py Message-ID: <20070214113056.C8C3B1E4016@bag.python.org> Author: martin.v.loewis Date: Wed Feb 14 12:30:56 2007 New Revision: 53776 Modified: python/trunk/setup.py Log: Ignore directory time stamps when considering whether to rerun libffi configure. Modified: python/trunk/setup.py ============================================================================== --- python/trunk/setup.py (original) +++ python/trunk/setup.py Wed Feb 14 12:30:56 2007 @@ -1319,7 +1319,8 @@ from distutils.dep_util import newer_group config_sources = [os.path.join(ffi_srcdir, fname) - for fname in os.listdir(ffi_srcdir)] + for fname in os.listdir(ffi_srcdir) + if os.path.isfile(os.path.join(ffi_srcdir, fname))] if self.force or newer_group(config_sources, ffi_configfile): from distutils.dir_util import mkpath From python-checkins at python.org Wed Feb 14 13:53:42 2007 From: python-checkins at python.org (martin.v.loewis) Date: Wed, 14 Feb 2007 13:53:42 +0100 (CET) Subject: [Python-checkins] r53777 - python/branches/release25-maint/setup.py Message-ID: <20070214125342.AA8161E4016@bag.python.org> Author: martin.v.loewis Date: Wed Feb 14 13:53:41 2007 New Revision: 53777 Modified: python/branches/release25-maint/setup.py Log: Backport 53776: Ignore directory time stamps when considering whether to rerun libffi configure. Modified: python/branches/release25-maint/setup.py ============================================================================== --- python/branches/release25-maint/setup.py (original) +++ python/branches/release25-maint/setup.py Wed Feb 14 13:53:41 2007 @@ -1316,7 +1316,8 @@ from distutils.dep_util import newer_group config_sources = [os.path.join(ffi_srcdir, fname) - for fname in os.listdir(ffi_srcdir)] + for fname in os.listdir(ffi_srcdir) + if os.path.isfile(os.path.join(ffi_srcdir, fname))] if self.force or newer_group(config_sources, ffi_configfile): from distutils.dir_util import mkpath From buildbot at python.org Wed Feb 14 14:08:13 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 14 Feb 2007 13:08:13 +0000 Subject: [Python-checkins] buildbot warnings in MIPS Debian trunk Message-ID: <20070214130813.CC7FB1E4016@bag.python.org> The Buildbot has detected a new failure of MIPS Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/MIPS%2520Debian%2520trunk/builds/618 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 5 tests failed: test___all__ test_cookielib test_mimetools test_pyclbr test_site Traceback (most recent call last): File "./Lib/test/regrtest.py", line 1381, in main() File "./Lib/test/regrtest.py", line 416, in main e = _ExpectedSkips() File "./Lib/test/regrtest.py", line 1318, in __init__ from test import test_socket_ssl File "/home/pybot/buildarea/trunk.klose-debian-mips/build/Lib/test/test_socket_ssl.py", line 5, in import socket File "/home/pybot/buildarea/trunk.klose-debian-mips/build/Lib/socket.py", line 45, in import _socket ImportError: No module named _socket make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Wed Feb 14 15:45:13 2007 From: python-checkins at python.org (lars.gustaebel) Date: Wed, 14 Feb 2007 15:45:13 +0100 (CET) Subject: [Python-checkins] r53778 - python/trunk/Lib/test/test_tarfile.py Message-ID: <20070214144513.A3F621E401F@bag.python.org> Author: lars.gustaebel Date: Wed Feb 14 15:45:12 2007 New Revision: 53778 Modified: python/trunk/Lib/test/test_tarfile.py Log: A missing binary mode in AppendTest caused failures in Windows Buildbot. Modified: python/trunk/Lib/test/test_tarfile.py ============================================================================== --- python/trunk/Lib/test/test_tarfile.py (original) +++ python/trunk/Lib/test/test_tarfile.py Wed Feb 14 15:45:12 2007 @@ -336,7 +336,7 @@ self._test() def test_empty(self): - open(self.tarname, "w").close() + open(self.tarname, "wb").close() self._add_testfile() self._test() @@ -348,7 +348,7 @@ def test_fileobj(self): self._create_testtar() - data = open(self.tarname).read() + data = open(self.tarname, "rb").read() fobj = StringIO.StringIO(data) self._add_testfile(fobj) fobj.seek(0) From thomas at python.org Wed Feb 14 20:13:20 2007 From: thomas at python.org (Thomas Wouters) Date: Wed, 14 Feb 2007 11:13:20 -0800 Subject: [Python-checkins] r53672 - in python/branches/release25-maint: Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c In-Reply-To: <20070208091352.8FC4B1E4005@bag.python.org> References: <20070208091352.8FC4B1E4005@bag.python.org> Message-ID: <9e804ac0702141113x13f68b41g59e5abd5e255ce03@mail.gmail.com> This should not be backported; it introduces a new exception where there previously was just working (albeit potentially bugged) code. (I'm working through some backlog, so apologies if someone caught it already.) On 2/8/07, martin.v.loewis < python-checkins at python.org> wrote: > > Author: martin.v.loewis > Date: Thu Feb 8 10:13:51 2007 > New Revision: 53672 > > Modified: > python/branches/release25-maint/Lib/test/test_datetime.py > python/branches/release25-maint/Misc/NEWS > python/branches/release25-maint/Modules/datetimemodule.c > Log: > Bug #1653736: Complain about keyword arguments to time.isoformat. > > > Modified: python/branches/release25-maint/Lib/test/test_datetime.py > ============================================================================== > > --- python/branches/release25-maint/Lib/test/test_datetime.py (original) > +++ python/branches/release25-maint/Lib/test/test_datetime.py Thu Feb 8 > 10:13:51 2007 > @@ -1740,6 +1740,11 @@ > self.assertEqual (t.isoformat(), "00:00:00.100000") > self.assertEqual(t.isoformat(), str(t)) > > + def test_1653736(self): > + # verify it doesn't accept extra keyword arguments > + t = self.theclass (second=1) > + self.assertRaises(TypeError, t.isoformat, foo=3) > + > def test_strftime(self): > t = self.theclass(1, 2, 3, 4) > self.assertEqual(t.strftime('%H %M %S'), "01 02 03") > > Modified: python/branches/release25-maint/Misc/NEWS > > ============================================================================== > --- python/branches/release25-maint/Misc/NEWS (original) > +++ python/branches/release25-maint/Misc/NEWS Thu Feb 8 10:13:51 2007 > @@ -105,6 +105,8 @@ > Extension Modules > ----------------- > > +- Bug #1653736: Complain about keyword arguments to time.isoformat. > + > - operator.count() now raises an OverflowError when the count reaches > sys.maxint. > > - Bug #1575169: operator.isSequenceType() now returns False for subclasses > of dict. > > Modified: python/branches/release25-maint/Modules/datetimemodule.c > ============================================================================== > > --- python/branches/release25-maint/Modules/datetimemodule.c (original) > +++ python/branches/release25-maint/Modules/datetimemodule.c Thu Feb 8 > 10:13:51 2007 > @@ -3167,7 +3167,7 @@ > } > > static PyObject * > -time_isoformat(PyDateTime_Time *self) > +time_isoformat(PyDateTime_Time *self, PyObject *unused) > { > char buf[100]; > PyObject *result; > @@ -3411,7 +3411,7 @@ > > static PyMethodDef time_methods[] = { > > - {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, > + {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, > PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" > "[+HH:MM].")}, > > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-checkins/attachments/20070214/6e5765d7/attachment-0001.htm From martin at v.loewis.de Wed Feb 14 20:35:50 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 14 Feb 2007 20:35:50 +0100 Subject: [Python-checkins] r53672 - in python/branches/release25-maint: Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c In-Reply-To: <9e804ac0702141113x13f68b41g59e5abd5e255ce03@mail.gmail.com> References: <20070208091352.8FC4B1E4005@bag.python.org> <9e804ac0702141113x13f68b41g59e5abd5e255ce03@mail.gmail.com> Message-ID: <45D36496.50700@v.loewis.de> Thomas Wouters schrieb: > This should not be backported; it introduces a new exception where there > previously was just working (albeit potentially bugged) code. (I'm > working through some backlog, so apologies if someone caught it already.) Ok. It still should be backported, but to not reject the arguments. Instead, the signature of the function should match its MethodDef entry. Regards, Martin From python-checkins at python.org Thu Feb 15 10:51:38 2007 From: python-checkins at python.org (martin.v.loewis) Date: Thu, 15 Feb 2007 10:51:38 +0100 (CET) Subject: [Python-checkins] r53782 - python/trunk/Objects/dictnotes.txt Message-ID: <20070215095138.A42641E401A@bag.python.org> Author: martin.v.loewis Date: Thu Feb 15 10:51:35 2007 New Revision: 53782 Modified: python/trunk/Objects/dictnotes.txt Log: Patch #1397848: add the reasoning behind no-resize-on-shrinkage. Modified: python/trunk/Objects/dictnotes.txt ============================================================================== --- python/trunk/Objects/dictnotes.txt (original) +++ python/trunk/Objects/dictnotes.txt Thu Feb 15 10:51:35 2007 @@ -98,6 +98,17 @@ depending on the size of the dictionary. Setting to *4 eliminates every other resize step. +* Maximum sparseness (minimum dictionary load). What percentage + of entries can be unused before the dictionary shrinks to + free up memory and speed up iteration? (The current CPython + code does not represent this parameter directly.) + +* Shrinkage rate upon exceeding maximum sparseness. The current + CPython code never even checks sparseness when deleting a + key. When a new key is added, it resizes based on the number + of active keys, so that the addition may trigger shrinkage + rather than growth. + Tune-ups should be measured across a broad range of applications and use cases. A change to any parameter will help in some situations and hurt in others. The key is to find settings that help the most common @@ -115,6 +126,15 @@ Also, every dictionary iterates at least twice, once for the memset() when it is created and once by dealloc(). +Dictionary operations involving only a single key can be O(1) unless +resizing is possible. By checking for a resize only when the +dictionary can grow (and may *require* resizing), other operations +remain O(1), and the odds of resize thrashing or memory fragmentation +are reduced. In particular, an algorithm that empties a dictionary +by repeatedly invoking .pop will see no resizing, which might +not be necessary at all because the dictionary is eventually +discarded entirely. + Results of Cache Locality Experiments ------------------------------------- From python-checkins at python.org Thu Feb 15 11:38:00 2007 From: python-checkins at python.org (georg.brandl) Date: Thu, 15 Feb 2007 11:38:00 +0100 (CET) Subject: [Python-checkins] r53783 - python/trunk/Doc/lib/libfunctools.tex Message-ID: <20070215103800.1026F1E4019@bag.python.org> Author: georg.brandl Date: Thu Feb 15 11:37:59 2007 New Revision: 53783 Modified: python/trunk/Doc/lib/libfunctools.tex Log: Make functools.wraps() docs a bit clearer. Modified: python/trunk/Doc/lib/libfunctools.tex ============================================================================== --- python/trunk/Doc/lib/libfunctools.tex (original) +++ python/trunk/Doc/lib/libfunctools.tex Thu Feb 15 11:37:59 2007 @@ -53,15 +53,16 @@ \begin{funcdesc}{update_wrapper} {wrapper, wrapped\optional{, assigned}\optional{, updated}} -Update a wrapper function to look like the wrapped function. The optional -arguments are tuples to specify which attributes of the original +Update a \var{wrapper} function to look like the \var{wrapped} function. +The optional arguments are tuples to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function and which attributes of the wrapper function are updated with the corresponding attributes from the original function. The default values for these arguments are the module level constants -\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's name, -module and documentation string) and \var{WRAPPER_UPDATES} (which -updates the wrapper function's instance dictionary). +\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's +\var{__name__}, \var{__module__} and \var{__doc__}, the documentation string) +and \var{WRAPPER_UPDATES} (which updates the wrapper function's \var{__dict__}, +i.e. the instance dictionary). The main intended use for this function is in decorator functions which wrap the decorated function and return the wrapper. If the @@ -85,6 +86,7 @@ ... >>> @my_decorator ... def example(): + ... """Docstring""" ... print 'Called example function' ... >>> example() @@ -92,9 +94,12 @@ Called example function >>> example.__name__ 'example' + >>> example.__doc__ + 'Docstring' \end{verbatim} Without the use of this decorator factory, the name of the example -function would have been \code{'wrapper'}. +function would have been \code{'wrapper'}, and the docstring of the +original \function{example()} would have been lost. \end{funcdesc} From python-checkins at python.org Thu Feb 15 11:38:03 2007 From: python-checkins at python.org (georg.brandl) Date: Thu, 15 Feb 2007 11:38:03 +0100 (CET) Subject: [Python-checkins] r53784 - python/branches/release25-maint/Doc/lib/libfunctools.tex Message-ID: <20070215103803.BFB841E401D@bag.python.org> Author: georg.brandl Date: Thu Feb 15 11:38:03 2007 New Revision: 53784 Modified: python/branches/release25-maint/Doc/lib/libfunctools.tex Log: Make functools.wraps() docs a bit clearer. (backport from rev. 53783) Modified: python/branches/release25-maint/Doc/lib/libfunctools.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libfunctools.tex (original) +++ python/branches/release25-maint/Doc/lib/libfunctools.tex Thu Feb 15 11:38:03 2007 @@ -53,15 +53,16 @@ \begin{funcdesc}{update_wrapper} {wrapper, wrapped\optional{, assigned}\optional{, updated}} -Update a wrapper function to look like the wrapped function. The optional -arguments are tuples to specify which attributes of the original +Update a \var{wrapper} function to look like the \var{wrapped} function. +The optional arguments are tuples to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function and which attributes of the wrapper function are updated with the corresponding attributes from the original function. The default values for these arguments are the module level constants -\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's name, -module and documentation string) and \var{WRAPPER_UPDATES} (which -updates the wrapper function's instance dictionary). +\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's +\var{__name__}, \var{__module__} and \var{__doc__}, the documentation string) +and \var{WRAPPER_UPDATES} (which updates the wrapper function's \var{__dict__}, +i.e. the instance dictionary). The main intended use for this function is in decorator functions which wrap the decorated function and return the wrapper. If the @@ -85,6 +86,7 @@ ... >>> @my_decorator ... def example(): + ... """Docstring""" ... print 'Called example function' ... >>> example() @@ -92,9 +94,12 @@ Called example function >>> example.__name__ 'example' + >>> example.__doc__ + 'Docstring' \end{verbatim} Without the use of this decorator factory, the name of the example -function would have been \code{'wrapper'}. +function would have been \code{'wrapper'}, and the docstring of the +original \function{example()} would have been lost. \end{funcdesc} From buildbot at python.org Thu Feb 15 11:49:33 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 15 Feb 2007 10:49:33 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 trunk Message-ID: <20070215104933.9BF1F1E4019@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%2520trunk/builds/1411 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket ====================================================================== FAIL: testInterruptedTimeout (test.test_socket.TCPTimeoutTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/net/ringneck/scratch1/nnorwitz/python/trunk.norwitz-tru64/build/Lib/test/test_socket.py", line 886, in testInterruptedTimeout self.fail("got Alarm in wrong place") AssertionError: got Alarm in wrong place sincerely, -The Buildbot From python-checkins at python.org Thu Feb 15 12:29:05 2007 From: python-checkins at python.org (georg.brandl) Date: Thu, 15 Feb 2007 12:29:05 +0100 (CET) Subject: [Python-checkins] r53785 - in python/trunk: Doc/lib/libstruct.tex Misc/NEWS Message-ID: <20070215112905.691071E4019@bag.python.org> Author: georg.brandl Date: Thu Feb 15 12:29:04 2007 New Revision: 53785 Modified: python/trunk/Doc/lib/libstruct.tex python/trunk/Misc/NEWS Log: Patch #1494140: Add documentation for the new struct.Struct object. Modified: python/trunk/Doc/lib/libstruct.tex ============================================================================== --- python/trunk/Doc/lib/libstruct.tex (original) +++ python/trunk/Doc/lib/libstruct.tex Thu Feb 15 12:29:04 2007 @@ -29,6 +29,13 @@ exactly. \end{funcdesc} +\begin{funcdesc}{pack_into}{fmt, buffer, offset, v1, v2, \moreargs} + Pack the values \code{\var{v1}, \var{v2}, \textrm{\ldots}} according to the given + format, write the packed bytes into the writable \var{buffer} starting at + \var{offset}. + Note that the offset is not an optional argument. +\end{funcdesc} + \begin{funcdesc}{unpack}{fmt, string} Unpack the string (presumably packed by \code{pack(\var{fmt}, \textrm{\ldots})}) according to the given format. The result is a @@ -37,6 +44,14 @@ (\code{len(\var{string})} must equal \code{calcsize(\var{fmt})}). \end{funcdesc} +\begin{funcdesc}{unpack_from}{fmt, buffer\optional{,offset \code{= 0}}} + Unpack the \var{buffer} according to tthe given format. + The result is a tuple even if it contains exactly one item. The + \var{buffer} must contain at least the amount of data required by the + format (\code{len(buffer[offset:])} must be at least + \code{calcsize(\var{fmt})}). +\end{funcdesc} + \begin{funcdesc}{calcsize}{fmt} Return the size of the struct (and hence of the string) corresponding to the given format. @@ -208,3 +223,43 @@ \seemodule{array}{Packed binary storage of homogeneous data.} \seemodule{xdrlib}{Packing and unpacking of XDR data.} \end{seealso} + +\subsection{Struct Objects \label{struct-objects}} + +The \module{struct} module also defines the following type: + +\begin{classdesc}{Struct}{format} + Return a new Struct object which writes and reads binary data according to + the format string \var{format}. Creating a Struct object once and calling + its methods is more efficient than calling the \module{struct} functions + with the same format since the format string only needs to be compiled once. + + \versionadded{2.5} +\end{classdesc} + +Compiled Struct objects support the following methods and attributes: + +\begin{methoddesc}[Struct]{pack}{v1, v2, \moreargs} + Identical to the \function{pack()} function, using the compiled format. + (\code{len(result)} will equal \member{self.size}.) +\end{methoddesc} + +\begin{methoddesc}[Struct]{pack_into}{buffer, offset, v1, v2, \moreargs} + Identical to the \function{pack_into()} function, using the compiled format. +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack}{string} + Identical to the \function{unpack()} function, using the compiled format. + (\code{len(string)} must equal \member{self.size}). +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack_from}{buffer\optional{,offset + \code{= 0}}} + Identical to the \function{unpack_from()} function, using the compiled format. + (\code{len(buffer[offset:])} must be at least \member{self.size}). +\end{methoddesc} + +\begin{memberdesc}[Struct]{format} + The format string used to construct this Struct object. +\end{memberdesc} + Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu Feb 15 12:29:04 2007 @@ -366,6 +366,8 @@ Extension Modules ----------------- +- Patch #1494140: Add documentation for the new struct.Struct object. + - Patch #1432399: Support the HCI protocol for bluetooth sockets - Patch #1657276: Make NETLINK_DNRTMSG conditional. From python-checkins at python.org Thu Feb 15 12:29:09 2007 From: python-checkins at python.org (georg.brandl) Date: Thu, 15 Feb 2007 12:29:09 +0100 (CET) Subject: [Python-checkins] r53786 - in python/branches/release25-maint: Doc/lib/libstruct.tex Misc/NEWS Message-ID: <20070215112909.D68A51E401C@bag.python.org> Author: georg.brandl Date: Thu Feb 15 12:29:08 2007 New Revision: 53786 Modified: python/branches/release25-maint/Doc/lib/libstruct.tex python/branches/release25-maint/Misc/NEWS Log: Patch #1494140: Add documentation for the new struct.Struct object. (backport from rev. 53785) Modified: python/branches/release25-maint/Doc/lib/libstruct.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libstruct.tex (original) +++ python/branches/release25-maint/Doc/lib/libstruct.tex Thu Feb 15 12:29:08 2007 @@ -29,6 +29,13 @@ exactly. \end{funcdesc} +\begin{funcdesc}{pack_into}{fmt, buffer, offset, v1, v2, \moreargs} + Pack the values \code{\var{v1}, \var{v2}, \textrm{\ldots}} according to the given + format, write the packed bytes into the writable \var{buffer} starting at + \var{offset}. + Note that the offset is not an optional argument. +\end{funcdesc} + \begin{funcdesc}{unpack}{fmt, string} Unpack the string (presumably packed by \code{pack(\var{fmt}, \textrm{\ldots})}) according to the given format. The result is a @@ -37,6 +44,14 @@ (\code{len(\var{string})} must equal \code{calcsize(\var{fmt})}). \end{funcdesc} +\begin{funcdesc}{unpack_from}{fmt, buffer\optional{,offset \code{= 0}}} + Unpack the \var{buffer} according to tthe given format. + The result is a tuple even if it contains exactly one item. The + \var{buffer} must contain at least the amount of data required by the + format (\code{len(buffer[offset:])} must be at least + \code{calcsize(\var{fmt})}). +\end{funcdesc} + \begin{funcdesc}{calcsize}{fmt} Return the size of the struct (and hence of the string) corresponding to the given format. @@ -195,3 +210,43 @@ \seemodule{array}{Packed binary storage of homogeneous data.} \seemodule{xdrlib}{Packing and unpacking of XDR data.} \end{seealso} + +\subsection{Struct Objects \label{struct-objects}} + +The \module{struct} module also defines the following type: + +\begin{classdesc}{Struct}{format} + Return a new Struct object which writes and reads binary data according to + the format string \var{format}. Creating a Struct object once and calling + its methods is more efficient than calling the \module{struct} functions + with the same format since the format string only needs to be compiled once. + + \versionadded{2.5} +\end{classdesc} + +Compiled Struct objects support the following methods and attributes: + +\begin{methoddesc}[Struct]{pack}{v1, v2, \moreargs} + Identical to the \function{pack()} function, using the compiled format. + (\code{len(result)} will equal \member{self.size}.) +\end{methoddesc} + +\begin{methoddesc}[Struct]{pack_into}{buffer, offset, v1, v2, \moreargs} + Identical to the \function{pack_into()} function, using the compiled format. +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack}{string} + Identical to the \function{unpack()} function, using the compiled format. + (\code{len(string)} must equal \member{self.size}). +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack_from}{buffer\optional{,offset + \code{= 0}}} + Identical to the \function{unpack_from()} function, using the compiled format. + (\code{len(buffer[offset:])} must be at least \member{self.size}). +\end{methoddesc} + +\begin{memberdesc}[Struct]{format} + The format string used to construct this Struct object. +\end{memberdesc} + Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Thu Feb 15 12:29:08 2007 @@ -107,6 +107,8 @@ Extension Modules ----------------- +- Patch #1494140: Add documentation for the new struct.Struct object. + - Patch #1657276: Make NETLINK_DNRTMSG conditional. - Bug #1653736: Complain about keyword arguments to time.isoformat. From python-checkins at python.org Thu Feb 15 12:29:55 2007 From: python-checkins at python.org (georg.brandl) Date: Thu, 15 Feb 2007 12:29:55 +0100 (CET) Subject: [Python-checkins] r53787 - python/trunk/Doc/lib/libstruct.tex Message-ID: <20070215112955.B514B1E4019@bag.python.org> Author: georg.brandl Date: Thu Feb 15 12:29:55 2007 New Revision: 53787 Modified: python/trunk/Doc/lib/libstruct.tex Log: Add missing \versionadded. Modified: python/trunk/Doc/lib/libstruct.tex ============================================================================== --- python/trunk/Doc/lib/libstruct.tex (original) +++ python/trunk/Doc/lib/libstruct.tex Thu Feb 15 12:29:55 2007 @@ -34,6 +34,8 @@ format, write the packed bytes into the writable \var{buffer} starting at \var{offset}. Note that the offset is not an optional argument. + + \versionadded{2.5} \end{funcdesc} \begin{funcdesc}{unpack}{fmt, string} @@ -50,6 +52,8 @@ \var{buffer} must contain at least the amount of data required by the format (\code{len(buffer[offset:])} must be at least \code{calcsize(\var{fmt})}). + + \versionadded{2.5} \end{funcdesc} \begin{funcdesc}{calcsize}{fmt} From python-checkins at python.org Thu Feb 15 12:29:58 2007 From: python-checkins at python.org (georg.brandl) Date: Thu, 15 Feb 2007 12:29:58 +0100 (CET) Subject: [Python-checkins] r53788 - python/branches/release25-maint/Doc/lib/libstruct.tex Message-ID: <20070215112958.A55AF1E4019@bag.python.org> Author: georg.brandl Date: Thu Feb 15 12:29:58 2007 New Revision: 53788 Modified: python/branches/release25-maint/Doc/lib/libstruct.tex Log: Add missing \versionadded. (backport from rev. 53787) Modified: python/branches/release25-maint/Doc/lib/libstruct.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libstruct.tex (original) +++ python/branches/release25-maint/Doc/lib/libstruct.tex Thu Feb 15 12:29:58 2007 @@ -34,6 +34,8 @@ format, write the packed bytes into the writable \var{buffer} starting at \var{offset}. Note that the offset is not an optional argument. + + \versionadded{2.5} \end{funcdesc} \begin{funcdesc}{unpack}{fmt, string} @@ -50,6 +52,8 @@ \var{buffer} must contain at least the amount of data required by the format (\code{len(buffer[offset:])} must be at least \code{calcsize(\var{fmt})}). + + \versionadded{2.5} \end{funcdesc} \begin{funcdesc}{calcsize}{fmt} From python-checkins at python.org Thu Feb 15 20:19:43 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 15 Feb 2007 20:19:43 +0100 (CET) Subject: [Python-checkins] r53790 - in sandbox/trunk/setuptools: setuptools.txt setuptools/command/develop.py Message-ID: <20070215191943.36D9A1E4019@bag.python.org> Author: phillip.eby Date: Thu Feb 15 20:19:41 2007 New Revision: 53790 Modified: sandbox/trunk/setuptools/setuptools.txt sandbox/trunk/setuptools/setuptools/command/develop.py Log: Add --egg-path option to force .egg-link files to use relative paths (allowing them to be shared across platforms on a networked drive). Modified: sandbox/trunk/setuptools/setuptools.txt ============================================================================== --- sandbox/trunk/setuptools/setuptools.txt (original) +++ sandbox/trunk/setuptools/setuptools.txt Thu Feb 15 20:19:41 2007 @@ -1888,6 +1888,15 @@ a requirement can be met using a distribution that is already available in a directory on ``sys.path``, it will not be copied to the staging area. +``--egg-path=DIR`` + Force the generated ``.egg-link`` file to use a specified relative path + to the source directory. This can be useful in circumstances where your + installation directory is being shared by code running under multiple + platforms (e.g. Mac and Windows) which have different absolute locations + for the code under development, but the same *relative* locations with + respect to the installation directory. If you use this option when + installing, you must supply the same relative path when uninstalling. + In addition to the above options, the ``develop`` command also accepts all of the same options accepted by ``easy_install``. If you've configured any ``easy_install`` settings in your ``setup.cfg`` (or other distutils config Modified: sandbox/trunk/setuptools/setuptools/command/develop.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/develop.py (original) +++ sandbox/trunk/setuptools/setuptools/command/develop.py Thu Feb 15 20:19:41 2007 @@ -12,6 +12,7 @@ user_options = easy_install.user_options + [ ("uninstall", "u", "Uninstall this source package"), + ("egg-path=", None, "Set the path to be used in the .egg-link file"), ] boolean_options = easy_install.boolean_options + ['uninstall'] @@ -28,6 +29,7 @@ def initialize_options(self): self.uninstall = None + self.egg_path = None easy_install.initialize_options(self) @@ -37,8 +39,6 @@ - - def finalize_options(self): ei = self.get_finalized_command("egg_info") if ei.broken_egg_info: @@ -50,14 +50,36 @@ easy_install.finalize_options(self) self.egg_link = os.path.join(self.install_dir, ei.egg_name+'.egg-link') self.egg_base = ei.egg_base - self.egg_path = os.path.abspath(ei.egg_base) + + if self.egg_path is None: + self.egg_path = os.path.abspath(ei.egg_base) + + target = normalize_path(self.egg_base) + if normalize_path(os.path.join(self.install_dir, self.egg_path)) != target: + raise DistutilsOptionError( + "--egg-path must be a relative path from the install" + " directory to "+target + ) + # Make a distribution for the package's source self.dist = Distribution( - normalize_path(self.egg_path), - PathMetadata(self.egg_path, os.path.abspath(ei.egg_info)), + target, + PathMetadata(target, os.path.abspath(ei.egg_info)), project_name = ei.egg_name ) + + + + + + + + + + + + def install_for_development(self): # Ensure metadata is up-to-date self.run_command('egg_info') @@ -75,11 +97,11 @@ f = open(self.egg_link,"w") f.write(self.egg_path) f.close() - # postprocess the installed distro, fixing up .pth, installing scripts, # and handling requirements self.process_distribution(None, self.dist, not self.no_deps) + def uninstall_link(self): if os.path.exists(self.egg_link): log.info("Removing %s (link to %s)", self.egg_link, self.egg_base) @@ -96,6 +118,9 @@ log.warn("Note: you must uninstall or replace scripts manually!") + + + def install_egg_scripts(self, dist): if dist is not self.dist: # Installing a dependency, so fall back to normal behavior @@ -121,3 +146,19 @@ + + + + + + + + + + + + + + + + From python-checkins at python.org Thu Feb 15 20:22:20 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 15 Feb 2007 20:22:20 +0100 (CET) Subject: [Python-checkins] r53791 - in sandbox/branches/setuptools-0.6: setuptools.txt setuptools/command/develop.py Message-ID: <20070215192220.2EC6C1E4019@bag.python.org> Author: phillip.eby Date: Thu Feb 15 20:22:19 2007 New Revision: 53791 Modified: sandbox/branches/setuptools-0.6/setuptools.txt sandbox/branches/setuptools-0.6/setuptools/command/develop.py Log: Added ``--egg-path`` option to ``develop`` command, allowing you to force ``.egg-link`` files to use relative paths (allowing them to be shared across platforms on a networked drive). (backport from trunk) Modified: sandbox/branches/setuptools-0.6/setuptools.txt ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools.txt (original) +++ sandbox/branches/setuptools-0.6/setuptools.txt Thu Feb 15 20:22:19 2007 @@ -1910,6 +1910,15 @@ a requirement can be met using a distribution that is already available in a directory on ``sys.path``, it will not be copied to the staging area. +``--egg-path=DIR`` + Force the generated ``.egg-link`` file to use a specified relative path + to the source directory. This can be useful in circumstances where your + installation directory is being shared by code running under multiple + platforms (e.g. Mac and Windows) which have different absolute locations + for the code under development, but the same *relative* locations with + respect to the installation directory. If you use this option when + installing, you must supply the same relative path when uninstalling. + In addition to the above options, the ``develop`` command also accepts all of the same options accepted by ``easy_install``. If you've configured any ``easy_install`` settings in your ``setup.cfg`` (or other distutils config @@ -2601,6 +2610,10 @@ ---------------------------- 0.6c6 + * Added ``--egg-path`` option to ``develop`` command, allowing you to force + ``.egg-link`` files to use relative paths (allowing them to be shared across + platforms on a networked drive). + * Fix not building binary RPMs correctly. * Fix "eggsecutables" (such as setuptools' own egg) only being runnable with Modified: sandbox/branches/setuptools-0.6/setuptools/command/develop.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/develop.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/develop.py Thu Feb 15 20:22:19 2007 @@ -12,6 +12,7 @@ user_options = easy_install.user_options + [ ("uninstall", "u", "Uninstall this source package"), + ("egg-path=", None, "Set the path to be used in the .egg-link file"), ] boolean_options = easy_install.boolean_options + ['uninstall'] @@ -28,6 +29,7 @@ def initialize_options(self): self.uninstall = None + self.egg_path = None easy_install.initialize_options(self) @@ -37,8 +39,6 @@ - - def finalize_options(self): ei = self.get_finalized_command("egg_info") if ei.broken_egg_info: @@ -50,14 +50,36 @@ easy_install.finalize_options(self) self.egg_link = os.path.join(self.install_dir, ei.egg_name+'.egg-link') self.egg_base = ei.egg_base - self.egg_path = os.path.abspath(ei.egg_base) + + if self.egg_path is None: + self.egg_path = os.path.abspath(ei.egg_base) + + target = normalize_path(self.egg_base) + if normalize_path(os.path.join(self.install_dir, self.egg_path)) != target: + raise DistutilsOptionError( + "--egg-path must be a relative path from the install" + " directory to "+target + ) + # Make a distribution for the package's source self.dist = Distribution( - normalize_path(self.egg_path), - PathMetadata(self.egg_path, os.path.abspath(ei.egg_info)), + target, + PathMetadata(target, os.path.abspath(ei.egg_info)), project_name = ei.egg_name ) + + + + + + + + + + + + def install_for_development(self): # Ensure metadata is up-to-date self.run_command('egg_info') @@ -75,11 +97,11 @@ f = open(self.egg_link,"w") f.write(self.egg_path) f.close() - # postprocess the installed distro, fixing up .pth, installing scripts, # and handling requirements self.process_distribution(None, self.dist, not self.no_deps) + def uninstall_link(self): if os.path.exists(self.egg_link): log.info("Removing %s (link to %s)", self.egg_link, self.egg_base) @@ -96,6 +118,9 @@ log.warn("Note: you must uninstall or replace scripts manually!") + + + def install_egg_scripts(self, dist): if dist is not self.dist: # Installing a dependency, so fall back to normal behavior @@ -121,3 +146,19 @@ + + + + + + + + + + + + + + + + From python-checkins at python.org Thu Feb 15 20:35:09 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 15 Feb 2007 20:35:09 +0100 (CET) Subject: [Python-checkins] r53792 - sandbox/trunk/setuptools/pkg_resources.py Message-ID: <20070215193509.5B40E1E4019@bag.python.org> Author: phillip.eby Date: Thu Feb 15 20:35:08 2007 New Revision: 53792 Modified: sandbox/trunk/setuptools/pkg_resources.py Log: Support .egg-link paths being relative Modified: sandbox/trunk/setuptools/pkg_resources.py ============================================================================== --- sandbox/trunk/setuptools/pkg_resources.py (original) +++ sandbox/trunk/setuptools/pkg_resources.py Thu Feb 15 20:35:08 2007 @@ -1551,7 +1551,7 @@ elif not only and lower.endswith('.egg-link'): for line in file(os.path.join(path_item, entry)): if not line.strip(): continue - for item in find_distributions(line.rstrip()): + for item in find_distributions(os.path.join(path_item,line.rstrip())): yield item register_finder(pkgutil.ImpImporter, find_on_path) From python-checkins at python.org Thu Feb 15 20:37:03 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 15 Feb 2007 20:37:03 +0100 (CET) Subject: [Python-checkins] r53793 - sandbox/trunk/setuptools/doc/formats.txt Message-ID: <20070215193703.4C63D1E4019@bag.python.org> Author: phillip.eby Date: Thu Feb 15 20:37:02 2007 New Revision: 53793 Modified: sandbox/trunk/setuptools/doc/formats.txt Log: Internals updated for relative .egg-link support Modified: sandbox/trunk/setuptools/doc/formats.txt ============================================================================== --- sandbox/trunk/setuptools/doc/formats.txt (original) +++ sandbox/trunk/setuptools/doc/formats.txt Thu Feb 15 20:37:02 2007 @@ -220,7 +220,8 @@ with no newlines. This filename should be the base location of one or more eggs. That is, the name must either end in ``.egg``, or else it should be the parent directory of one or more ``.egg-info`` format eggs. - +As of setuptools 0.6c6, the path may be specified as a relative path +from the directory containing the ``.egg-link`` file. ----------------- From python-checkins at python.org Thu Feb 15 20:38:21 2007 From: python-checkins at python.org (phillip.eby) Date: Thu, 15 Feb 2007 20:38:21 +0100 (CET) Subject: [Python-checkins] r53794 - sandbox/branches/setuptools-0.6/pkg_resources.py sandbox/branches/setuptools-0.6/pkg_resources.txt Message-ID: <20070215193821.5BEEF1E401D@bag.python.org> Author: phillip.eby Date: Thu Feb 15 20:38:20 2007 New Revision: 53794 Modified: sandbox/branches/setuptools-0.6/pkg_resources.py sandbox/branches/setuptools-0.6/pkg_resources.txt Log: Actually process relative .egg-link files (backport from trunk) Modified: sandbox/branches/setuptools-0.6/pkg_resources.py ============================================================================== --- sandbox/branches/setuptools-0.6/pkg_resources.py (original) +++ sandbox/branches/setuptools-0.6/pkg_resources.py Thu Feb 15 20:38:20 2007 @@ -1633,7 +1633,7 @@ elif not only and lower.endswith('.egg-link'): for line in file(os.path.join(path_item, entry)): if not line.strip(): continue - for item in find_distributions(line.rstrip()): + for item in find_distributions(os.path.join(path_item,line.rstrip())): yield item register_finder(ImpWrapper,find_on_path) Modified: sandbox/branches/setuptools-0.6/pkg_resources.txt ============================================================================== --- sandbox/branches/setuptools-0.6/pkg_resources.txt (original) +++ sandbox/branches/setuptools-0.6/pkg_resources.txt Thu Feb 15 20:38:20 2007 @@ -1695,6 +1695,8 @@ 0.6c6 * Fix extracted C extensions not having executable permissions under Cygwin. + * Allow ``.egg-link`` files to contain relative paths. + 0.6c4 * Fix "dev" versions being considered newer than release candidates. From python-checkins at python.org Thu Feb 15 23:54:40 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 15 Feb 2007 23:54:40 +0100 (CET) Subject: [Python-checkins] r53800 - in python/trunk: Lib/encodings/__init__.py Misc/NEWS Message-ID: <20070215225440.A72841E4003@bag.python.org> Author: brett.cannon Date: Thu Feb 15 23:54:39 2007 New Revision: 53800 Modified: python/trunk/Lib/encodings/__init__.py python/trunk/Misc/NEWS Log: Update the encoding package's search function to use absolute imports when calling __import__. This helps make the expected search locations for encoding modules be more explicit. One could use an explicit value for __path__ when making the call to __import__ to force the exact location searched for encodings. This would give the most strict search path possible if one is worried about malicious code being imported. The unfortunate side-effect of that is that if __path__ was modified on 'encodings' on purpose in a safe way it would not be picked up in future __import__ calls. Modified: python/trunk/Lib/encodings/__init__.py ============================================================================== --- python/trunk/Lib/encodings/__init__.py (original) +++ python/trunk/Lib/encodings/__init__.py Thu Feb 15 23:54:39 2007 @@ -93,8 +93,10 @@ if not modname or '.' in modname: continue try: - mod = __import__('encodings.' + modname, - globals(), locals(), _import_tail) + # Import equivalent to `` from .modname import *``. + # '*' is used so that __import__ returns the desired module and not + # 'encodings' itself. + mod = __import__(modname, globals(), locals(), ['*'], 1) except ImportError: pass else: Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu Feb 15 23:54:39 2007 @@ -128,6 +128,9 @@ Library ------- +- Have the encoding package's search function dynamically import using absolute + import semantics. + - Patch #1647484: Renamed GzipFile's filename attribute to name. - Patch #1517891: Mode 'a' for ZipFile now creates the file if it From mal at egenix.com Fri Feb 16 00:08:20 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 16 Feb 2007 00:08:20 +0100 Subject: [Python-checkins] r53800 - in python/trunk: Lib/encodings/__init__.py Misc/NEWS In-Reply-To: <20070215225440.A72841E4003@bag.python.org> References: <20070215225440.A72841E4003@bag.python.org> Message-ID: <45D4E7E4.7030006@egenix.com> On 2007-02-15 23:54, brett.cannon wrote: > Author: brett.cannon > Date: Thu Feb 15 23:54:39 2007 > New Revision: 53800 > > Modified: > python/trunk/Lib/encodings/__init__.py > python/trunk/Misc/NEWS > Log: > Update the encoding package's search function to use absolute imports when > calling __import__. This helps make the expected search locations for encoding > modules be more explicit. Your change does not make the import absolute - to the contrary: we now have a relative import. Please change that back to the original scheme which is indeed an absolute import. If you want to make sure that the search function is not importing from encodings.encodings, then you can add a 0 parameter as last parameter to __import__(). The other changes are not necessary. Thanks. > One could use an explicit value for __path__ when making the call to __import__ > to force the exact location searched for encodings. This would give the most > strict search path possible if one is worried about malicious code being > imported. The unfortunate side-effect of that is that if __path__ was modified > on 'encodings' on purpose in a safe way it would not be picked up in future > __import__ calls. > > > Modified: python/trunk/Lib/encodings/__init__.py > ============================================================================== > --- python/trunk/Lib/encodings/__init__.py (original) > +++ python/trunk/Lib/encodings/__init__.py Thu Feb 15 23:54:39 2007 > @@ -93,8 +93,10 @@ > if not modname or '.' in modname: > continue > try: > - mod = __import__('encodings.' + modname, > - globals(), locals(), _import_tail) > + # Import equivalent to `` from .modname import *``. > + # '*' is used so that __import__ returns the desired module and not > + # 'encodings' itself. > + mod = __import__(modname, globals(), locals(), ['*'], 1) > except ImportError: > pass > else: > > Modified: python/trunk/Misc/NEWS > ============================================================================== > --- python/trunk/Misc/NEWS (original) > +++ python/trunk/Misc/NEWS Thu Feb 15 23:54:39 2007 > @@ -128,6 +128,9 @@ > Library > ------- > > +- Have the encoding package's search function dynamically import using absolute > + import semantics. > + > - Patch #1647484: Renamed GzipFile's filename attribute to name. > > - Patch #1517891: Mode 'a' for ZipFile now creates the file if it > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 16 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: From brett at python.org Fri Feb 16 00:51:51 2007 From: brett at python.org (Brett Cannon) Date: Thu, 15 Feb 2007 15:51:51 -0800 Subject: [Python-checkins] r53800 - in python/trunk: Lib/encodings/__init__.py Misc/NEWS In-Reply-To: <45D4E7E4.7030006@egenix.com> References: <20070215225440.A72841E4003@bag.python.org> <45D4E7E4.7030006@egenix.com> Message-ID: On 2/15/07, M.-A. Lemburg wrote: > On 2007-02-15 23:54, brett.cannon wrote: > > Author: brett.cannon > > Date: Thu Feb 15 23:54:39 2007 > > New Revision: 53800 > > > > Modified: > > python/trunk/Lib/encodings/__init__.py > > python/trunk/Misc/NEWS > > Log: > > Update the encoding package's search function to use absolute imports when > > calling __import__. This helps make the expected search locations for encoding > > modules be more explicit. > > Your change does not make the import absolute - to the contrary: we > now have a relative import. > Right, but I just associate it with the absolute import PEP and the term. Probably could have called it a "new-style import" or something. > Please change that back to the original scheme which is indeed an > absolute import. Why? What's wrong with a relative import? > If you want to make sure that the search function > is not importing from encodings.encodings, then you can add > a 0 parameter as last parameter to __import__(). Right. But that will essentially do the same thing I just committed since what you are proposing will grab 'encodings' from sys.modules, pull out its __path__ entry, and then do the import from there. What I did above skips that look up for 'encodings' and instead uses the module that the function was defined in. -Brett > The other changes > are not necessary. > > Thanks. > > > One could use an explicit value for __path__ when making the call to __import__ > > to force the exact location searched for encodings. This would give the most > > strict search path possible if one is worried about malicious code being > > imported. The unfortunate side-effect of that is that if __path__ was modified > > on 'encodings' on purpose in a safe way it would not be picked up in future > > __import__ calls. > > > > > > Modified: python/trunk/Lib/encodings/__init__.py > > ============================================================================== > > --- python/trunk/Lib/encodings/__init__.py (original) > > +++ python/trunk/Lib/encodings/__init__.py Thu Feb 15 23:54:39 2007 > > @@ -93,8 +93,10 @@ > > if not modname or '.' in modname: > > continue > > try: > > - mod = __import__('encodings.' + modname, > > - globals(), locals(), _import_tail) > > + # Import equivalent to `` from .modname import *``. > > + # '*' is used so that __import__ returns the desired module and not > > + # 'encodings' itself. > > + mod = __import__(modname, globals(), locals(), ['*'], 1) > > except ImportError: > > pass > > else: > > > > Modified: python/trunk/Misc/NEWS > > ============================================================================== > > --- python/trunk/Misc/NEWS (original) > > +++ python/trunk/Misc/NEWS Thu Feb 15 23:54:39 2007 > > @@ -128,6 +128,9 @@ > > Library > > ------- > > > > +- Have the encoding package's search function dynamically import using absolute > > + import semantics. > > + > > - Patch #1647484: Renamed GzipFile's filename attribute to name. > > > > - Patch #1517891: Mode 'a' for ZipFile now creates the file if it > > _______________________________________________ > > Python-checkins mailing list > > Python-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-checkins > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Feb 16 2007) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > From mal at egenix.com Fri Feb 16 12:20:24 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 16 Feb 2007 12:20:24 +0100 Subject: [Python-checkins] r53800 - in python/trunk: Lib/encodings/__init__.py Misc/NEWS In-Reply-To: References: <20070215225440.A72841E4003@bag.python.org> <45D4E7E4.7030006@egenix.com> Message-ID: <45D59378.60203@egenix.com> On 2007-02-16 00:51, Brett Cannon wrote: > On 2/15/07, M.-A. Lemburg wrote: >> On 2007-02-15 23:54, brett.cannon wrote: >>> Author: brett.cannon >>> Date: Thu Feb 15 23:54:39 2007 >>> New Revision: 53800 >>> >>> Modified: >>> python/trunk/Lib/encodings/__init__.py >>> python/trunk/Misc/NEWS >>> Log: >>> Update the encoding package's search function to use absolute imports when >>> calling __import__. This helps make the expected search locations for encoding >>> modules be more explicit. >> Your change does not make the import absolute - to the contrary: we >> now have a relative import. >> > > Right, but I just associate it with the absolute import PEP and the > term. Probably could have called it a "new-style import" or > something. > >> Please change that back to the original scheme which is indeed an >> absolute import. > > Why? What's wrong with a relative import? Whenever possible we should use absolute imports. Relative imports are really only necessary when you want to make packages relocatable which is not the case for the encodings package. >> If you want to make sure that the search function >> is not importing from encodings.encodings, then you can add >> a 0 parameter as last parameter to __import__(). > > Right. But that will essentially do the same thing I just committed > since what you are proposing will grab 'encodings' from sys.modules, > pull out its __path__ entry, and then do the import from there. What > I did above skips that look up for 'encodings' and instead uses the > module that the function was defined in. If you look at the import source code, you'll find that both methods turn out to do the same thing. They both end up with a lookup for 'encodings'. > -Brett > > >> The other changes >> are not necessary. >> >> Thanks. >> >>> One could use an explicit value for __path__ when making the call to __import__ >>> to force the exact location searched for encodings. This would give the most >>> strict search path possible if one is worried about malicious code being >>> imported. The unfortunate side-effect of that is that if __path__ was modified >>> on 'encodings' on purpose in a safe way it would not be picked up in future >>> __import__ calls. >>> >>> >>> Modified: python/trunk/Lib/encodings/__init__.py >>> ============================================================================== >>> --- python/trunk/Lib/encodings/__init__.py (original) >>> +++ python/trunk/Lib/encodings/__init__.py Thu Feb 15 23:54:39 2007 >>> @@ -93,8 +93,10 @@ >>> if not modname or '.' in modname: >>> continue >>> try: >>> - mod = __import__('encodings.' + modname, >>> - globals(), locals(), _import_tail) >>> + # Import equivalent to `` from .modname import *``. >>> + # '*' is used so that __import__ returns the desired module and not >>> + # 'encodings' itself. >>> + mod = __import__(modname, globals(), locals(), ['*'], 1) >>> except ImportError: >>> pass >>> else: >>> >>> Modified: python/trunk/Misc/NEWS >>> ============================================================================== >>> --- python/trunk/Misc/NEWS (original) >>> +++ python/trunk/Misc/NEWS Thu Feb 15 23:54:39 2007 >>> @@ -128,6 +128,9 @@ >>> Library >>> ------- >>> >>> +- Have the encoding package's search function dynamically import using absolute >>> + import semantics. >>> + >>> - Patch #1647484: Renamed GzipFile's filename attribute to name. >>> >>> - Patch #1517891: Mode 'a' for ZipFile now creates the file if it >>> _______________________________________________ >>> Python-checkins mailing list >>> Python-checkins at python.org >>> http://mail.python.org/mailman/listinfo/python-checkins >> -- >> Marc-Andre Lemburg >> eGenix.com >> >> Professional Python Services directly from the Source (#1, Feb 16 2007) >>>>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ >> ________________________________________________________________________ >> >> :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: >> > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 16 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: From buildbot at python.org Fri Feb 16 13:02:01 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 16 Feb 2007 12:02:01 +0000 Subject: [Python-checkins] buildbot warnings in hppa Ubuntu dapper trunk Message-ID: <20070216120201.A1FF41E4022@bag.python.org> The Buildbot has detected a new failure of hppa Ubuntu dapper trunk. Full details are available at: http://www.python.org/dev/buildbot/all/hppa%2520Ubuntu%2520dapper%2520trunk/builds/71 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: armin.rigo,brett.cannon,georg.brandl,lars.gustaebel,martin.v.loewis,skip.montanaro Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From udgwms at weichertclark.com Fri Feb 16 13:41:17 2007 From: udgwms at weichertclark.com (Crow F.Hilary) Date: Fri, 16 Feb 2007 21:41:17 +0900 Subject: [Python-checkins] He didn't seem all that impressed though. Message-ID: <45D5A66D.1020907@jeanerette.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-checkins/attachments/20070216/09b51bb4/attachment-0001.html -------------- next part -------------- A non-text attachment was scrubbed... Name: political.gif Type: image/gif Size: 18982 bytes Desc: not available Url : http://mail.python.org/pipermail/python-checkins/attachments/20070216/09b51bb4/attachment-0001.gif From guido at python.org Fri Feb 16 17:44:45 2007 From: guido at python.org (Guido van Rossum) Date: Fri, 16 Feb 2007 08:44:45 -0800 Subject: [Python-checkins] r53800 - in python/trunk: Lib/encodings/__init__.py Misc/NEWS In-Reply-To: <45D59378.60203@egenix.com> References: <20070215225440.A72841E4003@bag.python.org> <45D4E7E4.7030006@egenix.com> <45D59378.60203@egenix.com> Message-ID: On 2/16/07, M.-A. Lemburg wrote: > On 2007-02-16 00:51, Brett Cannon wrote: > > Why? What's wrong with a relative import? > > Whenever possible we should use absolute imports. Relative imports > are really only necessary when you want to make packages relocatable > which is not the case for the encodings package. I support this. -- --Guido van Rossum (home page: http://www.python.org/~guido/) From brett at python.org Fri Feb 16 20:23:27 2007 From: brett at python.org (Brett Cannon) Date: Fri, 16 Feb 2007 11:23:27 -0800 Subject: [Python-checkins] r53800 - in python/trunk: Lib/encodings/__init__.py Misc/NEWS In-Reply-To: <45D59378.60203@egenix.com> References: <20070215225440.A72841E4003@bag.python.org> <45D4E7E4.7030006@egenix.com> <45D59378.60203@egenix.com> Message-ID: On 2/16/07, M.-A. Lemburg wrote: > On 2007-02-16 00:51, Brett Cannon wrote: > > On 2/15/07, M.-A. Lemburg wrote: > >> On 2007-02-15 23:54, brett.cannon wrote: > >>> Author: brett.cannon > >>> Date: Thu Feb 15 23:54:39 2007 > >>> New Revision: 53800 > >>> > >>> Modified: > >>> python/trunk/Lib/encodings/__init__.py > >>> python/trunk/Misc/NEWS > >>> Log: > >>> Update the encoding package's search function to use absolute imports when > >>> calling __import__. This helps make the expected search locations for encoding > >>> modules be more explicit. > >> Your change does not make the import absolute - to the contrary: we > >> now have a relative import. > >> > > > > Right, but I just associate it with the absolute import PEP and the > > term. Probably could have called it a "new-style import" or > > something. > > > >> Please change that back to the original scheme which is indeed an > >> absolute import. > > > > Why? What's wrong with a relative import? > > Whenever possible we should use absolute imports. Relative imports > are really only necessary when you want to make packages relocatable > which is not the case for the encodings package. > True, but my motivation was to enforce importing from the 'encodings' package to prevent people from importing modules with side-effects that are not in the package. But absolute imports do the same thing, so I am running regrtest and then will check in an absolute import once that is done. -Brett From buildbot at python.org Fri Feb 16 20:31:02 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 16 Feb 2007 19:31:02 +0000 Subject: [Python-checkins] buildbot failure in sparc solaris10 gcc 2.5 Message-ID: <20070216193102.B8DF41E400B@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%25202.5/builds/226 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Heriberto': Blaise Build Source Stamp: [branch Abram] Jonah Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Fri Feb 16 20:31:36 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 16 Feb 2007 19:31:36 +0000 Subject: [Python-checkins] buildbot failure in x86 gentoo 2.5 Message-ID: <20070216193136.DEEB11E400B@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/233 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Jaylon': Rigoberto Build Source Stamp: [branch Colten] Stuart Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From mal at egenix.com Fri Feb 16 20:31:41 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 16 Feb 2007 20:31:41 +0100 Subject: [Python-checkins] r53800 - in python/trunk: Lib/encodings/__init__.py Misc/NEWS In-Reply-To: References: <20070215225440.A72841E4003@bag.python.org> <45D4E7E4.7030006@egenix.com> <45D59378.60203@egenix.com> Message-ID: <45D6069D.3060307@egenix.com> On 2007-02-16 20:23, Brett Cannon wrote: > On 2/16/07, M.-A. Lemburg wrote: >> On 2007-02-16 00:51, Brett Cannon wrote: >> > On 2/15/07, M.-A. Lemburg wrote: >> >> On 2007-02-15 23:54, brett.cannon wrote: >> >>> Author: brett.cannon >> >>> Date: Thu Feb 15 23:54:39 2007 >> >>> New Revision: 53800 >> >>> >> >>> Modified: >> >>> python/trunk/Lib/encodings/__init__.py >> >>> python/trunk/Misc/NEWS >> >>> Log: >> >>> Update the encoding package's search function to use absolute >> imports when >> >>> calling __import__. This helps make the expected search locations >> for encoding >> >>> modules be more explicit. >> >> Your change does not make the import absolute - to the contrary: we >> >> now have a relative import. >> >> >> > >> > Right, but I just associate it with the absolute import PEP and the >> > term. Probably could have called it a "new-style import" or >> > something. >> > >> >> Please change that back to the original scheme which is indeed an >> >> absolute import. >> > >> > Why? What's wrong with a relative import? >> >> Whenever possible we should use absolute imports. Relative imports >> are really only necessary when you want to make packages relocatable >> which is not the case for the encodings package. >> > > True, but my motivation was to enforce importing from the 'encodings' > package to prevent people from importing modules with side-effects > that are not in the package. That was the motivation to add the "'encodings.' +" in front of the module name :-) Note that before we made that change, the fact that you could import codecs from the PYTHONPATH was actually an (undocumented) feature and used by a few people to be able to easily add their own codec packages to the global namespace. The right way to do this is to register your own search function, of course, which is why we decided to break this feature in favor of preventing DOS attacks like u"abc".encode('test.testall'). > But absolute imports do the same thing, so I am running regrtest and > then will check in an absolute import once that is done. Ok. Thanks, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 16 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From python-checkins at python.org Fri Feb 16 20:33:01 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 16 Feb 2007 20:33:01 +0100 (CET) Subject: [Python-checkins] r53801 - python/trunk/Lib/encodings/__init__.py Message-ID: <20070216193301.B25561E400B@bag.python.org> Author: brett.cannon Date: Fri Feb 16 20:33:01 2007 New Revision: 53801 Modified: python/trunk/Lib/encodings/__init__.py Log: Make the __import__ call in encodings.__init__ absolute with a level 0 call. Modified: python/trunk/Lib/encodings/__init__.py ============================================================================== --- python/trunk/Lib/encodings/__init__.py (original) +++ python/trunk/Lib/encodings/__init__.py Fri Feb 16 20:33:01 2007 @@ -93,10 +93,10 @@ if not modname or '.' in modname: continue try: - # Import equivalent to `` from .modname import *``. - # '*' is used so that __import__ returns the desired module and not - # 'encodings' itself. - mod = __import__(modname, globals(), locals(), ['*'], 1) + # Import is absolute to prevent the possibly malicious import of a + # module with side-effects that is not in the 'encodings' package. + mod = __import__('encodings.' + modname, fromlist=_import_tail, + level=0) except ImportError: pass else: From python-checkins at python.org Fri Feb 16 20:52:34 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 16 Feb 2007 20:52:34 +0100 (CET) Subject: [Python-checkins] r53802 - sandbox/trunk/import_in_py/importlib.py Message-ID: <20070216195234.0C9F71E400B@bag.python.org> Author: brett.cannon Date: Fri Feb 16 20:52:33 2007 New Revision: 53802 Modified: sandbox/trunk/import_in_py/importlib.py Log: Add a comment about whether using __path__ from globals is worth considering. Modified: sandbox/trunk/import_in_py/importlib.py ============================================================================== --- sandbox/trunk/import_in_py/importlib.py (original) +++ sandbox/trunk/import_in_py/importlib.py Fri Feb 16 20:52:33 2007 @@ -762,6 +762,13 @@ current_name = ".".join(current_name_parts) if parent_module: try: + # XXX Better to use __path__ as found in 'globals' argument + # in __call__? Possibly different if module in sys.modules + # resolves to a different one from where the import call + # was made. Not sure if this worth worrying about, though, + # since relative imports could easily negate use of + # __path__ and sys.modules is totally reasonable to + # consider the canonical modules. path_list = parent_module.__path__ except AttributeError: pass @@ -807,8 +814,8 @@ def _return_module(self, absolute_name, relative_name, fromlist): """Return the proper module based on what module was requested (and its - absolute module name), who is - requesting it, and whether any speicific attributes were specified. + absolute module name), who is requesting it, and whether any speicific + attributes were specified. The semantics of this method revolve around 'fromlist'. When it is empty, the module up to the first dot is to be returned. When the From python-checkins at python.org Fri Feb 16 23:36:25 2007 From: python-checkins at python.org (vinay.sajip) Date: Fri, 16 Feb 2007 23:36:25 +0100 (CET) Subject: [Python-checkins] r53809 - python/trunk/Lib/logging/__init__.py Message-ID: <20070216223625.11C321E4029@bag.python.org> Author: vinay.sajip Date: Fri Feb 16 23:36:24 2007 New Revision: 53809 Modified: python/trunk/Lib/logging/__init__.py Log: Minor fix for currentframe (SF #1652788). Modified: python/trunk/Lib/logging/__init__.py ============================================================================== --- python/trunk/Lib/logging/__init__.py (original) +++ python/trunk/Lib/logging/__init__.py Fri Feb 16 23:36:24 2007 @@ -1,4 +1,4 @@ -# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, @@ -21,7 +21,7 @@ Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. -Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.5.0.1" -__date__ = "09 January 2007" +__version__ = "0.5.0.2" +__date__ = "16 February 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -68,7 +68,7 @@ except: return sys.exc_traceback.tb_frame.f_back -if hasattr(sys, '_getframe'): currentframe = sys._getframe +if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) # done filching # _srcfile is only used in conjunction with sys._getframe(). From buildbot at python.org Sat Feb 17 00:23:54 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 16 Feb 2007 23:23:54 +0000 Subject: [Python-checkins] buildbot warnings in ppc Debian unstable trunk Message-ID: <20070216232354.CB59E1E400B@bag.python.org> The Buildbot has detected a new failure of ppc Debian unstable trunk. Full details are available at: http://www.python.org/dev/buildbot/all/ppc%2520Debian%2520unstable%2520trunk/builds/79 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: vinay.sajip Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_bsddb3 make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Sat Feb 17 00:26:37 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 16 Feb 2007 23:26:37 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian trunk Message-ID: <20070216232637.AE6061E4014@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%2520trunk/builds/78 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: vinay.sajip Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_bsddb3 make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Sat Feb 17 00:30:29 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 16 Feb 2007 23:30:29 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 trunk Message-ID: <20070216233029.89B6D1E400B@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%2520trunk/builds/1414 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: vinay.sajip Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket sincerely, -The Buildbot From python-checkins at python.org Sat Feb 17 02:37:51 2007 From: python-checkins at python.org (vinay.sajip) Date: Sat, 17 Feb 2007 02:37:51 +0100 (CET) Subject: [Python-checkins] r53811 - python/branches/release25-maint/Lib/logging/__init__.py Message-ID: <20070217013751.05A8F1E4014@bag.python.org> Author: vinay.sajip Date: Sat Feb 17 02:37:50 2007 New Revision: 53811 Modified: python/branches/release25-maint/Lib/logging/__init__.py Log: Minor fix for currentframe (SF #1652788). Modified: python/branches/release25-maint/Lib/logging/__init__.py ============================================================================== --- python/branches/release25-maint/Lib/logging/__init__.py (original) +++ python/branches/release25-maint/Lib/logging/__init__.py Sat Feb 17 02:37:50 2007 @@ -1,4 +1,4 @@ -# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, @@ -21,7 +21,7 @@ Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. -Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.4.9.9" -__date__ = "06 February 2006" +__version__ = "0.5.0.2" +__date__ = "16 February 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -68,7 +68,7 @@ except: return sys.exc_traceback.tb_frame.f_back -if hasattr(sys, '_getframe'): currentframe = sys._getframe +if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) # done filching # _srcfile is only used in conjunction with sys._getframe(). From python-checkins at python.org Sat Feb 17 02:39:18 2007 From: python-checkins at python.org (vinay.sajip) Date: Sat, 17 Feb 2007 02:39:18 +0100 (CET) Subject: [Python-checkins] r53812 - python/branches/release24-maint/Lib/logging/__init__.py Message-ID: <20070217013918.070651E400B@bag.python.org> Author: vinay.sajip Date: Sat Feb 17 02:39:17 2007 New Revision: 53812 Modified: python/branches/release24-maint/Lib/logging/__init__.py Log: Minor fix for currentframe (SF #1652788). Modified: python/branches/release24-maint/Lib/logging/__init__.py ============================================================================== --- python/branches/release24-maint/Lib/logging/__init__.py (original) +++ python/branches/release24-maint/Lib/logging/__init__.py Sat Feb 17 02:39:17 2007 @@ -1,4 +1,4 @@ -# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, @@ -21,7 +21,7 @@ Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. -Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ @@ -68,7 +68,7 @@ except: return sys.exc_traceback.tb_frame.f_back -if hasattr(sys, '_getframe'): currentframe = sys._getframe +if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) # done filching # _srcfile is only used in conjunction with sys._getframe(). From buildbot at python.org Sat Feb 17 03:01:36 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 17 Feb 2007 02:01:36 +0000 Subject: [Python-checkins] buildbot failure in amd64 gentoo 2.5 Message-ID: <20070217020136.9B2851E400B@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%25202.5/builds/236 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Colton': Jan Build Source Stamp: [branch Houston] Gael Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sat Feb 17 03:04:17 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 17 Feb 2007 02:04:17 +0000 Subject: [Python-checkins] buildbot failure in x86 gentoo 2.5 Message-ID: <20070217020418.159521E4014@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/235 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Mauricio': Terrence Build Source Stamp: [branch Robert] Estevan Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sat Feb 17 03:21:52 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 17 Feb 2007 02:21:52 +0000 Subject: [Python-checkins] buildbot failure in g4 osx.4 2.5 Message-ID: <20070217022153.0F7F71E400B@bag.python.org> The Buildbot has detected a new failure of g4 osx.4 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/g4%2520osx.4%25202.5/builds/221 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Desmond': Keenan Build Source Stamp: [branch Dandre] Stacey Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sat Feb 17 03:23:57 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 17 Feb 2007 02:23:57 +0000 Subject: [Python-checkins] buildbot failure in sparc solaris10 gcc 2.5 Message-ID: <20070217022357.5CAF91E400B@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%25202.5/builds/228 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Titus': Griffin Build Source Stamp: [branch Addison] Branden Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sat Feb 17 03:29:46 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 17 Feb 2007 02:29:46 +0000 Subject: [Python-checkins] buildbot failure in x86 XP 2.5 Message-ID: <20070217022946.DD0371E400B@bag.python.org> The Buildbot has detected a new failure of x86 XP 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%25202.5/builds/120 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Rhett': Cedric Build Source Stamp: [branch Jett] Karl Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Sat Feb 17 14:29:00 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 17 Feb 2007 13:29:00 +0000 Subject: [Python-checkins] buildbot failure in x86 cygwin 2.5 Message-ID: <20070217132901.2AC701E4014@bag.python.org> The Buildbot has detected a new failure of x86 cygwin 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520cygwin%25202.5/builds/11 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: georg.brandl,vinay.sajip BUILD FAILED: failed failed slave lost sincerely, -The Buildbot From python-checkins at python.org Sat Feb 17 18:53:46 2007 From: python-checkins at python.org (phillip.eby) Date: Sat, 17 Feb 2007 18:53:46 +0100 (CET) Subject: [Python-checkins] r53813 - sandbox/trunk/setuptools/setuptools/command/easy_install.py Message-ID: <20070217175346.6A8831E400C@bag.python.org> Author: phillip.eby Date: Sat Feb 17 18:53:45 2007 New Revision: 53813 Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py Log: Fix error if script contains null byte. Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/easy_install.py (original) +++ sandbox/trunk/setuptools/setuptools/command/easy_install.py Sat Feb 17 18:53:45 2007 @@ -1460,7 +1460,7 @@ "Is this string a valid Python script?" try: compile(text, filename, 'exec') - except SyntaxError: + except (SyntaxError, TypeError): return False else: return True From python-checkins at python.org Sat Feb 17 18:55:44 2007 From: python-checkins at python.org (phillip.eby) Date: Sat, 17 Feb 2007 18:55:44 +0100 (CET) Subject: [Python-checkins] r53814 - sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Message-ID: <20070217175544.3D25D1E4028@bag.python.org> Author: phillip.eby Date: Sat Feb 17 18:55:43 2007 New Revision: 53814 Modified: sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Log: Fix error if script contains null byte. (backport from trunk) Modified: sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Sat Feb 17 18:55:43 2007 @@ -1460,7 +1460,7 @@ "Is this string a valid Python script?" try: compile(text, filename, 'exec') - except SyntaxError: + except (SyntaxError, TypeError): return False else: return True From python-checkins at python.org Sat Feb 17 19:42:39 2007 From: python-checkins at python.org (georg.brandl) Date: Sat, 17 Feb 2007 19:42:39 +0100 (CET) Subject: [Python-checkins] r53815 - peps/trunk/pep-0000.txt peps/trunk/pep-0226.txt peps/trunk/pep-0328.txt peps/trunk/pep-3102.txt peps/trunk/pep-3105.txt peps/trunk/pep-3106.txt peps/trunk/pep-3107.txt peps/trunk/pep-3109.txt peps/trunk/pep-3110.txt Message-ID: <20070217184239.7CCE11E400C@bag.python.org> Author: georg.brandl Date: Sat Feb 17 19:42:37 2007 New Revision: 53815 Modified: peps/trunk/pep-0000.txt peps/trunk/pep-0226.txt peps/trunk/pep-0328.txt peps/trunk/pep-3102.txt peps/trunk/pep-3105.txt peps/trunk/pep-3106.txt peps/trunk/pep-3107.txt peps/trunk/pep-3109.txt peps/trunk/pep-3110.txt Log: Mark diverse Py3000 PEPs as accepted, mark PEPs 328 and 3105 as Final. Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Sat Feb 17 19:42:37 2007 @@ -54,14 +54,20 @@ I 42 Feature Requests Hylton I 101 Doing Python Releases 101 Warsaw, GvR I 102 Doing Python Micro Releases Baxter, Warsaw, GvR + IF 160 Python 1.6 Release Schedule Drake + IF 200 Python 2.0 Release Schedule Hylton + IF 226 Python 2.1 Release Schedule Hylton IF 247 API for Cryptographic Hash Functions Kuchling IF 248 Python Database API Specification v1.0 Lemburg IF 249 Python Database API Specification v2.0 Lemburg + IF 251 Python 2.2 Release Schedule Warsaw, GvR I 257 Docstring Conventions Goodger, GvR IF 272 API for Block Encryption Algorithms v1.0 Kuchling + IF 283 Python 2.3 Release Schedule GvR I 290 Code Migration and Modernization Hettinger I 291 Backward Compatibility for Standard Library Norwitz I 306 How to Change Python's Grammar Hudson + IF 320 Python 2.4 Release Schedule Warsaw, et al I 333 Python Web Server Gateway Interface v1.0 Eby I 339 Design of the CPython Compiler Cannon IF 356 Python 2.5 Release Schedule Norwitz, et al @@ -71,7 +77,11 @@ Accepted PEPs (accepted; may not be implemented yet) - SA 328 Imports: Multi-Line and Absolute/Relative Aahz + SA 3102 Keyword-Only Arguments Talin + SA 3106 Revamping dict.keys(), .values() and .items() GvR + SA 3107 Function Annotations Winter, Lownds + SA 3109 Raising Exceptions in Python 3000 Winter + SA 3110 Catching Exceptions in Python 3000 Winter Open PEPs (under consideration) @@ -101,21 +111,13 @@ S 363 Syntax For Dynamic Attribute Access North S 754 IEEE 754 Floating Point Special Values Warnes S 3101 Advanced String Formatting Talin - S 3102 Keyword-Only Arguments Talin S 3103 A Switch/Case Statement GvR S 3104 Access to Names in Outer Scopes Yee - S 3105 Make print a function Brandl - S 3106 Revamping dict.keys(), .values() and .items() GvR - S 3107 Function Annotations Winter, Lownds I 3108 Standard Library Reorganization Cannon - S 3109 Raising Exceptions in Python 3000 Winter - S 3110 Catching Exceptions in Python 3000 Winter Finished PEPs (done, implemented in Subversion) SF 100 Python Unicode Integration Lemburg - IF 160 Python 1.6 Release Schedule Drake - IF 200 Python 2.0 Release Schedule Hylton SF 201 Lockstep Iteration Warsaw SF 202 List Comprehensions Warsaw SF 203 Augmented Assignments Wouters @@ -127,7 +129,6 @@ SF 218 Adding a Built-In Set Object Type Wilson, Hettinger SF 221 Import As Wouters SF 223 Change the Meaning of \x Escapes Peters - I 226 Python 2.1 Release Schedule Hylton S 227 Statically Nested Scopes Hylton SF 229 Using Distutils to Build Python Kuchling SF 230 Warning Framework GvR @@ -138,7 +139,6 @@ SF 238 Changing the Division Operator Zadka, GvR SF 241 Metadata for Python Software Packages Kuchling SF 250 Using site-packages on Windows Moore - IF 251 Python 2.2 Release Schedule Warsaw, GvR SF 252 Making Types Look More Like Classes GvR SF 253 Subtyping Built-in Types GvR SF 255 Simple Generators Schemenauer, et al @@ -151,7 +151,6 @@ SF 278 Universal Newline Support Jansen SF 279 The enumerate() built-in function Hettinger SF 282 A Logging System Sajip, Mick - IF 283 Python 2.3 Release Schedule GvR SF 285 Adding a bool type GvR SF 289 Generator Expressions Hettinger SF 292 Simpler String Substitutions Warsaw @@ -164,10 +163,10 @@ SF 311 Simplified GIL Acquisition for Extensions Hammond SF 314 Metadata for Python Software Packages v1.1 Kuchling, Jones SF 318 Decorators for Functions and Methods Smith, et al - IF 320 Python 2.4 Release Schedule Warsaw, et al SF 322 Reverse Iteration Hettinger SF 324 subprocess - New process module Astrand SF 327 Decimal Data Type Batista + SF 328 Imports: Multi-Line and Absolute/Relative Aahz SF 338 Executing Modules as Scripts Coghlan SF 341 Unifying try-except and try-finally Brandl SF 342 Coroutines via Enhanced Generators GvR, Eby @@ -175,6 +174,7 @@ SF 352 Required Superclass for Exceptions GvR, Cannon SF 353 Using ssize_t as the index type von Loewis SF 357 Allowing Any Object to be Used for Slicing Oliphant + SF 3105 Make print a function Brandl Empty PEPs (or containing only an abstract) @@ -299,7 +299,7 @@ SF 223 Change the Meaning of \x Escapes Peters SR 224 Attribute Docstrings Lemburg SD 225 Elementwise/Objectwise Operators Zhu, Lielens - I 226 Python 2.1 Release Schedule Hylton + IF 226 Python 2.1 Release Schedule Hylton S 227 Statically Nested Scopes Hylton S 228 Reworking Python's Numeric Model Zadka, GvR SF 229 Using Distutils to Build Python Kuchling @@ -400,7 +400,7 @@ SR 325 Resource-Release Support for Generators Pedroni SR 326 A Case for Top and Bottom Values Carlson, Reedy SF 327 Decimal Data Type Batista - SA 328 Imports: Multi-Line and Absolute/Relative Aahz + SF 328 Imports: Multi-Line and Absolute/Relative Aahz SR 329 Treating Builtins as Constants in the Standard Library Hettinger SR 330 Python Bytecode Verification Pelletier S 331 Locale-Independent Float/String Conversions Reis @@ -444,15 +444,15 @@ I 3099 Things that will Not Change in Python 3000 Brandl I 3100 Python 3.0 Plans Kuchling, Cannon S 3101 Advanced String Formatting Talin - S 3102 Keyword-Only Arguments Talin + SA 3102 Keyword-Only Arguments Talin S 3103 A Switch/Case Statement GvR S 3104 Access to Names in Outer Scopes Yee - S 3105 Make print a function Brandl - S 3106 Revamping dict.keys(), .values() and .items() GvR - S 3107 Function Annotations Winter, Lownds + SF 3105 Make print a function Brandl + SA 3106 Revamping dict.keys(), .values() and .items() GvR + SA 3107 Function Annotations Winter, Lownds I 3108 Standard Library Reorganization Cannon - S 3109 Raising Exceptions in Python 3000 Winter - S 3110 Catching Exceptions in Python 3000 Winter + SA 3109 Raising Exceptions in Python 3000 Winter + SA 3110 Catching Exceptions in Python 3000 Winter Key Modified: peps/trunk/pep-0226.txt ============================================================================== --- peps/trunk/pep-0226.txt (original) +++ peps/trunk/pep-0226.txt Sat Feb 17 19:42:37 2007 @@ -3,7 +3,7 @@ Version: $Revision$ Last-Modified: $Date$ Author: Jeremy Hylton -Status: Incomplete +Status: Final Type: Informational Created: 16-Oct-2000 Python-Version: 2.1 Modified: peps/trunk/pep-0328.txt ============================================================================== --- peps/trunk/pep-0328.txt (original) +++ peps/trunk/pep-0328.txt Sat Feb 17 19:42:37 2007 @@ -3,7 +3,7 @@ Version: $Revision$ Last-Modified: $Date$ Author: Aahz -Status: Accepted +Status: Final Type: Standards Track Python-Version: 2.4, 2,5, 2.6, 2.7 Content-Type: text/x-rst @@ -268,7 +268,7 @@ Relative Imports and __name__ -=============================== +============================= Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does Modified: peps/trunk/pep-3102.txt ============================================================================== --- peps/trunk/pep-3102.txt (original) +++ peps/trunk/pep-3102.txt Sat Feb 17 19:42:37 2007 @@ -3,7 +3,7 @@ Version: $Revision$ Last-Modified: $Date$ Author: Talin -Status: Draft +Status: Accepted Type: Standards Content-Type: text/plain Created: 22-Apr-2006 Modified: peps/trunk/pep-3105.txt ============================================================================== --- peps/trunk/pep-3105.txt (original) +++ peps/trunk/pep-3105.txt Sat Feb 17 19:42:37 2007 @@ -3,7 +3,7 @@ Version: $Revision$ Last-Modified: $Date$ Author: Georg Brandl -Status: Draft +Status: Final Type: Standards Content-Type: text/x-rst Created: 19-Nov-2006 @@ -102,6 +102,15 @@ mentioned tool). +Implementation +============== + +The proposed changes were implemented in the Python 3000 branch in the +Subversion revisions 53685 to 53704. Most of the legacy code in the +library has been converted too, but it is an ongoing effort to catch +every print statement that may be left in the distribution. + + References ========== Modified: peps/trunk/pep-3106.txt ============================================================================== --- peps/trunk/pep-3106.txt (original) +++ peps/trunk/pep-3106.txt Sat Feb 17 19:42:37 2007 @@ -3,7 +3,7 @@ Version: $Revision$ Last-Modified: $Date$ Author: Guido van Rossum -Status: Draft +Status: Accepted Type: Standards Content-Type: text/x-rst Created: 19-Dec-2006 Modified: peps/trunk/pep-3107.txt ============================================================================== --- peps/trunk/pep-3107.txt (original) +++ peps/trunk/pep-3107.txt Sat Feb 17 19:42:37 2007 @@ -4,7 +4,7 @@ Last-Modified: $Date$ Author: Collin Winter , Tony Lownds -Status: Draft +Status: Accepted Type: Standards Track Requires: 362 Content-Type: text/x-rst Modified: peps/trunk/pep-3109.txt ============================================================================== --- peps/trunk/pep-3109.txt (original) +++ peps/trunk/pep-3109.txt Sat Feb 17 19:42:37 2007 @@ -3,7 +3,7 @@ Version: $Revision$ Last-Modified: $Date$ Author: Collin Winter -Status: Draft +Status: Accepted Type: Standards Track Content-Type: text/x-rst Created: 19-Jan-2006 Modified: peps/trunk/pep-3110.txt ============================================================================== --- peps/trunk/pep-3110.txt (original) +++ peps/trunk/pep-3110.txt Sat Feb 17 19:42:37 2007 @@ -3,7 +3,7 @@ Version: $Revision$ Last-Modified: $Date$ Author: Collin Winter -Status: Draft +Status: Accepted Type: Standards Track Content-Type: text/x-rst Created: 16-Jan-2006 From python-checkins at python.org Sun Feb 18 09:50:39 2007 From: python-checkins at python.org (martin.v.loewis) Date: Sun, 18 Feb 2007 09:50:39 +0100 (CET) Subject: [Python-checkins] r53816 - in python/branches/release25-maint: Misc/NEWS Modules/datetimemodule.c Message-ID: <20070218085039.D2EB51E4006@bag.python.org> Author: martin.v.loewis Date: Sun Feb 18 09:50:38 2007 New Revision: 53816 Modified: python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Modules/datetimemodule.c Log: Revert r53672, just fix signature of time_isoformat instead. Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Sun Feb 18 09:50:38 2007 @@ -111,7 +111,7 @@ - Patch #1657276: Make NETLINK_DNRTMSG conditional. -- Bug #1653736: Complain about keyword arguments to time.isoformat. +- Bug #1653736: Fix signature of time_isoformat. - operator.count() now raises an OverflowError when the count reaches sys.maxint. Modified: python/branches/release25-maint/Modules/datetimemodule.c ============================================================================== --- python/branches/release25-maint/Modules/datetimemodule.c (original) +++ python/branches/release25-maint/Modules/datetimemodule.c Sun Feb 18 09:50:38 2007 @@ -3166,8 +3166,11 @@ return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); } +/* Even though this silently ignores all arguments, it cannot + be fixed to reject them in release25-maint */ static PyObject * -time_isoformat(PyDateTime_Time *self, PyObject *unused) +time_isoformat(PyDateTime_Time *self, PyObject *unused_args, + PyObject *unused_keywords) { char buf[100]; PyObject *result; @@ -3411,7 +3414,7 @@ static PyMethodDef time_methods[] = { - {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, + {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" "[+HH:MM].")}, From python-checkins at python.org Sun Feb 18 09:54:33 2007 From: python-checkins at python.org (martin.v.loewis) Date: Sun, 18 Feb 2007 09:54:33 +0100 (CET) Subject: [Python-checkins] r53817 - python/branches/release25-maint/Lib/test/test_datetime.py Message-ID: <20070218085433.694F41E4006@bag.python.org> Author: martin.v.loewis Date: Sun Feb 18 09:54:32 2007 New Revision: 53817 Modified: python/branches/release25-maint/Lib/test/test_datetime.py Log: Revert r53672. Modified: python/branches/release25-maint/Lib/test/test_datetime.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_datetime.py (original) +++ python/branches/release25-maint/Lib/test/test_datetime.py Sun Feb 18 09:54:32 2007 @@ -1740,11 +1740,6 @@ self.assertEqual(t.isoformat(), "00:00:00.100000") self.assertEqual(t.isoformat(), str(t)) - def test_1653736(self): - # verify it doesn't accept extra keyword arguments - t = self.theclass(second=1) - self.assertRaises(TypeError, t.isoformat, foo=3) - def test_strftime(self): t = self.theclass(1, 2, 3, 4) self.assertEqual(t.strftime('%H %M %S'), "01 02 03") From buildbot at python.org Sun Feb 18 10:23:11 2007 From: buildbot at python.org (buildbot at python.org) Date: Sun, 18 Feb 2007 09:23:11 +0000 Subject: [Python-checkins] buildbot warnings in amd64 gentoo 2.5 Message-ID: <20070218092311.B81991E4006@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%25202.5/builds/238 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket_ssl make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Sun Feb 18 10:31:32 2007 From: buildbot at python.org (buildbot at python.org) Date: Sun, 18 Feb 2007 09:31:32 +0000 Subject: [Python-checkins] buildbot warnings in x86 gentoo 2.5 Message-ID: <20070218093132.A633B1E4006@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/237 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: martin.v.loewis Build had warnings: warnings test Excerpt from the test logfile: Traceback (most recent call last): File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30996, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') 1 test failed: test_socket_ssl make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Mon Feb 19 03:03:23 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 03:03:23 +0100 (CET) Subject: [Python-checkins] r53818 - in python/trunk: Include/dictobject.h Lib/test/test_set.py Objects/dictobject.c Objects/setobject.c Message-ID: <20070219020323.8E0311E4006@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 03:03:19 2007 New Revision: 53818 Modified: python/trunk/Include/dictobject.h python/trunk/Lib/test/test_set.py python/trunk/Objects/dictobject.c python/trunk/Objects/setobject.c Log: Extend work on revision 52962: Eliminate redundant calls to PyObject_Hash(). Modified: python/trunk/Include/dictobject.h ============================================================================== --- python/trunk/Include/dictobject.h (original) +++ python/trunk/Include/dictobject.h Mon Feb 19 03:03:19 2007 @@ -100,12 +100,15 @@ PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); PyAPI_FUNC(int) PyDict_Next( PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); +PyAPI_FUNC(int) _PyDict_Next( + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp); PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp); PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key); +PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, long hash); /* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */ PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other); Modified: python/trunk/Lib/test/test_set.py ============================================================================== --- python/trunk/Lib/test/test_set.py (original) +++ python/trunk/Lib/test/test_set.py Mon Feb 19 03:03:19 2007 @@ -26,6 +26,14 @@ def __repr__(self): return repr(self.value) +class HashCountingInt(int): + 'int-like object that counts the number of times __hash__ is called' + def __init__(self, *args): + self.hash_count = 0 + def __hash__(self): + self.hash_count += 1 + return int.__hash__(self) + class TestJointOps(unittest.TestCase): # Tests common to both set and frozenset @@ -270,6 +278,18 @@ fo.close() os.remove(test_support.TESTFN) + def test_do_not_rehash_dict_keys(self): + n = 10 + d = dict.fromkeys(map(HashCountingInt, xrange(n))) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s = self.thetype(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s.difference(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + if hasattr(s, 'symmetric_difference_update'): + s.symmetric_difference_update(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + class TestSet(TestJointOps): thetype = set Modified: python/trunk/Objects/dictobject.c ============================================================================== --- python/trunk/Objects/dictobject.c (original) +++ python/trunk/Objects/dictobject.c Mon Feb 19 03:03:19 2007 @@ -803,6 +803,34 @@ return 1; } +/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/ +int +_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash) +{ + register Py_ssize_t i; + register Py_ssize_t mask; + register dictentry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((dictobject *)op)->ma_table; + mask = ((dictobject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + *phash = (long)(ep[i].me_hash); + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; +} + /* Methods */ static void @@ -1987,6 +2015,17 @@ return ep == NULL ? -1 : (ep->me_value != NULL); } +/* Internal version of PyDict_Contains used when the hash value is already known */ +int +_PyDict_Contains(PyObject *op, PyObject *key, long hash) +{ + dictobject *mp = (dictobject *)op; + dictentry *ep; + + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); +} + /* Hack to implement "key in dict" */ static PySequenceMethods dict_as_sequence = { 0, /* sq_length */ Modified: python/trunk/Objects/setobject.c ============================================================================== --- python/trunk/Objects/setobject.c (original) +++ python/trunk/Objects/setobject.c Mon Feb 19 03:03:19 2007 @@ -918,8 +918,14 @@ if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; - while (PyDict_Next(other, &pos, &key, &value)) { - if (set_add_key(so, key) == -1) + long hash; + + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { + setentry an_entry; + + an_entry.hash = hash; + an_entry.key = key; + if (set_add_entry(so, &an_entry) == -1) return -1; } return 0; @@ -1382,7 +1388,7 @@ setentry entrycopy; entrycopy.hash = entry->hash; entrycopy.key = entry->key; - if (!PyDict_Contains(other, entry->key)) { + if (!_PyDict_Contains(other, entry->key, entry->hash)) { if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { Py_DECREF(result); return NULL; @@ -1453,12 +1459,10 @@ if (PyDict_CheckExact(other)) { PyObject *value; int rv; - while (PyDict_Next(other, &pos, &key, &value)) { + long hash; + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { setentry an_entry; - long hash = PyObject_Hash(key); - if (hash == -1) - return NULL; an_entry.hash = hash; an_entry.key = key; rv = set_discard_entry(so, &an_entry); From python-checkins at python.org Mon Feb 19 04:04:46 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 04:04:46 +0100 (CET) Subject: [Python-checkins] r53819 - in python/branches/release25-maint: Include/dictobject.h Lib/test/test_set.py Objects/dictobject.c Objects/setobject.c Message-ID: <20070219030446.E2A361E4006@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 04:04:45 2007 New Revision: 53819 Modified: python/branches/release25-maint/Include/dictobject.h python/branches/release25-maint/Lib/test/test_set.py python/branches/release25-maint/Objects/dictobject.c python/branches/release25-maint/Objects/setobject.c Log: Extend work on revision 52962: Eliminate redundant calls to PyObject_Hash(). Modified: python/branches/release25-maint/Include/dictobject.h ============================================================================== --- python/branches/release25-maint/Include/dictobject.h (original) +++ python/branches/release25-maint/Include/dictobject.h Mon Feb 19 04:04:45 2007 @@ -100,12 +100,15 @@ PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); PyAPI_FUNC(int) PyDict_Next( PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); +PyAPI_FUNC(int) _PyDict_Next( + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp); PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp); PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key); +PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, long hash); /* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */ PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other); Modified: python/branches/release25-maint/Lib/test/test_set.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_set.py (original) +++ python/branches/release25-maint/Lib/test/test_set.py Mon Feb 19 04:04:45 2007 @@ -26,6 +26,14 @@ def __repr__(self): return repr(self.value) +class HashCountingInt(int): + 'int-like object that counts the number of times __hash__ is called' + def __init__(self, *args): + self.hash_count = 0 + def __hash__(self): + self.hash_count += 1 + return int.__hash__(self) + class TestJointOps(unittest.TestCase): # Tests common to both set and frozenset @@ -270,6 +278,18 @@ fo.close() os.remove(test_support.TESTFN) + def test_do_not_rehash_dict_keys(self): + n = 10 + d = dict.fromkeys(map(HashCountingInt, xrange(n))) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s = self.thetype(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s.difference(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + if hasattr(s, 'symmetric_difference_update'): + s.symmetric_difference_update(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + class TestSet(TestJointOps): thetype = set Modified: python/branches/release25-maint/Objects/dictobject.c ============================================================================== --- python/branches/release25-maint/Objects/dictobject.c (original) +++ python/branches/release25-maint/Objects/dictobject.c Mon Feb 19 04:04:45 2007 @@ -803,6 +803,34 @@ return 1; } +/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/ +int +_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash) +{ + register Py_ssize_t i; + register Py_ssize_t mask; + register dictentry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((dictobject *)op)->ma_table; + mask = ((dictobject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + *phash = (long)(ep[i].me_hash); + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; +} + /* Methods */ static void @@ -1987,6 +2015,17 @@ return ep == NULL ? -1 : (ep->me_value != NULL); } +/* Internal version of PyDict_Contains used when the hash value is already known */ +int +_PyDict_Contains(PyObject *op, PyObject *key, long hash) +{ + dictobject *mp = (dictobject *)op; + dictentry *ep; + + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); +} + /* Hack to implement "key in dict" */ static PySequenceMethods dict_as_sequence = { 0, /* sq_length */ Modified: python/branches/release25-maint/Objects/setobject.c ============================================================================== --- python/branches/release25-maint/Objects/setobject.c (original) +++ python/branches/release25-maint/Objects/setobject.c Mon Feb 19 04:04:45 2007 @@ -918,8 +918,14 @@ if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; - while (PyDict_Next(other, &pos, &key, &value)) { - if (set_add_key(so, key) == -1) + long hash; + + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { + setentry an_entry; + + an_entry.hash = hash; + an_entry.key = key; + if (set_add_entry(so, &an_entry) == -1) return -1; } return 0; @@ -1382,7 +1388,7 @@ setentry entrycopy; entrycopy.hash = entry->hash; entrycopy.key = entry->key; - if (!PyDict_Contains(other, entry->key)) { + if (!_PyDict_Contains(other, entry->key, entry->hash)) { if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { Py_DECREF(result); return NULL; @@ -1453,12 +1459,10 @@ if (PyDict_CheckExact(other)) { PyObject *value; int rv; - while (PyDict_Next(other, &pos, &key, &value)) { + long hash; + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { setentry an_entry; - long hash = PyObject_Hash(key); - if (hash == -1) - return NULL; an_entry.hash = hash; an_entry.key = key; rv = set_discard_entry(so, &an_entry); From python-checkins at python.org Mon Feb 19 05:08:48 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 05:08:48 +0100 (CET) Subject: [Python-checkins] r53820 - in python/trunk: Doc/lib/libheapq.tex Lib/heapq.py Lib/test/test_heapq.py Misc/NEWS Message-ID: <20070219040848.0FFCE1E4006@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 05:08:43 2007 New Revision: 53820 Modified: python/trunk/Doc/lib/libheapq.tex python/trunk/Lib/heapq.py python/trunk/Lib/test/test_heapq.py python/trunk/Misc/NEWS Log: Add merge() function to heapq. Modified: python/trunk/Doc/lib/libheapq.tex ============================================================================== --- python/trunk/Doc/lib/libheapq.tex (original) +++ python/trunk/Doc/lib/libheapq.tex Mon Feb 19 05:08:43 2007 @@ -88,7 +88,18 @@ >>> \end{verbatim} -The module also offers two general purpose functions based on heaps. +The module also offers three general purpose functions based on heaps. + +\begin{funcdesc}{merge}{*iterables} +Merge multiple sorted inputs into a single sorted output (for example, merge +timestamped entries from multiple log files). Returns an iterator over +over the sorted values. + +Similar to \code{sorted(itertools.chain(*iterables))} but returns an iterable, +does not pull the data into memory all at once, and reduces the number of +comparisons by assuming that each of the input streams is already sorted. +\versionadded{2.6} +\end{funcdesc} \begin{funcdesc}{nlargest}{n, iterable\optional{, key}} Return a list with the \var{n} largest elements from the dataset defined @@ -110,7 +121,7 @@ \versionchanged[Added the optional \var{key} argument]{2.5} \end{funcdesc} -Both functions perform best for smaller values of \var{n}. For larger +The latter two functions perform best for smaller values of \var{n}. For larger values, it is more efficient to use the \function{sorted()} function. Also, when \code{n==1}, it is more efficient to use the builtin \function{min()} and \function{max()} functions. Modified: python/trunk/Lib/heapq.py ============================================================================== --- python/trunk/Lib/heapq.py (original) +++ python/trunk/Lib/heapq.py Mon Feb 19 05:08:43 2007 @@ -126,8 +126,8 @@ From all times, sorting has always been a Great Art! :-) """ -__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'nlargest', - 'nsmallest'] +__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', + 'nlargest', 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee from operator import itemgetter, neg @@ -308,6 +308,41 @@ except ImportError: pass +def merge(*iterables): + '''Merge multiple sorted inputs into a single sorted output. + + Similar to sorted(itertools.chain(*iterables)) but returns an iterable, + does not pull the data into memory all at once, and reduces the number + of comparisons by assuming that each of the input streams is already sorted. + + >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) + [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] + + ''' + _heappop, siftup, _StopIteration = heappop, _siftup, StopIteration + + h = [] + h_append = h.append + for it in map(iter, iterables): + try: + next = it.next + h_append([next(), next]) + except _StopIteration: + pass + heapify(h) + + while 1: + try: + while 1: + v, next = s = h[0] # raises IndexError when h is empty + yield v + s[0] = next() # raises StopIteration when exhausted + siftup(h, 0) # restore heap condition + except _StopIteration: + _heappop(h) # remove empty iterator + except IndexError: + return + # Extend the implementations of nsmallest and nlargest to use a key= argument _nsmallest = nsmallest def nsmallest(n, iterable, key=None): @@ -341,3 +376,6 @@ while heap: sort.append(heappop(heap)) print sort + + import doctest + doctest.testmod() Modified: python/trunk/Lib/test/test_heapq.py ============================================================================== --- python/trunk/Lib/test/test_heapq.py (original) +++ python/trunk/Lib/test/test_heapq.py Mon Feb 19 05:08:43 2007 @@ -1,6 +1,6 @@ """Unittests for heapq.""" -from heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest +from heapq import heappush, heappop, heapify, heapreplace, merge, nlargest, nsmallest import random import unittest from test import test_support @@ -103,6 +103,14 @@ heap_sorted = [heappop(heap) for i in range(size)] self.assertEqual(heap_sorted, sorted(data)) + def test_merge(self): + inputs = [] + for i in xrange(random.randrange(5)): + row = sorted(random.randrange(1000) for j in range(random.randrange(10))) + inputs.append(row) + self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs))) + self.assertEqual(list(merge()), []) + def test_nsmallest(self): data = [(random.randrange(2000), i) for i in range(1000)] for f in (None, lambda x: x[0] * 547 % 2000): Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon Feb 19 05:08:43 2007 @@ -128,6 +128,8 @@ Library ------- +- Added heapq.merge() for merging sorted input streams. + - Have the encoding package's search function dynamically import using absolute import semantics. From python-checkins at python.org Mon Feb 19 06:28:34 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 06:28:34 +0100 (CET) Subject: [Python-checkins] r53821 - python/trunk/Lib/heapq.py Message-ID: <20070219052834.418491E4006@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 06:28:28 2007 New Revision: 53821 Modified: python/trunk/Lib/heapq.py Log: Add tie-breaker count to preserve sort stability. Modified: python/trunk/Lib/heapq.py ============================================================================== --- python/trunk/Lib/heapq.py (original) +++ python/trunk/Lib/heapq.py Mon Feb 19 06:28:28 2007 @@ -323,10 +323,10 @@ h = [] h_append = h.append - for it in map(iter, iterables): + for itnum, it in enumerate(map(iter, iterables)): try: next = it.next - h_append([next(), next]) + h_append([next(), itnum, next]) except _StopIteration: pass heapify(h) @@ -334,12 +334,12 @@ while 1: try: while 1: - v, next = s = h[0] # raises IndexError when h is empty + v, itnum, next = s = h[0] # raises IndexError when h is empty yield v - s[0] = next() # raises StopIteration when exhausted - siftup(h, 0) # restore heap condition + s[0] = next() # raises StopIteration when exhausted + siftup(h, 0) # restore heap condition except _StopIteration: - _heappop(h) # remove empty iterator + _heappop(h) # remove empty iterator except IndexError: return From buildbot at python.org Mon Feb 19 07:40:25 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 19 Feb 2007 06:40:25 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) trunk Message-ID: <20070219064025.EA6921E400C@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%2520trunk/builds/1197 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout sincerely, -The Buildbot From python-checkins at python.org Mon Feb 19 07:59:32 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 07:59:32 +0100 (CET) Subject: [Python-checkins] r53822 - python/trunk/Lib/heapq.py Message-ID: <20070219065932.BAEB31E4006@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 07:59:32 2007 New Revision: 53822 Modified: python/trunk/Lib/heapq.py Log: Use C heapreplace() instead of slower _siftup() in pure python. Modified: python/trunk/Lib/heapq.py ============================================================================== --- python/trunk/Lib/heapq.py (original) +++ python/trunk/Lib/heapq.py Mon Feb 19 07:59:32 2007 @@ -319,7 +319,7 @@ [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] ''' - _heappop, siftup, _StopIteration = heappop, _siftup, StopIteration + _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration h = [] h_append = h.append @@ -337,7 +337,7 @@ v, itnum, next = s = h[0] # raises IndexError when h is empty yield v s[0] = next() # raises StopIteration when exhausted - siftup(h, 0) # restore heap condition + _heapreplace(h, s) # restore heap condition except _StopIteration: _heappop(h) # remove empty iterator except IndexError: From python-checkins at python.org Mon Feb 19 08:30:21 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 08:30:21 +0100 (CET) Subject: [Python-checkins] r53823 - python/trunk/Lib/test/test_heapq.py Message-ID: <20070219073021.ED1071E4006@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 08:30:21 2007 New Revision: 53823 Modified: python/trunk/Lib/test/test_heapq.py Log: Add test for merge stability Modified: python/trunk/Lib/test/test_heapq.py ============================================================================== --- python/trunk/Lib/test/test_heapq.py (original) +++ python/trunk/Lib/test/test_heapq.py Mon Feb 19 08:30:21 2007 @@ -111,6 +111,21 @@ self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs))) self.assertEqual(list(merge()), []) + def test_merge_stability(self): + class Int(int): + pass + inputs = [[], [], [], []] + for i in range(20000): + stream = random.randrange(4) + x = random.randrange(500) + obj = Int(x) + obj.pair = (x, stream) + inputs[stream].append(obj) + for stream in inputs: + stream.sort() + result = [i.pair for i in merge(*inputs)] + self.assertEqual(result, sorted(result)) + def test_nsmallest(self): data = [(random.randrange(2000), i) for i in range(1000)] for f in (None, lambda x: x[0] * 547 % 2000): From buildbot at python.org Mon Feb 19 09:11:15 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 19 Feb 2007 08:11:15 +0000 Subject: [Python-checkins] buildbot warnings in ppc Debian unstable trunk Message-ID: <20070219081115.7EC1D1E401B@bag.python.org> The Buildbot has detected a new failure of ppc Debian unstable trunk. Full details are available at: http://www.python.org/dev/buildbot/all/ppc%2520Debian%2520unstable%2520trunk/builds/84 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Mon Feb 19 09:14:33 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 19 Feb 2007 08:14:33 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian trunk Message-ID: <20070219081433.F39551E4006@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%2520trunk/builds/83 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_timeout make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Mon Feb 19 10:14:10 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 10:14:10 +0100 (CET) Subject: [Python-checkins] r53824 - python/trunk/Doc/lib/libcollections.tex Message-ID: <20070219091410.002D61E4006@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 10:14:10 2007 New Revision: 53824 Modified: python/trunk/Doc/lib/libcollections.tex Log: Provide an example of defaultdict with non-zero constant factory function. Modified: python/trunk/Doc/lib/libcollections.tex ============================================================================== --- python/trunk/Doc/lib/libcollections.tex (original) +++ python/trunk/Doc/lib/libcollections.tex Mon Feb 19 10:14:10 2007 @@ -311,16 +311,20 @@ When a letter is first encountered, it is missing from the mapping, so the \member{default_factory} function calls \function{int()} to supply a default count of zero. The increment operation then builds up the count for each -letter. This technique makes counting simpler and faster than an equivalent -technique using \method{dict.get()}: +letter. -\begin{verbatim} ->>> d = {} ->>> for k in s: - d[k] = d.get(k, 0) + 1 +The function \function{int()} which always returns zero is just a special +case of constant functions. A faster and more flexible way to create +constant functions is to use \function{itertools.repeat()} which can supply +any constant value (not just zero): ->>> d.items() -[('i', 4), ('p', 2), ('s', 4), ('m', 1)] +\begin{verbatim} +>>> def constant_factory(value): +... return itertools.repeat(value).next +>>> d = defaultdict(constant_factory('')) +>>> d.update(name='John', action='ran') +>>> '%(name)s %(action)s to %(object)s' % d +'John ran to ' \end{verbatim} Setting the \member{default_factory} to \class{set} makes the From python-checkins at python.org Mon Feb 19 10:54:49 2007 From: python-checkins at python.org (lars.gustaebel) Date: Mon, 19 Feb 2007 10:54:49 +0100 (CET) Subject: [Python-checkins] r53825 - python/trunk/Misc/NEWS Message-ID: <20070219095449.C2B971E4006@bag.python.org> Author: lars.gustaebel Date: Mon Feb 19 10:54:47 2007 New Revision: 53825 Modified: python/trunk/Misc/NEWS Log: Moved misplaced news item. Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon Feb 19 10:54:47 2007 @@ -26,9 +26,6 @@ - patch #1630975: Fix crash when replacing sys.stdout in sitecustomize.py -- Patch #1507247: tarfile.py: use current umask for intermediate - directories. - - Bug #1637022: Prefix AST symbols with _Py_. - Prevent seg fault on shutdown which could occur if an object @@ -167,6 +164,9 @@ - Patch #1643874: memory leak in ctypes fixed. +- Patch #1507247: tarfile.py: use current umask for intermediate + directories. + - Patch #1627441: close sockets properly in urllib2. - Bug #494589: make ntpath.expandvars behave according to its docstring. From python-checkins at python.org Mon Feb 19 11:55:33 2007 From: python-checkins at python.org (martin.v.loewis) Date: Mon, 19 Feb 2007 11:55:33 +0100 (CET) Subject: [Python-checkins] r53826 - in python/trunk: Doc/lib/libos.tex Doc/lib/libshutil.tex Lib/shutil.py Lib/stat.py Lib/test/test_posix.py Misc/ACKS Misc/NEWS Modules/posixmodule.c configure configure.in pyconfig.h.in Message-ID: <20070219105533.EB7D41E4006@bag.python.org> Author: martin.v.loewis Date: Mon Feb 19 11:55:19 2007 New Revision: 53826 Modified: python/trunk/Doc/lib/libos.tex python/trunk/Doc/lib/libshutil.tex python/trunk/Lib/shutil.py python/trunk/Lib/stat.py python/trunk/Lib/test/test_posix.py python/trunk/Misc/ACKS python/trunk/Misc/NEWS python/trunk/Modules/posixmodule.c python/trunk/configure python/trunk/configure.in python/trunk/pyconfig.h.in Log: Patch #1490190: posixmodule now includes os.chflags() and os.lchflags() functions on platforms where the underlying system calls are available. Modified: python/trunk/Doc/lib/libos.tex ============================================================================== --- python/trunk/Doc/lib/libos.tex (original) +++ python/trunk/Doc/lib/libos.tex Mon Feb 19 11:55:19 2007 @@ -758,6 +758,26 @@ \versionadded{2.3} \end{funcdesc} +\begin{funcdesc}{chflags}{path, flags} +Set the flags of \var{path} to the numeric \var{flags}. +\var{flags} may take a combination (bitwise OR) of the following values +(as defined in the \module{stat} module): +\begin{itemize} + \item \code{UF_NODUMP} + \item \code{UF_IMMUTABLE} + \item \code{UF_APPEND} + \item \code{UF_OPAQUE} + \item \code{UF_NOUNLINK} + \item \code{SF_ARCHIVED} + \item \code{SF_IMMUTABLE} + \item \code{SF_APPEND} + \item \code{SF_NOUNLINK} + \item \code{SF_SNAPSHOT} +\end{itemize} +Availability: Macintosh, \UNIX. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{chroot}{path} Change the root directory of the current process to \var{path}. Availability: Macintosh, \UNIX. @@ -804,6 +824,13 @@ Availability: Macintosh, \UNIX. \end{funcdesc} +\begin{funcdesc}{lchflags}{path, flags} +Set the flags of \var{path} to the numeric \var{flags}, like +\function{chflags()}, but do not follow symbolic links. +Availability: \UNIX. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{lchown}{path, uid, gid} Change the owner and group id of \var{path} to the numeric \var{uid} and gid. This function will not follow symbolic links. Modified: python/trunk/Doc/lib/libshutil.tex ============================================================================== --- python/trunk/Doc/lib/libshutil.tex (original) +++ python/trunk/Doc/lib/libshutil.tex Mon Feb 19 11:55:19 2007 @@ -44,8 +44,8 @@ \end{funcdesc} \begin{funcdesc}{copystat}{src, dst} - Copy the permission bits, last access time, and last modification - time from \var{src} to \var{dst}. The file contents, owner, and + Copy the permission bits, last access time, last modification time, + and flags from \var{src} to \var{dst}. The file contents, owner, and group are unaffected. \var{src} and \var{dst} are path names given as strings. \end{funcdesc} Modified: python/trunk/Lib/shutil.py ============================================================================== --- python/trunk/Lib/shutil.py (original) +++ python/trunk/Lib/shutil.py Mon Feb 19 11:55:19 2007 @@ -60,13 +60,15 @@ os.chmod(dst, mode) def copystat(src, dst): - """Copy all stat info (mode bits, atime and mtime) from src to dst""" + """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) + if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): + os.chflags(dst, st.st_flags) def copy(src, dst): Modified: python/trunk/Lib/stat.py ============================================================================== --- python/trunk/Lib/stat.py (original) +++ python/trunk/Lib/stat.py Mon Feb 19 11:55:19 2007 @@ -84,3 +84,16 @@ S_IROTH = 00004 S_IWOTH = 00002 S_IXOTH = 00001 + +# Names for file flags + +UF_NODUMP = 0x00000001 +UF_IMMUTABLE = 0x00000002 +UF_APPEND = 0x00000004 +UF_OPAQUE = 0x00000008 +UF_NOUNLINK = 0x00000010 +SF_ARCHIVED = 0x00010000 +SF_IMMUTABLE = 0x00020000 +SF_APPEND = 0x00040000 +SF_NOUNLINK = 0x00100000 +SF_SNAPSHOT = 0x00200000 Modified: python/trunk/Lib/test/test_posix.py ============================================================================== --- python/trunk/Lib/test/test_posix.py (original) +++ python/trunk/Lib/test/test_posix.py Mon Feb 19 11:55:19 2007 @@ -192,6 +192,18 @@ posix.utime(test_support.TESTFN, (int(now), int(now))) posix.utime(test_support.TESTFN, (now, now)) + def test_chflags(self): + if hasattr(posix, 'chflags'): + st = os.stat(test_support.TESTFN) + if hasattr(st, 'st_flags'): + posix.chflags(test_support.TESTFN, st.st_flags) + + def test_lchflags(self): + if hasattr(posix, 'lchflags'): + st = os.stat(test_support.TESTFN) + if hasattr(st, 'st_flags'): + posix.lchflags(test_support.TESTFN, st.st_flags) + def test_main(): test_support.run_unittest(PosixTester) Modified: python/trunk/Misc/ACKS ============================================================================== --- python/trunk/Misc/ACKS (original) +++ python/trunk/Misc/ACKS Mon Feb 19 11:55:19 2007 @@ -377,6 +377,7 @@ Kip Lehman Joerg Lehmann Marc-Andre Lemburg +Mark Levinson William Lewis Robert van Liere Martin Ligr Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon Feb 19 11:55:19 2007 @@ -371,6 +371,9 @@ Extension Modules ----------------- +- Patch #1490190: posixmodule now includes os.chflags() and os.lchflags() + functions on platforms where the underlying system calls are available. + - Patch #1494140: Add documentation for the new struct.Struct object. - Patch #1432399: Support the HCI protocol for bluetooth sockets Modified: python/trunk/Modules/posixmodule.c ============================================================================== --- python/trunk/Modules/posixmodule.c (original) +++ python/trunk/Modules/posixmodule.c Mon Feb 19 11:55:19 2007 @@ -1692,6 +1692,57 @@ } +#ifdef HAVE_CHFLAGS +PyDoc_STRVAR(posix_chflags__doc__, +"chflags(path, flags)\n\n\ +Set file flags."); + +static PyObject * +posix_chflags(PyObject *self, PyObject *args) +{ + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:chflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +} +#endif /* HAVE_CHFLAGS */ + +#ifdef HAVE_LCHFLAGS +PyDoc_STRVAR(posix_lchflags__doc__, +"lchflags(path, flags)\n\n\ +Set file flags.\n\ +This function will not follow symbolic links."); + +static PyObject * +posix_lchflags(PyObject *self, PyObject *args) +{ + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:lchflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +} +#endif /* HAVE_LCHFLAGS */ + #ifdef HAVE_CHROOT PyDoc_STRVAR(posix_chroot__doc__, "chroot(path)\n\n\ @@ -8081,10 +8132,16 @@ {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, #endif {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, +#ifdef HAVE_CHFLAGS + {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, +#endif /* HAVE_CHFLAGS */ {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, #ifdef HAVE_CHOWN {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, #endif /* HAVE_CHOWN */ +#ifdef HAVE_LCHFLAGS + {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, +#endif /* HAVE_LCHFLAGS */ #ifdef HAVE_LCHOWN {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, #endif /* HAVE_LCHOWN */ Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Mon Feb 19 11:55:19 2007 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 52843 . +# From configure.in Revision: 53508 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.59 for python 2.6. # @@ -14718,11 +14718,13 @@ -for ac_func in alarm bind_textdomain_codeset chown clock confstr ctermid \ - execv fork fpathconf ftime ftruncate \ + + +for ac_func in alarm bind_textdomain_codeset chflags chown clock confstr \ + ctermid execv fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ - kill killpg lchown lstat mkfifo mknod mktime \ + kill killpg lchflags lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink realpath \ select setegid seteuid setgid \ Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Mon Feb 19 11:55:19 2007 @@ -2282,11 +2282,11 @@ AC_MSG_RESULT(MACHDEP_OBJS) # checks for library functions -AC_CHECK_FUNCS(alarm bind_textdomain_codeset chown clock confstr ctermid \ - execv fork fpathconf ftime ftruncate \ +AC_CHECK_FUNCS(alarm bind_textdomain_codeset chflags chown clock confstr \ + ctermid execv fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ - kill killpg lchown lstat mkfifo mknod mktime \ + kill killpg lchflags lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink realpath \ select setegid seteuid setgid \ Modified: python/trunk/pyconfig.h.in ============================================================================== --- python/trunk/pyconfig.h.in (original) +++ python/trunk/pyconfig.h.in Mon Feb 19 11:55:19 2007 @@ -67,6 +67,9 @@ /* Define this if you have the type _Bool. */ #undef HAVE_C99_BOOL +/* Define to 1 if you have the `chflags' function. */ +#undef HAVE_CHFLAGS + /* Define to 1 if you have the `chown' function. */ #undef HAVE_CHOWN @@ -290,6 +293,9 @@ Solaris and Linux, the necessary defines are already defined.) */ #undef HAVE_LARGEFILE_SUPPORT +/* Define to 1 if you have the `lchflags' function. */ +#undef HAVE_LCHFLAGS + /* Define to 1 if you have the `lchown' function. */ #undef HAVE_LCHOWN From buildbot at python.org Mon Feb 19 12:16:05 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 19 Feb 2007 11:16:05 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 trunk Message-ID: <20070219111605.7F85B1E4019@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%2520trunk/builds/1420 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: lars.gustaebel,martin.v.loewis,raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From python-checkins at python.org Mon Feb 19 19:15:08 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 19:15:08 +0100 (CET) Subject: [Python-checkins] r53827 - in python/trunk: Doc/lib/libheapq.tex Lib/heapq.py Message-ID: <20070219181508.52DC01E4007@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 19:15:04 2007 New Revision: 53827 Modified: python/trunk/Doc/lib/libheapq.tex python/trunk/Lib/heapq.py Log: Fixup docstrings for merge(). Modified: python/trunk/Doc/lib/libheapq.tex ============================================================================== --- python/trunk/Doc/lib/libheapq.tex (original) +++ python/trunk/Doc/lib/libheapq.tex Mon Feb 19 19:15:04 2007 @@ -96,8 +96,8 @@ over the sorted values. Similar to \code{sorted(itertools.chain(*iterables))} but returns an iterable, -does not pull the data into memory all at once, and reduces the number of -comparisons by assuming that each of the input streams is already sorted. +does not pull the data into memory all at once, and assumes that each of the +input streams is already sorted (smallest to largest). \versionadded{2.6} \end{funcdesc} Modified: python/trunk/Lib/heapq.py ============================================================================== --- python/trunk/Lib/heapq.py (original) +++ python/trunk/Lib/heapq.py Mon Feb 19 19:15:04 2007 @@ -312,8 +312,8 @@ '''Merge multiple sorted inputs into a single sorted output. Similar to sorted(itertools.chain(*iterables)) but returns an iterable, - does not pull the data into memory all at once, and reduces the number - of comparisons by assuming that each of the input streams is already sorted. + does not pull the data into memory all at once, and assumes that each of + the input streams is already sorted (smallest to largest). >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] From buildbot at python.org Mon Feb 19 20:18:10 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 19 Feb 2007 19:18:10 +0000 Subject: [Python-checkins] buildbot warnings in x86 OpenBSD trunk Message-ID: <20070219191810.7648D1E4009@bag.python.org> The Buildbot has detected a new failure of x86 OpenBSD trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520OpenBSD%2520trunk/builds/1570 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket_ssl sincerely, -The Buildbot From python-checkins at python.org Mon Feb 19 20:26:22 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 20:26:22 +0100 (CET) Subject: [Python-checkins] r53828 - python/branches/release25-maint/Doc/lib/libcollections.tex Message-ID: <20070219192622.D9C211E4009@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 20:26:16 2007 New Revision: 53828 Modified: python/branches/release25-maint/Doc/lib/libcollections.tex Log: Provide an example of defaultdict with non-zero constant factory function. Modified: python/branches/release25-maint/Doc/lib/libcollections.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libcollections.tex (original) +++ python/branches/release25-maint/Doc/lib/libcollections.tex Mon Feb 19 20:26:16 2007 @@ -311,16 +311,20 @@ When a letter is first encountered, it is missing from the mapping, so the \member{default_factory} function calls \function{int()} to supply a default count of zero. The increment operation then builds up the count for each -letter. This technique makes counting simpler and faster than an equivalent -technique using \method{dict.get()}: +letter. -\begin{verbatim} ->>> d = {} ->>> for k in s: - d[k] = d.get(k, 0) + 1 +The function \function{int()} which always returns zero is just a special +case of constant functions. A faster and more flexible way to create +constant functions is to use \function{itertools.repeat()} which can supply +any constant value (not just zero): ->>> d.items() -[('i', 4), ('p', 2), ('s', 4), ('m', 1)] +\begin{verbatim} +>>> def constant_factory(value): +... return itertools.repeat(value).next +>>> d = defaultdict(constant_factory('')) +>>> d.update(name='John', action='ran') +>>> '%(name)s %(action)s to %(object)s' % d +'John ran to ' \end{verbatim} Setting the \member{default_factory} to \class{set} makes the From python-checkins at python.org Mon Feb 19 21:44:06 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 21:44:06 +0100 (CET) Subject: [Python-checkins] r53829 - python/trunk/Objects/setobject.c Message-ID: <20070219204406.08A3D1E4019@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 21:44:04 2007 New Revision: 53829 Modified: python/trunk/Objects/setobject.c Log: Fixup set/dict interoperability. Modified: python/trunk/Objects/setobject.c ============================================================================== --- python/trunk/Objects/setobject.c (original) +++ python/trunk/Objects/setobject.c Mon Feb 19 21:44:04 2007 @@ -919,7 +919,18 @@ PyObject *value; Py_ssize_t pos = 0; long hash; + Py_ssize_t dictsize = PyDict_Size(other); + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if (dictsize == -1) + return -1; + if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + dictsize)*2) != 0) + return -1; + } while (_PyDict_Next(other, &pos, &key, &value, &hash)) { setentry an_entry; From python-checkins at python.org Mon Feb 19 21:45:47 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 19 Feb 2007 21:45:47 +0100 (CET) Subject: [Python-checkins] r53830 - python/branches/release25-maint/Objects/setobject.c Message-ID: <20070219204547.DB2A91E400B@bag.python.org> Author: raymond.hettinger Date: Mon Feb 19 21:45:46 2007 New Revision: 53830 Modified: python/branches/release25-maint/Objects/setobject.c Log: Fixup set/dict interoperability. Modified: python/branches/release25-maint/Objects/setobject.c ============================================================================== --- python/branches/release25-maint/Objects/setobject.c (original) +++ python/branches/release25-maint/Objects/setobject.c Mon Feb 19 21:45:46 2007 @@ -919,7 +919,18 @@ PyObject *value; Py_ssize_t pos = 0; long hash; + Py_ssize_t dictsize = PyDict_Size(other); + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if (dictsize == -1) + return -1; + if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + dictsize)*2) != 0) + return -1; + } while (_PyDict_Next(other, &pos, &key, &value, &hash)) { setentry an_entry; From python-checkins at python.org Tue Feb 20 04:30:59 2007 From: python-checkins at python.org (david.goodger) Date: Tue, 20 Feb 2007 04:30:59 +0100 (CET) Subject: [Python-checkins] r53831 - peps/trunk/pep-0363.txt Message-ID: <20070220033059.D3EE11E4009@bag.python.org> Author: david.goodger Date: Tue Feb 20 04:30:58 2007 New Revision: 53831 Modified: peps/trunk/pep-0363.txt Log: update from the author Modified: peps/trunk/pep-0363.txt ============================================================================== --- peps/trunk/pep-0363.txt (original) +++ peps/trunk/pep-0363.txt Tue Feb 20 04:30:58 2007 @@ -2,12 +2,12 @@ Title: Syntax For Dynamic Attribute Access Version: $Revision$ Last-Modified: $Date$ -Author: Ben North -Status: Draft +Author: Ben North +Status: Rejected Type: Standards Track Content-Type: text/plain Created: 29-Jan-2007 -Post-History: +Post-History: 12-Feb-2007 Abstract @@ -28,13 +28,6 @@ z = getattr(getattr(y, 'foo_%d' % n), 'bar_%s' % s) -Note - - I wrote this patch mostly to advance my own understanding of and - experiment with the python language, but I've written it up in the - style of a PEP in case it might be a useful idea. - - Rationale Dictionary access and indexing both have a friendly invocation @@ -64,18 +57,17 @@ x = getattr(y, 'foo_%d' % n, 0) This PEP describes a new syntax for dynamic attribute access --- - "x.(expr)" --- with examples given in the Abstract above. The new - syntax also allows the provision of a default value in the "get" - case, as in: + "x.(expr)" --- with examples given in the Abstract above. + + (The new syntax could also allow the provision of a default value in + the "get" case, as in: x = y.('foo_%d' % n, None) - This 2-argument form of dynamic attribute access is not permitted as - the target of an (augmented or normal) assignment. Also, this part - of the new syntax was not as well received [6] in initial - discussions on python-ideas, and I agree that it does not fit so - cleanly. I'm happy to prepare a revised PEP/patch without the - 2-argument form if the consensus is that this would be preferred. + This 2-argument form of dynamic attribute access would not be + permitted as the target of an (augmented or normal) assignment. The + "Discussion" section below includes opinions specifically on the + 2-argument extension.) Finally, the new syntax can be used with the "del" statement, as in @@ -144,80 +136,18 @@ be a performance penalty of around 1% in the pystones score with the patched version. One suggestion is that this is because the longer main loop in ceval.c hurts the cache behaviour, but this has not - been confirmed. (Maybe a tool like valgrind [2] could help here?) + been confirmed. On the other hand, measurements suggest a speed-up of around 40--45% for dynamic attribute access. -Discussion To Date - - Initial posting of this PEP in draft form was to python-ideas on - 20070209 [4], and the response was generally positive: - - I've thought of the same syntax. I think you should submit this - to the PEP editor and argue on Python-dev for its inclusion in - Python 2.6 -- there's no benefit that I see of waiting until - 3.0. --- Guido van Rossum [5] - - Wow! I have to say this is a compelling idea. The syntax is a - bit foreign looking, but [...] I feel like I could learn to like - it anyway. --- Greg Falcon [6] - - I look forward to seeing this in Python 2.6. --- Josiah - Carlson, further down the thread [8] - - with Greg Falcon expressing the reservations about the 2-argument - form already noted above, and Josiah Carlson raising a query about - performance: - - My only concern with your propsed change is your draft - implementation. [...] Specifically, your changes [...] may - negatively affect general Python performance. --- Josiah - Carlson [7] - - Some initial measurements (see above) suggest the performance - penalty is small, and Josiah Carlson said of such cost that it - "isn't really substantial". [8] - - -Questions To Be Resolved - - * Whether to allow the 2-argument form for default arguments. - - * Whether the performance impact is real; whether it is acceptable; - whether alternative implementations might improve this aspect. - - -Alternative Syntax For The New Feature - - Other syntaxes could be used, for example braces are currently - invalid in a "trailer", so could be used here, giving - - x{'foo_%d' % n} += 1 - - My personal preference is for the - - x.('foo_%d' % n) += 1 - - syntax though: the presence of the dot shows there is attribute - access going on; the parentheses have an analogous meaning to the - mathematical "work this out first" meaning. This is also the - syntax used in the language Matlab [1] for dynamic "field" access - (where "field" is the Matlab term analogous to Python's - "attribute"). - - Discussions on python-ideas (see above) made no comment on the brace - alternative, and the .() notation was well-enough received, so the - brace alternative should be considered rejected, I think. - - Error Cases Only strings are permitted as attribute names, so for instance the following error is produced: - >>> x.(99) = 8 + >>> x.(99) = 8 Traceback (most recent call last): File "", line 1, in TypeError: attribute name must be string, not 'int' @@ -233,29 +163,78 @@ compile.c, and three new opcodes (load/store/del) with accompanying changes to opcode.h and ceval.c. The patch consists of c.180 additional lines in the core code, and c.100 additional - lines of tests. It is available as sourceforge patch #1657573 [3]. - - -References + lines of tests. It is available as sourceforge patch #1657573 [1]. - [1] Using Dynamic Field Names :: Data Types (MATLAB Programming) - http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f2-41859.html - [2] Valgrind: "suite of tools for debugging and profiling Linux programs" - http://www.valgrind.org/ +Mailing Lists Discussion - [3] Sourceforge patch #1657573 - http://sourceforge.net/tracker/index.php?func=detail&aid=1657573&group_id=5470&atid=305470 + Initial posting of this PEP in draft form was to python-ideas on + 20070209 [2], and the response was generally positive. The PEP was + then posted to python-dev on 20070212 [3], and an interesting + discussion ensued. A brief summary: + + Initially, there was reasonable (but not unanimous) support for the + idea, although the precise choice of syntax had a more mixed + reception. Several people thought the "." would be too easily + overlooked, with the result that the syntax could be confused with a + method/function call. A few alternative syntaxes were suggested: + + obj.(foo) + obj.[foo] + obj.{foo} + obj{foo} + obj.*foo + obj->foo + obj<-foo + obj@[foo] + obj.[[foo]] + + with "obj.[foo]" emerging as the preferred one. In this initial + discussion, the two-argument form was universally disliked, so it + was to be taken out of the PEP. + + Discussion then took a step back to whether this particular feature + provided enough benefit to justify new syntax. As well as requiring + coders to become familiar with the new syntax, there would also be + the problem of backward compatibility --- code using the new syntax + would not run on older pythons. + + Instead of new syntax, a new "wrapper class" was proposed, with the + following specification / conceptual implementation suggested by + Martin von Loewis: + + class attrs: + def __init__(self, obj): + self.obj = obj + def __getitem__(self, name): + return getattr(self.obj, name) + def __setitem__(self, name, value): + return setattr(self.obj, name, value) + def __delitem__(self, name): + return delattr(self, name) + def __contains__(self, name): + return hasattr(self, name) + + This was considered a cleaner and more elegant solution to the + original problem. (Another suggestion was a mixin class providing + dictionary-style access to an object's attributes.) + + The decision was made that the present PEP did not meet the burden + of proof for the introduction of new syntax, a view which had been + put forward by some from the beginning of the discussion. The + wrapper class idea was left open as a possibility for a future PEP. - [4] http://mail.python.org/pipermail/python-ideas/2007-February/000210.html - [5] http://mail.python.org/pipermail/python-ideas/2007-February/000211.html +References - [6] http://mail.python.org/pipermail/python-ideas/2007-February/000212.html + [1] Sourceforge patch #1657573 + http://sourceforge.net/tracker/index.php?func=detail&aid=1657573&group_id=5470&atid=305470 - [7] http://mail.python.org/pipermail/python-ideas/2007-February/000213.html + [2] http://mail.python.org/pipermail/python-ideas/2007-February/000210.html + and following posts - [8] http://mail.python.org/pipermail/python-ideas/2007-February/000227.html + [3] http://mail.python.org/pipermail/python-dev/2007-February/070939.html + and following posts Copyright From python-checkins at python.org Tue Feb 20 04:33:03 2007 From: python-checkins at python.org (david.goodger) Date: Tue, 20 Feb 2007 04:33:03 +0100 (CET) Subject: [Python-checkins] r53832 - peps/trunk/pep-0000.txt Message-ID: <20070220033303.596141E4009@bag.python.org> Author: david.goodger Date: Tue Feb 20 04:32:58 2007 New Revision: 53832 Modified: peps/trunk/pep-0000.txt Log: mark PEP 363 rejected Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Tue Feb 20 04:32:58 2007 @@ -108,7 +108,6 @@ S 355 Path - Object oriented filesystem paths Lindqvist S 358 The "bytes" Object Schemenauer S 362 Function Signature Object Cannon, Seo - S 363 Syntax For Dynamic Attribute Access North S 754 IEEE 754 Floating Point Special Values Warnes S 3101 Advanced String Formatting Talin S 3103 A Switch/Case Statement GvR @@ -245,6 +244,7 @@ SD 349 Allow str() to return unicode strings Schemenauer SR 351 The freeze protocol Warsaw SW 359 The "make" Statement Bethard + SR 363 Syntax For Dynamic Attribute Access North SR 666 Reject Foolish Indentation Creighton @@ -435,7 +435,7 @@ I 360 Externally Maintained Packages Cannon I 361 Python 2.6 Release Schedule Norwitz, et al S 362 Function Signature Object Cannon, Seo - S 363 Syntax For Dynamic Attribute Access North + SR 363 Syntax For Dynamic Attribute Access North SR 666 Reject Foolish Indentation Creighton S 754 IEEE 754 Floating Point Special Values Warnes P 3000 Python 3000 GvR From nnorwitz at gmail.com Tue Feb 20 13:42:05 2007 From: nnorwitz at gmail.com (Neal Norwitz) Date: Tue, 20 Feb 2007 18:12:05 +0530 Subject: [Python-checkins] r53815 - peps/trunk/pep-0000.txt peps/trunk/pep-0226.txt peps/trunk/pep-0328.txt peps/trunk/pep-3102.txt peps/trunk/pep-3105.txt peps/trunk/pep-3106.txt peps/trunk/pep-3107.txt peps/trunk/pep-3109.txt peps/trunk/pep-3110.txt In-Reply-To: <20070217184239.7CCE11E400C@bag.python.org> References: <20070217184239.7CCE11E400C@bag.python.org> Message-ID: On 2/18/07, georg.brandl wrote: > Modified: peps/trunk/pep-0328.txt > ============================================================================== > --- peps/trunk/pep-0328.txt (original) > +++ peps/trunk/pep-0328.txt Sat Feb 17 19:42:37 2007 > @@ -3,7 +3,7 @@ > Version: $Revision$ > Last-Modified: $Date$ > Author: Aahz > -Status: Accepted > +Status: Final > Type: Standards Track > Python-Version: 2.4, 2,5, 2.6, 2.7 > Content-Type: text/x-rst Should 328 be final given that there are more things that need to be done in 2.6 (was this change made to the 2.6 code?) and 2.7? n From buildbot at python.org Tue Feb 20 14:05:22 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 20 Feb 2007 13:05:22 +0000 Subject: [Python-checkins] buildbot failure in g4 osx.4 2.5 Message-ID: <20070220130523.637F21E4019@bag.python.org> The Buildbot has detected a new failure of g4 osx.4 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/g4%2520osx.4%25202.5/builds/226 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Preston': Corey Build Source Stamp: [branch Elijah] Kalvin Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Tue Feb 20 14:06:26 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 20 Feb 2007 13:06:26 +0000 Subject: [Python-checkins] buildbot failure in sparc solaris10 gcc 2.5 Message-ID: <20070220130627.909F41E401C@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%25202.5/builds/233 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Bill': Avery Build Source Stamp: [branch Phillip] Victor Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Tue Feb 20 14:11:28 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 20 Feb 2007 13:11:28 +0000 Subject: [Python-checkins] buildbot failure in x86 XP 2.5 Message-ID: <20070220131128.6ED4B1E4010@bag.python.org> The Buildbot has detected a new failure of x86 XP 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%25202.5/builds/125 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Calvin': Damien Build Source Stamp: [branch Carl] Rashad Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Tue Feb 20 14:13:01 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 20 Feb 2007 13:13:01 +0000 Subject: [Python-checkins] buildbot failure in amd64 gentoo 2.5 Message-ID: <20070220131302.75F031E400D@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%25202.5/builds/241 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Omar': Kamron Build Source Stamp: [branch Jameson] Raymond Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From g.brandl at gmx.net Tue Feb 20 14:18:52 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Tue, 20 Feb 2007 14:18:52 +0100 Subject: [Python-checkins] r53815 - peps/trunk/pep-0000.txt peps/trunk/pep-0226.txt peps/trunk/pep-0328.txt peps/trunk/pep-3102.txt peps/trunk/pep-3105.txt peps/trunk/pep-3106.txt peps/trunk/pep-3107.txt peps/trunk/pep-3109.txt peps/trunk/pep-3110.txt In-Reply-To: References: <20070217184239.7CCE11E400C@bag.python.org> Message-ID: Neal Norwitz schrieb: > On 2/18/07, georg.brandl wrote: >> Modified: peps/trunk/pep-0328.txt >> ============================================================================== >> --- peps/trunk/pep-0328.txt (original) >> +++ peps/trunk/pep-0328.txt Sat Feb 17 19:42:37 2007 >> @@ -3,7 +3,7 @@ >> Version: $Revision$ >> Last-Modified: $Date$ >> Author: Aahz >> -Status: Accepted >> +Status: Final >> Type: Standards Track >> Python-Version: 2.4, 2,5, 2.6, 2.7 >> Content-Type: text/x-rst > > Should 328 be final given that there are more things that need to be > done in 2.6 (was this change made to the 2.6 code?) and 2.7? I thought that now that the roadmap is set out and will be followed, the PEP can be marked as final. I'll revert that if "Final" is not appropriate herefore. Georg From python-checkins at python.org Tue Feb 20 14:57:07 2007 From: python-checkins at python.org (nick.coghlan) Date: Tue, 20 Feb 2007 14:57:07 +0100 (CET) Subject: [Python-checkins] r53833 - peps/trunk/pep-0000.txt peps/trunk/pep-3111.txt Message-ID: <20070220135707.D2FE61E400E@bag.python.org> Author: nick.coghlan Date: Tue Feb 20 14:57:06 2007 New Revision: 53833 Added: peps/trunk/pep-3111.txt (contents, props changed) Modified: peps/trunk/pep-0000.txt Log: Formally record December's acceptance of the raw_input() -> input() renaming. Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Tue Feb 20 14:57:06 2007 @@ -82,6 +82,7 @@ SA 3107 Function Annotations Winter, Lownds SA 3109 Raising Exceptions in Python 3000 Winter SA 3110 Catching Exceptions in Python 3000 Winter + SA 3111 Simple input built-in in Python 3000 Roberge Open PEPs (under consideration) @@ -453,6 +454,7 @@ I 3108 Standard Library Reorganization Cannon SA 3109 Raising Exceptions in Python 3000 Winter SA 3110 Catching Exceptions in Python 3000 Winter + SA 3111 Simple input built-in in Python 3000 Roberge Key @@ -544,6 +546,7 @@ Reifschneider, Sean jafo-pep at tummy.com Reis, Christian R. kiko at async.com.br Riehl, Jonathan jriehl at spaceship.com + Roberge, Andr? andre.roberge at gmail.com van Rossum, Guido (GvR) guido at python.org van Rossum, Just (JvR) just at letterror.com Sajip, Vinay vinay_sajip at red-dove.com Added: peps/trunk/pep-3111.txt ============================================================================== --- (empty file) +++ peps/trunk/pep-3111.txt Tue Feb 20 14:57:06 2007 @@ -0,0 +1,162 @@ +PEP: 3111 +Title: Simple input built-in in Python 3000 +Version: $Revision$ +Last-Modified: $Date$ +Author: Andr? Roberge +Status: Draft +Type: Standards Track +Content-Type: text/x-rst +Created: 13-Sep-2006 +Python-Version: 3.0 +Post-History: 22-Dec-2006 + + +Abstract +======== + +Input and output are core features of computer programs. Currently, +Python provides a simple means of output through the print keyword +and two simple means of interactive input through the input() +and raw_input() built-in functions. + +Python 3.0 will introduce various incompatible changes with previous +Python versions[1]. Among the proposed changes, print will become a built-in +function, print(), while input() and raw_input() would be removed completely +from the built-in namespace, requiring importing some module to provide +even the most basic input capability. + +This PEP proposes that Python 3.0 retains some simple interactive user +input capability, equivalent to raw_input(), within the built-in namespace. + +It was accepted by the BDFL in December 2006 [5]. + + +Motivation +========== + +With its easy readability and its support for many programming styles +(e.g. procedural, object-oriented, etc.) among others, Python is perhaps +the best computer language to use in introductory programming classes. +Simple programs often need to provide information to the user (output) +and to obtain information from the user (interactive input). +Any computer language intended to be used in an educational setting should +provide straightforward methods for both output and interactive input. + +The current proposals for Python 3.0 [1] include a simple output pathway +via a built-in function named print(), but a more complicated method for +input [e.g. via sys.stdin.readline()], one that requires importing an external +module. Current versions of Python (pre-3.0) include raw_input() as a +built-in function. With the availability of such a function, programs that +require simple input/output can be written from day one, without requiring +discussions of importing modules, streams, etc. + + +Rationale +========= + +Current built-in functions, like input() and raw_input(), are found to be +extremely useful in traditional teaching settings. (For more details, +see [2] and the discussion that followed.) +While the BDFL has clearly stated [3] that input() was not to be kept in +Python 3000, he has also stated that he was not against revising the +decision of killing raw_input(). + +raw_input() provides a simple mean to ask a question and obtain a response +from a user. The proposed plans for Python 3.0 would require the replacement +of the single statement:: + + name = raw_input("What is your name?") + +by the more complicated:: + + import sys + print("What is your name?") + same = sys.stdin.readline() + +However, from the point of view of many Python beginners and educators, the +use of sys.stdin.readline() presents the following problems: + +1. Compared to the name "raw_input", the name "sys.stdin.readline()" +is clunky and inelegant. + +2. The names "sys" and "stdin" have no meaning for most beginners, +who are mainly interested in *what* the function does, and not *where* +in the package structure it is located. The lack of meaning also makes +it difficult to remember: +is it "sys.stdin.readline()", or " stdin.sys.readline()"? +To a programming novice, there is not any obvious reason to prefer +one over the other. In contrast, functions simple and direct names like +print, input, and raw_input, and open are easier to remember. + +3. The use of "." notation is unmotivated and confusing to many beginners. +For example, it may lead some beginners to think "." is a standard +character that could be used in any identifier. + +4. There is an asymmetry with the print function: why is print not called +sys.stdout.print()? + + +Specification +============= + +The existing ``raw_input()`` function will be renamed to ``input()``. + +The Python 2 to 3 conversion tool will replace calls to ``input()`` with +``eval(input())`` and ``raw_input()`` with ``input()``. + + +Naming Discussion +================= + +With ``input()`` effectively removed from the language, the name ``raw_input()`` +makes much less sense and alternatives should be considered. The +various possibilities mentioned in various forums include:: + + ask() + ask_user() + get_string() + input() # initially rejected by BDFL, later accepted + prompt() + read() + user_input() + get_response() + +While it was initially rejected by the BDFL, it has been suggested that the most +direct solution would be to rename "raw_input" to "input" in Python 3000. +The main objection is that Python 2.x already has a function named "input", +and, even though it is not going to be included in Python 3000, +having a built-in function with the same name but different semantics may +confuse programmers migrating from 2.x to 3000. Certainly, this is no problem +for beginners, and the scope of the problem is unclear for more experienced +programmers, since raw_input(), while popular with many, is not in +universal use. In this instance, the good it does for beginners could be +seen to outweigh the harm it does to experienced programmers - +although it could cause confusion for people reading older books or tutorials. + +The rationale for accepting the renaming can be found here [4]. + + +References +========== + +.. [1] PEP 3100, Miscellaneous Python 3.0 Plans, Kuchling, Cannon + http://www.python.org/dev/peps/pep-3100/ + +.. [2] The fate of raw_input() in Python 3000 + http://mail.python.org/pipermail/edu-sig/2006-September/006967.html + +.. [3] Educational aspects of Python 3000 + http://mail.python.org/pipermail/python-3000/2006-September/003589.html + +.. [4] Rationale for going with the straight renaming + http://mail.python.org/pipermail/python-3000/2006-December/005249.html + +.. [5] BDFL acceptance of the PEP + http://mail.python.org/pipermail/python-3000/2006-December/005257.html + +Copyright +========= + +This document has been placed in the public domain. + + From python-checkins at python.org Tue Feb 20 23:45:41 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 20 Feb 2007 23:45:41 +0100 (CET) Subject: [Python-checkins] r53834 - sandbox/trunk/setuptools/setuptools/command/install.py Message-ID: <20070220224541.B3EB11E4002@bag.python.org> Author: phillip.eby Date: Tue Feb 20 23:45:40 2007 New Revision: 53834 Modified: sandbox/trunk/setuptools/setuptools/command/install.py Log: Respect possible entry point override of 'easy_install' command. Modified: sandbox/trunk/setuptools/setuptools/command/install.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/install.py (original) +++ sandbox/trunk/setuptools/setuptools/command/install.py Tue Feb 20 23:45:40 2007 @@ -82,7 +82,7 @@ def do_egg_install(self): - from setuptools.command.easy_install import easy_install + easy_install = self.distribution.get_command_class('easy_install') cmd = easy_install( self.distribution, args="x", root=self.root, record=self.record, From python-checkins at python.org Tue Feb 20 23:50:44 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 20 Feb 2007 23:50:44 +0100 (CET) Subject: [Python-checkins] r53835 - sandbox/branches/setuptools-0.6/setuptools/command/install.py Message-ID: <20070220225044.4388D1E4002@bag.python.org> Author: phillip.eby Date: Tue Feb 20 23:50:42 2007 New Revision: 53835 Modified: sandbox/branches/setuptools-0.6/setuptools/command/install.py Log: Respect possible entry point override of 'easy_install' command. (backport from trunk) Modified: sandbox/branches/setuptools-0.6/setuptools/command/install.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/install.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/install.py Tue Feb 20 23:50:42 2007 @@ -82,7 +82,7 @@ def do_egg_install(self): - from setuptools.command.easy_install import easy_install + easy_install = self.distribution.get_command_class('easy_install') cmd = easy_install( self.distribution, args="x", root=self.root, record=self.record, From python-checkins at python.org Wed Feb 21 00:32:42 2007 From: python-checkins at python.org (guido.van.rossum) Date: Wed, 21 Feb 2007 00:32:42 +0100 (CET) Subject: [Python-checkins] r53836 - peps/trunk/pep-0000.txt peps/trunk/pep-3106.txt Message-ID: <20070220233242.4C2241E4002@bag.python.org> Author: guido.van.rossum Date: Wed Feb 21 00:32:28 2007 New Revision: 53836 Modified: peps/trunk/pep-0000.txt peps/trunk/pep-3106.txt Log: Sorry, PEP 3106 is not yet accepted. Also removed mutating operations and added some clarifications. Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Wed Feb 21 00:32:28 2007 @@ -78,7 +78,7 @@ Accepted PEPs (accepted; may not be implemented yet) SA 3102 Keyword-Only Arguments Talin - SA 3106 Revamping dict.keys(), .values() and .items() GvR + S 3106 Revamping dict.keys(), .values() and .items() GvR SA 3107 Function Annotations Winter, Lownds SA 3109 Raising Exceptions in Python 3000 Winter SA 3110 Catching Exceptions in Python 3000 Winter @@ -449,7 +449,7 @@ S 3103 A Switch/Case Statement GvR S 3104 Access to Names in Outer Scopes Yee SF 3105 Make print a function Brandl - SA 3106 Revamping dict.keys(), .values() and .items() GvR + S 3106 Revamping dict.keys(), .values() and .items() GvR SA 3107 Function Annotations Winter, Lownds I 3108 Standard Library Reorganization Cannon SA 3109 Raising Exceptions in Python 3000 Winter Modified: peps/trunk/pep-3106.txt ============================================================================== --- peps/trunk/pep-3106.txt (original) +++ peps/trunk/pep-3106.txt Wed Feb 21 00:32:28 2007 @@ -3,7 +3,7 @@ Version: $Revision$ Last-Modified: $Date$ Author: Guido van Rossum -Status: Accepted +Status: Draft Type: Standards Content-Type: text/x-rst Created: 19-Dec-2006 @@ -14,11 +14,10 @@ ======== This PEP proposes to change the .keys(), .values() and .items() -methods of the built-in dict type to return a set-like or -multiset-like (== bag-like) object whose contents are derived of the -underlying dictionary rather than a list which is a copy of the keys, -etc.; and to remove the .iterkeys(), .itervalues() and .iteritems() -methods. +methods of the built-in dict type to return a set-like or unordered +container object whose contents are derived of the underlying +dictionary rather than a list which is a copy of the keys, etc.; and +to remove the .iterkeys(), .itervalues() and .iteritems() methods. The approach is inspired by that taken in the Java Collections Framework [1]_. @@ -72,25 +71,16 @@ have to write the iter() call because it is implied by a for-loop. The objects returned by the .keys() and .items() methods behave like -sets with limited mutability; they allow removing elements, but not -adding them. Removing an item from these sets removes it from the -underlying dict. The object returned by the values() method behaves -like a multiset (Java calls this a Collection). It does not allow -removing elements, because a value might occur multiple times and the -implementation wouldn't know which key to remove from the underlying -dict. (The Java Collections Framework has a way around this by -removing from an iterator, but I see no practical use case for that -functionality.) +sets. The object returned by the values() method behaves like a much +simpler unordered collection; anything more would require too much +implementation effort for the rare use case. Because of the set behavior, it will be possible to check whether two dicts have the same keys by simply testing:: if a.keys() == b.keys(): ... -and similarly for values. (Two multisets are deemed equal if they -have the same elements with the same cardinalities, e.g. the multiset -{1, 2, 2} is equal to the multiset {2, 1, 2} but differs from the -multiset {1, 2}.) +and similarly for .items(). These operations are thread-safe only to the extent that using them in a thread-unsafe way may cause an exception but will not cause @@ -145,26 +135,12 @@ for key in self.__d: yield key - def remove(self, key): - del self.__d[key] - - def discard(self, key): - if key in self: - self.remove(key) - - def pop(self): - return self.__d.popitem()[0] - - def clear(self): - self.__d.clear() - # The following operations should be implemented to be # compatible with sets; this can be done by exploiting # the above primitive operations: # # <, <=, ==, !=, >=, > (returning a bool) # &, |, ^, - (returning a new, real set object) - # &=, -= (updating in place and returning self; but not |=, ^=) # # as well as their method counterparts (.union(), etc.). # @@ -191,23 +167,6 @@ for key in self.__d: yield key, self.__d[key] - def remove(self, (key, value)): - if (key, value) not in self: - raise KeyError((key, value)) - del self.__d[key] - - def discard(self, item): - # Defined in terms of 'in' and .remove() so overriding - # those will update discard appropriately. - if item in self: - self.remove(item) - - def pop(self): - return self.__d.popitem() - - def clear(self): - self.__d.clear() - # As well as the set operations mentioned for d_keys above. # However the specifications suggested there will not work if # the values aren't hashable. Fortunately, the operations can @@ -288,11 +247,8 @@ # XXX Sometimes this could be optimized, but these are the # semantics: we can't depend on the values to be hashable # or comparable. - o = list(other) for x in self: - try: - o.remove(x) - except ValueError: + if not o in other: return False return True @@ -302,13 +258,21 @@ result = not result return result -Note that we don't implement .copy() -- the presence of a .copy() +Notes: + +The view objects are not directly mutable, but don't implement +__hash__(); their value can change if the underlying dict is mutated. + +The only requirements on the underlying dict are that it implements +__getitem__(), __contains__(), __iter__(), and __len__(0. + +We don't implement .copy() -- the presence of a .copy() method suggests that the copy has the same type as the original, but that's not feasible without copying the underlying dict. If you want a copy of a specific type, like list or set, you can just pass one of the above to the list() or set() constructor. -Also note that the specification implies that the order in which items +The specification implies that the order in which items are returned by .keys(), .values() and .items() is the same (just as it was in Python 2.x), because the order is all derived from the dict iterator (which is presumably arbitrary but stable as long as a dict @@ -325,7 +289,7 @@ speak for itself. I've left out the implementation of various set operations. These -could still present surprises. +could still present small surprises. It would be okay if multiple calls to d.keys() (etc.) returned the same object, since the object's only state is the dict to which it @@ -334,11 +298,6 @@ live forever once created? Strawman: probably not worth the extra slots in every dict. -Should d_values have mutating methods (pop(), clear())? Strawman: no. - -Should d_values implement set operations (as defined for multisets). -Strawman: no. - Should d_keys, d_values and d_items have a public instance variable or method through which one can retrieve the underlying dict? Strawman: yes (but what should it be called?). From buildbot at python.org Wed Feb 21 02:06:00 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 21 Feb 2007 01:06:00 +0000 Subject: [Python-checkins] buildbot failure in x86 gentoo 2.5 Message-ID: <20070221010600.B9B081E4002@bag.python.org> The Buildbot has detected a new failure of x86 gentoo 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%25202.5/builds/240 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Cornelius': Maximilian Build Source Stamp: [branch Bryon] Sabastian Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Wed Feb 21 02:09:11 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 21 Feb 2007 01:09:11 +0000 Subject: [Python-checkins] buildbot failure in x86 OpenBSD 2.5 Message-ID: <20070221010912.6A58A1E4002@bag.python.org> The Buildbot has detected a new failure of x86 OpenBSD 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520OpenBSD%25202.5/builds/215 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: The web-page 'force build' button was pressed by 'Ulysses': Maximo Build Source Stamp: [branch Seth] Mark Blamelist: BUILD FAILED: failed svn sincerely, -The Buildbot From python-checkins at python.org Wed Feb 21 06:20:42 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 21 Feb 2007 06:20:42 +0100 (CET) Subject: [Python-checkins] r53837 - in python/trunk: Doc/lib/libitertools.tex Lib/test/test_itertools.py Misc/NEWS Modules/itertoolsmodule.c Message-ID: <20070221052042.CFDD01E4002@bag.python.org> Author: raymond.hettinger Date: Wed Feb 21 06:20:38 2007 New Revision: 53837 Modified: python/trunk/Doc/lib/libitertools.tex python/trunk/Lib/test/test_itertools.py python/trunk/Misc/NEWS python/trunk/Modules/itertoolsmodule.c Log: Add itertools.izip_longest(). Modified: python/trunk/Doc/lib/libitertools.tex ============================================================================== --- python/trunk/Doc/lib/libitertools.tex (original) +++ python/trunk/Doc/lib/libitertools.tex Wed Feb 21 06:20:38 2007 @@ -302,6 +302,33 @@ don't care about trailing, unmatched values from the longer iterables. \end{funcdesc} +\begin{funcdesc}{izip_longest}{*iterables\optional{, fillvalue}} + Make an iterator that aggregates elements from each of the iterables. + If the iterables are of uneven length, missing values are filled-in + with \var{fillvalue}. Iteration continues until the longest iterable + is exhausted. Equivalent to: + + \begin{verbatim} + def izip_longest(*args, **kwds): + fillvalue = kwds.get('fillvalue') + def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): + yield counter() # yields the fillvalue, or raises IndexError + fillers = repeat(fillvalue) + iters = [chain(it, sentinel(), fillers) for it in args] + try: + for tup in izip(*iters): + yield tup + except IndexError: + pass + \end{verbatim} + + If one of the iterables is potentially infinite, then the + \function{izip_longest()} function should be wrapped with something + that limits the number of calls (for example \function{islice()} or + \function{take()}). + \versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{repeat}{object\optional{, times}} Make an iterator that returns \var{object} over and over again. Runs indefinitely unless the \var{times} argument is specified. Modified: python/trunk/Lib/test/test_itertools.py ============================================================================== --- python/trunk/Lib/test/test_itertools.py (original) +++ python/trunk/Lib/test/test_itertools.py Wed Feb 21 06:20:38 2007 @@ -198,6 +198,51 @@ ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + def test_iziplongest(self): + for args in [ + ['abc', range(6)], + [range(6), 'abc'], + [range(1000), range(2000,2100), range(3000,3050)], + [range(1000), range(0), range(3000,3050), range(1200), range(1500)], + [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)], + ]: + target = map(None, *args) + self.assertEqual(list(izip_longest(*args)), target) + self.assertEqual(list(izip_longest(*args, **{})), target) + target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X' + self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target) + + self.assertEqual(take(3,izip_longest('abcdef', count())), zip('abcdef', range(3))) # take 3 from infinite input + + self.assertEqual(list(izip_longest()), zip()) + self.assertEqual(list(izip_longest([])), zip([])) + self.assertEqual(list(izip_longest('abcdef')), zip('abcdef')) + + self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict + self.assertRaises(TypeError, izip_longest, 3) + self.assertRaises(TypeError, izip_longest, range(3), 3) + + for stmt in [ + "izip_longest('abc', fv=1)", + "izip_longest('abc', fillvalue=1, bogus_keyword=None)", + ]: + try: + eval(stmt, globals(), locals()) + except TypeError: + pass + else: + self.fail('Did not raise Type in: ' + stmt) + + # Check tuple re-use (implementation detail) + self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')], + zip('abc', 'def')) + self.assertEqual([pair for pair in izip_longest('abc', 'def')], + zip('abc', 'def')) + ids = map(id, izip_longest('abc', 'def')) + self.assertEqual(min(ids), max(ids)) + ids = map(id, list(izip_longest('abc', 'def'))) + self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + def test_repeat(self): self.assertEqual(zip(xrange(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) @@ -611,6 +656,15 @@ self.assertRaises(TypeError, list, izip(N(s))) self.assertRaises(ZeroDivisionError, list, izip(E(s))) + def test_iziplongest(self): + for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): + for g in (G, I, Ig, S, L, R): + self.assertEqual(list(izip_longest(g(s))), zip(g(s))) + self.assertEqual(list(izip_longest(g(s), g(s))), zip(g(s), g(s))) + self.assertRaises(TypeError, izip_longest, X(s)) + self.assertRaises(TypeError, list, izip_longest(N(s))) + self.assertRaises(ZeroDivisionError, list, izip_longest(E(s))) + def test_imap(self): for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)): for g in (G, I, Ig, S, L, R): Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed Feb 21 06:20:38 2007 @@ -127,6 +127,8 @@ - Added heapq.merge() for merging sorted input streams. +- Added itertools.izip_longest(). + - Have the encoding package's search function dynamically import using absolute import semantics. Modified: python/trunk/Modules/itertoolsmodule.c ============================================================================== --- python/trunk/Modules/itertoolsmodule.c (original) +++ python/trunk/Modules/itertoolsmodule.c Wed Feb 21 06:20:38 2007 @@ -2472,6 +2472,238 @@ PyObject_GC_Del, /* tp_free */ }; +/* iziplongest object ************************************************************/ + +#include "Python.h" + +typedef struct { + PyObject_HEAD + Py_ssize_t tuplesize; + Py_ssize_t numactive; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue; + PyObject *filler; /* repeat(fillvalue) */ +} iziplongestobject; + +static PyTypeObject iziplongest_type; + +static PyObject * +izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + iziplongestobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue = Py_None; + PyObject *filler; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { + fillvalue = PyDict_GetItemString(kwds, "fillvalue"); + if (fillvalue == NULL || PyDict_Size(kwds) > 1) { + PyErr_SetString(PyExc_TypeError, + "izip_longest() got an unexpected keyword argument"); + return NULL; + } + } + + /* args must be a tuple */ + assert(PyTuple_Check(args)); + + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "izip_longest argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } + + filler = PyObject_CallFunctionObjArgs((PyObject *)(&repeat_type), fillvalue, NULL); + if (filler == NULL) { + Py_DECREF(ittuple); + return NULL; + } + + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + Py_DECREF(filler); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create iziplongestobject structure */ + lz = (iziplongestobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(filler); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->numactive = tuplesize; + lz->result = result; + Py_INCREF(fillvalue); + lz->fillvalue = fillvalue; + Py_INCREF(filler); + lz->filler = filler; /* XXX */ + return (PyObject *)lz; +} + +static void +izip_longest_dealloc(iziplongestobject *lz) +{ + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_XDECREF(lz->fillvalue); + Py_XDECREF(lz->filler); + lz->ob_type->tp_free(lz); +} + +static int +izip_longest_traverse(iziplongestobject *lz, visitproc visit, void *arg) +{ + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + Py_VISIT(lz->fillvalue); + Py_VISIT(lz->filler); + return 0; +} + +static PyObject * +izip_longest_next(iziplongestobject *lz) +{ + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (result->ob_refcnt == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + if (lz->numactive <= 1) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->filler); + PyTuple_SET_ITEM(lz->ittuple, i, lz->filler); + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + Py_DECREF(it); + lz->numactive -= 1; + } + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + if (lz->numactive <= 1) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->filler); + PyTuple_SET_ITEM(lz->ittuple, i, lz->filler); + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + Py_DECREF(it); + lz->numactive -= 1; + } + } + PyTuple_SET_ITEM(result, i, item); + } + } + return result; +} + +PyDoc_STRVAR(izip_longest_doc, +"izip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> izip_longest object\n\ +\n\ +Return an izip_longest object whose .next() method returns a tuple where\n\ +the i-th element comes from the i-th iterable argument. The .next()\n\ +method continues until the longest iterable in the argument sequence\n\ +is exhausted and then it raises StopIteration. When the shorter iterables\n\ +are exhausted, the fillvalue is substituted in their place. The fillvalue\n\ +defaults to None or can be specified by a keyword argument.\n\ +"); + +static PyTypeObject iziplongest_type = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + "itertools.izip_longest", /* tp_name */ + sizeof(iziplongestobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)izip_longest_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + izip_longest_doc, /* tp_doc */ + (traverseproc)izip_longest_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)izip_longest_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + izip_longest_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ +}; /* module level code ********************************************************/ @@ -2485,6 +2717,7 @@ \n\ Iterators terminating on the shortest input sequence:\n\ izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ +izip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ ifilter(pred, seq) --> elements of seq where pred(elem) is True\n\ ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\ islice(seq, [start,] stop [, step]) --> elements from\n\ @@ -2522,6 +2755,7 @@ &ifilterfalse_type, &count_type, &izip_type, + &iziplongest_type, &repeat_type, &groupby_type, NULL From buildbot at python.org Wed Feb 21 06:38:23 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 21 Feb 2007 05:38:23 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP trunk Message-ID: <20070221053823.376671E4002@bag.python.org> The Buildbot has detected a new failure of x86 XP trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%2520trunk/builds/208 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings failed slave lost sincerely, -The Buildbot From nnorwitz at gmail.com Wed Feb 21 11:15:15 2007 From: nnorwitz at gmail.com (Neal Norwitz) Date: Wed, 21 Feb 2007 05:15:15 -0500 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20070221101515.GA6553@python.psfb.org> test_cmd_line leaked [0, 17, 0] references test_itertools leaked [188, 188, 188] references From g.brandl at gmx.net Wed Feb 21 11:33:23 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Wed, 21 Feb 2007 11:33:23 +0100 Subject: [Python-checkins] r53837 - in python/trunk: Doc/lib/libitertools.tex Lib/test/test_itertools.py Misc/NEWS Modules/itertoolsmodule.c In-Reply-To: <20070221052042.CFDD01E4002@bag.python.org> References: <20070221052042.CFDD01E4002@bag.python.org> Message-ID: raymond.hettinger schrieb: > Author: raymond.hettinger > Date: Wed Feb 21 06:20:38 2007 > New Revision: 53837 > > Modified: > python/trunk/Doc/lib/libitertools.tex > python/trunk/Lib/test/test_itertools.py > python/trunk/Misc/NEWS > python/trunk/Modules/itertoolsmodule.c > Log: > Add itertools.izip_longest(). > +static PyObject * > +izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) > +{ > + iziplongestobject *lz; > + Py_ssize_t i; > + PyObject *ittuple; /* tuple of iterators */ > + PyObject *result; > + PyObject *fillvalue = Py_None; > + PyObject *filler; > + Py_ssize_t tuplesize = PySequence_Length(args); > + > + if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { > + fillvalue = PyDict_GetItemString(kwds, "fillvalue"); > + if (fillvalue == NULL || PyDict_Size(kwds) > 1) { > + PyErr_SetString(PyExc_TypeError, > + "izip_longest() got an unexpected keyword argument"); > + return NULL; > + } > + } > + > + /* args must be a tuple */ > + assert(PyTuple_Check(args)); > + > + /* obtain iterators */ > + ittuple = PyTuple_New(tuplesize); > + if (ittuple == NULL) > + return NULL; > + for (i=0; i < tuplesize; ++i) { > + PyObject *item = PyTuple_GET_ITEM(args, i); > + PyObject *it = PyObject_GetIter(item); > + if (it == NULL) { > + if (PyErr_ExceptionMatches(PyExc_TypeError)) > + PyErr_Format(PyExc_TypeError, > + "izip_longest argument #%zd must support iteration", > + i+1); > + Py_DECREF(ittuple); > + return NULL; > + } > + PyTuple_SET_ITEM(ittuple, i, it); > + } > + > + filler = PyObject_CallFunctionObjArgs((PyObject *)(&repeat_type), fillvalue, NULL); > + if (filler == NULL) { > + Py_DECREF(ittuple); > + return NULL; > + } > + > + /* create a result holder */ > + result = PyTuple_New(tuplesize); > + if (result == NULL) { > + Py_DECREF(ittuple); > + Py_DECREF(filler); > + return NULL; > + } > + for (i=0 ; i < tuplesize ; i++) { > + Py_INCREF(Py_None); > + PyTuple_SET_ITEM(result, i, Py_None); > + } > + > + /* create iziplongestobject structure */ > + lz = (iziplongestobject *)type->tp_alloc(type, 0); > + if (lz == NULL) { > + Py_DECREF(ittuple); > + Py_DECREF(filler); > + Py_DECREF(result); > + return NULL; > + } > + lz->ittuple = ittuple; > + lz->tuplesize = tuplesize; > + lz->numactive = tuplesize; > + lz->result = result; > + Py_INCREF(fillvalue); > + lz->fillvalue = fillvalue; > + Py_INCREF(filler); filler doesn't need to be INCREF'd here, this causes the refleaks seen in Neal's automated test run. Georg From python-checkins at python.org Wed Feb 21 18:22:10 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 21 Feb 2007 18:22:10 +0100 (CET) Subject: [Python-checkins] r53838 - python/trunk/Modules/itertoolsmodule.c Message-ID: <20070221172210.6266B1E4002@bag.python.org> Author: raymond.hettinger Date: Wed Feb 21 18:22:05 2007 New Revision: 53838 Modified: python/trunk/Modules/itertoolsmodule.c Log: Remove filler struct item and fix leak. Modified: python/trunk/Modules/itertoolsmodule.c ============================================================================== --- python/trunk/Modules/itertoolsmodule.c (original) +++ python/trunk/Modules/itertoolsmodule.c Wed Feb 21 18:22:05 2007 @@ -2483,7 +2483,6 @@ PyObject *ittuple; /* tuple of iterators */ PyObject *result; PyObject *fillvalue; - PyObject *filler; /* repeat(fillvalue) */ } iziplongestobject; static PyTypeObject iziplongest_type; @@ -2496,7 +2495,6 @@ PyObject *ittuple; /* tuple of iterators */ PyObject *result; PyObject *fillvalue = Py_None; - PyObject *filler; Py_ssize_t tuplesize = PySequence_Length(args); if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { @@ -2529,17 +2527,10 @@ PyTuple_SET_ITEM(ittuple, i, it); } - filler = PyObject_CallFunctionObjArgs((PyObject *)(&repeat_type), fillvalue, NULL); - if (filler == NULL) { - Py_DECREF(ittuple); - return NULL; - } - /* create a result holder */ result = PyTuple_New(tuplesize); if (result == NULL) { Py_DECREF(ittuple); - Py_DECREF(filler); return NULL; } for (i=0 ; i < tuplesize ; i++) { @@ -2551,7 +2542,6 @@ lz = (iziplongestobject *)type->tp_alloc(type, 0); if (lz == NULL) { Py_DECREF(ittuple); - Py_DECREF(filler); Py_DECREF(result); return NULL; } @@ -2561,8 +2551,6 @@ lz->result = result; Py_INCREF(fillvalue); lz->fillvalue = fillvalue; - Py_INCREF(filler); - lz->filler = filler; /* XXX */ return (PyObject *)lz; } @@ -2573,7 +2561,6 @@ Py_XDECREF(lz->ittuple); Py_XDECREF(lz->result); Py_XDECREF(lz->fillvalue); - Py_XDECREF(lz->filler); lz->ob_type->tp_free(lz); } @@ -2583,7 +2570,6 @@ Py_VISIT(lz->ittuple); Py_VISIT(lz->result); Py_VISIT(lz->fillvalue); - Py_VISIT(lz->filler); return 0; } @@ -2599,25 +2585,31 @@ if (tuplesize == 0) return NULL; + if (lz->numactive == 0) + return NULL; if (result->ob_refcnt == 1) { Py_INCREF(result); for (i=0 ; i < tuplesize ; i++) { it = PyTuple_GET_ITEM(lz->ittuple, i); - assert(PyIter_Check(it)); - item = (*it->ob_type->tp_iternext)(it); - if (item == NULL) { - if (lz->numactive <= 1) { - Py_DECREF(result); - return NULL; - } else { - Py_INCREF(lz->filler); - PyTuple_SET_ITEM(lz->ittuple, i, lz->filler); - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - Py_DECREF(it); - lz->numactive -= 1; - } - } + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } olditem = PyTuple_GET_ITEM(result, i); PyTuple_SET_ITEM(result, i, item); Py_DECREF(olditem); @@ -2628,21 +2620,25 @@ return NULL; for (i=0 ; i < tuplesize ; i++) { it = PyTuple_GET_ITEM(lz->ittuple, i); - assert(PyIter_Check(it)); - item = (*it->ob_type->tp_iternext)(it); - if (item == NULL) { - if (lz->numactive <= 1) { - Py_DECREF(result); - return NULL; - } else { - Py_INCREF(lz->filler); - PyTuple_SET_ITEM(lz->ittuple, i, lz->filler); - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - Py_DECREF(it); - lz->numactive -= 1; - } - } + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } PyTuple_SET_ITEM(result, i, item); } } From buildbot at python.org Wed Feb 21 19:38:52 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 21 Feb 2007 18:38:52 +0000 Subject: [Python-checkins] buildbot warnings in x86 Ubuntu edgy (icc) trunk Message-ID: <20070221183857.0960D1E4002@bag.python.org> The Buildbot has detected a new failure of x86 Ubuntu edgy (icc) trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520Ubuntu%2520edgy%2520%2528icc%2529%2520trunk/builds/1204 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger Build had warnings: warnings failed slave lost sincerely, -The Buildbot From python-checkins at python.org Wed Feb 21 22:40:27 2007 From: python-checkins at python.org (erik.forsberg) Date: Wed, 21 Feb 2007 22:40:27 +0100 (CET) Subject: [Python-checkins] r53842 - in tracker: importer/sfxmlhandlers.py instances/python-dev/initial_data.py Message-ID: <20070221214027.808941E4002@bag.python.org> Author: erik.forsberg Date: Wed Feb 21 22:40:25 2007 New Revision: 53842 Modified: tracker/importer/sfxmlhandlers.py tracker/instances/python-dev/initial_data.py Log: Add 'patch' to list of initially created keywords. Set 'patch' keyword on issues that were of artifact_type 'Patches' on sf. Modified: tracker/importer/sfxmlhandlers.py ============================================================================== --- tracker/importer/sfxmlhandlers.py (original) +++ tracker/importer/sfxmlhandlers.py Wed Feb 21 22:40:25 2007 @@ -403,6 +403,8 @@ def handle(self, fields, roundupdata): if "Feature Requests" == fields[self.source].text: roundupdata[self.target] = self.db.issue_type.lookup("rfe") + elif "Patches" == fields[self.source].text: + roundupdata['keywords'].append(self.db.keyword.lookup("patch")) class GroupHandler(SFXMLHandler): def handle(self, fields, roundupdata): @@ -414,7 +416,7 @@ roundupdata['type'] = self.db.issue_type.lookup("rfe") return elif "Python 3000" == group: - roundupdata['keywords'] = [self.db.keyword.lookup('py3k')] + roundupdata['keywords'].append(self.db.keyword.lookup('py3k')) try: version = self.db.version.lookup(group) roundupdata[self.target] = version Modified: tracker/instances/python-dev/initial_data.py ============================================================================== --- tracker/instances/python-dev/initial_data.py (original) +++ tracker/instances/python-dev/initial_data.py Wed Feb 21 22:40:25 2007 @@ -78,6 +78,7 @@ keyword = db.getclass("keyword") keyword.create(name="py3k", description="Python 3000 bugs") +keyword.create(name="patch", description="Contains patch") # # create the two default users From python-checkins at python.org Thu Feb 22 00:48:00 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 00:48:00 +0100 (CET) Subject: [Python-checkins] r53846 - sandbox/pep362 Message-ID: <20070221234800.2CD071E4002@bag.python.org> Author: brett.cannon Date: Thu Feb 22 00:47:55 2007 New Revision: 53846 Added: sandbox/pep362/ Log: Create a place in the sandbox for work on PEP 362 (Function Signature object). From python-checkins at python.org Thu Feb 22 00:49:06 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 00:49:06 +0100 (CET) Subject: [Python-checkins] r53847 - sandbox/trunk/pep362 Message-ID: <20070221234906.C29641E4002@bag.python.org> Author: brett.cannon Date: Thu Feb 22 00:48:53 2007 New Revision: 53847 Added: sandbox/trunk/pep362/ Log: Create a place in the sandbox for work on PEP 362 (Function Signature object). From python-checkins at python.org Thu Feb 22 00:54:21 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 00:54:21 +0100 (CET) Subject: [Python-checkins] r53848 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070221235421.234401E4002@bag.python.org> Author: brett.cannon Date: Thu Feb 22 00:54:17 2007 New Revision: 53848 Added: sandbox/trunk/pep362/pep362.py (contents, props changed) sandbox/trunk/pep362/test_pep362.py (contents, props changed) Log: Initial commit of PEP 362 implementation. Torn directly out of local branch of trunk where code was integrated into the 'inspect' module (and test_inspect), so will need to fix imports and tests before any of this is usable. Added: sandbox/trunk/pep362/pep362.py ============================================================================== --- (empty file) +++ sandbox/trunk/pep362/pep362.py Thu Feb 22 00:54:17 2007 @@ -0,0 +1,174 @@ +class BindError(TypeError): + """Represent a failure of inspect.Signature.bind() being able to to + determine if a binding of arguments to parameters is possible.""" + pass + +class Signature(object): + + """Object to represent the signature of a function/method.""" + + def __init__(self, func): + """Initialize from a function or method object.""" + if hasattr(func, 'im_func'): + func = func.im_func + self.name = func.__name__ + + argspec = getargspec(func) + + self.var_args = argspec[1] if (argspec[1] is not None) else '' + self.var_kw_args = argspec[2] if (argspec[2] is not None) else '' + + arg_count = len(argspec[0]) + defaults_start = (arg_count - len(argspec[3]) + if argspec[3] else arg_count) + parameters = [] + for index, arg_name in enumerate(argspec[0]): + if isinstance(arg_name, list): + arg_name = self.__list2tuple(arg_name) + + if index >= defaults_start: + parameters.append(Parameter(arg_name, index, True, + argspec[3][index - defaults_start])) + else: + parameters.append(Parameter(arg_name, index, False)) + + self.parameters = tuple(parameters) + + @classmethod + def __list2tuple(cls, list_): + if not isinstance(list_, list): + return list_ + else: + return tuple(cls.__list2tuple(x) for x in list_) + + def __str__(self): + """String representation of a signature as one might write it in source + code.""" + result = "%s(" % self.name + result += ", ".join(str(param) for param in self.parameters) + if self.var_args: + if self.parameters: + result +=", " + result += "*%s" % self.var_args + if self.var_kw_args: + if self.parameters or self.var_args: + result += ", " + result += "**%s" % self.var_kw_args + result += ")" + return result + + @classmethod + def __tuple_bind_ok(cls, tuple_, arg): + """Verify that 'arg' will unpack properly to be used with 'tuple_'.""" + try: + if len(tuple_) != len(arg): + return False + except TypeError: + raise BindError("cannot determine the length of the argument") + if (hasattr(arg, '__iter__') and hasattr(arg, 'next') and + callable(arg.__iter__) and callable(arg.next)): + raise IndexError("do not want to mutate an iterator") + for tuple_item, arg_item in zip(tuple_, arg): + if isinstance(tuple_item, tuple): + if not cls.__tuple_bind_ok(tuple_item, arg_item): + return False + return True + + @classmethod + def __positional_bind(cls, parameter, arg, bindings): + """Bind 'argument' to 'parameter' in 'bindings' if it is a legitimate + binding. + + A binding can be illegitimate if the parameter is a tuple and the + argument will either unpack improperly or it cannot be determined if it + will without possibly mutating the object (e.g., if it is an + iterator). + + """ + if isinstance(parameter, tuple): + if not cls.__tuple_bind_ok(parameter, arg): + raise TypeError("cannot unpack argument for %s" % parameter) + bindings[parameter] = arg + + def bind(self, *args, **kwargs): + """Return a dictionary mapping function arguments to their parameter + variables, if possible. + + If the only way to determine the proper binding when tuple parameters + are present is to posssibly mutate an iterator then the method gives up + and raises a BindError. This is to prevent something like a generator + which is about to be used for an actual function call from being + exhausted by this method.""" + bindings = {} + arg_names_seq = [param.name for param in self.parameters] + arg_names_set = set(arg_names_seq) + arg_names_cnt = len(arg_names_set) + required_args = set(param.name for param in self.parameters + if not param.has_default) + required_args_cnt = len(required_args) + # *args. + if self.var_args: + bindings[self.var_args] = args[arg_names_cnt:] + args = args[:arg_names_cnt] + if len(args) > arg_names_cnt: + raise TypeError("too many positional arguments provided") + for arg_name, value in zip(arg_names_seq, args): + self.__positional_bind(arg_name, value, bindings) + # Keyword arguments. + var_kw_args = {} + for key, value in kwargs.items(): + if key not in arg_names_set: + if not self.var_kw_args: + raise TypeError("unexpected keyword argument: %r" % key) + else: + var_kw_args[key] = value + else: + if key in bindings: + raise TypeError("got multiple values for argument %r" % + key) + else: + bindings[key] = value + del kwargs[key] + if kwargs: + raise TypeError("too many keyword arguments provided") + # **kwargs. + if self.var_kw_args: + bindings[self.var_kw_args] = var_kw_args + # Default values. + for param in self.parameters: + if param.has_default: + if param.name not in bindings: + bindings[param.name] = param.default_value + + # Make sure all required arguments are bound to. + for bound in bindings.iterkeys(): + try: + required_args.remove(bound) + except KeyError: + pass + else: + if required_args: + raise TypeError("too few arguments provided") + return bindings + + +def getsignature(func): + """Return a Signature object for the function or method. + + If possible, return the existing value stored in __signature__. If that + attribute does not exist, then try to store the Signature object at that + attribute if possible (but is not required). + + """ + if hasattr(func, 'im_func'): + func = func.im_func + sig = Signature(func) + if not hasattr(func, '__signature__'): + try: + func.__signature__ = sig + except AttributeError: + pass + else: + sig = func.__signature__ + + return sig Added: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- (empty file) +++ sandbox/trunk/pep362/test_pep362.py Thu Feb 22 00:54:17 2007 @@ -0,0 +1,255 @@ +class ParameterObjectTests(unittest.TestCase): + + """Test the Parameter object.""" + + def test_name(self): + # Test that 'name' attribute works. + # Must test both using a string and a tuple of strings. + name = "test" + param = inspect.Parameter(name, 0, False) + self.failUnlessEqual(param.name, name) + name = ('a', ('b',)) + param = inspect.Parameter(name, 0, False) + self.failUnlessEqual(param.name, name) + + def test_position(self): + # Test the 'position' attribute. + pos = 42 + param = inspect.Parameter("_", pos, False) + self.failUnlessEqual(param.position, pos) + + def test_has_default(self): + # Test the 'has_default' attribute. + # Testing that 'default_value' is not set is handled in the testing of + # that attribute. + param = inspect.Parameter('_', 0, True, None) + self.failUnlessEqual(param.has_default, True) + param = inspect.Parameter('_', 0, False) + self.failUnlessEqual(param.has_default, False) + self.failUnlessRaises(TypeError, inspect.Parameter, + ('_', 0, False, 'extra arg')) + self.failUnlessRaises(TypeError, inspect.Parameter, + ('_', 0, True)) + self.failUnlessRaises(TypeError, inspect.Parameter, + ('_', 0, True, 'default', 'extra')) + + def test_default_value(self): + # Test the 'default_value' attribute. + # Make sure that if has_default is set to False that default_value is + # not defined. + param = inspect.Parameter('_', 0, False) + self.failUnless(not hasattr(param, 'default_value')) + default = 42 + param = inspect.Parameter('_', 0, True, default) + self.failUnlessEqual(param.default_value, default) + + def test_str(self): + # Test __str__(). + name = "X" + param = inspect.Parameter(name, 0, False) + self.failUnlessEqual(name, str(param)) + default_value = 42 + param = inspect.Parameter(name, 0, True, default_value) + self.failUnlessEqual("%s=%s" % (name, default_value), str(param)) + + def test_repr(self): + # Test __repr__(). + name = "X" + pos = 0 + param = inspect.Parameter(name, pos, False) + self.failUnlessEqual("Parameter(%r, %r, False)" % (name, pos), + repr(param)) + default_value = 42 + param = inspect.Parameter(name, pos, True, default_value) + self.failUnlessEqual("Parameter(%r, %r, True, %r)" % + (name, pos, default_value), + repr(param)) + + +class SignatureObjectTests(unittest.TestCase): + + def test_no_args(self): + # Test a function with no arguments. + sig = inspect.Signature(mod.no_args) + self.failUnlessEqual('no_args', sig.name) + self.failUnless(not sig.var_args) + self.failUnless(not sig.var_kw_args) + self.failUnlessEqual(0, len(sig.parameters)) + + def test_var_args(self): + # Test the var_args attribute. + sig = inspect.Signature(mod.var_args) + self.failUnlessEqual('args', sig.var_args) + self.failUnlessEqual(0, len(sig.parameters)) + sig = inspect.Signature(mod.no_args) + self.failUnlessEqual('', sig.var_args) + + def test_var_kw_args(self): + # Test the var_kw_args attribute. + sig = inspect.Signature(mod.var_kw_args) + self.failUnlessEqual('var_kw_args', sig.name) + self.failUnlessEqual('kwargs', sig.var_kw_args) + self.failUnlessEqual(0, len(sig.parameters)) + sig = inspect.Signature(mod.no_args) + self.failUnlessEqual('', sig.var_kw_args) + + def test_parameter_positional(self): + sig = inspect.Signature(mod.no_default_args) + self.failUnlessEqual('no_default_args', sig.name) + param = sig.parameters[0] + self.failUnlessEqual('a', param.name) + self.failUnlessEqual(0, param.position) + self.failUnless(not param.has_default) + self.failUnless(not hasattr(param, 'default_value')) + + def test_parameter_default(self): + sig = inspect.Signature(mod.default_args) + self.failUnlessEqual('default_args', sig.name) + param = sig.parameters[0] + self.failUnlessEqual('a', param.name) + self.failUnlessEqual(0, param.position) + self.failUnless(param.has_default) + self.failUnlessEqual(42, param.default_value) + + def test_parameter_tuple(self): + sig = inspect.Signature(mod.tuple_args) + self.failUnlessEqual('tuple_args', sig.name) + param = sig.parameters[0] + self.failUnless(isinstance(param.name, tuple)) + self.failUnlessEqual(('a', ('b',)), param.name) + self.failUnlessEqual(0, param.position) + self.failUnless(not param.has_default) + self.failUnless(not hasattr(param, 'default_value')) + + def test_parameter_tuple_default(self): + sig = inspect.Signature(mod.default_tuple_args) + self.failUnlessEqual('default_tuple_args', sig.name) + param = sig.parameters[0] + self.failUnlessEqual(('a', ('b',)), param.name) + self.failUnlessEqual(0, param.position) + self.failUnless(param.has_default) + self.failUnlessEqual((1, (2,)), param.default_value) + + def test_positioning(self): + sig = inspect.Signature(mod.all_args) + param = sig.parameters[2] + self.failUnlessEqual('d', param.name) + + def test_getsignature(self): + def fresh_func(): + pass + self.failUnless(not hasattr(fresh_func, '__signature__')) + sig = inspect.getsignature(fresh_func) + self.failUnlessEqual(sig, fresh_func.__signature__) + sig2 = inspect.getsignature(fresh_func) + self.failUnlessEqual(sig, sig2) + class FreshClass(object): + def fresh_method(self): + pass + sig = inspect.getsignature(FreshClass.fresh_method) + self.failUnlessEqual(sig, FreshClass.fresh_method.im_func.__signature__) + + def test_str(self): + # Test __str__(). + sig = inspect.Signature(mod.no_args) + self.failUnlessEqual("no_args()", str(sig)) + sig = inspect.Signature(mod.var_args) + self.failUnlessEqual("var_args(*args)", str(sig)) + sig = inspect.Signature(mod.var_kw_args) + self.failUnlessEqual("var_kw_args(**kwargs)", str(sig)) + sig = inspect.Signature(mod.default_args) + self.failUnlessEqual("default_args(a=42)", str(sig)) + sig = inspect.Signature(mod.no_default_args) + self.failUnlessEqual("no_default_args(a)", str(sig)) + sig = inspect.Signature(mod.tuple_args) + self.failUnlessEqual("tuple_args((a, (b,)))", str(sig)) + sig = inspect.Signature(mod.default_tuple_args) + self.failUnlessEqual("default_tuple_args((a, (b,))=(1, (2,)))", + str(sig)) + sig = inspect.Signature(mod.all_args) + self.failUnlessEqual("all_args(a, (b, (c,)), d=0, " + "(e, (f,))=(1, (2,)), *g, **h)", + str(sig)) + +class SignatureBindTests(unittest.TestCase): + + """Test Signature.bind().""" + + def test_no_parameters(self): + sig = inspect.Signature(mod.no_args) + binding = sig.bind() + self.failUnlessEqual({}, binding) + self.failUnlessRaises(TypeError, sig.bind, 42) + self.failUnlessRaises(TypeError, sig.bind, a=0) + + def test_var_parameters(self): + sig = inspect.Signature(mod.var_args) + binding = sig.bind(0, 1, 2) + self.failUnlessEqual({'args':(0, 1, 2)}, binding) + binding = sig.bind() + self.failUnlessEqual({'args':tuple()}, binding) + self.failUnlessRaises(TypeError, sig.bind, a=0) + + def test_var_kw_parameters(self): + sig = inspect.Signature(mod.var_kw_args) + binding = sig.bind(a=0) + self.failUnlessEqual({'kwargs':{'a':0}}, binding) + binding = sig.bind() + self.failUnlessEqual({'kwargs':{}}, binding) + self.failUnlessRaises(TypeError, sig.bind, 42) + + def test_positional_parameters(self): + sig = inspect.Signature(mod.no_default_args) + binding = sig.bind(42) + self.failUnlessEqual({'a':42}, binding) + binding = sig.bind(a=42) + self.failUnlessEqual({'a':42}, binding) + self.failUnlessRaises(TypeError, sig.bind) + self.failUnlessRaises(TypeError, sig.bind, 0, 1) + self.failUnlessRaises(TypeError, sig.bind, b=0) + + def test_keyword_parameters(self): + sig = inspect.Signature(mod.default_args) + binding = sig.bind(0) + self.failUnlessEqual({'a':0}, binding) + binding = sig.bind() + self.failUnlessEqual({'a':42}, binding) + binding = sig.bind(a=0) + self.failUnlessEqual({'a':0}, binding) + self.failUnlessRaises(TypeError, sig.bind, 0, 1) + self.failUnlessRaises(TypeError, sig.bind, a=0, b=1) + self.failUnlessRaises(TypeError, sig.bind, b=1) + + def test_tuple_parameter(self): + sig = inspect.Signature(mod.tuple_args) + binding = sig.bind((1, (2,))) + self.failUnlessEqual({('a', ('b',)):(1, (2,))}, binding) + arg = (1, ((2,),)) + binding = sig.bind(arg) + self.failUnlessEqual({('a', ('b',)):arg}, binding) + self.failUnlessRaises(TypeError, sig.bind, (1,2,3)) + self.failUnlessRaises(TypeError, sig.bind, (1, 2)) + + def test_default_tuple_parameter(self): + sig = inspect.Signature(mod.default_tuple_args) + binding = sig.bind() + self.failUnlessEqual({('a', ('b',)):(1, (2,))}, binding) + arg = (0, (1,)) + binding = sig.bind(arg) + self.failUnlessEqual({('a', ('b',)):arg}, binding) + + def test_all_parameter_types(self): + sig = inspect.Signature(mod.all_args) + binding = sig.bind(0, (1, (2,)), 3, (4, (5,)), 6, i=7) + expected = {'a':0, ('b', ('c',)):(1, (2,)), 'd':3, + ('e', ('f',)):(4, (5,)), 'g':(6,), 'h':{'i':7}} + self.failUnlessEqual(expected, binding) + + def test_BindError(self): + def gen(): + yield 0 + yield (1,) + sig = inspect.Signature(mod.tuple_args) + self.failUnlessRaises(inspect.BindError, sig.bind, gen()) + + From python-checkins at python.org Thu Feb 22 00:56:52 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 00:56:52 +0100 (CET) Subject: [Python-checkins] r53849 - sandbox/pep362 Message-ID: <20070221235652.4FEBC1E4002@bag.python.org> Author: brett.cannon Date: Thu Feb 22 00:56:50 2007 New Revision: 53849 Removed: sandbox/pep362/ Log: Remove accidental addition of a directory; should have been in the trunk of the sandbox. From python-checkins at python.org Thu Feb 22 01:03:01 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 01:03:01 +0100 (CET) Subject: [Python-checkins] r53850 - sandbox/trunk/pep362/pep362.py Message-ID: <20070222000301.9345B1E4003@bag.python.org> Author: brett.cannon Date: Thu Feb 22 01:02:57 2007 New Revision: 53850 Modified: sandbox/trunk/pep362/pep362.py Log: Add Parameter class that was accidentally skipped in initial copy from local branch work. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Thu Feb 22 01:02:57 2007 @@ -3,6 +3,57 @@ determine if a binding of arguments to parameters is possible.""" pass + +class Parameter(object): + + """Represent a parameter in a function signature.""" + + def __init__(self, name, position, has_default, *args): + self.name = name + self.position = position + if not has_default: + self.has_default = False + else: + self.has_default = True + if len(args) != 1: + raise ValueError("Parameter requires a default value to be " + "specified when has_default has been set " + "to True") + self.default_value = args[0] + + @classmethod + def __tuple2param(self, tuple_): + if not isinstance(tuple_, tuple): + return str(tuple_) + elif len(tuple_) == 1: + return "(" + str(tuple_[0]) +",)" + else: + return ('(' + + ', '.join(self.__tuple2param(x) for x in tuple_) + + ')') + + def __str__(self): + """Return the string representation of the parameter as it would look + in a function's signature.""" + if isinstance(self.name, tuple): + result = self.__tuple2param(self.name) + else: + result = self.name + if self.has_default: + result+= "=" + str(self.default_value) + return result + + def __repr__(self): + """Return the string required to create an equivalent instance of this + parameter.""" + result = "%s(%r, %r, %r" % (self.__class__.__name__, + self.name, self.position, self.has_default) + if self.has_default: + result +=", %r" % self.default_value + result += ")" + return result + + class Signature(object): """Object to represent the signature of a function/method.""" @@ -152,7 +203,7 @@ return bindings -def getsignature(func): +def signature(func): """Return a Signature object for the function or method. If possible, return the existing value stored in __signature__. If that From python-checkins at python.org Thu Feb 22 01:15:56 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 01:15:56 +0100 (CET) Subject: [Python-checkins] r53851 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070222001556.26C9D1E4015@bag.python.org> Author: brett.cannon Date: Thu Feb 22 01:15:54 2007 New Revision: 53851 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Get code back into shape so that it passes all unit tests again. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Thu Feb 22 01:15:54 2007 @@ -1,3 +1,6 @@ +import inspect + + class BindError(TypeError): """Represent a failure of inspect.Signature.bind() being able to to determine if a binding of arguments to parameters is possible.""" @@ -64,7 +67,7 @@ func = func.im_func self.name = func.__name__ - argspec = getargspec(func) + argspec = inspect.getargspec(func) self.var_args = argspec[1] if (argspec[1] is not None) else '' self.var_kw_args = argspec[2] if (argspec[2] is not None) else '' Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Thu Feb 22 01:15:54 2007 @@ -1,3 +1,9 @@ +import pep362 + +import unittest +from test import test_support +import pep362_fodder + class ParameterObjectTests(unittest.TestCase): """Test the Parameter object.""" @@ -6,61 +12,61 @@ # Test that 'name' attribute works. # Must test both using a string and a tuple of strings. name = "test" - param = inspect.Parameter(name, 0, False) + param = pep362.Parameter(name, 0, False) self.failUnlessEqual(param.name, name) name = ('a', ('b',)) - param = inspect.Parameter(name, 0, False) + param = pep362.Parameter(name, 0, False) self.failUnlessEqual(param.name, name) def test_position(self): # Test the 'position' attribute. pos = 42 - param = inspect.Parameter("_", pos, False) + param = pep362.Parameter("_", pos, False) self.failUnlessEqual(param.position, pos) def test_has_default(self): # Test the 'has_default' attribute. # Testing that 'default_value' is not set is handled in the testing of # that attribute. - param = inspect.Parameter('_', 0, True, None) + param = pep362.Parameter('_', 0, True, None) self.failUnlessEqual(param.has_default, True) - param = inspect.Parameter('_', 0, False) + param = pep362.Parameter('_', 0, False) self.failUnlessEqual(param.has_default, False) - self.failUnlessRaises(TypeError, inspect.Parameter, + self.failUnlessRaises(TypeError, pep362.Parameter, ('_', 0, False, 'extra arg')) - self.failUnlessRaises(TypeError, inspect.Parameter, + self.failUnlessRaises(TypeError, pep362.Parameter, ('_', 0, True)) - self.failUnlessRaises(TypeError, inspect.Parameter, + self.failUnlessRaises(TypeError, pep362.Parameter, ('_', 0, True, 'default', 'extra')) def test_default_value(self): # Test the 'default_value' attribute. # Make sure that if has_default is set to False that default_value is # not defined. - param = inspect.Parameter('_', 0, False) + param = pep362.Parameter('_', 0, False) self.failUnless(not hasattr(param, 'default_value')) default = 42 - param = inspect.Parameter('_', 0, True, default) + param = pep362.Parameter('_', 0, True, default) self.failUnlessEqual(param.default_value, default) def test_str(self): # Test __str__(). name = "X" - param = inspect.Parameter(name, 0, False) + param = pep362.Parameter(name, 0, False) self.failUnlessEqual(name, str(param)) default_value = 42 - param = inspect.Parameter(name, 0, True, default_value) + param = pep362.Parameter(name, 0, True, default_value) self.failUnlessEqual("%s=%s" % (name, default_value), str(param)) def test_repr(self): # Test __repr__(). name = "X" pos = 0 - param = inspect.Parameter(name, pos, False) + param = pep362.Parameter(name, pos, False) self.failUnlessEqual("Parameter(%r, %r, False)" % (name, pos), repr(param)) default_value = 42 - param = inspect.Parameter(name, pos, True, default_value) + param = pep362.Parameter(name, pos, True, default_value) self.failUnlessEqual("Parameter(%r, %r, True, %r)" % (name, pos, default_value), repr(param)) @@ -70,7 +76,7 @@ def test_no_args(self): # Test a function with no arguments. - sig = inspect.Signature(mod.no_args) + sig = pep362.Signature(pep362_fodder.no_args) self.failUnlessEqual('no_args', sig.name) self.failUnless(not sig.var_args) self.failUnless(not sig.var_kw_args) @@ -78,23 +84,23 @@ def test_var_args(self): # Test the var_args attribute. - sig = inspect.Signature(mod.var_args) + sig = pep362.Signature(pep362_fodder.var_args) self.failUnlessEqual('args', sig.var_args) self.failUnlessEqual(0, len(sig.parameters)) - sig = inspect.Signature(mod.no_args) + sig = pep362.Signature(pep362_fodder.no_args) self.failUnlessEqual('', sig.var_args) def test_var_kw_args(self): # Test the var_kw_args attribute. - sig = inspect.Signature(mod.var_kw_args) + sig = pep362.Signature(pep362_fodder.var_kw_args) self.failUnlessEqual('var_kw_args', sig.name) self.failUnlessEqual('kwargs', sig.var_kw_args) self.failUnlessEqual(0, len(sig.parameters)) - sig = inspect.Signature(mod.no_args) + sig = pep362.Signature(pep362_fodder.no_args) self.failUnlessEqual('', sig.var_kw_args) def test_parameter_positional(self): - sig = inspect.Signature(mod.no_default_args) + sig = pep362.Signature(pep362_fodder.no_default_args) self.failUnlessEqual('no_default_args', sig.name) param = sig.parameters[0] self.failUnlessEqual('a', param.name) @@ -103,7 +109,7 @@ self.failUnless(not hasattr(param, 'default_value')) def test_parameter_default(self): - sig = inspect.Signature(mod.default_args) + sig = pep362.Signature(pep362_fodder.default_args) self.failUnlessEqual('default_args', sig.name) param = sig.parameters[0] self.failUnlessEqual('a', param.name) @@ -112,7 +118,7 @@ self.failUnlessEqual(42, param.default_value) def test_parameter_tuple(self): - sig = inspect.Signature(mod.tuple_args) + sig = pep362.Signature(pep362_fodder.tuple_args) self.failUnlessEqual('tuple_args', sig.name) param = sig.parameters[0] self.failUnless(isinstance(param.name, tuple)) @@ -122,7 +128,7 @@ self.failUnless(not hasattr(param, 'default_value')) def test_parameter_tuple_default(self): - sig = inspect.Signature(mod.default_tuple_args) + sig = pep362.Signature(pep362_fodder.default_tuple_args) self.failUnlessEqual('default_tuple_args', sig.name) param = sig.parameters[0] self.failUnlessEqual(('a', ('b',)), param.name) @@ -131,42 +137,42 @@ self.failUnlessEqual((1, (2,)), param.default_value) def test_positioning(self): - sig = inspect.Signature(mod.all_args) + sig = pep362.Signature(pep362_fodder.all_args) param = sig.parameters[2] self.failUnlessEqual('d', param.name) - def test_getsignature(self): + def test_signature(self): def fresh_func(): pass self.failUnless(not hasattr(fresh_func, '__signature__')) - sig = inspect.getsignature(fresh_func) + sig = pep362.signature(fresh_func) self.failUnlessEqual(sig, fresh_func.__signature__) - sig2 = inspect.getsignature(fresh_func) + sig2 = pep362.signature(fresh_func) self.failUnlessEqual(sig, sig2) class FreshClass(object): def fresh_method(self): pass - sig = inspect.getsignature(FreshClass.fresh_method) + sig = pep362.signature(FreshClass.fresh_method) self.failUnlessEqual(sig, FreshClass.fresh_method.im_func.__signature__) def test_str(self): # Test __str__(). - sig = inspect.Signature(mod.no_args) + sig = pep362.Signature(pep362_fodder.no_args) self.failUnlessEqual("no_args()", str(sig)) - sig = inspect.Signature(mod.var_args) + sig = pep362.Signature(pep362_fodder.var_args) self.failUnlessEqual("var_args(*args)", str(sig)) - sig = inspect.Signature(mod.var_kw_args) + sig = pep362.Signature(pep362_fodder.var_kw_args) self.failUnlessEqual("var_kw_args(**kwargs)", str(sig)) - sig = inspect.Signature(mod.default_args) + sig = pep362.Signature(pep362_fodder.default_args) self.failUnlessEqual("default_args(a=42)", str(sig)) - sig = inspect.Signature(mod.no_default_args) + sig = pep362.Signature(pep362_fodder.no_default_args) self.failUnlessEqual("no_default_args(a)", str(sig)) - sig = inspect.Signature(mod.tuple_args) + sig = pep362.Signature(pep362_fodder.tuple_args) self.failUnlessEqual("tuple_args((a, (b,)))", str(sig)) - sig = inspect.Signature(mod.default_tuple_args) + sig = pep362.Signature(pep362_fodder.default_tuple_args) self.failUnlessEqual("default_tuple_args((a, (b,))=(1, (2,)))", str(sig)) - sig = inspect.Signature(mod.all_args) + sig = pep362.Signature(pep362_fodder.all_args) self.failUnlessEqual("all_args(a, (b, (c,)), d=0, " "(e, (f,))=(1, (2,)), *g, **h)", str(sig)) @@ -176,14 +182,14 @@ """Test Signature.bind().""" def test_no_parameters(self): - sig = inspect.Signature(mod.no_args) + sig = pep362.Signature(pep362_fodder.no_args) binding = sig.bind() self.failUnlessEqual({}, binding) self.failUnlessRaises(TypeError, sig.bind, 42) self.failUnlessRaises(TypeError, sig.bind, a=0) def test_var_parameters(self): - sig = inspect.Signature(mod.var_args) + sig = pep362.Signature(pep362_fodder.var_args) binding = sig.bind(0, 1, 2) self.failUnlessEqual({'args':(0, 1, 2)}, binding) binding = sig.bind() @@ -191,7 +197,7 @@ self.failUnlessRaises(TypeError, sig.bind, a=0) def test_var_kw_parameters(self): - sig = inspect.Signature(mod.var_kw_args) + sig = pep362.Signature(pep362_fodder.var_kw_args) binding = sig.bind(a=0) self.failUnlessEqual({'kwargs':{'a':0}}, binding) binding = sig.bind() @@ -199,7 +205,7 @@ self.failUnlessRaises(TypeError, sig.bind, 42) def test_positional_parameters(self): - sig = inspect.Signature(mod.no_default_args) + sig = pep362.Signature(pep362_fodder.no_default_args) binding = sig.bind(42) self.failUnlessEqual({'a':42}, binding) binding = sig.bind(a=42) @@ -209,7 +215,7 @@ self.failUnlessRaises(TypeError, sig.bind, b=0) def test_keyword_parameters(self): - sig = inspect.Signature(mod.default_args) + sig = pep362.Signature(pep362_fodder.default_args) binding = sig.bind(0) self.failUnlessEqual({'a':0}, binding) binding = sig.bind() @@ -221,7 +227,7 @@ self.failUnlessRaises(TypeError, sig.bind, b=1) def test_tuple_parameter(self): - sig = inspect.Signature(mod.tuple_args) + sig = pep362.Signature(pep362_fodder.tuple_args) binding = sig.bind((1, (2,))) self.failUnlessEqual({('a', ('b',)):(1, (2,))}, binding) arg = (1, ((2,),)) @@ -231,7 +237,7 @@ self.failUnlessRaises(TypeError, sig.bind, (1, 2)) def test_default_tuple_parameter(self): - sig = inspect.Signature(mod.default_tuple_args) + sig = pep362.Signature(pep362_fodder.default_tuple_args) binding = sig.bind() self.failUnlessEqual({('a', ('b',)):(1, (2,))}, binding) arg = (0, (1,)) @@ -239,7 +245,7 @@ self.failUnlessEqual({('a', ('b',)):arg}, binding) def test_all_parameter_types(self): - sig = inspect.Signature(mod.all_args) + sig = pep362.Signature(pep362_fodder.all_args) binding = sig.bind(0, (1, (2,)), 3, (4, (5,)), 6, i=7) expected = {'a':0, ('b', ('c',)):(1, (2,)), 'd':3, ('e', ('f',)):(4, (5,)), 'g':(6,), 'h':{'i':7}} @@ -249,7 +255,15 @@ def gen(): yield 0 yield (1,) - sig = inspect.Signature(mod.tuple_args) - self.failUnlessRaises(inspect.BindError, sig.bind, gen()) + sig = pep362.Signature(pep362_fodder.tuple_args) + self.failUnlessRaises(pep362.BindError, sig.bind, gen()) + + +def test_main(): + test_support.run_unittest(ParameterObjectTests, + SignatureObjectTests, + ) +if __name__ == '__main__': + test_main() From cilfp at that90sporn.com Thu Feb 22 19:05:58 2007 From: cilfp at that90sporn.com (Steve Meyer) Date: Thu, 22 Feb 2007 18:05:58 +0000 Subject: [Python-checkins] tourism potato Message-ID: <45DDDB86.4030102@specialty-bulb-lamp.cn> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-checkins/attachments/20070222/eaf36e7b/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: thin.gif Type: image/gif Size: 17265 bytes Desc: not available Url : http://mail.python.org/pipermail/python-checkins/attachments/20070222/eaf36e7b/attachment.gif From python-checkins at python.org Fri Feb 23 00:57:47 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 23 Feb 2007 00:57:47 +0100 (CET) Subject: [Python-checkins] r53860 - peps/trunk/pep-0000.txt peps/trunk/pep-0358.txt Message-ID: <20070222235747.3546F1E4003@bag.python.org> Author: guido.van.rossum Date: Fri Feb 23 00:57:46 2007 New Revision: 53860 Modified: peps/trunk/pep-0000.txt peps/trunk/pep-0358.txt Log: Update the bytes object to better resemble my intentions. Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Fri Feb 23 00:57:46 2007 @@ -107,7 +107,7 @@ I 350 Codetags Elliott S 354 Enumerations in Python Finney S 355 Path - Object oriented filesystem paths Lindqvist - S 358 The "bytes" Object Schemenauer + S 358 The "bytes" Object Schemenauer, GvR S 362 Function Signature Object Cannon, Seo S 754 IEEE 754 Floating Point Special Values Warnes S 3101 Advanced String Formatting Talin @@ -431,7 +431,7 @@ S 355 Path - Object oriented filesystem paths Lindqvist IF 356 Python 2.5 Release Schedule Norwitz, et al SF 357 Allowing Any Object to be Used for Slicing Oliphant - S 358 The "bytes" Object Schemenauer + S 358 The "bytes" Object Schemenauer, GvR SW 359 The "make" Statement Bethard I 360 Externally Maintained Packages Cannon I 361 Python 2.6 Release Schedule Norwitz, et al Modified: peps/trunk/pep-0358.txt ============================================================================== --- peps/trunk/pep-0358.txt (original) +++ peps/trunk/pep-0358.txt Fri Feb 23 00:57:46 2007 @@ -2,12 +2,12 @@ Title: The "bytes" Object Version: $Revision$ Last-Modified: $Date$ -Author: Neil Schemenauer +Author: Neil Schemenauer , Guido van Rossum Status: Draft Type: Standards Track Content-Type: text/plain Created: 15-Feb-2006 -Python-Version: 2.5 +Python-Version: 2.6, 3.0 Post-History: @@ -20,74 +20,86 @@ Motivation - Python's current string objects are overloaded. They serve to hold - both sequences of characters and sequences of bytes. This - overloading of purpose leads to confusion and bugs. In future + Python's current string objects are overloaded. They serve to hold + both sequences of characters and sequences of bytes. This + overloading of purpose leads to confusion and bugs. In future versions of Python, string objects will be used for holding - character data. The bytes object will fulfil the role of a byte - container. Eventually the unicode built-in will be renamed to str + character data. The bytes object will fulfil the role of a byte + container. Eventually the unicode built-in will be renamed to str and the str object will be removed. Specification - A bytes object stores a mutable sequence of integers that are in the - range 0 to 255. Unlike string objects, indexing a bytes object - returns an integer. Assigning an element using a object that is not - an integer causes a TypeError exception. Assigning an element to a - value outside the range 0 to 255 causes a ValueError exception. The - __len__ method of bytes returns the number of integers stored in the - sequence (i.e. the number of bytes). + A bytes object stores a mutable sequence of integers that are in + the range 0 to 255. Unlike string objects, indexing a bytes + object returns an integer. Assigning an element using a object + that is not an integer causes a TypeError exception. Assigning an + element to a value outside the range 0 to 255 causes a ValueError + exception. The .__len__() method of bytes returns the number of + integers stored in the sequence (i.e. the number of bytes). The constructor of the bytes object has the following signature: bytes([initialiser[, [encoding]]) If no arguments are provided then an object containing zero elements - is created and returned. The initialiser argument can be a string - or a sequence of integers. The pseudo-code for the constructor is: + is created and returned. The initialiser argument can be a string, + a sequence of integers, or a single integer. The pseudo-code for the + constructor is: def bytes(initialiser=[], encoding=None): - if isinstance(initialiser, basestring): - if isinstance(initialiser, unicode): + if isinstance(initialiser, int): # In 2.6, (int, long) + initialiser = [0]*initialiser + elif isinstance(initialiser, basestring): + if isinstance(initialiser, unicode): # In 3.0, always if encoding is None: + # In 3.0, raise TypeError("explicit encoding required") encoding = sys.getdefaultencoding() initialiser = initialiser.encode(encoding) initialiser = [ord(c) for c in initialiser] - elif encoding is not None: - raise TypeError("explicit encoding invalid for non-string " - "initialiser") - create bytes object and fill with integers from initialiser + else: + if encoding is not None: + raise TypeError("explicit encoding invalid for non-string " + "initialiser") + # Create bytes object and fill with integers from initialiser + # while ensuring each integer is in range(256); initialiser + # can be any iterable return bytes object - The __repr__ method returns a string that can be evaluated to + The .__repr__() method returns a string that can be evaluated to generate a new bytes object containing the same sequence of - integers. The sequence is represented by a list of ints. For - example: + integers. The sequence is represented by a list of ints using + hexadecimal notation. For example: >>> repr(bytes[10, 20, 30]) - 'bytes([10, 20, 30])' + 'bytes([0x0a, 0x14, 0x1e])' - The object has a decode method equivalent to the decode method of - the str object. The object has a classmethod fromhex that takes a - string of characters from the set [0-9a-zA-Z ] and returns a bytes - object (similar to binascii.unhexlify). For example: + The object has a .decode() method equivalent to the .decode() + method of the str object. (This is redundant since it can also be + decoded by calling unicode(b, ) (in 2.6) or str(b, + ) (in 3.0); do we need encode/decode methods? In a + sense the spelling using a constructor is cleaner.) The object + has a classmethod .fromhex() that takes a string of characters + from the set [0-9a-zA-Z ] and returns a bytes object (similar to + binascii.unhexlify). For example: >>> bytes.fromhex('5c5350ff') bytes([92, 83, 80, 255]]) >>> bytes.fromhex('5c 53 50 ff') bytes([92, 83, 80, 255]]) - The object has a hex method that does the reverse conversion + The object has a .hex() method that does the reverse conversion (similar to binascii.hexlify): >> bytes([92, 83, 80, 255]]).hex() '5c5350ff' - The bytes object has methods similar to the list object: + The bytes object has some methods similar to list method, and + others similar to str methods: __add__ - __contains__ + __contains__ (with int arg, like list; with bytes arg, like str) __delitem__ __delslice__ __eq__ @@ -95,7 +107,6 @@ __getitem__ __getslice__ __gt__ - __hash__ __iadd__ __imul__ __iter__ @@ -107,16 +118,39 @@ __reduce__ __reduce_ex__ __repr__ + __reversed__ __rmul__ __setitem__ __setslice__ append count + decode + endswith extend + find index insert + join + partition pop remove + replace + rindex + rpartition + split + startswith + reverse + rfind + rindex + rsplit + translate + + Note the conspicuous absence of .isupper(), .upper(), and friends. + There is no __hash__ because the object is mutable. There is no + usecase for a .sort() method. + + The bytes also supports the buffer interface, supporting reading + and writing binary (but not character) data. Out of scope issues @@ -127,7 +161,9 @@ (which requires lexer and parser support in addition to everything else). Since there appears to be no immediate need for a literal representation, designing and implementing one is out of the scope - of this PEP. + of this PEP. (Hmm... A b"..." literal accepting only ASCII + values is likely to be added to 3.0; not clear about 2.6. This + needs a PEP.) * Python 3k will have a much different I/O subsystem. Deciding how that I/O subsystem will work and interact with the bytes object is @@ -140,19 +176,19 @@ Unresolved issues - * Perhaps the bytes object should be implemented as a extension - module until we are more sure of the design (similar to how the - set object was prototyped). - - * Should the bytes object implement the buffer interface? Probably, - but we need to look into the implications of that (e.g. regex - operations on byte arrays). + * Need to specify the methods more carefully. + + * Should all those list methods really be implemented? + + * A case could be made for supporting .ljust(), .rjust(), + .center() with a mandatory second argument. + + * A case could be made for supporting .split() with a mandatory + argument. - * Should the object implement __reversed__ and reverse? Should it - implement sort? + * How should pickling and marshalling work? - * Need to clarify what some of the methods do. How are comparisons - done? Hashing? Pickling and marshalling? + * I probably forgot a few things. Questions and answers @@ -174,7 +210,7 @@ Q: Why does bytes ignore the encoding argument if the initialiser is - a str? + a str? (This only applies to 2.6.) A: There is no sane meaning that the encoding can have in that case. str objects *are* byte arrays and they know nothing about the From python-checkins at python.org Fri Feb 23 01:22:40 2007 From: python-checkins at python.org (neal.norwitz) Date: Fri, 23 Feb 2007 01:22:40 +0100 (CET) Subject: [Python-checkins] r53861 - python/trunk/Lib/test/test_bsddb.py Message-ID: <20070223002240.668A31E4003@bag.python.org> Author: neal.norwitz Date: Fri Feb 23 01:22:39 2007 New Revision: 53861 Modified: python/trunk/Lib/test/test_bsddb.py Log: Fix typo in comment Modified: python/trunk/Lib/test/test_bsddb.py ============================================================================== --- python/trunk/Lib/test/test_bsddb.py (original) +++ python/trunk/Lib/test/test_bsddb.py Fri Feb 23 01:22:39 2007 @@ -205,7 +205,7 @@ # create iterator i = self.f.iteritems() nc2 = len(self.f._cursor_refs) - # use the iterator (should run to the first yeild, creating the cursor) + # use the iterator (should run to the first yield, creating the cursor) k, v = i.next() nc3 = len(self.f._cursor_refs) # destroy the iterator; this should cause the weakref callback From jimjjewett at gmail.com Fri Feb 23 03:38:08 2007 From: jimjjewett at gmail.com (Jim Jewett) Date: Thu, 22 Feb 2007 21:38:08 -0500 Subject: [Python-checkins] r53860 - peps/trunk/pep-0000.txt peps/trunk/pep-0358.txt In-Reply-To: <20070222235747.3546F1E4003@bag.python.org> References: <20070222235747.3546F1E4003@bag.python.org> Message-ID: > __setitem__ > __setslice__ > append > count > + decode > + endswith > extend > + find > index > insert > + join > + partition > remove > + replace > + rindex > + rpartition > + split > + startswith > + rfind > + rindex > + rsplit > + translate What sort of arguments do they take? Other bytes objects? (Then the literal is more important.) Unicode? With an extra decoding argument? Sequences of integers? Is startswith(500) False or a ValueException? Single integers? startswith(ord('A')) + Note the conspicuous absence of .isupper(), .upper(), and friends. This does force the use of more regular expressions, by ruling out data.upper().startswith("ERROR:") -jJ From python-checkins at python.org Fri Feb 23 05:31:19 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 23 Feb 2007 05:31:19 +0100 (CET) Subject: [Python-checkins] r53862 - peps/trunk/pep-0358.txt Message-ID: <20070223043119.401051E4011@bag.python.org> Author: guido.van.rossum Date: Fri Feb 23 05:31:15 2007 New Revision: 53862 Modified: peps/trunk/pep-0358.txt Log: Another update, clarifying (I hope) the method signatures and mentioning other stuff that came up over dinner. Modified: peps/trunk/pep-0358.txt ============================================================================== --- peps/trunk/pep-0358.txt (original) +++ peps/trunk/pep-0358.txt Fri Feb 23 05:31:15 2007 @@ -13,9 +13,16 @@ Abstract - This PEP outlines the introduction of a raw bytes sequence object. - Adding the bytes object is one step in the transition to Unicode - based str objects. + This PEP outlines the introduction of a raw bytes sequence type. + Adding the bytes type is one step in the transition to Unicode + based str objects which will be introduced in Python 3.0. + + The PEP describes how the bytes type should work in Python 2.6, as + well as how it should work in Python 3.0. (Occasionally there are + differences because in Python 2.6, we have two string types, str + and unicode, while in Python 3.0 we will only have one string + type, whose name will be str but whose semantics will be like the + 2.6 unicode type.) Motivation @@ -33,39 +40,48 @@ A bytes object stores a mutable sequence of integers that are in the range 0 to 255. Unlike string objects, indexing a bytes - object returns an integer. Assigning an element using a object - that is not an integer causes a TypeError exception. Assigning an - element to a value outside the range 0 to 255 causes a ValueError - exception. The .__len__() method of bytes returns the number of - integers stored in the sequence (i.e. the number of bytes). + object returns an integer. Assigning or comparin an object that + is not an integer to an element causes a TypeError exception. + Assigning an element to a value outside the range 0 to 255 causes + a ValueError exception. The .__len__() method of bytes returns + the number of integers stored in the sequence (i.e. the number of + bytes). The constructor of the bytes object has the following signature: - bytes([initialiser[, [encoding]]) + bytes([initializer[, encoding]]) - If no arguments are provided then an object containing zero elements - is created and returned. The initialiser argument can be a string, - a sequence of integers, or a single integer. The pseudo-code for the - constructor is: - - def bytes(initialiser=[], encoding=None): - if isinstance(initialiser, int): # In 2.6, (int, long) - initialiser = [0]*initialiser - elif isinstance(initialiser, basestring): - if isinstance(initialiser, unicode): # In 3.0, always + If no arguments are provided then a bytes object containing zero + elements is created and returned. The initializer argument can be + a string (in 2.6, either str or unicode), an iterable of integers, + or a single integer. The pseudo-code for the constructor + (optimized for clear semantics, not for speed) is: + + def bytes(initializer=0, encoding=None): + if isinstance(initializer, int): # In 2.6, (int, long) + initializer = [0]*initializer + elif isinstance(initializer, basestring): + if isinstance(initializer, unicode): # In 3.0, always if encoding is None: # In 3.0, raise TypeError("explicit encoding required") encoding = sys.getdefaultencoding() - initialiser = initialiser.encode(encoding) - initialiser = [ord(c) for c in initialiser] + initializer = initializer.encode(encoding) + initializer = [ord(c) for c in initializer] else: if encoding is not None: - raise TypeError("explicit encoding invalid for non-string " - "initialiser") - # Create bytes object and fill with integers from initialiser - # while ensuring each integer is in range(256); initialiser - # can be any iterable - return bytes object + raise TypeError("no encoding allowed for this initializer") + tmp = [] + for c in initializer: + if not isinstance(c, int): + raise TypeError("initializer must be iterable of ints") + if not 0 <= c < 256: + raise ValueError("initializer element out of range") + tmp.append(c) + initializer = tmp + new = + for i, c in enumerate(initializer): + new[i] = c + return new The .__repr__() method returns a string that can be evaluated to generate a new bytes object containing the same sequence of @@ -76,13 +92,10 @@ 'bytes([0x0a, 0x14, 0x1e])' The object has a .decode() method equivalent to the .decode() - method of the str object. (This is redundant since it can also be - decoded by calling unicode(b, ) (in 2.6) or str(b, - ) (in 3.0); do we need encode/decode methods? In a - sense the spelling using a constructor is cleaner.) The object - has a classmethod .fromhex() that takes a string of characters - from the set [0-9a-zA-Z ] and returns a bytes object (similar to - binascii.unhexlify). For example: + method of the str object. The object has a classmethod .fromhex() + that takes a string of characters from the set [0-9a-zA-Z ] and + returns a bytes object (similar to binascii.unhexlify). For + example: >>> bytes.fromhex('5c5350ff') bytes([92, 83, 80, 255]]) @@ -96,102 +109,118 @@ '5c5350ff' The bytes object has some methods similar to list method, and - others similar to str methods: + others similar to str methods. Here is a complete list of + methods, with their approximate signatures: - __add__ - __contains__ (with int arg, like list; with bytes arg, like str) - __delitem__ - __delslice__ - __eq__ - __ge__ - __getitem__ - __getslice__ - __gt__ - __iadd__ - __imul__ - __iter__ - __le__ - __len__ - __lt__ - __mul__ - __ne__ - __reduce__ - __reduce_ex__ - __repr__ - __reversed__ - __rmul__ - __setitem__ - __setslice__ - append - count - decode - endswith - extend - find - index - insert - join - partition - pop - remove - replace - rindex - rpartition - split - startswith - reverse - rfind - rindex - rsplit - translate + .__add__(bytes) -> bytes + .__contains__(int | bytes) -> bool + .__delitem__(int | slice) -> None + .__delslice__(int, int) -> None + .__eq__(bytes) -> bool + .__ge__(bytes) -> bool + .__getitem__(int | slice) -> int | bytes + .__getslice__(int, int) -> bytes + .__gt__(bytes) -> bool + .__iadd__(bytes) -> bytes + .__imul__(int) -> bytes + .__iter__() -> iterator + .__le__(bytes) -> bool + .__len__() -> int + .__lt__(bytes) -> bool + .__mul__(int) -> bytes + .__ne__(bytes) -> bool + .__reduce__(...) -> ... + .__reduce_ex__(...) -> ... + .__repr__() -> str + .__reversed__() -> bytes + .__rmul__(int) -> bytes + .__setitem__(int | slice, int | iterable[int]) -> None + .__setslice__(int, int, iterable[int]) -> Bote + .append(int) -> None + .count(int) -> int + .decode(str) -> str | unicode # in 3.0, only str + .endswith(bytes) -> bool + .extend(iterable[int]) -> None + .find(bytes) -> int + .index(bytes | int) -> int + .insert(int, int) -> None + .join(iterable[bytes]) -> bytes + .partition(bytes) -> (bytes, bytes, bytes) + .pop([int]) -> int + .remove(int) -> None + .replace(bytes, bytes) -> bytes + .rindex(bytes | int) -> int + .rpartition(bytes) -> (bytes, bytes, bytes) + .split(bytes) -> list[bytes] + .startswith(bytes) -> bool + .reverse() -> None + .rfind(bytes) -> int + .rindex(bytes | int) -> int + .rsplit(bytes) -> list[bytes] + .translate(bytes, [bytes]) -> bytes Note the conspicuous absence of .isupper(), .upper(), and friends. - There is no __hash__ because the object is mutable. There is no - usecase for a .sort() method. + (But see "Open Issues" below.) There is no .__hash__() because + the object is mutable. There is no use case for a .sort() method. - The bytes also supports the buffer interface, supporting reading - and writing binary (but not character) data. + The bytes type also supports the buffer interface, supporting + reading and writing binary (but not character) data. -Out of scope issues +Out of Scope Issues - * If we provide a literal syntax for bytes then it should look - distinctly different than the syntax for literal strings. Also, a - new type, even built-in, is much less drastic than a new literal - (which requires lexer and parser support in addition to everything - else). Since there appears to be no immediate need for a literal - representation, designing and implementing one is out of the scope - of this PEP. (Hmm... A b"..." literal accepting only ASCII - values is likely to be added to 3.0; not clear about 2.6. This - needs a PEP.) - - * Python 3k will have a much different I/O subsystem. Deciding how - that I/O subsystem will work and interact with the bytes object is - out of the scope of this PEP. + * Python 3k will have a much different I/O subsystem. Deciding + how that I/O subsystem will work and interact with the bytes + object is out of the scope of this PEP. The expectation however + is that binary I/O will read and write bytes, while text I/O + will read strings. Since the bytes type supports the buffer + interface, the existing binary I/O operations in Python 2.6 will + support bytes objects. - * It has been suggested that a special method named __bytes__ be - added to language to allow objects to be converted into byte + * It has been suggested that a special method named .__bytes__() + be added to language to allow objects to be converted into byte arrays. This decision is out of scope. -Unresolved issues +Open Issues - * Need to specify the methods more carefully. + * The .decode() method is redundant since a bytes object b can + also be decoded by calling unicode(b, ) (in 2.6) or + str(b, ) (in 3.0). Do we need encode/decode methods + at all? In a sense the spelling using a constructor is cleaner. + + * Need to specify the methods still more carefully. + + * Pickling and marshalling support need to be specified. * Should all those list methods really be implemented? + * There is growing support for a b"..." literal. Here's a brief + spec. Each invocation of b"..." produces a new bytes object + (this is unlike "..." but similar to [...] and {...}). Inside + the literal, only ASCII characters and non-Unicode backslash + escapes are allowed; non-ASCII characters not specified as + escapes are rejected by the compiler regardless of the source + encoding. The resulting object's value is the same as if + bytes(map(ord, "...")) were called. + * A case could be made for supporting .ljust(), .rjust(), .center() with a mandatory second argument. * A case could be made for supporting .split() with a mandatory argument. - * How should pickling and marshalling work? - - * I probably forgot a few things. + * A case could even be made for supporting .islower(), .isupper(), + .isspace(), .isalpha(), .isalnum(), .isdigit() and the + corresponding conversions (.lower() etc.), using the ASCII + definitions for letters, digits and whitespace. If this is + accepted, the cases for .ljust(), .rjust(), .center() and + .split() become much stronger, and they should have default + arguments as well, using an ASCII space or all ASCII whitespace + (for .split()). -Questions and answers +Frequently Asked Questions Q: Why have the optional encoding argument when the encode method of Unicode objects does the same thing. @@ -209,7 +238,7 @@ in which case you have to use the former. - Q: Why does bytes ignore the encoding argument if the initialiser is + Q: Why does bytes ignore the encoding argument if the initializer is a str? (This only applies to 2.6.) A: There is no sane meaning that the encoding can have in that case. From python-checkins at python.org Fri Feb 23 10:01:56 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 23 Feb 2007 10:01:56 +0100 (CET) Subject: [Python-checkins] r53863 - peps/trunk/pep-0358.txt Message-ID: <20070223090156.CE1191E4004@bag.python.org> Author: guido.van.rossum Date: Fri Feb 23 10:01:52 2007 New Revision: 53863 Modified: peps/trunk/pep-0358.txt Log: Use trailing Emacs section from plaintext template. Modified: peps/trunk/pep-0358.txt ============================================================================== --- peps/trunk/pep-0358.txt (original) +++ peps/trunk/pep-0358.txt Fri Feb 23 10:01:52 2007 @@ -269,10 +269,10 @@ -.. - Local Variables: - mode: indented-text - indent-tabs-mode: nil - sentence-end-double-space: t - fill-column: 70 - End: +Local Variables: +mode: indented-text +indent-tabs-mode: nil +sentence-end-double-space: t +fill-column: 70 +coding: utf-8 +End: From ncoghlan at gmail.com Fri Feb 23 11:48:01 2007 From: ncoghlan at gmail.com (Nick Coghlan) Date: Fri, 23 Feb 2007 20:48:01 +1000 Subject: [Python-checkins] r53860 - peps/trunk/pep-0000.txt peps/trunk/pep-0358.txt In-Reply-To: References: <20070222235747.3546F1E4003@bag.python.org> Message-ID: <45DEC661.5060103@gmail.com> Jim Jewett wrote: > This does force the use of more regular expressions, by ruling out > > data.upper().startswith("ERROR:") It merelyforces you to make the encoding explicit (rather than assuming ASCII or latin-1) by converting the bytes to a character sequence first: str(data, 'latin-1').upper().startswith("ERROR:") This makes sense, since 'uppercase' and 'lowercase' are attributes of characters, not of bytes. Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- http://www.boredomandlaziness.org From python-checkins at python.org Fri Feb 23 15:28:28 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 23 Feb 2007 15:28:28 +0100 (CET) Subject: [Python-checkins] r53864 - python/trunk/Lib/test/test_pep352.py Message-ID: <20070223142828.0B10C1E4008@bag.python.org> Author: brett.cannon Date: Fri Feb 23 15:28:25 2007 New Revision: 53864 Modified: python/trunk/Lib/test/test_pep352.py Log: Refactor PEP 352 tests to make it easier in the future to make sure certain things cannot be raised or caught. Modified: python/trunk/Lib/test/test_pep352.py ============================================================================== --- python/trunk/Lib/test/test_pep352.py (original) +++ python/trunk/Lib/test/test_pep352.py Fri Feb 23 15:28:25 2007 @@ -113,6 +113,37 @@ """Test usage of exceptions""" + def raise_fails(self, object_): + """Make sure that raising 'object_' triggers a TypeError.""" + try: + raise object_ + except TypeError: + return # What is expected. + self.fail("TypeError expected for raising %s" % type(object_)) + + def catch_fails(self, object_): + """Catching 'object_' should raise a TypeError.""" + try: + try: + raise StandardError + except object_: + pass + except TypeError: + pass + except StandardError: + self.fail("TypeError expected when catching %s" % type(object_)) + + try: + try: + raise StandardError + except (object_,): + pass + except TypeError: + return + except StandardError: + self.fail("TypeError expected when catching %s as specified in a " + "tuple" % type(object_)) + def test_raise_classic(self): # Raising a classic class is okay (for now). class ClassicClass: @@ -137,27 +168,12 @@ # inherit from it. class NewStyleClass(object): pass - try: - raise NewStyleClass - except TypeError: - pass - except: - self.fail("able to raise new-style class") - try: - raise NewStyleClass() - except TypeError: - pass - except: - self.fail("able to raise new-style class instance") + self.raise_fails(NewStyleClass) + self.raise_fails(NewStyleClass()) def test_raise_string(self): # Raising a string raises TypeError. - try: - raise "spam" - except TypeError: - pass - except: - self.fail("was able to raise a string exception") + self.raise_fails("spam") def test_catch_string(self): # Catching a string should trigger a DeprecationWarning. From python-checkins at python.org Fri Feb 23 15:41:43 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 23 Feb 2007 15:41:43 +0100 (CET) Subject: [Python-checkins] r53865 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070223144143.DCB9C1E4008@bag.python.org> Author: brett.cannon Date: Fri Feb 23 15:41:40 2007 New Revision: 53865 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Add keyword-only and annotation support to Parameter.__init__. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Fri Feb 23 15:41:40 2007 @@ -9,20 +9,46 @@ class Parameter(object): - """Represent a parameter in a function signature.""" + """Represent a parameter in a function signature. - def __init__(self, name, position, has_default, *args): + Each parameter has the following attributes: + * name + The name of the parameter. + * position + The position in the parameter list for the argument, no including any + variable position argument. + * keyword_only + True if the parameter is keyword-only. + * has_annotation + True if the parameter has an annotation. If it does, the 'annotation' + attribute will store the annotation. + * has_default + True if the parameter has a default value. If it does, the + 'default_value' attribute will store the default value. + + """ + + def __init__(self, name, position, has_default=False, default_value=None, + keyword_only=False, has_annotation=False, annotation=None): + """Initialize a Parameter instance. + + For has_* arguments, if they are False then the corresponding * + parameter is ignored. + + """ self.name = name self.position = position if not has_default: self.has_default = False else: self.has_default = True - if len(args) != 1: - raise ValueError("Parameter requires a default value to be " - "specified when has_default has been set " - "to True") - self.default_value = args[0] + self.default_value = default_value + self.keyword_only = keyword_only + if not has_annotation: + self.has_annotation = False + else: + self.has_annotation = True + self.annotation = annotation @classmethod def __tuple2param(self, tuple_): @@ -46,16 +72,6 @@ result+= "=" + str(self.default_value) return result - def __repr__(self): - """Return the string required to create an equivalent instance of this - parameter.""" - result = "%s(%r, %r, %r" % (self.__class__.__name__, - self.name, self.position, self.has_default) - if self.has_default: - result +=", %r" % self.default_value - result += ")" - return result - class Signature(object): Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Fri Feb 23 15:41:40 2007 @@ -12,42 +12,45 @@ # Test that 'name' attribute works. # Must test both using a string and a tuple of strings. name = "test" - param = pep362.Parameter(name, 0, False) + param = pep362.Parameter(name, 0) self.failUnlessEqual(param.name, name) name = ('a', ('b',)) - param = pep362.Parameter(name, 0, False) + param = pep362.Parameter(name, 0) self.failUnlessEqual(param.name, name) def test_position(self): # Test the 'position' attribute. pos = 42 - param = pep362.Parameter("_", pos, False) + param = pep362.Parameter("_", pos) self.failUnlessEqual(param.position, pos) - def test_has_default(self): + def test_default_values(self): # Test the 'has_default' attribute. # Testing that 'default_value' is not set is handled in the testing of # that attribute. - param = pep362.Parameter('_', 0, True, None) + default_value = 42 + param = pep362.Parameter('_', 0, True, default_value) self.failUnlessEqual(param.has_default, True) + self.failUnlessEqual(param.default_value, default_value) param = pep362.Parameter('_', 0, False) self.failUnlessEqual(param.has_default, False) - self.failUnlessRaises(TypeError, pep362.Parameter, - ('_', 0, False, 'extra arg')) - self.failUnlessRaises(TypeError, pep362.Parameter, - ('_', 0, True)) - self.failUnlessRaises(TypeError, pep362.Parameter, - ('_', 0, True, 'default', 'extra')) - - def test_default_value(self): - # Test the 'default_value' attribute. - # Make sure that if has_default is set to False that default_value is - # not defined. - param = pep362.Parameter('_', 0, False) - self.failUnless(not hasattr(param, 'default_value')) - default = 42 - param = pep362.Parameter('_', 0, True, default) - self.failUnlessEqual(param.default_value, default) + + def test_keyword_only(self): + # Setting the value for keyword_only should create an attribute. + for value in (True, False): + param = pep362.Parameter('_', 0, keyword_only=value) + self.failUnlessEqual(param.keyword_only, value) + + def test_annotations(self): + # If has_annotation is False then 'annotation' should not exist. + param = pep362.Parameter('_', 0, has_annotation=False) + self.failUnlessEqual(param.has_annotation, False) + self.failUnless(not hasattr(param, 'annotation')) + annotation = 42 + param = pep362.Parameter('_', 0, has_annotation=True, + annotation=annotation) + self.failUnlessEqual(param.has_annotation, True) + self.failUnlessEqual(param.annotation, annotation) def test_str(self): # Test __str__(). @@ -58,20 +61,6 @@ param = pep362.Parameter(name, 0, True, default_value) self.failUnlessEqual("%s=%s" % (name, default_value), str(param)) - def test_repr(self): - # Test __repr__(). - name = "X" - pos = 0 - param = pep362.Parameter(name, pos, False) - self.failUnlessEqual("Parameter(%r, %r, False)" % (name, pos), - repr(param)) - default_value = 42 - param = pep362.Parameter(name, pos, True, default_value) - self.failUnlessEqual("Parameter(%r, %r, True, %r)" % - (name, pos, default_value), - repr(param)) - - class SignatureObjectTests(unittest.TestCase): def test_no_args(self): From python-checkins at python.org Fri Feb 23 16:08:29 2007 From: python-checkins at python.org (thomas.wouters) Date: Fri, 23 Feb 2007 16:08:29 +0100 (CET) Subject: [Python-checkins] r53866 - in python/branches/p3yk: Doc/lib/emailgenerator.tex Doc/lib/libcollections.tex Doc/lib/libfunctools.tex Doc/lib/libheapq.tex Doc/lib/libitertools.tex Doc/lib/liblocale.tex Doc/lib/libos.tex Doc/lib/libshutil.tex Doc/lib/libstdtypes.tex Doc/lib/libstruct.tex Doc/lib/libtarfile.tex Doc/lib/libzipfile.tex Include/Python-ast.h Include/dictobject.h Lib/decimal.py Lib/distutils/command/build_ext.py Lib/encodings/__init__.py Lib/gzip.py Lib/heapq.py Lib/idlelib/AutoCompleteWindow.py Lib/idlelib/CallTips.py Lib/idlelib/CodeContext.py Lib/idlelib/IOBinding.py Lib/idlelib/NEWS.txt Lib/idlelib/PyShell.py Lib/idlelib/configHandler.py Lib/idlelib/help.txt Lib/imputil.py Lib/logging/__init__.py Lib/shutil.py Lib/stat.py Lib/subprocess.py Lib/tarfile.py Lib/test/test_datetime.py Lib/test/test_defaultdict.py Lib/test/test_descr.py Lib/test/test_dict.py Lib/test/test_gzip.py Lib/test/test_heapq.py Lib/test/test_itertools.py Lib/test/test_operator.py Lib/test/test_posix.py Lib/test/test_sax.py Lib/test/test_set.py Lib/test/test_tarfile.py Lib/test/test_zipfile.py Lib/trace.py Lib/xml/sax/saxutils.py Lib/zipfile.py Misc/ACKS Modules/collectionsmodule.c Modules/datetimemodule.c Modules/itertoolsmodule.c Modules/posixmodule.c Modules/socketmodule.c Modules/socketmodule.h Objects/abstract.c Objects/dictnotes.txt Objects/dictobject.c Objects/enumobject.c Objects/setobject.c Objects/typeobject.c Parser/Python.asdl Parser/asdl_c.py Python/Python-ast.c configure configure.in pyconfig.h.in setup.py Message-ID: <20070223150829.1F5EB1E4008@bag.python.org> Author: thomas.wouters Date: Fri Feb 23 16:07:44 2007 New Revision: 53866 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/lib/emailgenerator.tex python/branches/p3yk/Doc/lib/libcollections.tex python/branches/p3yk/Doc/lib/libfunctools.tex python/branches/p3yk/Doc/lib/libheapq.tex python/branches/p3yk/Doc/lib/libitertools.tex python/branches/p3yk/Doc/lib/liblocale.tex python/branches/p3yk/Doc/lib/libos.tex python/branches/p3yk/Doc/lib/libshutil.tex python/branches/p3yk/Doc/lib/libstdtypes.tex python/branches/p3yk/Doc/lib/libstruct.tex python/branches/p3yk/Doc/lib/libtarfile.tex python/branches/p3yk/Doc/lib/libzipfile.tex python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Include/dictobject.h python/branches/p3yk/Lib/decimal.py python/branches/p3yk/Lib/distutils/command/build_ext.py python/branches/p3yk/Lib/encodings/__init__.py python/branches/p3yk/Lib/gzip.py python/branches/p3yk/Lib/heapq.py python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py python/branches/p3yk/Lib/idlelib/CallTips.py python/branches/p3yk/Lib/idlelib/CodeContext.py python/branches/p3yk/Lib/idlelib/IOBinding.py python/branches/p3yk/Lib/idlelib/NEWS.txt python/branches/p3yk/Lib/idlelib/PyShell.py python/branches/p3yk/Lib/idlelib/configHandler.py python/branches/p3yk/Lib/idlelib/help.txt python/branches/p3yk/Lib/imputil.py python/branches/p3yk/Lib/logging/__init__.py python/branches/p3yk/Lib/shutil.py python/branches/p3yk/Lib/stat.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/test/test_datetime.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_gzip.py python/branches/p3yk/Lib/test/test_heapq.py python/branches/p3yk/Lib/test/test_itertools.py python/branches/p3yk/Lib/test/test_operator.py python/branches/p3yk/Lib/test/test_posix.py python/branches/p3yk/Lib/test/test_sax.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Lib/test/test_tarfile.py python/branches/p3yk/Lib/test/test_zipfile.py python/branches/p3yk/Lib/trace.py python/branches/p3yk/Lib/xml/sax/saxutils.py python/branches/p3yk/Lib/zipfile.py python/branches/p3yk/Misc/ACKS python/branches/p3yk/Modules/collectionsmodule.c python/branches/p3yk/Modules/datetimemodule.c python/branches/p3yk/Modules/itertoolsmodule.c python/branches/p3yk/Modules/posixmodule.c python/branches/p3yk/Modules/socketmodule.c python/branches/p3yk/Modules/socketmodule.h python/branches/p3yk/Objects/abstract.c python/branches/p3yk/Objects/dictnotes.txt python/branches/p3yk/Objects/dictobject.c python/branches/p3yk/Objects/enumobject.c python/branches/p3yk/Objects/setobject.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Parser/asdl_c.py python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/configure python/branches/p3yk/configure.in python/branches/p3yk/pyconfig.h.in python/branches/p3yk/setup.py Log: Merged revisions 53623-53858 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53624 | peter.astrand | 2007-02-02 20:06:36 +0100 (Fri, 02 Feb 2007) | 1 line We had several if statements checking the value of a fd. This is unsafe, since valid fds might be zero. We should check for not None instead. ........ r53635 | kurt.kaiser | 2007-02-05 07:03:18 +0100 (Mon, 05 Feb 2007) | 2 lines Add 'raw' support to configHandler. Patch 1650174 Tal Einat. ........ r53641 | kurt.kaiser | 2007-02-06 00:02:16 +0100 (Tue, 06 Feb 2007) | 5 lines 1. Calltips now 'handle' tuples in the argument list (display '' :) Suggested solution by Christos Georgiou, Bug 791968. 2. Clean up tests, were not failing when they should have been. 4. Remove some camelcase and an unneeded try/except block. ........ r53644 | kurt.kaiser | 2007-02-06 04:21:40 +0100 (Tue, 06 Feb 2007) | 2 lines Clean up ModifiedInterpreter.runcode() structure ........ r53646 | peter.astrand | 2007-02-06 16:37:50 +0100 (Tue, 06 Feb 2007) | 1 line Applied patch 1124861.3.patch to solve bug #1124861: Automatically create pipes on Windows, if GetStdHandle fails. Will backport. ........ r53648 | lars.gustaebel | 2007-02-06 19:38:13 +0100 (Tue, 06 Feb 2007) | 4 lines Patch #1652681: create nonexistent files in append mode and allow appending to empty files. ........ r53649 | kurt.kaiser | 2007-02-06 20:09:43 +0100 (Tue, 06 Feb 2007) | 4 lines Updated patch (CodeContext.061217.patch) to [ 1362975 ] CodeContext - Improved text indentation Tal Einat 16Dec06 ........ r53650 | kurt.kaiser | 2007-02-06 20:21:19 +0100 (Tue, 06 Feb 2007) | 2 lines narrow exception per [ 1540849 ] except too broad ........ r53653 | kurt.kaiser | 2007-02-07 04:39:41 +0100 (Wed, 07 Feb 2007) | 4 lines [ 1621265 ] Auto-completion list placement Move AC window below input line unless not enough space, then put it above. Patch: Tal Einat ........ r53654 | kurt.kaiser | 2007-02-07 09:07:13 +0100 (Wed, 07 Feb 2007) | 2 lines Handle AttributeError during calltip lookup ........ r53656 | raymond.hettinger | 2007-02-07 21:08:22 +0100 (Wed, 07 Feb 2007) | 3 lines SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses ........ r53658 | raymond.hettinger | 2007-02-07 22:04:20 +0100 (Wed, 07 Feb 2007) | 1 line SF: 1397711 Set docs conflated immutable and hashable ........ r53660 | raymond.hettinger | 2007-02-07 22:42:17 +0100 (Wed, 07 Feb 2007) | 1 line Check for a common user error with defaultdict(). ........ r53662 | raymond.hettinger | 2007-02-07 23:24:07 +0100 (Wed, 07 Feb 2007) | 1 line Bug #1575169: operator.isSequenceType() now returns False for subclasses of dict. ........ r53664 | raymond.hettinger | 2007-02-08 00:49:03 +0100 (Thu, 08 Feb 2007) | 1 line Silence compiler warning ........ r53666 | raymond.hettinger | 2007-02-08 01:07:32 +0100 (Thu, 08 Feb 2007) | 1 line Do not let overflows in enumerate() and count() pass silently. ........ r53668 | raymond.hettinger | 2007-02-08 01:50:39 +0100 (Thu, 08 Feb 2007) | 1 line Bypass set specific optimizations for set and frozenset subclasses. ........ r53670 | raymond.hettinger | 2007-02-08 02:42:35 +0100 (Thu, 08 Feb 2007) | 1 line Fix docstring bug ........ r53671 | martin.v.loewis | 2007-02-08 10:13:36 +0100 (Thu, 08 Feb 2007) | 3 lines Bug #1653736: Complain about keyword arguments to time.isoformat. Will backport to 2.5. ........ r53679 | kurt.kaiser | 2007-02-08 23:58:18 +0100 (Thu, 08 Feb 2007) | 6 lines Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented; mouse and cursor selection in ACWindow implemented; double Tab inserts current selection and closes ACW (similar to double-click and Return); scroll wheel now works in ACW. Added AutoComplete instructions to IDLE Help. ........ r53689 | martin.v.loewis | 2007-02-09 13:19:32 +0100 (Fri, 09 Feb 2007) | 3 lines Bug #1653736: Properly discard third argument to slot_nb_inplace_power. Will backport. ........ r53691 | martin.v.loewis | 2007-02-09 13:36:48 +0100 (Fri, 09 Feb 2007) | 4 lines Bug #1600860: Search for shared python library in LIBDIR, not lib/python/config, on "linux" and "gnu" systems. Will backport. ........ r53693 | martin.v.loewis | 2007-02-09 13:58:49 +0100 (Fri, 09 Feb 2007) | 2 lines Update broken link. Will backport to 2.5. ........ r53697 | georg.brandl | 2007-02-09 19:48:41 +0100 (Fri, 09 Feb 2007) | 2 lines Bug #1656078: typo in in profile docs. ........ r53731 | brett.cannon | 2007-02-11 06:36:00 +0100 (Sun, 11 Feb 2007) | 3 lines Change a very minor inconsistency (that is purely cosmetic) in the AST definition. ........ r53735 | skip.montanaro | 2007-02-11 19:24:37 +0100 (Sun, 11 Feb 2007) | 1 line fix trace.py --ignore-dir ........ r53741 | brett.cannon | 2007-02-11 20:44:41 +0100 (Sun, 11 Feb 2007) | 3 lines Check in changed Python-ast.c from a cosmetic change to Python.asdl (in r53731). ........ r53751 | brett.cannon | 2007-02-12 04:51:02 +0100 (Mon, 12 Feb 2007) | 5 lines Modify Parser/asdl_c.py so that the __version__ number for Python/Python-ast.c is specified at the top of the file. Also add a note that Python/Python-ast.c needs to be committed separately after a change to the AST grammar to capture the revision number of the change (which is what __version__ is set to). ........ r53752 | lars.gustaebel | 2007-02-12 10:25:53 +0100 (Mon, 12 Feb 2007) | 3 lines Bug #1656581: Point out that external file objects are supposed to be at position 0. ........ r53754 | martin.v.loewis | 2007-02-12 13:21:10 +0100 (Mon, 12 Feb 2007) | 3 lines Patch 1463026: Support default namespace in XMLGenerator. Fixes #847665. Will backport. ........ r53757 | armin.rigo | 2007-02-12 17:23:24 +0100 (Mon, 12 Feb 2007) | 4 lines Fix the line to what is my guess at the original author's meaning. (The line has no effect anyway, but is present because it's customary call the base class __init__). ........ r53763 | martin.v.loewis | 2007-02-13 09:34:45 +0100 (Tue, 13 Feb 2007) | 3 lines Patch #685268: Consider a package's __path__ in imputil. Will backport. ........ r53765 | martin.v.loewis | 2007-02-13 10:49:38 +0100 (Tue, 13 Feb 2007) | 2 lines Patch #698833: Support file decryption in zipfile. ........ r53766 | martin.v.loewis | 2007-02-13 11:10:39 +0100 (Tue, 13 Feb 2007) | 3 lines Patch #1517891: Make 'a' create the file if it doesn't exist. Fixes #1514451. ........ r53767 | martin.v.loewis | 2007-02-13 13:08:24 +0100 (Tue, 13 Feb 2007) | 3 lines Bug #1658794: Remove extraneous 'this'. Will backport to 2.5. ........ r53769 | martin.v.loewis | 2007-02-13 13:14:19 +0100 (Tue, 13 Feb 2007) | 3 lines Patch #1657276: Make NETLINK_DNRTMSG conditional. Will backport. ........ r53771 | lars.gustaebel | 2007-02-13 17:09:24 +0100 (Tue, 13 Feb 2007) | 4 lines Patch #1647484: Renamed GzipFile's filename attribute to name. The filename attribute is still accessible as a property that emits a DeprecationWarning. ........ r53772 | lars.gustaebel | 2007-02-13 17:24:00 +0100 (Tue, 13 Feb 2007) | 3 lines Strip the '.gz' extension from the filename that is written to the gzip header. ........ r53774 | martin.v.loewis | 2007-02-14 11:07:37 +0100 (Wed, 14 Feb 2007) | 2 lines Patch #1432399: Add HCI sockets. ........ r53775 | martin.v.loewis | 2007-02-14 12:30:07 +0100 (Wed, 14 Feb 2007) | 2 lines Update 1432399 to removal of _BT_SOCKADDR_MEMB. ........ r53776 | martin.v.loewis | 2007-02-14 12:30:56 +0100 (Wed, 14 Feb 2007) | 3 lines Ignore directory time stamps when considering whether to rerun libffi configure. ........ r53778 | lars.gustaebel | 2007-02-14 15:45:12 +0100 (Wed, 14 Feb 2007) | 4 lines A missing binary mode in AppendTest caused failures in Windows Buildbot. ........ r53782 | martin.v.loewis | 2007-02-15 10:51:35 +0100 (Thu, 15 Feb 2007) | 2 lines Patch #1397848: add the reasoning behind no-resize-on-shrinkage. ........ r53783 | georg.brandl | 2007-02-15 11:37:59 +0100 (Thu, 15 Feb 2007) | 2 lines Make functools.wraps() docs a bit clearer. ........ r53785 | georg.brandl | 2007-02-15 12:29:04 +0100 (Thu, 15 Feb 2007) | 2 lines Patch #1494140: Add documentation for the new struct.Struct object. ........ r53787 | georg.brandl | 2007-02-15 12:29:55 +0100 (Thu, 15 Feb 2007) | 2 lines Add missing \versionadded. ........ r53800 | brett.cannon | 2007-02-15 23:54:39 +0100 (Thu, 15 Feb 2007) | 11 lines Update the encoding package's search function to use absolute imports when calling __import__. This helps make the expected search locations for encoding modules be more explicit. One could use an explicit value for __path__ when making the call to __import__ to force the exact location searched for encodings. This would give the most strict search path possible if one is worried about malicious code being imported. The unfortunate side-effect of that is that if __path__ was modified on 'encodings' on purpose in a safe way it would not be picked up in future __import__ calls. ........ r53801 | brett.cannon | 2007-02-16 20:33:01 +0100 (Fri, 16 Feb 2007) | 2 lines Make the __import__ call in encodings.__init__ absolute with a level 0 call. ........ r53809 | vinay.sajip | 2007-02-16 23:36:24 +0100 (Fri, 16 Feb 2007) | 1 line Minor fix for currentframe (SF #1652788). ........ r53818 | raymond.hettinger | 2007-02-19 03:03:19 +0100 (Mon, 19 Feb 2007) | 3 lines Extend work on revision 52962: Eliminate redundant calls to PyObject_Hash(). ........ r53820 | raymond.hettinger | 2007-02-19 05:08:43 +0100 (Mon, 19 Feb 2007) | 1 line Add merge() function to heapq. ........ r53821 | raymond.hettinger | 2007-02-19 06:28:28 +0100 (Mon, 19 Feb 2007) | 1 line Add tie-breaker count to preserve sort stability. ........ r53822 | raymond.hettinger | 2007-02-19 07:59:32 +0100 (Mon, 19 Feb 2007) | 1 line Use C heapreplace() instead of slower _siftup() in pure python. ........ r53823 | raymond.hettinger | 2007-02-19 08:30:21 +0100 (Mon, 19 Feb 2007) | 1 line Add test for merge stability ........ r53824 | raymond.hettinger | 2007-02-19 10:14:10 +0100 (Mon, 19 Feb 2007) | 1 line Provide an example of defaultdict with non-zero constant factory function. ........ r53825 | lars.gustaebel | 2007-02-19 10:54:47 +0100 (Mon, 19 Feb 2007) | 2 lines Moved misplaced news item. ........ r53826 | martin.v.loewis | 2007-02-19 11:55:19 +0100 (Mon, 19 Feb 2007) | 3 lines Patch #1490190: posixmodule now includes os.chflags() and os.lchflags() functions on platforms where the underlying system calls are available. ........ r53827 | raymond.hettinger | 2007-02-19 19:15:04 +0100 (Mon, 19 Feb 2007) | 1 line Fixup docstrings for merge(). ........ r53829 | raymond.hettinger | 2007-02-19 21:44:04 +0100 (Mon, 19 Feb 2007) | 1 line Fixup set/dict interoperability. ........ r53837 | raymond.hettinger | 2007-02-21 06:20:38 +0100 (Wed, 21 Feb 2007) | 1 line Add itertools.izip_longest(). ........ r53838 | raymond.hettinger | 2007-02-21 18:22:05 +0100 (Wed, 21 Feb 2007) | 1 line Remove filler struct item and fix leak. ........ Modified: python/branches/p3yk/Doc/lib/emailgenerator.tex ============================================================================== --- python/branches/p3yk/Doc/lib/emailgenerator.tex (original) +++ python/branches/p3yk/Doc/lib/emailgenerator.tex Fri Feb 23 16:07:44 2007 @@ -33,7 +33,7 @@ line. This is the only guaranteed portable way to avoid having such lines be mistaken for a \UNIX{} mailbox format envelope header separator (see \ulink{WHY THE CONTENT-LENGTH FORMAT IS BAD} -{http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html} +{http://www.jwz.org/doc/content-length.html} for details). \var{mangle_from_} defaults to \code{True}, but you might want to set this to \code{False} if you are not writing \UNIX{} mailbox format files. Modified: python/branches/p3yk/Doc/lib/libcollections.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libcollections.tex (original) +++ python/branches/p3yk/Doc/lib/libcollections.tex Fri Feb 23 16:07:44 2007 @@ -311,16 +311,20 @@ When a letter is first encountered, it is missing from the mapping, so the \member{default_factory} function calls \function{int()} to supply a default count of zero. The increment operation then builds up the count for each -letter. This technique makes counting simpler and faster than an equivalent -technique using \method{dict.get()}: +letter. -\begin{verbatim} ->>> d = {} ->>> for k in s: - d[k] = d.get(k, 0) + 1 +The function \function{int()} which always returns zero is just a special +case of constant functions. A faster and more flexible way to create +constant functions is to use \function{itertools.repeat()} which can supply +any constant value (not just zero): ->>> d.items() -[('i', 4), ('p', 2), ('s', 4), ('m', 1)] +\begin{verbatim} +>>> def constant_factory(value): +... return itertools.repeat(value).next +>>> d = defaultdict(constant_factory('')) +>>> d.update(name='John', action='ran') +>>> '%(name)s %(action)s to %(object)s' % d +'John ran to ' \end{verbatim} Setting the \member{default_factory} to \class{set} makes the Modified: python/branches/p3yk/Doc/lib/libfunctools.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libfunctools.tex (original) +++ python/branches/p3yk/Doc/lib/libfunctools.tex Fri Feb 23 16:07:44 2007 @@ -66,15 +66,16 @@ \begin{funcdesc}{update_wrapper} {wrapper, wrapped\optional{, assigned}\optional{, updated}} -Update a wrapper function to look like the wrapped function. The optional -arguments are tuples to specify which attributes of the original +Update a \var{wrapper} function to look like the \var{wrapped} function. +The optional arguments are tuples to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function and which attributes of the wrapper function are updated with the corresponding attributes from the original function. The default values for these arguments are the module level constants -\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's name, -module and documentation string) and \var{WRAPPER_UPDATES} (which -updates the wrapper function's instance dictionary). +\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's +\var{__name__}, \var{__module__} and \var{__doc__}, the documentation string) +and \var{WRAPPER_UPDATES} (which updates the wrapper function's \var{__dict__}, +i.e. the instance dictionary). The main intended use for this function is in decorator functions which wrap the decorated function and return the wrapper. If the @@ -98,6 +99,7 @@ ... >>> @my_decorator ... def example(): + ... """Docstring""" ... print 'Called example function' ... >>> example() @@ -105,9 +107,12 @@ Called example function >>> example.__name__ 'example' + >>> example.__doc__ + 'Docstring' \end{verbatim} Without the use of this decorator factory, the name of the example -function would have been \code{'wrapper'}. +function would have been \code{'wrapper'}, and the docstring of the +original \function{example()} would have been lost. \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/libheapq.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libheapq.tex (original) +++ python/branches/p3yk/Doc/lib/libheapq.tex Fri Feb 23 16:07:44 2007 @@ -88,7 +88,18 @@ >>> \end{verbatim} -The module also offers two general purpose functions based on heaps. +The module also offers three general purpose functions based on heaps. + +\begin{funcdesc}{merge}{*iterables} +Merge multiple sorted inputs into a single sorted output (for example, merge +timestamped entries from multiple log files). Returns an iterator over +over the sorted values. + +Similar to \code{sorted(itertools.chain(*iterables))} but returns an iterable, +does not pull the data into memory all at once, and assumes that each of the +input streams is already sorted (smallest to largest). +\versionadded{2.6} +\end{funcdesc} \begin{funcdesc}{nlargest}{n, iterable\optional{, key}} Return a list with the \var{n} largest elements from the dataset defined @@ -110,7 +121,7 @@ \versionchanged[Added the optional \var{key} argument]{2.5} \end{funcdesc} -Both functions perform best for smaller values of \var{n}. For larger +The latter two functions perform best for smaller values of \var{n}. For larger values, it is more efficient to use the \function{sorted()} function. Also, when \code{n==1}, it is more efficient to use the builtin \function{min()} and \function{max()} functions. Modified: python/branches/p3yk/Doc/lib/libitertools.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libitertools.tex (original) +++ python/branches/p3yk/Doc/lib/libitertools.tex Fri Feb 23 16:07:44 2007 @@ -302,6 +302,33 @@ don't care about trailing, unmatched values from the longer iterables. \end{funcdesc} +\begin{funcdesc}{izip_longest}{*iterables\optional{, fillvalue}} + Make an iterator that aggregates elements from each of the iterables. + If the iterables are of uneven length, missing values are filled-in + with \var{fillvalue}. Iteration continues until the longest iterable + is exhausted. Equivalent to: + + \begin{verbatim} + def izip_longest(*args, **kwds): + fillvalue = kwds.get('fillvalue') + def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): + yield counter() # yields the fillvalue, or raises IndexError + fillers = repeat(fillvalue) + iters = [chain(it, sentinel(), fillers) for it in args] + try: + for tup in izip(*iters): + yield tup + except IndexError: + pass + \end{verbatim} + + If one of the iterables is potentially infinite, then the + \function{izip_longest()} function should be wrapped with something + that limits the number of calls (for example \function{islice()} or + \function{take()}). + \versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{repeat}{object\optional{, times}} Make an iterator that returns \var{object} over and over again. Runs indefinitely unless the \var{times} argument is specified. Modified: python/branches/p3yk/Doc/lib/liblocale.tex ============================================================================== --- python/branches/p3yk/Doc/lib/liblocale.tex (original) +++ python/branches/p3yk/Doc/lib/liblocale.tex Fri Feb 23 16:07:44 2007 @@ -481,7 +481,7 @@ locale settings. When a call to the \function{setlocale()} function changes the \constant{LC_CTYPE} settings, the variables \code{string.lowercase}, \code{string.uppercase} and -\code{string.letters} are recalculated. Note that this code that uses +\code{string.letters} are recalculated. Note that code that uses these variable through `\keyword{from} ... \keyword{import} ...', e.g.\ \code{from string import letters}, is not affected by subsequent \function{setlocale()} calls. Modified: python/branches/p3yk/Doc/lib/libos.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libos.tex (original) +++ python/branches/p3yk/Doc/lib/libos.tex Fri Feb 23 16:07:44 2007 @@ -758,6 +758,26 @@ \versionadded{2.3} \end{funcdesc} +\begin{funcdesc}{chflags}{path, flags} +Set the flags of \var{path} to the numeric \var{flags}. +\var{flags} may take a combination (bitwise OR) of the following values +(as defined in the \module{stat} module): +\begin{itemize} + \item \code{UF_NODUMP} + \item \code{UF_IMMUTABLE} + \item \code{UF_APPEND} + \item \code{UF_OPAQUE} + \item \code{UF_NOUNLINK} + \item \code{SF_ARCHIVED} + \item \code{SF_IMMUTABLE} + \item \code{SF_APPEND} + \item \code{SF_NOUNLINK} + \item \code{SF_SNAPSHOT} +\end{itemize} +Availability: Macintosh, \UNIX. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{chroot}{path} Change the root directory of the current process to \var{path}. Availability: Macintosh, \UNIX. @@ -804,6 +824,13 @@ Availability: Macintosh, \UNIX. \end{funcdesc} +\begin{funcdesc}{lchflags}{path, flags} +Set the flags of \var{path} to the numeric \var{flags}, like +\function{chflags()}, but do not follow symbolic links. +Availability: \UNIX. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{lchown}{path, uid, gid} Change the owner and group id of \var{path} to the numeric \var{uid} and gid. This function will not follow symbolic links. Modified: python/branches/p3yk/Doc/lib/libshutil.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libshutil.tex (original) +++ python/branches/p3yk/Doc/lib/libshutil.tex Fri Feb 23 16:07:44 2007 @@ -44,8 +44,8 @@ \end{funcdesc} \begin{funcdesc}{copystat}{src, dst} - Copy the permission bits, last access time, and last modification - time from \var{src} to \var{dst}. The file contents, owner, and + Copy the permission bits, last access time, last modification time, + and flags from \var{src} to \var{dst}. The file contents, owner, and group are unaffected. \var{src} and \var{dst} are path names given as strings. \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 Fri Feb 23 16:07:44 2007 @@ -1212,7 +1212,7 @@ \label{types-set}} \obindex{set} -A \dfn{set} object is an unordered collection of immutable values. +A \dfn{set} object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. Modified: python/branches/p3yk/Doc/lib/libstruct.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstruct.tex (original) +++ python/branches/p3yk/Doc/lib/libstruct.tex Fri Feb 23 16:07:44 2007 @@ -29,6 +29,15 @@ exactly. \end{funcdesc} +\begin{funcdesc}{pack_into}{fmt, buffer, offset, v1, v2, \moreargs} + Pack the values \code{\var{v1}, \var{v2}, \textrm{\ldots}} according to the given + format, write the packed bytes into the writable \var{buffer} starting at + \var{offset}. + Note that the offset is not an optional argument. + + \versionadded{2.5} +\end{funcdesc} + \begin{funcdesc}{unpack}{fmt, string} Unpack the string (presumably packed by \code{pack(\var{fmt}, \textrm{\ldots})}) according to the given format. The result is a @@ -37,6 +46,16 @@ (\code{len(\var{string})} must equal \code{calcsize(\var{fmt})}). \end{funcdesc} +\begin{funcdesc}{unpack_from}{fmt, buffer\optional{,offset \code{= 0}}} + Unpack the \var{buffer} according to tthe given format. + The result is a tuple even if it contains exactly one item. The + \var{buffer} must contain at least the amount of data required by the + format (\code{len(buffer[offset:])} must be at least + \code{calcsize(\var{fmt})}). + + \versionadded{2.5} +\end{funcdesc} + \begin{funcdesc}{calcsize}{fmt} Return the size of the struct (and hence of the string) corresponding to the given format. @@ -208,3 +227,43 @@ \seemodule{array}{Packed binary storage of homogeneous data.} \seemodule{xdrlib}{Packing and unpacking of XDR data.} \end{seealso} + +\subsection{Struct Objects \label{struct-objects}} + +The \module{struct} module also defines the following type: + +\begin{classdesc}{Struct}{format} + Return a new Struct object which writes and reads binary data according to + the format string \var{format}. Creating a Struct object once and calling + its methods is more efficient than calling the \module{struct} functions + with the same format since the format string only needs to be compiled once. + + \versionadded{2.5} +\end{classdesc} + +Compiled Struct objects support the following methods and attributes: + +\begin{methoddesc}[Struct]{pack}{v1, v2, \moreargs} + Identical to the \function{pack()} function, using the compiled format. + (\code{len(result)} will equal \member{self.size}.) +\end{methoddesc} + +\begin{methoddesc}[Struct]{pack_into}{buffer, offset, v1, v2, \moreargs} + Identical to the \function{pack_into()} function, using the compiled format. +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack}{string} + Identical to the \function{unpack()} function, using the compiled format. + (\code{len(string)} must equal \member{self.size}). +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack_from}{buffer\optional{,offset + \code{= 0}}} + Identical to the \function{unpack_from()} function, using the compiled format. + (\code{len(buffer[offset:])} must be at least \member{self.size}). +\end{methoddesc} + +\begin{memberdesc}[Struct]{format} + The format string used to construct this Struct object. +\end{memberdesc} + Modified: python/branches/p3yk/Doc/lib/libtarfile.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtarfile.tex (original) +++ python/branches/p3yk/Doc/lib/libtarfile.tex Fri Feb 23 16:07:44 2007 @@ -36,7 +36,8 @@ \lineii{'r:'}{Open for reading exclusively without compression.} \lineii{'r:gz'}{Open for reading with gzip compression.} \lineii{'r:bz2'}{Open for reading with bzip2 compression.} - \lineii{'a' or 'a:'}{Open for appending with no compression.} + \lineii{'a' or 'a:'}{Open for appending with no compression. The file + is created if it does not exist.} \lineii{'w' or 'w:'}{Open for uncompressed writing.} \lineii{'w:gz'}{Open for gzip compressed writing.} \lineii{'w:bz2'}{Open for bzip2 compressed writing.} @@ -48,8 +49,8 @@ avoid this. If a compression method is not supported, \exception{CompressionError} is raised. - If \var{fileobj} is specified, it is used as an alternative to - a file object opened for \var{name}. + If \var{fileobj} is specified, it is used as an alternative to a file + object opened for \var{name}. It is supposed to be at position 0. For special purposes, there is a second format for \var{mode}: \code{'filemode|[compression]'}. \function{open()} will return a @@ -160,6 +161,7 @@ If \var{fileobj} is given, it is used for reading or writing data. If it can be determined, \var{mode} is overridden by \var{fileobj}'s mode. + \var{fileobj} will be used from position 0. \begin{notice} \var{fileobj} is not closed, when \class{TarFile} is closed. \end{notice} Modified: python/branches/p3yk/Doc/lib/libzipfile.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libzipfile.tex (original) +++ python/branches/p3yk/Doc/lib/libzipfile.tex Fri Feb 23 16:07:44 2007 @@ -17,8 +17,10 @@ {PKZIP Application Note}. This module does not currently handle ZIP files which have appended -comments, or multi-disk ZIP files. It can handle ZIP files that use the -ZIP64 extensions (that is ZIP files that are more than 4 GByte in size). +comments, or multi-disk ZIP files. It can handle ZIP files that use +the ZIP64 extensions (that is ZIP files that are more than 4 GByte in +size). It supports decryption of encrypted files in ZIP archives, but +it cannot currently create an encrypted file. The available attributes of this module are: @@ -99,6 +101,8 @@ \end{verbatim} also works, and at least \program{WinZip} can read such files. + If \var{mode} is \code{a} and the file does not exist at all, + it is created. \var{compression} is the ZIP compression method to use when writing the archive, and should be \constant{ZIP_STORED} or \constant{ZIP_DEFLATED}; unrecognized values will cause @@ -112,6 +116,9 @@ ZIP file would require ZIP64 extensions. ZIP64 extensions are disabled by default because the default \program{zip} and \program{unzip} commands on \UNIX{} (the InfoZIP utilities) don't support these extensions. + + \versionchanged[If the file does not exist, it is created if the + mode is 'a']{2.6} \end{classdesc} \begin{methoddesc}{close}{} @@ -138,9 +145,18 @@ Print a table of contents for the archive to \code{sys.stdout}. \end{methoddesc} -\begin{methoddesc}{read}{name} +\begin{methoddesc}{setpassword}{pwd} + Set \var{pwd} as default password to extract encrypted files. + \versionadded{2.6} +\end{methoddesc} + +\begin{methoddesc}{read}{name\optional{, pwd}} Return the bytes of the file in the archive. The archive must be - open for read or append. + open for read or append. \var{pwd} is the password used for encrypted + files and, if specified, it will override the default password set with + \method{setpassword()}. + + \versionchanged[\var{pwd} was added]{2.6} \end{methoddesc} \begin{methoddesc}{testzip}{} Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Fri Feb 23 16:07:44 2007 @@ -1,4 +1,4 @@ -/* File automatically generated by Parser/asdl_c.py */ +/* File automatically generated by Parser/asdl_c.py. */ #include "asdl.h" Modified: python/branches/p3yk/Include/dictobject.h ============================================================================== --- python/branches/p3yk/Include/dictobject.h (original) +++ python/branches/p3yk/Include/dictobject.h Fri Feb 23 16:07:44 2007 @@ -100,12 +100,15 @@ PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); PyAPI_FUNC(int) PyDict_Next( PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); +PyAPI_FUNC(int) _PyDict_Next( + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp); PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp); PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key); +PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, long hash); /* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */ PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other); Modified: python/branches/p3yk/Lib/decimal.py ============================================================================== --- python/branches/p3yk/Lib/decimal.py (original) +++ python/branches/p3yk/Lib/decimal.py Fri Feb 23 16:07:44 2007 @@ -487,7 +487,7 @@ 28 >>> with localcontext(): ... ctx = getcontext() - ... ctx.prec() += 2 + ... ctx.prec += 2 ... print(ctx.prec) ... 30 Modified: python/branches/p3yk/Lib/distutils/command/build_ext.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/build_ext.py (original) +++ python/branches/p3yk/Lib/distutils/command/build_ext.py Fri Feb 23 16:07:44 2007 @@ -185,9 +185,7 @@ # for extensions under Cygwin and AtheOS Python's library directory must be # appended to library_dirs - if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos' or \ - ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')) and - sysconfig.get_config_var('Py_ENABLE_SHARED')): + if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos': if string.find(sys.executable, sys.exec_prefix) != -1: # building third party extensions self.library_dirs.append(os.path.join(sys.prefix, "lib", @@ -197,6 +195,17 @@ # building python standard extensions self.library_dirs.append('.') + # for extensions under Linux with a shared Python library, + # Python's library directory must be appended to library_dirs + if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \ + and sysconfig.get_config_var('Py_ENABLE_SHARED'): + if string.find(sys.executable, sys.exec_prefix) != -1: + # building third party extensions + self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) + else: + # building python standard extensions + self.library_dirs.append('.') + # The argument parsing will result in self.define being a string, but # it has to be a list of 2-tuples. All the preprocessor symbols # specified by the 'define' option will be set to '1'. Multiple Modified: python/branches/p3yk/Lib/encodings/__init__.py ============================================================================== --- python/branches/p3yk/Lib/encodings/__init__.py (original) +++ python/branches/p3yk/Lib/encodings/__init__.py Fri Feb 23 16:07:44 2007 @@ -93,8 +93,10 @@ if not modname or '.' in modname: continue try: - mod = __import__('encodings.' + modname, - globals(), locals(), _import_tail) + # Import is absolute to prevent the possibly malicious import of a + # module with side-effects that is not in the 'encodings' package. + mod = __import__('encodings.' + modname, fromlist=_import_tail, + level=0) except ImportError: pass else: Modified: python/branches/p3yk/Lib/gzip.py ============================================================================== --- python/branches/p3yk/Lib/gzip.py (original) +++ python/branches/p3yk/Lib/gzip.py Fri Feb 23 16:07:44 2007 @@ -106,7 +106,7 @@ self._new_member = True self.extrabuf = "" self.extrasize = 0 - self.filename = filename + self.name = filename # Starts small, scales exponentially self.min_readsize = 100 @@ -127,14 +127,20 @@ if self.mode == WRITE: self._write_gzip_header() + @property + def filename(self): + import warnings + warnings.warn("use the name attribute", DeprecationWarning) + if self.mode == WRITE and self.name[-3:] != ".gz": + return self.name + ".gz" + return self.name + def __repr__(self): s = repr(self.fileobj) return '' def _init_write(self, filename): - if filename[-3:] != '.gz': - filename = filename + '.gz' - self.filename = filename + self.name = filename self.crc = zlib.crc32("") self.size = 0 self.writebuf = [] @@ -143,7 +149,9 @@ def _write_gzip_header(self): self.fileobj.write('\037\213') # magic header self.fileobj.write('\010') # compression method - fname = self.filename[:-3] + fname = self.name + if fname.endswith(".gz"): + fname = fname[:-3] flags = 0 if fname: flags = FNAME Modified: python/branches/p3yk/Lib/heapq.py ============================================================================== --- python/branches/p3yk/Lib/heapq.py (original) +++ python/branches/p3yk/Lib/heapq.py Fri Feb 23 16:07:44 2007 @@ -126,8 +126,8 @@ From all times, sorting has always been a Great Art! :-) """ -__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'nlargest', - 'nsmallest'] +__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', + 'nlargest', 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee from operator import itemgetter, neg @@ -308,6 +308,41 @@ except ImportError: pass +def merge(*iterables): + '''Merge multiple sorted inputs into a single sorted output. + + Similar to sorted(itertools.chain(*iterables)) but returns an iterable, + does not pull the data into memory all at once, and assumes that each of + the input streams is already sorted (smallest to largest). + + >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) + [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] + + ''' + _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration + + h = [] + h_append = h.append + for itnum, it in enumerate(map(iter, iterables)): + try: + next = it.next + h_append([next(), itnum, next]) + except _StopIteration: + pass + heapify(h) + + while 1: + try: + while 1: + v, itnum, next = s = h[0] # raises IndexError when h is empty + yield v + s[0] = next() # raises StopIteration when exhausted + _heapreplace(h, s) # restore heap condition + except _StopIteration: + _heappop(h) # remove empty iterator + except IndexError: + return + # Extend the implementations of nsmallest and nlargest to use a key= argument _nsmallest = nsmallest def nsmallest(n, iterable, key=None): @@ -341,3 +376,6 @@ while heap: sort.append(heappop(heap)) print(sort) + + import doctest + doctest.testmod() Modified: python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py Fri Feb 23 16:07:44 2007 @@ -10,13 +10,14 @@ KEYPRESS_VIRTUAL_EVENT_NAME = "<>" # We need to bind event beyond so that the function will be called # before the default specific IDLE function -KEYPRESS_SEQUENCES = ("", "", "", - "", "", "", "") +KEYPRESS_SEQUENCES = ("", "", "", "", + "", "", "", "", + "", "") KEYRELEASE_VIRTUAL_EVENT_NAME = "<>" KEYRELEASE_SEQUENCE = "" -LISTUPDATE_SEQUENCE = "" +LISTUPDATE_SEQUENCE = "" WINCONFIG_SEQUENCE = "" -DOUBLECLICK_SEQUENCE = "" +DOUBLECLICK_SEQUENCE = "" class AutoCompleteWindow: @@ -49,6 +50,8 @@ # event ids self.hideid = self.keypressid = self.listupdateid = self.winconfigid \ = self.keyreleaseid = self.doubleclickid = None + # Flag set if last keypress was a tab + self.lastkey_was_tab = False def _change_start(self, newstart): i = 0 @@ -118,11 +121,6 @@ i = 0 while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]: i += 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) @@ -206,7 +204,7 @@ self.keyrelease_event) self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE) self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, - self.listupdate_event) + self.listselect_event) self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event) self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, self.doubleclick_event) @@ -215,24 +213,34 @@ if not self.is_active(): return # Position the completion list window + text = self.widget + text.see(self.startindex) + x, y, cx, cy = text.bbox(self.startindex) acw = self.autocompletewindow - self.widget.see(self.startindex) - x, y, cx, cy = self.widget.bbox(self.startindex) - acw.wm_geometry("+%d+%d" % (x + self.widget.winfo_rootx(), - y + self.widget.winfo_rooty() \ - -acw.winfo_height())) - + acw_width, acw_height = acw.winfo_width(), acw.winfo_height() + text_width, text_height = text.winfo_width(), text.winfo_height() + new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width)) + new_y = text.winfo_rooty() + y + if (text_height - (y + cy) >= acw_height # enough height below + or y < acw_height): # not enough height above + # place acw below current line + new_y += cy + else: + # place acw above current line + new_y -= acw_height + acw.wm_geometry("+%d+%d" % (new_x, new_y)) def hide_event(self, event): if not self.is_active(): return self.hide_window() - def listupdate_event(self, event): + def listselect_event(self, event): if not self.is_active(): return self.userwantswindow = True - self._selection_changed() + cursel = int(self.listbox.curselection()[0]) + self._change_start(self.completions[cursel]) def doubleclick_event(self, event): # Put the selected completion in the text, and close the list @@ -248,7 +256,8 @@ state = event.mc_state else: state = 0 - + if keysym != "Tab": + self.lastkey_was_tab = False if (len(keysym) == 1 or keysym in ("underscore", "BackSpace") or (self.mode==AutoComplete.COMPLETE_FILES and keysym in ("period", "minus"))) \ @@ -330,13 +339,21 @@ self.listbox.select_clear(cursel) self.listbox.select_set(newsel) self._selection_changed() + self._change_start(self.completions[newsel]) return "break" elif (keysym == "Tab" and not state): - # The user wants a completion, but it is handled by AutoComplete - # (not AutoCompleteWindow), so ignore. - self.userwantswindow = True - return + if self.lastkey_was_tab: + # two tabs in a row; insert current selection and close acw + cursel = int(self.listbox.curselection()[0]) + self._change_start(self.completions[cursel]) + self.hide_window() + return "break" + else: + # first tab; let AutoComplete handle the completion + self.userwantswindow = True + self.lastkey_was_tab = True + return elif any(s in keysym for s in ("Shift", "Control", "Alt", "Meta", "Command", "Option")): Modified: python/branches/p3yk/Lib/idlelib/CallTips.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/CallTips.py (original) +++ python/branches/p3yk/Lib/idlelib/CallTips.py Fri Feb 23 16:07:44 2007 @@ -3,7 +3,9 @@ Call Tips are floating windows which display function, class, and method parameter and docstring information when you type an opening parenthesis, and which disappear when you type a closing parenthesis. + """ +import re import sys import types @@ -89,6 +91,8 @@ two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. + To find methods, fetch_tip must be fed a fully qualified name. + """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt @@ -108,7 +112,7 @@ namespace.update(__main__.__dict__) try: return eval(name, namespace) - except: + except (NameError, AttributeError): return None def _find_constructor(class_ob): @@ -124,39 +128,37 @@ def get_arg_text(ob): """Get a string describing the arguments for the given object""" - argText = "" + arg_text = "" if ob is not None: - argOffset = 0 + arg_offset = 0 if type(ob) in (types.ClassType, types.TypeType): # Look for the highest __init__ in the class chain. fob = _find_constructor(ob) if fob is None: fob = lambda: None else: - argOffset = 1 + arg_offset = 1 elif type(ob)==types.MethodType: # bit of a hack for methods - turn it into a function # but we drop the "self" param. fob = ob.im_func - argOffset = 1 + arg_offset = 1 else: fob = ob - # Try and build one for Python defined functions + # Try to build one for Python defined functions if type(fob) in [types.FunctionType, types.LambdaType]: - try: - realArgs = fob.func_code.co_varnames[argOffset:fob.func_code.co_argcount] - defaults = fob.func_defaults or [] - defaults = list(map(lambda name: "=%s" % repr(name), defaults)) - defaults = [""] * (len(realArgs)-len(defaults)) + defaults - items = map(lambda arg, dflt: arg+dflt, realArgs, defaults) - if fob.func_code.co_flags & 0x4: - items.append("...") - if fob.func_code.co_flags & 0x8: - items.append("***") - argText = ", ".join(items) - argText = "(%s)" % argText - except: - pass + argcount = fob.func_code.co_argcount + real_args = fob.func_code.co_varnames[arg_offset:argcount] + defaults = fob.func_defaults or [] + defaults = list(map(lambda name: "=%s" % repr(name), defaults)) + defaults = [""] * (len(real_args) - len(defaults)) + defaults + items = map(lambda arg, dflt: arg + dflt, real_args, defaults) + if fob.func_code.co_flags & 0x4: + items.append("...") + if fob.func_code.co_flags & 0x8: + items.append("***") + arg_text = ", ".join(items) + arg_text = "(%s)" % re.sub("\.\d+", "", arg_text) # See if we can use the docstring doc = getattr(ob, "__doc__", "") if doc: @@ -164,10 +166,10 @@ pos = doc.find("\n") if pos < 0 or pos > 70: pos = 70 - if argText: - argText += "\n" - argText += doc[:pos] - return argText + if arg_text: + arg_text += "\n" + arg_text += doc[:pos] + return arg_text ################################################# # @@ -181,16 +183,18 @@ def t4(*args): "(...)" def t5(a, *args): "(a, ...)" def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)" + def t7((a, b), c, (d, e)): "(, c, )" - class TC: - "(a=None, ...)" - def __init__(self, a=None, *b): "(a=None, ...)" + class TC(object): + "(ai=None, ...)" + def __init__(self, ai=None, *b): "(ai=None, ...)" def t1(self): "()" - def t2(self, a, b=None): "(a, b=None)" - def t3(self, a, *args): "(a, ...)" + def t2(self, ai, b=None): "(ai, b=None)" + def t3(self, ai, *args): "(ai, ...)" def t4(self, *args): "(...)" - def t5(self, a, *args): "(a, ...)" - def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)" + def t5(self, ai, *args): "(ai, ...)" + def t6(self, ai, b=None, *args, **kw): "(ai, b=None, ..., ***)" + def t7(self, (ai, b), c, (d, e)): "(, c, )" def test(tests): ct = CallTips() @@ -198,15 +202,20 @@ for t in tests: expected = t.__doc__ + "\n" + t.__doc__ name = t.__name__ - arg_text = ct.fetch_tip(name) + # exercise fetch_tip(), not just get_arg_text() + try: + qualified_name = "%s.%s" % (t.im_class.__name__, name) + except AttributeError: + qualified_name = name + arg_text = ct.fetch_tip(qualified_name) if arg_text != expected: failed.append(t) - print("%s - expected %s, but got %s" % (t, expected, - get_arg_text(entity))) + fmt = "%s - expected %s, but got %s" + print(fmt % (t.__name__, expected, get_arg_text(t))) print("%d of %d tests failed" % (len(failed), len(tests))) tc = TC() - tests = (t1, t2, t3, t4, t5, t6, - TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6) + tests = (t1, t2, t3, t4, t5, t6, t7, + TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6, tc.t7) test(tests) Modified: python/branches/p3yk/Lib/idlelib/CodeContext.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/CodeContext.py (original) +++ python/branches/p3yk/Lib/idlelib/CodeContext.py Fri Feb 23 16:07:44 2007 @@ -10,6 +10,7 @@ """ import Tkinter +from Tkconstants import TOP, LEFT, X, W, SUNKEN from configHandler import idleConf import re from sys import maxint as INFINITY @@ -24,7 +25,6 @@ class CodeContext: menudefs = [('options', [('!Code Conte_xt', '<>')])] - context_depth = idleConf.GetOption("extensions", "CodeContext", "numlines", type="int", default=3) bgcolor = idleConf.GetOption("extensions", "CodeContext", @@ -54,66 +54,33 @@ def toggle_code_context_event(self, event=None): if not self.label: - # The following code attempts to figure out the required border - # width and vertical padding required for the CodeContext widget - # to be perfectly aligned with the text in the main Text widget. - # This is done by retrieving the appropriate attributes from the - # editwin.text and editwin.text_frame widgets. + # Calculate the border width and horizontal padding required to + # align the context with the text in the main Text widget. # # All values are passed through int(str()), since some - # values may be pixel objects, which can't simply be added added - # to ints. - # - # This code is considered somewhat unstable since it relies on - # some of Tk's inner workings. However its effect is merely - # cosmetic; failure will only cause the CodeContext text to be - # somewhat misaligned with the text in the main Text widget. - # - # To avoid possible errors, all references to the inner workings - # of Tk are executed inside try/except blocks. - - widgets_for_width_calc = self.editwin.text, self.editwin.text_frame - - # calculate the required vertical padding + # values may be pixel objects, which can't simply be added to ints. + widgets = self.editwin.text, self.editwin.text_frame + # Calculate the required vertical padding padx = 0 - for widget in widgets_for_width_calc: - try: - # retrieve the "padx" attribte from widget's pack info - padx += int(str( widget.pack_info()['padx'] )) - except: - pass - try: - # retrieve the widget's "padx" attribte - padx += int(str( widget.cget('padx') )) - except: - pass - - # calculate the required border width - border_width = 0 - for widget in widgets_for_width_calc: - try: - # retrieve the widget's "border" attribte - border_width += int(str( widget.cget('border') )) - except: - pass - + for widget in widgets: + padx += int(str( widget.pack_info()['padx'] )) + padx += int(str( widget.cget('padx') )) + # Calculate the required border width + border = 0 + for widget in widgets: + border += int(str( widget.cget('border') )) self.label = Tkinter.Label(self.editwin.top, text="\n" * (self.context_depth - 1), - anchor="w", justify="left", + anchor=W, justify=LEFT, font=self.textfont, bg=self.bgcolor, fg=self.fgcolor, width=1, #don't request more than we get - padx=padx, #line up with text widget - border=border_width, #match border width - relief="sunken", - ) - - # CodeContext's label widget is packed before and above the - # text_frame widget, thus ensuring that it will appear directly - # above it. - self.label.pack(side="top", fill="x", expand=False, + padx=padx, border=border, + relief=SUNKEN) + # Pack the label widget before and above the text_frame widget, + # thus ensuring that it will appear directly above text_frame + self.label.pack(side=TOP, fill=X, expand=False, before=self.editwin.text_frame) - else: self.label.destroy() self.label = None @@ -190,7 +157,6 @@ stopindent) self.info.extend(lines) self.topvisible = new_topvisible - # empty lines in context pane: context_strings = [""] * max(0, self.context_depth - len(self.info)) # followed by the context hint lines: Modified: python/branches/p3yk/Lib/idlelib/IOBinding.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/IOBinding.py (original) +++ python/branches/p3yk/Lib/idlelib/IOBinding.py Fri Feb 23 16:07:44 2007 @@ -209,7 +209,7 @@ # gets set to "not modified" at every new prompt. try: interp = self.editwin.interp - except: + except AttributeError: interp = None if not self.filename and self.get_saved() and not interp: self.editwin.flist.open(filename, self.loadfile) Modified: python/branches/p3yk/Lib/idlelib/NEWS.txt ============================================================================== --- python/branches/p3yk/Lib/idlelib/NEWS.txt (original) +++ python/branches/p3yk/Lib/idlelib/NEWS.txt Fri Feb 23 16:07:44 2007 @@ -3,6 +3,19 @@ *Release date: XX-XXX-200X* +- Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented; + mouse and cursor selection in ACWindow implemented; double Tab inserts + current selection and closes ACW (similar to double-click and Return); scroll + wheel now works in ACW. Added AutoComplete instructions to IDLE Help. + +- AutoCompleteWindow moved below input line, will move above if there + isn't enough space. Patch 1621265 Tal Einat + +- Calltips now 'handle' tuples in the argument list (display '' :) + Suggested solution by Christos Georgiou, Bug 791968. + +- Add 'raw' support to configHandler. Patch 1650174 Tal Einat. + - Avoid hang when encountering a duplicate in a completion list. Bug 1571112. - Patch #1362975: Rework CodeContext indentation algorithm to Modified: python/branches/p3yk/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/PyShell.py (original) +++ python/branches/p3yk/Lib/idlelib/PyShell.py Fri Feb 23 16:07:44 2007 @@ -706,34 +706,36 @@ debugger = self.debugger try: self.tkconsole.beginexecuting() - try: - if not debugger and self.rpcclt is not None: - self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", - (code,), {}) - elif debugger: - debugger.run(code, self.locals) - else: - exec(code, self.locals) - except SystemExit: - if not self.tkconsole.closing: - if tkMessageBox.askyesno( - "Exit?", - "Do you want to exit altogether?", - default="yes", - master=self.tkconsole.text): - raise - else: - self.showtraceback() - else: + if not debugger and self.rpcclt is not None: + self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", + (code,), {}) + elif debugger: + debugger.run(code, self.locals) + else: + exec(code, self.locals) + except SystemExit: + if not self.tkconsole.closing: + if tkMessageBox.askyesno( + "Exit?", + "Do you want to exit altogether?", + default="yes", + master=self.tkconsole.text): raise - except: - if use_subprocess: - # When run w/o subprocess, both user and IDLE errors - # are printed here; skip message in that case. - print("IDLE internal error in runcode()", file=self.tkconsole.stderr) + else: + else: + raise + except: + if use_subprocess: + print("IDLE internal error in runcode()", + file=self.tkconsole.stderr) self.showtraceback() - if use_subprocess: - self.tkconsole.endexecuting() + self.tkconsole.endexecuting() + else: + if self.tkconsole.canceled: + self.tkconsole.canceled = False + print("KeyboardInterrupt", file=self.tkconsole.stderr) + else: + self.showtraceback() finally: if not use_subprocess: try: Modified: python/branches/p3yk/Lib/idlelib/configHandler.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/configHandler.py (original) +++ python/branches/p3yk/Lib/idlelib/configHandler.py Fri Feb 23 16:07:44 2007 @@ -39,22 +39,19 @@ self.file=cfgFile ConfigParser.__init__(self,defaults=cfgDefaults) - def Get(self, section, option, type=None, default=None): + def Get(self, section, option, type=None, default=None, raw=False): """ Get an option value for given section/option or return default. If type is specified, return as type. """ + if not self.has_option(section, option): + return default if type=='bool': - getVal=self.getboolean + return self.getboolean(section, option) elif type=='int': - getVal=self.getint - else: - getVal=self.get - if self.has_option(section,option): - #return getVal(section, option, raw, vars, default) - return getVal(section, option) + return self.getint(section, option) else: - return default + return self.get(section, option, raw=raw) def GetOptionList(self,section): """ @@ -219,7 +216,7 @@ return userDir def GetOption(self, configType, section, option, default=None, type=None, - warn_on_default=True): + warn_on_default=True, raw=False): """ Get an option value for given config type and given general configuration section/option or return a default. If type is specified, @@ -233,9 +230,11 @@ """ if self.userCfg[configType].has_option(section,option): - return self.userCfg[configType].Get(section, option, type=type) + return self.userCfg[configType].Get(section, option, + type=type, raw=raw) elif self.defaultCfg[configType].has_option(section,option): - return self.defaultCfg[configType].Get(section, option, type=type) + return self.defaultCfg[configType].Get(section, option, + type=type, raw=raw) else: #returning default, print warning if warn_on_default: warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n' Modified: python/branches/p3yk/Lib/idlelib/help.txt ============================================================================== --- python/branches/p3yk/Lib/idlelib/help.txt (original) +++ python/branches/p3yk/Lib/idlelib/help.txt Fri Feb 23 16:07:44 2007 @@ -44,6 +44,10 @@ Find in Files... -- Open a search dialog box for searching files Replace... -- Open a search-and-replace dialog box Go to Line -- Ask for a line number and show that line + Show Calltip -- Open a small window with function param hints + Show Completions -- Open a scroll window allowing selection keywords + and attributes. (see '*TIPS*', below) + Show Parens -- Highlight the surrounding parenthesis Expand Word -- Expand the word you have typed to match another word in the same buffer; repeat to get a different expansion @@ -91,6 +95,7 @@ Code Context -- Open a pane at the top of the edit window which shows the block context of the section of code which is scrolling off the top or the window. + (Not present in Shell window.) Windows Menu: @@ -138,8 +143,11 @@ Control-left/right Arrow moves by words in a strange but useful way. Home/End go to begin/end of line. Control-Home/End go to begin/end of file. - Some useful Emacs bindings (Control-a, Control-e, Control-k, etc.) - are inherited from Tcl/Tk. + Some useful Emacs bindings are inherited from Tcl/Tk: + Control-a beginning of line + Control-e end of line + Control-k kill line (but doesn't put it in clipboard) + Control-l center window around the insertion point Standard Windows bindings may work on that platform. Keybindings are selected in the Settings Dialog, look there. @@ -155,6 +163,52 @@ See also the indent/dedent region commands in the edit menu. +Completions: + + Completions are supplied for functions, classes, and attributes of + classes, both built-in and user-defined. Completions are also provided + for filenames. + + The AutoCompleteWindow (ACW) will open after a predefined delay + (default is two seconds) after a '.' or (in a string) an os.sep is + typed. If after one of those characters (plus zero or more other + characters) you type a Tab the ACW will open immediately if a possible + continuation is found. + + If there is only one possible completion for the characters entered, a + Tab will supply that completion without opening the ACW. + + 'Show Completions' will force open a completions window. In an empty + string, this will contain the files in the current directory. On a + blank line, it will contain the built-in and user-defined functions and + classes in the current name spaces, plus any modules imported. If some + characters have been entered, the ACW will attempt to be more specific. + + If string of characters is typed, the ACW selection will jump to the + entry most closely matching those characters. Entering a Tab will cause + the longest non-ambiguous match to be entered in the Edit window or + Shell. Two Tabs in a row will supply the current ACW selection, as + will Return or a double click. Cursor keys, Page Up/Down, mouse + selection, and the scrollwheel all operate on the ACW. + + 'Hidden' attributes can be accessed by typing the beginning of hidden + name after a '.'. e.g. '_'. This allows access to modules with + '__all__' set, or to class-private attributes. + + Completions and the 'Expand Word' facility can save a lot of typing! + + Completions are currently limited to those in the namespaces. Names in + an Edit window which are not via __main__ or sys.modules will not be + found. Run the module once with your imports to correct this + situation. Note that IDLE itself places quite a few modules in + sys.modules, so much can be found by default, e.g. the re module. + + If you don't like the ACW popping up unbidden, simply make the delay + longer or disable the extension. OTOH, you could make the delay zero. + + You could also switch off the CallTips extension. (We will be adding + a delay to the call tip window.) + Python Shell window: Control-c interrupts executing command. @@ -165,7 +219,7 @@ Alt-p retrieves previous command matching what you have typed. Alt-n retrieves next. - (These are Control-p, Control-n on the Mac) + (These are Control-p, Control-n on the Mac) Return while cursor is on a previous command retrieves that command. Expand word is also useful to reduce typing. @@ -196,7 +250,7 @@ be changed using the Settings dialog. Command line usage: - + Enter idle -h at the command prompt to get a usage message. Running without a subprocess: @@ -211,3 +265,18 @@ re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. + +Extensions: + + IDLE contains an extension facility. See the beginning of + config-extensions.def in the idlelib directory for further information. + The default extensions are currently: + + FormatParagraph + AutoExpand + ZoomHeight + ScriptBinding + CallTips + ParenMatch + AutoComplete + CodeContext Modified: python/branches/p3yk/Lib/imputil.py ============================================================================== --- python/branches/p3yk/Lib/imputil.py (original) +++ python/branches/p3yk/Lib/imputil.py Fri Feb 23 16:07:44 2007 @@ -552,6 +552,10 @@ # This method is only used when we look for a module within a package. assert parent + for submodule_path in parent.__path__: + code = self._import_pathname(_os_path_join(submodule_path, modname), fqname) + if code is not None: + return code return self._import_pathname(_os_path_join(parent.__pkgdir__, modname), fqname) Modified: python/branches/p3yk/Lib/logging/__init__.py ============================================================================== --- python/branches/p3yk/Lib/logging/__init__.py (original) +++ python/branches/p3yk/Lib/logging/__init__.py Fri Feb 23 16:07:44 2007 @@ -1,4 +1,4 @@ -# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, @@ -21,7 +21,7 @@ Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. -Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.5.0.1" -__date__ = "09 January 2007" +__version__ = "0.5.0.2" +__date__ = "16 February 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -68,7 +68,7 @@ except: return sys.exc_traceback.tb_frame.f_back -if hasattr(sys, '_getframe'): currentframe = sys._getframe +if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) # done filching # _srcfile is only used in conjunction with sys._getframe(). Modified: python/branches/p3yk/Lib/shutil.py ============================================================================== --- python/branches/p3yk/Lib/shutil.py (original) +++ python/branches/p3yk/Lib/shutil.py Fri Feb 23 16:07:44 2007 @@ -60,13 +60,15 @@ os.chmod(dst, mode) def copystat(src, dst): - """Copy all stat info (mode bits, atime and mtime) from src to dst""" + """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) + if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): + os.chflags(dst, st.st_flags) def copy(src, dst): Modified: python/branches/p3yk/Lib/stat.py ============================================================================== --- python/branches/p3yk/Lib/stat.py (original) +++ python/branches/p3yk/Lib/stat.py Fri Feb 23 16:07:44 2007 @@ -84,3 +84,16 @@ S_IROTH = 00004 S_IWOTH = 00002 S_IXOTH = 00001 + +# Names for file flags + +UF_NODUMP = 0x00000001 +UF_IMMUTABLE = 0x00000002 +UF_APPEND = 0x00000004 +UF_OPAQUE = 0x00000008 +UF_NOUNLINK = 0x00000010 +SF_ARCHIVED = 0x00010000 +SF_IMMUTABLE = 0x00020000 +SF_APPEND = 0x00040000 +SF_NOUNLINK = 0x00100000 +SF_SNAPSHOT = 0x00200000 Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Fri Feb 23 16:07:44 2007 @@ -593,14 +593,30 @@ c2pread, c2pwrite, errread, errwrite) - if p2cwrite: + # On Windows, you cannot just redirect one or two handles: You + # either have to redirect all three or none. If the subprocess + # user has only redirected one or two handles, we are + # automatically creating PIPEs for the rest. We should close + # these after the process is started. See bug #1124861. + if mswindows: + if stdin is None and p2cwrite is not None: + os.close(p2cwrite) + p2cwrite = None + if stdout is None and c2pread is not None: + os.close(c2pread) + c2pread = None + if stderr is None and errread is not None: + os.close(errread) + errread = None + + if p2cwrite is not None: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) - if c2pread: + if c2pread is not None: if universal_newlines: self.stdout = os.fdopen(c2pread, 'rU', bufsize) else: self.stdout = os.fdopen(c2pread, 'rb', bufsize) - if errread: + if errread is not None: if universal_newlines: self.stderr = os.fdopen(errread, 'rU', bufsize) else: @@ -669,7 +685,9 @@ if stdin is None: p2cread = GetStdHandle(STD_INPUT_HANDLE) - elif stdin == PIPE: + if p2cread is not None: + pass + elif stdin is None or stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) # Detach and turn into fd p2cwrite = p2cwrite.Detach() @@ -683,7 +701,9 @@ if stdout is None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) - elif stdout == PIPE: + if c2pwrite is not None: + pass + elif stdout is None or stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) # Detach and turn into fd c2pread = c2pread.Detach() @@ -697,7 +717,9 @@ if stderr is None: errwrite = GetStdHandle(STD_ERROR_HANDLE) - elif stderr == PIPE: + if errwrite is not None: + pass + elif stderr is None or stderr == PIPE: errread, errwrite = CreatePipe(None, 0) # Detach and turn into fd errread = errread.Detach() @@ -987,29 +1009,29 @@ # Child try: # Close parent's pipe ends - if p2cwrite: + if p2cwrite is not None: os.close(p2cwrite) - if c2pread: + if c2pread is not None: os.close(c2pread) - if errread: + if errread is not None: os.close(errread) os.close(errpipe_read) # Dup fds for child - if p2cread: + if p2cread is not None: os.dup2(p2cread, 0) - if c2pwrite: + if c2pwrite is not None: os.dup2(c2pwrite, 1) - if errwrite: + if errwrite is not None: os.dup2(errwrite, 2) # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - if p2cread and p2cread not in (0,): + if p2cread is not None and p2cread not in (0,): os.close(p2cread) - if c2pwrite and c2pwrite not in (p2cread, 1): + if c2pwrite is not None and c2pwrite not in (p2cread, 1): os.close(c2pwrite) - if errwrite and errwrite not in (p2cread, c2pwrite, 2): + if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2): os.close(errwrite) # Close all other fds, if asked for @@ -1042,11 +1064,11 @@ # Parent os.close(errpipe_write) - if p2cread and p2cwrite: + if p2cread is not None and p2cwrite is not None: os.close(p2cread) - if c2pwrite and c2pread: + if c2pwrite is not None and c2pread is not None: os.close(c2pwrite) - if errwrite and errread: + if errwrite is not None and errread is not None: os.close(errwrite) # Wait for exec to fail or succeed; possibly raising exception Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Fri Feb 23 16:07:44 2007 @@ -1062,6 +1062,10 @@ self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode] if not fileobj: + if self._mode == "a" and not os.path.exists(self.name): + # Create nonexistent files in append mode. + self._mode = "w" + self.mode = "wb" fileobj = _open(self.name, self.mode) self._extfileobj = False else: @@ -1095,7 +1099,8 @@ self.fileobj.seek(0) break if tarinfo is None: - self.fileobj.seek(- BLOCKSIZE, 1) + if self.offset > 0: + self.fileobj.seek(- BLOCKSIZE, 1) break if self._mode in "aw": @@ -1122,7 +1127,7 @@ 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression - 'a' or 'a:' open for appending + 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 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 Fri Feb 23 16:07:44 2007 @@ -1767,6 +1767,11 @@ self.assertEqual(t.isoformat(), "00:00:00.100000") self.assertEqual(t.isoformat(), str(t)) + def test_1653736(self): + # verify it doesn't accept extra keyword arguments + t = self.theclass(second=1) + self.assertRaises(TypeError, t.isoformat, foo=3) + def test_strftime(self): t = self.theclass(1, 2, 3, 4) self.assertEqual(t.strftime('%H %M %S'), "01 02 03") 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 Fri Feb 23 16:07:44 2007 @@ -47,6 +47,7 @@ self.assertEqual(err.args, (15,)) else: self.fail("d2[15] didn't raise KeyError") + self.assertRaises(TypeError, defaultdict, 1) def test_missing(self): d1 = defaultdict() @@ -60,10 +61,10 @@ self.assertEqual(repr(d1), "defaultdict(None, {})") d1[11] = 41 self.assertEqual(repr(d1), "defaultdict(None, {11: 41})") - d2 = defaultdict(0) - self.assertEqual(d2.default_factory, 0) + d2 = defaultdict(int) + self.assertEqual(d2.default_factory, int) d2[12] = 42 - self.assertEqual(repr(d2), "defaultdict(0, {12: 42})") + self.assertEqual(repr(d2), "defaultdict(, {12: 42})") def foo(): return 43 d3 = defaultdict(foo) self.assert_(d3.default_factory is foo) 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 Fri Feb 23 16:07:44 2007 @@ -2093,7 +2093,7 @@ __slots__ = ['prec'] def __init__(self, value=0.0, prec=12): self.prec = int(prec) - float.__init__(value) + float.__init__(self, value) def __repr__(self): return "%.*g" % (self.prec, self) vereq(repr(precfloat(1.1)), "1.1") 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 Fri Feb 23 16:07:44 2007 @@ -182,6 +182,14 @@ self.assertRaises(ValueError, {}.update, [(1, 2, 3)]) + # SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses + class KeyUpperDict(dict): + def __getitem__(self, key): + return key.upper() + d.clear() + d.update(KeyUpperDict.fromkeys('abc')) + self.assertEqual(d, {'a':'A', 'b':'B', 'c':'C'}) + def test_fromkeys(self): self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = {} Modified: python/branches/p3yk/Lib/test/test_gzip.py ============================================================================== --- python/branches/p3yk/Lib/test/test_gzip.py (original) +++ python/branches/p3yk/Lib/test/test_gzip.py Fri Feb 23 16:07:44 2007 @@ -153,6 +153,13 @@ self.assertEqual(f.myfileobj.mode, 'rb') f.close() + def test_1647484(self): + for mode in ('wb', 'rb'): + f = gzip.GzipFile(self.filename, mode) + self.assert_(hasattr(f, "name")) + self.assertEqual(f.name, self.filename) + f.close() + def test_main(verbose=None): test_support.run_unittest(TestGzip) 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 Fri Feb 23 16:07:44 2007 @@ -1,6 +1,6 @@ """Unittests for heapq.""" -from heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest +from heapq import heappush, heappop, heapify, heapreplace, merge, nlargest, nsmallest import random import unittest from test import test_support @@ -103,6 +103,29 @@ heap_sorted = [heappop(heap) for i in range(size)] self.assertEqual(heap_sorted, sorted(data)) + def test_merge(self): + inputs = [] + for i in xrange(random.randrange(5)): + row = sorted(random.randrange(1000) for j in range(random.randrange(10))) + inputs.append(row) + self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs))) + self.assertEqual(list(merge()), []) + + def test_merge_stability(self): + class Int(int): + pass + inputs = [[], [], [], []] + for i in range(20000): + stream = random.randrange(4) + x = random.randrange(500) + obj = Int(x) + obj.pair = (x, stream) + inputs[stream].append(obj) + for stream in inputs: + stream.sort() + result = [i.pair for i in merge(*inputs)] + self.assertEqual(result, sorted(result)) + def test_nsmallest(self): data = [(random.randrange(2000), i) for i in range(1000)] for f in (None, lambda x: x[0] * 547 % 2000): Modified: python/branches/p3yk/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_itertools.py (original) +++ python/branches/p3yk/Lib/test/test_itertools.py Fri Feb 23 16:07:44 2007 @@ -55,8 +55,7 @@ self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)]) self.assertRaises(TypeError, count, 2, 3) self.assertRaises(TypeError, count, 'a') - c = count(sys.maxint-2) # verify that rollover doesn't crash - c.next(); c.next(); c.next(); c.next(); c.next() + self.assertRaises(OverflowError, list, islice(count(sys.maxint-5), 10)) c = count(3) self.assertEqual(repr(c), 'count(3)') c.next() @@ -203,6 +202,51 @@ ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + def test_iziplongest(self): + for args in [ + ['abc', range(6)], + [range(6), 'abc'], + [range(1000), range(2000,2100), range(3000,3050)], + [range(1000), range(0), range(3000,3050), range(1200), range(1500)], + [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)], + ]: + target = map(None, *args) + self.assertEqual(list(izip_longest(*args)), target) + self.assertEqual(list(izip_longest(*args, **{})), target) + target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X' + self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target) + + self.assertEqual(take(3,izip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input + + self.assertEqual(list(izip_longest()), list(zip())) + self.assertEqual(list(izip_longest([])), list(zip([]))) + self.assertEqual(list(izip_longest('abcdef')), list(zip('abcdef'))) + + self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict + self.assertRaises(TypeError, izip_longest, 3) + self.assertRaises(TypeError, izip_longest, range(3), 3) + + for stmt in [ + "izip_longest('abc', fv=1)", + "izip_longest('abc', fillvalue=1, bogus_keyword=None)", + ]: + try: + eval(stmt, globals(), locals()) + except TypeError: + pass + else: + self.fail('Did not raise Type in: ' + stmt) + + # Check tuple re-use (implementation detail) + self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')], + list(zip('abc', 'def'))) + self.assertEqual([pair for pair in izip_longest('abc', 'def')], + list(zip('abc', 'def'))) + ids = map(id, izip_longest('abc', 'def')) + self.assertEqual(min(ids), max(ids)) + ids = map(id, list(izip_longest('abc', 'def'))) + self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + def test_repeat(self): self.assertEqual(lzip(xrange(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) @@ -616,6 +660,15 @@ self.assertRaises(TypeError, izip, N(s)) self.assertRaises(ZeroDivisionError, list, izip(E(s))) + def test_iziplongest(self): + for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): + for g in (G, I, Ig, S, L, R): + self.assertEqual(list(izip_longest(g(s))), list(zip(g(s)))) + self.assertEqual(list(izip_longest(g(s), g(s))), list(zip(g(s), g(s)))) + self.assertRaises(TypeError, izip_longest, X(s)) + self.assertRaises(TypeError, izip_longest, N(s)) + self.assertRaises(ZeroDivisionError, list, izip_longest(E(s))) + def test_imap(self): for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)): for g in (G, I, Ig, S, L, R): 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 Fri Feb 23 16:07:44 2007 @@ -210,6 +210,8 @@ self.failUnless(operator.isSequenceType(xrange(10))) self.failUnless(operator.isSequenceType('yeahbuddy')) self.failIf(operator.isSequenceType(3)) + class Dict(dict): pass + self.failIf(operator.isSequenceType(Dict())) def test_lshift(self): self.failUnlessRaises(TypeError, operator.lshift) Modified: python/branches/p3yk/Lib/test/test_posix.py ============================================================================== --- python/branches/p3yk/Lib/test/test_posix.py (original) +++ python/branches/p3yk/Lib/test/test_posix.py Fri Feb 23 16:07:44 2007 @@ -192,6 +192,18 @@ posix.utime(test_support.TESTFN, (int(now), int(now))) posix.utime(test_support.TESTFN, (now, now)) + def test_chflags(self): + if hasattr(posix, 'chflags'): + st = os.stat(test_support.TESTFN) + if hasattr(st, 'st_flags'): + posix.chflags(test_support.TESTFN, st.st_flags) + + def test_lchflags(self): + if hasattr(posix, 'lchflags'): + st = os.stat(test_support.TESTFN) + if hasattr(st, 'st_flags'): + posix.lchflags(test_support.TESTFN, st.st_flags) + def test_main(): test_support.run_unittest(PosixTester) 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 Fri Feb 23 16:07:44 2007 @@ -216,7 +216,44 @@ ('' % ns_uri) -# ===== XMLFilterBase +def test_1463026_1(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS((None, 'a'), 'a') + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_2(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping(None, 'qux') + gen.startElementNS(('qux', 'a'), 'a', {}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping(None) + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_3(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping('my', 'qux') + gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping('my') + gen.endDocument() + + return result.getvalue() == start+'' + +# ===== Xmlfilterbase def test_filter_basic(): result = StringIO() 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 Fri Feb 23 16:07:44 2007 @@ -26,6 +26,14 @@ def __repr__(self): return repr(self.value) +class HashCountingInt(int): + 'int-like object that counts the number of times __hash__ is called' + def __init__(self, *args): + self.hash_count = 0 + def __hash__(self): + self.hash_count += 1 + return int.__hash__(self) + class TestJointOps(unittest.TestCase): # Tests common to both set and frozenset @@ -273,6 +281,18 @@ fo.close() os.remove(test_support.TESTFN) + def test_do_not_rehash_dict_keys(self): + n = 10 + d = dict.fromkeys(map(HashCountingInt, xrange(n))) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s = self.thetype(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s.difference(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + if hasattr(s, 'symmetric_difference_update'): + s.symmetric_difference_update(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + class TestSet(TestJointOps): thetype = set 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 Fri Feb 23 16:07:44 2007 @@ -305,6 +305,61 @@ self.assertEqual(self.dst.getnames(), [], "added the archive to itself") +class AppendTest(unittest.TestCase): + # Test append mode (cp. patch #1652681). + + def setUp(self): + self.tarname = tmpname() + if os.path.exists(self.tarname): + os.remove(self.tarname) + + def _add_testfile(self, fileobj=None): + tar = tarfile.open(self.tarname, "a", fileobj=fileobj) + tar.addfile(tarfile.TarInfo("bar")) + tar.close() + + def _create_testtar(self): + src = tarfile.open(tarname()) + t = src.getmember("0-REGTYPE") + t.name = "foo" + f = src.extractfile(t) + tar = tarfile.open(self.tarname, "w") + tar.addfile(t, f) + tar.close() + + def _test(self, names=["bar"], fileobj=None): + tar = tarfile.open(self.tarname, fileobj=fileobj) + self.assert_(tar.getnames() == names) + + def test_non_existing(self): + self._add_testfile() + self._test() + + def test_empty(self): + open(self.tarname, "wb").close() + self._add_testfile() + self._test() + + def test_empty_fileobj(self): + fobj = StringIO.StringIO() + self._add_testfile(fobj) + fobj.seek(0) + self._test(fileobj=fobj) + + def test_fileobj(self): + self._create_testtar() + data = open(self.tarname, "rb").read() + fobj = StringIO.StringIO(data) + self._add_testfile(fobj) + fobj.seek(0) + self._test(names=["foo", "bar"], fileobj=fobj) + + def test_existing(self): + self._create_testtar() + self._add_testfile() + self._test(names=["foo", "bar"]) + + class Write100Test(BaseTest): # The name field in a tar header stores strings of at most 100 chars. # If a string is shorter than 100 chars it has to be padded with '\0', @@ -711,6 +766,7 @@ ReadAsteriskTest, ReadStreamAsteriskTest, WriteTest, + AppendTest, Write100Test, WriteSize0Test, WriteStreamTest, Modified: python/branches/p3yk/Lib/test/test_zipfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_zipfile.py (original) +++ python/branches/p3yk/Lib/test/test_zipfile.py Fri Feb 23 16:07:44 2007 @@ -307,6 +307,28 @@ class OtherTests(unittest.TestCase): + def testCreateNonExistentFileForAppend(self): + if os.path.exists(TESTFN): + os.unlink(TESTFN) + + filename = 'testfile.txt' + content = 'hello, world. this is some content.' + + try: + zf = zipfile.ZipFile(TESTFN, 'a') + zf.writestr(filename, content) + zf.close() + except IOError: + self.fail('Could not append data to a non-existent zip file.') + + self.assert_(os.path.exists(TESTFN)) + + zf = zipfile.ZipFile(TESTFN, 'r') + self.assertEqual(zf.read(filename), content) + zf.close() + + os.unlink(TESTFN) + def testCloseErroneousFile(self): # This test checks that the ZipFile constructor closes the file object # it opens if there's an error in the file. If it doesn't, the traceback @@ -349,8 +371,49 @@ # and report that the first file in the archive was corrupt. self.assertRaises(RuntimeError, zipf.testzip) + +class DecryptionTests(unittest.TestCase): + # This test checks that ZIP decryption works. Since the library does not + # support encryption at the moment, we use a pre-generated encrypted + # ZIP file + + data = ( + 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00' + '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y' + '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl' + 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00' + '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81' + '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00' + '\x00\x00L\x00\x00\x00\x00\x00' ) + + plain = 'zipfile.py encryption test' + + def setUp(self): + fp = open(TESTFN, "wb") + fp.write(self.data) + fp.close() + self.zip = zipfile.ZipFile(TESTFN, "r") + + def tearDown(self): + self.zip.close() + os.unlink(TESTFN) + + def testNoPassword(self): + # Reading the encrypted file without password + # must generate a RunTime exception + self.assertRaises(RuntimeError, self.zip.read, "test.txt") + + def testBadPassword(self): + self.zip.setpassword("perl") + self.assertRaises(RuntimeError, self.zip.read, "test.txt") + + def testGoodPassword(self): + self.zip.setpassword("python") + self.assertEquals(self.zip.read("test.txt"), self.plain) + def test_main(): - run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, PyZipFileTests) + run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, + PyZipFileTests, DecryptionTests) #run_unittest(TestZip64InSmallFiles) if __name__ == "__main__": Modified: python/branches/p3yk/Lib/trace.py ============================================================================== --- python/branches/p3yk/Lib/trace.py (original) +++ python/branches/p3yk/Lib/trace.py Fri Feb 23 16:07:44 2007 @@ -587,7 +587,7 @@ """ if why == 'call': code = frame.f_code - filename = code.co_filename + filename = frame.f_globals.get('__file__', None) if filename: # XXX modname() doesn't work right for packages, so # the ignore support won't work right for packages Modified: python/branches/p3yk/Lib/xml/sax/saxutils.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/saxutils.py (original) +++ python/branches/p3yk/Lib/xml/sax/saxutils.py Fri Feb 23 16:07:44 2007 @@ -100,6 +100,17 @@ else: self._out.write(text.encode(self._encoding, _error_handling)) + def _qname(self, name): + """Builds a qualified name from a (ns_url, localname) pair""" + if name[0]: + # The name is in a non-empty namespace + prefix = self._current_context[name[0]] + if prefix: + # If it is not the default namespace, prepend the prefix + return prefix + ":" + name[1] + # Return the unqualified name + return name[1] + # ContentHandler methods def startDocument(self): @@ -125,29 +136,21 @@ self._write('' % name) def startElementNS(self, name, qname, attrs): - if name[0] is None: - # if the name was not namespace-scoped, use the unqualified part - name = name[1] - else: - # else try to restore the original prefix from the namespace - name = self._current_context[name[0]] + ":" + name[1] - self._write('<' + name) + self._write('<' + self._qname(name)) - for pair in self._undeclared_ns_maps: - self._write(' xmlns:%s="%s"' % pair) + for prefix, uri in self._undeclared_ns_maps: + if prefix: + self._out.write(' xmlns:%s="%s"' % (prefix, uri)) + else: + self._out.write(' xmlns="%s"' % uri) self._undeclared_ns_maps = [] for (name, value) in attrs.items(): - name = self._current_context[name[0]] + ":" + name[1] - self._write(' %s=%s' % (name, quoteattr(value))) + self._write(' %s=%s' % (self._qname(name), quoteattr(value))) self._write('>') def endElementNS(self, name, qname): - if name[0] is None: - name = name[1] - else: - name = self._current_context[name[0]] + ":" + name[1] - self._write('' % name) + self._write('' % self._qname(name)) def characters(self, content): self._write(escape(content)) Modified: python/branches/p3yk/Lib/zipfile.py ============================================================================== --- python/branches/p3yk/Lib/zipfile.py (original) +++ python/branches/p3yk/Lib/zipfile.py Fri Feb 23 16:07:44 2007 @@ -296,6 +296,65 @@ extra = extra[ln+4:] +class _ZipDecrypter: + """Class to handle decryption of files stored within a ZIP archive. + + ZIP supports a password-based form of encryption. Even though known + plaintext attacks have been found against it, it is still useful + for low-level securicy. + + Usage: + zd = _ZipDecrypter(mypwd) + plain_char = zd(cypher_char) + plain_text = map(zd, cypher_text) + """ + + def _GenerateCRCTable(): + """Generate a CRC-32 table. + + ZIP encryption uses the CRC32 one-byte primitive for scrambling some + internal keys. We noticed that a direct implementation is faster than + relying on binascii.crc32(). + """ + poly = 0xedb88320 + table = [0] * 256 + for i in range(256): + crc = i + for j in range(8): + if crc & 1: + crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly + else: + crc = ((crc >> 1) & 0x7FFFFFFF) + table[i] = crc + return table + crctable = _GenerateCRCTable() + + def _crc32(self, ch, crc): + """Compute the CRC32 primitive on one byte.""" + return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] + + def __init__(self, pwd): + self.key0 = 305419896 + self.key1 = 591751049 + self.key2 = 878082192 + for p in pwd: + self._UpdateKeys(p) + + def _UpdateKeys(self, c): + self.key0 = self._crc32(c, self.key0) + self.key1 = (self.key1 + (self.key0 & 255)) & 4294967295 + self.key1 = (self.key1 * 134775813 + 1) & 4294967295 + self.key2 = self._crc32(chr((self.key1 >> 24) & 255), self.key2) + + def __call__(self, c): + """Decrypt a single character.""" + c = ord(c) + k = self.key2 | 2 + c = c ^ (((k * (k^1)) >> 8) & 255) + c = chr(c) + self._UpdateKeys(c) + return c + class ZipFile: """ Class with methods to open, read, write, close, list zip files. @@ -330,13 +389,21 @@ self.filelist = [] # List of ZipInfo instances for archive self.compression = compression # Method of compression self.mode = key = mode.replace('b', '')[0] + self.pwd = None # Check if we were passed a file-like object if isinstance(file, basestring): self._filePassed = 0 self.filename = file modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'} - self.fp = open(file, modeDict[mode]) + try: + self.fp = open(file, modeDict[mode]) + except IOError: + if mode == 'a': + mode = key = 'w' + self.fp = open(file, modeDict[mode]) + else: + raise else: self._filePassed = 1 self.fp = file @@ -461,7 +528,11 @@ """Return the instance of ZipInfo given 'name'.""" return self.NameToInfo[name] - def read(self, name): + def setpassword(self, pwd): + """Set default password for encrypted files.""" + self.pwd = pwd + + def read(self, name, pwd=None): """Return file bytes (as a string) for name.""" if self.mode not in ("r", "a"): raise RuntimeError, 'read() requires mode "r" or "a"' @@ -469,6 +540,13 @@ raise RuntimeError, \ "Attempt to read ZIP archive that was already closed" zinfo = self.getinfo(name) + is_encrypted = zinfo.flag_bits & 0x1 + if is_encrypted: + if not pwd: + pwd = self.pwd + if not pwd: + raise RuntimeError, "File %s is encrypted, " \ + "password required for extraction" % name filepos = self.fp.tell() self.fp.seek(zinfo.header_offset, 0) @@ -489,6 +567,18 @@ zinfo.orig_filename, fname) bytes = self.fp.read(zinfo.compress_size) + # Go with decryption + if is_encrypted: + zd = _ZipDecrypter(pwd) + # The first 12 bytes in the cypher stream is an encryption header + # used to strengthen the algorithm. The first 11 bytes are + # completely random, while the 12th contains the MSB of the CRC, + # and is used to check the correctness of the password. + h = map(zd, bytes[0:12]) + if ord(h[11]) != ((zinfo.CRC>>24)&255): + raise RuntimeError, "Bad password for file %s" % name + bytes = "".join(map(zd, bytes[12:])) + # Go with decompression self.fp.seek(filepos, 0) if zinfo.compress_type == ZIP_STORED: pass Modified: python/branches/p3yk/Misc/ACKS ============================================================================== --- python/branches/p3yk/Misc/ACKS (original) +++ python/branches/p3yk/Misc/ACKS Fri Feb 23 16:07:44 2007 @@ -377,6 +377,7 @@ Kip Lehman Joerg Lehmann Marc-Andre Lemburg +Mark Levinson William Lewis Robert van Liere Martin Ligr Modified: python/branches/p3yk/Modules/collectionsmodule.c ============================================================================== --- python/branches/p3yk/Modules/collectionsmodule.c (original) +++ python/branches/p3yk/Modules/collectionsmodule.c Fri Feb 23 16:07:44 2007 @@ -1259,8 +1259,14 @@ newargs = PyTuple_New(0); else { Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n > 0) + if (n > 0) { newdefault = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(newdefault)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return -1; + } + } newargs = PySequence_GetSlice(args, 1, n); } if (newargs == NULL) Modified: python/branches/p3yk/Modules/datetimemodule.c ============================================================================== --- python/branches/p3yk/Modules/datetimemodule.c (original) +++ python/branches/p3yk/Modules/datetimemodule.c Fri Feb 23 16:07:44 2007 @@ -3138,7 +3138,7 @@ } static PyObject * -time_isoformat(PyDateTime_Time *self) +time_isoformat(PyDateTime_Time *self, PyObject *unused) { char buf[100]; PyObject *result; @@ -3374,7 +3374,7 @@ static PyMethodDef time_methods[] = { - {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, + {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" "[+HH:MM].")}, Modified: python/branches/p3yk/Modules/itertoolsmodule.c ============================================================================== --- python/branches/p3yk/Modules/itertoolsmodule.c (original) +++ python/branches/p3yk/Modules/itertoolsmodule.c Fri Feb 23 16:07:44 2007 @@ -2073,6 +2073,11 @@ static PyObject * count_next(countobject *lz) { + if (lz->cnt == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot count beyond LONG_MAX"); + return NULL; + } return PyInt_FromSsize_t(lz->cnt++); } @@ -2467,6 +2472,234 @@ PyObject_GC_Del, /* tp_free */ }; +/* iziplongest object ************************************************************/ + +#include "Python.h" + +typedef struct { + PyObject_HEAD + Py_ssize_t tuplesize; + Py_ssize_t numactive; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue; +} iziplongestobject; + +static PyTypeObject iziplongest_type; + +static PyObject * +izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + iziplongestobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue = Py_None; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { + fillvalue = PyDict_GetItemString(kwds, "fillvalue"); + if (fillvalue == NULL || PyDict_Size(kwds) > 1) { + PyErr_SetString(PyExc_TypeError, + "izip_longest() got an unexpected keyword argument"); + return NULL; + } + } + + /* args must be a tuple */ + assert(PyTuple_Check(args)); + + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "izip_longest argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } + + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create iziplongestobject structure */ + lz = (iziplongestobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->numactive = tuplesize; + lz->result = result; + Py_INCREF(fillvalue); + lz->fillvalue = fillvalue; + return (PyObject *)lz; +} + +static void +izip_longest_dealloc(iziplongestobject *lz) +{ + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_XDECREF(lz->fillvalue); + lz->ob_type->tp_free(lz); +} + +static int +izip_longest_traverse(iziplongestobject *lz, visitproc visit, void *arg) +{ + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + Py_VISIT(lz->fillvalue); + return 0; +} + +static PyObject * +izip_longest_next(iziplongestobject *lz) +{ + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (lz->numactive == 0) + return NULL; + if (result->ob_refcnt == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } + PyTuple_SET_ITEM(result, i, item); + } + } + return result; +} + +PyDoc_STRVAR(izip_longest_doc, +"izip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> izip_longest object\n\ +\n\ +Return an izip_longest object whose .next() method returns a tuple where\n\ +the i-th element comes from the i-th iterable argument. The .next()\n\ +method continues until the longest iterable in the argument sequence\n\ +is exhausted and then it raises StopIteration. When the shorter iterables\n\ +are exhausted, the fillvalue is substituted in their place. The fillvalue\n\ +defaults to None or can be specified by a keyword argument.\n\ +"); + +static PyTypeObject iziplongest_type = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + "itertools.izip_longest", /* tp_name */ + sizeof(iziplongestobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)izip_longest_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + izip_longest_doc, /* tp_doc */ + (traverseproc)izip_longest_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)izip_longest_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + izip_longest_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ +}; /* module level code ********************************************************/ @@ -2480,6 +2713,7 @@ \n\ Iterators terminating on the shortest input sequence:\n\ izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ +izip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ ifilter(pred, seq) --> elements of seq where pred(elem) is True\n\ ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\ islice(seq, [start,] stop [, step]) --> elements from\n\ @@ -2517,6 +2751,7 @@ &ifilterfalse_type, &count_type, &izip_type, + &iziplongest_type, &repeat_type, &groupby_type, NULL Modified: python/branches/p3yk/Modules/posixmodule.c ============================================================================== --- python/branches/p3yk/Modules/posixmodule.c (original) +++ python/branches/p3yk/Modules/posixmodule.c Fri Feb 23 16:07:44 2007 @@ -1692,6 +1692,57 @@ } +#ifdef HAVE_CHFLAGS +PyDoc_STRVAR(posix_chflags__doc__, +"chflags(path, flags)\n\n\ +Set file flags."); + +static PyObject * +posix_chflags(PyObject *self, PyObject *args) +{ + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:chflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +} +#endif /* HAVE_CHFLAGS */ + +#ifdef HAVE_LCHFLAGS +PyDoc_STRVAR(posix_lchflags__doc__, +"lchflags(path, flags)\n\n\ +Set file flags.\n\ +This function will not follow symbolic links."); + +static PyObject * +posix_lchflags(PyObject *self, PyObject *args) +{ + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:lchflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +} +#endif /* HAVE_LCHFLAGS */ + #ifdef HAVE_CHROOT PyDoc_STRVAR(posix_chroot__doc__, "chroot(path)\n\n\ @@ -8070,10 +8121,16 @@ {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, #endif {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, +#ifdef HAVE_CHFLAGS + {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, +#endif /* HAVE_CHFLAGS */ {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, #ifdef HAVE_CHOWN {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, #endif /* HAVE_CHOWN */ +#ifdef HAVE_LCHFLAGS + {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, +#endif /* HAVE_LCHFLAGS */ #ifdef HAVE_LCHOWN {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, #endif /* HAVE_LCHOWN */ Modified: python/branches/p3yk/Modules/socketmodule.c ============================================================================== --- python/branches/p3yk/Modules/socketmodule.c (original) +++ python/branches/p3yk/Modules/socketmodule.c Fri Feb 23 16:07:44 2007 @@ -362,20 +362,25 @@ #if defined(__FreeBSD__) #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM +#define BTPROTO_HCI BLUETOOTH_PROTO_HCI #define sockaddr_l2 sockaddr_l2cap #define sockaddr_rc sockaddr_rfcomm #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb) #elif defined(__NetBSD__) #define sockaddr_l2 sockaddr_bt #define sockaddr_rc sockaddr_bt +#define sockaddr_hci sockaddr_bt #define sockaddr_sco sockaddr_bt #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb) #else #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb) #endif #endif @@ -1119,6 +1124,14 @@ return ret; } + case BTPROTO_HCI: + { + struct sockaddr_hci *a = (struct sockaddr_hci *) addr; + PyObject *ret = NULL; + ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); + return ret; + } + #if !defined(__FreeBSD__) case BTPROTO_SCO: { @@ -1347,6 +1360,18 @@ *len_ret = sizeof *addr; return 1; } + case BTPROTO_HCI: + { + struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; + _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + *len_ret = sizeof *addr; + return 1; + } #if !defined(__FreeBSD__) case BTPROTO_SCO: { @@ -1485,6 +1510,9 @@ case BTPROTO_RFCOMM: *len_ret = sizeof (struct sockaddr_rc); return 1; + case BTPROTO_HCI: + *len_ret = sizeof (struct sockaddr_hci); + return 1; #if !defined(__FreeBSD__) case BTPROTO_SCO: *len_ret = sizeof (struct sockaddr_sco); @@ -4363,7 +4391,9 @@ PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); #endif PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); +#ifdef NETLINK_DNRTMSG PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); +#endif #ifdef NETLINK_TAPBASE PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); #endif @@ -4408,6 +4438,11 @@ #ifdef USE_BLUETOOTH PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); + PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); + PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); + PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); + PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); + PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); #if !defined(__FreeBSD__) PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); #endif Modified: python/branches/p3yk/Modules/socketmodule.h ============================================================================== --- python/branches/p3yk/Modules/socketmodule.h (original) +++ python/branches/p3yk/Modules/socketmodule.h Fri Feb 23 16:07:44 2007 @@ -46,6 +46,7 @@ #include #include #include +#include #endif #ifdef HAVE_BLUETOOTH_H @@ -98,6 +99,7 @@ struct sockaddr_l2 bt_l2; struct sockaddr_rc bt_rc; struct sockaddr_sco bt_sco; + struct sockaddr_hci bt_hci; #endif #ifdef HAVE_NETPACKET_PACKET_H struct sockaddr_ll ll; Modified: python/branches/p3yk/Objects/abstract.c ============================================================================== --- python/branches/p3yk/Objects/abstract.c (original) +++ python/branches/p3yk/Objects/abstract.c Fri Feb 23 16:07:44 2007 @@ -980,6 +980,8 @@ int PySequence_Check(PyObject *s) { + if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type)) + return 0; return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } Modified: python/branches/p3yk/Objects/dictnotes.txt ============================================================================== --- python/branches/p3yk/Objects/dictnotes.txt (original) +++ python/branches/p3yk/Objects/dictnotes.txt Fri Feb 23 16:07:44 2007 @@ -98,6 +98,17 @@ depending on the size of the dictionary. Setting to *4 eliminates every other resize step. +* Maximum sparseness (minimum dictionary load). What percentage + of entries can be unused before the dictionary shrinks to + free up memory and speed up iteration? (The current CPython + code does not represent this parameter directly.) + +* Shrinkage rate upon exceeding maximum sparseness. The current + CPython code never even checks sparseness when deleting a + key. When a new key is added, it resizes based on the number + of active keys, so that the addition may trigger shrinkage + rather than growth. + Tune-ups should be measured across a broad range of applications and use cases. A change to any parameter will help in some situations and hurt in others. The key is to find settings that help the most common @@ -115,6 +126,15 @@ Also, every dictionary iterates at least twice, once for the memset() when it is created and once by dealloc(). +Dictionary operations involving only a single key can be O(1) unless +resizing is possible. By checking for a resize only when the +dictionary can grow (and may *require* resizing), other operations +remain O(1), and the odds of resize thrashing or memory fragmentation +are reduced. In particular, an algorithm that empties a dictionary +by repeatedly invoking .pop will see no resizing, which might +not be necessary at all because the dictionary is eventually +discarded entirely. + Results of Cache Locality Experiments ------------------------------------- Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Fri Feb 23 16:07:44 2007 @@ -833,6 +833,34 @@ return 1; } +/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/ +int +_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash) +{ + register Py_ssize_t i; + register Py_ssize_t mask; + register dictentry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((dictobject *)op)->ma_table; + mask = ((dictobject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + *phash = (long)(ep[i].me_hash); + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; +} + /* Methods */ static void @@ -1336,7 +1364,7 @@ return -1; } mp = (dictobject*)a; - if (PyDict_Check(b)) { + if (PyDict_CheckExact(b)) { other = (dictobject*)b; if (other == mp || other->ma_used == 0) /* a.update(a) or a.update({}); nothing to do */ @@ -1909,6 +1937,17 @@ return ep == NULL ? -1 : (ep->me_value != NULL); } +/* Internal version of PyDict_Contains used when the hash value is already known */ +int +_PyDict_Contains(PyObject *op, PyObject *key, long hash) +{ + dictobject *mp = (dictobject *)op; + dictentry *ep; + + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); +} + /* Hack to implement "key in dict" */ static PySequenceMethods dict_as_sequence = { 0, /* sq_length */ Modified: python/branches/p3yk/Objects/enumobject.c ============================================================================== --- python/branches/p3yk/Objects/enumobject.c (original) +++ python/branches/p3yk/Objects/enumobject.c Fri Feb 23 16:07:44 2007 @@ -62,6 +62,12 @@ PyObject *result = en->en_result; PyObject *it = en->en_sit; + if (en->en_index == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "enumerate() is limited to LONG_MAX items"); + return NULL; + } + next_item = (*it->ob_type->tp_iternext)(it); if (next_item == NULL) return NULL; Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Fri Feb 23 16:07:44 2007 @@ -932,14 +932,31 @@ { PyObject *key, *it; - if (PyAnySet_Check(other)) + if (PyAnySet_CheckExact(other)) return set_merge(so, other); if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; - while (PyDict_Next(other, &pos, &key, &value)) { - if (set_add_key(so, key) == -1) + long hash; + Py_ssize_t dictsize = PyDict_Size(other); + + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if (dictsize == -1) + return -1; + if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + dictsize)*2) != 0) + return -1; + } + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { + setentry an_entry; + + an_entry.hash = hash; + an_entry.key = key; + if (set_add_entry(so, &an_entry) == -1) return -1; } return 0; @@ -1210,7 +1227,7 @@ if (result == NULL) return NULL; - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_ssize_t pos = 0; setentry *entry; @@ -1334,7 +1351,7 @@ if ((PyObject *)so == other) return set_clear_internal(so); - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { setentry *entry; Py_ssize_t pos = 0; @@ -1383,7 +1400,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { + if (!PyAnySet_CheckExact(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1402,7 +1419,7 @@ setentry entrycopy; entrycopy.hash = entry->hash; entrycopy.key = entry->key; - if (!PyDict_Contains(other, entry->key)) { + if (!_PyDict_Contains(other, entry->key, entry->hash)) { if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { Py_DECREF(result); return NULL; @@ -1473,12 +1490,10 @@ if (PyDict_CheckExact(other)) { PyObject *value; int rv; - while (PyDict_Next(other, &pos, &key, &value)) { + long hash; + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { setentry an_entry; - long hash = PyObject_Hash(key); - if (hash == -1) - return NULL; an_entry.hash = hash; an_entry.key = key; rv = set_discard_entry(so, &an_entry); @@ -1492,7 +1507,7 @@ Py_RETURN_NONE; } - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_INCREF(other); otherset = (PySetObject *)other; } else { @@ -1575,7 +1590,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { PyObject *tmp, *result; tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) @@ -1604,7 +1619,7 @@ { PyObject *tmp, *result; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) return NULL; Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Fri Feb 23 16:07:44 2007 @@ -4279,7 +4279,13 @@ SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O") SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O") SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O") -SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O") +/* Can't use SLOT1 here, because nb_inplace_power is ternary */ +static PyObject * +slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) +{ + static PyObject *cache_str; + return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); +} SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O") SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O") SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O") Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Fri Feb 23 16:07:44 2007 @@ -68,7 +68,7 @@ | Subscript(expr value, slice slice, expr_context ctx) | Name(identifier id, expr_context ctx) | List(expr* elts, expr_context ctx) - | Tuple(expr *elts, expr_context ctx) + | Tuple(expr* elts, expr_context ctx) -- col_offset is the byte offset in the utf8 string the parser uses attributes (int lineno, int col_offset) Modified: python/branches/p3yk/Parser/asdl_c.py ============================================================================== --- python/branches/p3yk/Parser/asdl_c.py (original) +++ python/branches/p3yk/Parser/asdl_c.py Fri Feb 23 16:07:44 2007 @@ -525,6 +525,9 @@ (cons.name, cons.name), 1) self.emit("if (!%s_singleton) return 0;" % cons.name, 1) +def parse_version(mod): + return mod.version.value[12:-3] + class ASTModuleVisitor(PickleVisitor): def visitModule(self, mod): @@ -540,7 +543,8 @@ self.emit('if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)', 1) self.emit("return;", 2) # Value of version: "$Revision$" - self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)' % mod.version.value[12:-3], 1) + self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)' + % parse_version(mod), 1) self.emit("return;", 2) for dfn in mod.dfns: self.visit(dfn) @@ -721,11 +725,23 @@ v.visit(object) v.emit("", 0) +common_msg = "/* File automatically generated by %s. */\n" + +c_file_msg = """ +/* + __version__ %s. + + This module must be committed separately after each AST grammar change; + The __version__ number is set to the revision number of the commit + containing the grammar change. +*/ +""" + def main(srcfile): argv0 = sys.argv[0] components = argv0.split(os.sep) argv0 = os.sep.join(components[-2:]) - auto_gen_msg = '/* File automatically generated by %s */\n' % argv0 + auto_gen_msg = common_msg % argv0 mod = asdl.parse(srcfile) if not asdl.check(mod): sys.exit(1) @@ -746,6 +762,7 @@ p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") f = open(p, "wb") print >> f, auto_gen_msg + print >> f, c_file_msg % parse_version(mod) print >> f, '#include "Python.h"' print >> f, '#include "%s-ast.h"' % mod.name print >> f Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Fri Feb 23 16:07:44 2007 @@ -1,4 +1,13 @@ -/* File automatically generated by Parser/asdl_c.py */ +/* File automatically generated by Parser/asdl_c.py. */ + + +/* + __version__ 53731. + + This module must be committed separately after each AST grammar change; + The __version__ number is set to the revision number of the commit + containing the grammar change. +*/ #include "Python.h" #include "Python-ast.h" @@ -3080,7 +3089,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__", "53704") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53731") < 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/configure ============================================================================== --- python/branches/p3yk/configure (original) +++ python/branches/p3yk/configure Fri Feb 23 16:07:44 2007 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 53017 . +# From configure.in Revision: 53610 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -15068,11 +15068,13 @@ -for ac_func in alarm bind_textdomain_codeset chown clock confstr ctermid \ - execv fork fpathconf ftime ftruncate \ + + +for ac_func in alarm bind_textdomain_codeset chflags chown clock confstr \ + ctermid execv fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ - kill killpg lchown lstat mkfifo mknod mktime \ + kill killpg lchflags lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink realpath \ select setegid seteuid setgid \ Modified: python/branches/p3yk/configure.in ============================================================================== --- python/branches/p3yk/configure.in (original) +++ python/branches/p3yk/configure.in Fri Feb 23 16:07:44 2007 @@ -2282,11 +2282,11 @@ AC_MSG_RESULT(MACHDEP_OBJS) # checks for library functions -AC_CHECK_FUNCS(alarm bind_textdomain_codeset chown clock confstr ctermid \ - execv fork fpathconf ftime ftruncate \ +AC_CHECK_FUNCS(alarm bind_textdomain_codeset chflags chown clock confstr \ + ctermid execv fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ - kill killpg lchown lstat mkfifo mknod mktime \ + kill killpg lchflags lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink realpath \ select setegid seteuid setgid \ Modified: python/branches/p3yk/pyconfig.h.in ============================================================================== --- python/branches/p3yk/pyconfig.h.in (original) +++ python/branches/p3yk/pyconfig.h.in Fri Feb 23 16:07:44 2007 @@ -67,6 +67,9 @@ /* Define this if you have the type _Bool. */ #undef HAVE_C99_BOOL +/* Define to 1 if you have the `chflags' function. */ +#undef HAVE_CHFLAGS + /* Define to 1 if you have the `chown' function. */ #undef HAVE_CHOWN @@ -290,6 +293,9 @@ Solaris and Linux, the necessary defines are already defined.) */ #undef HAVE_LARGEFILE_SUPPORT +/* Define to 1 if you have the `lchflags' function. */ +#undef HAVE_LCHFLAGS + /* Define to 1 if you have the `lchown' function. */ #undef HAVE_LCHOWN Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Fri Feb 23 16:07:44 2007 @@ -1318,7 +1318,8 @@ from distutils.dep_util import newer_group config_sources = [os.path.join(ffi_srcdir, fname) - for fname in os.listdir(ffi_srcdir)] + for fname in os.listdir(ffi_srcdir) + if os.path.isfile(os.path.join(ffi_srcdir, fname))] if self.force or newer_group(config_sources, ffi_configfile): from distutils.dir_util import mkpath From buildbot at python.org Fri Feb 23 16:52:00 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 23 Feb 2007 15:52:00 +0000 Subject: [Python-checkins] buildbot warnings in MIPS Debian trunk Message-ID: <20070223155200.61ACE1E401B@bag.python.org> The Buildbot has detected a new failure of MIPS Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/MIPS%2520Debian%2520trunk/builds/633 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: brett.cannon Build had warnings: warnings failed slave lost sincerely, -The Buildbot From python-checkins at python.org Fri Feb 23 18:33:06 2007 From: python-checkins at python.org (thomas.wouters) Date: Fri, 23 Feb 2007 18:33:06 +0100 (CET) Subject: [Python-checkins] r53867 - in python/branches/p3yk-noslice: BROKEN Doc/api/concrete.tex Doc/commontex/license.tex Doc/dist/dist.tex Doc/howto/TODO Doc/howto/curses.tex Doc/howto/doanddont.tex Doc/howto/regex.tex Doc/lib/emailgenerator.tex Doc/lib/libcollections.tex Doc/lib/libdis.tex Doc/lib/libexcs.tex Doc/lib/libfunctools.tex Doc/lib/libheapq.tex Doc/lib/libimageop.tex Doc/lib/libitertools.tex Doc/lib/liblocale.tex Doc/lib/liblogging.tex Doc/lib/libmailbox.tex Doc/lib/libos.tex Doc/lib/librandom.tex Doc/lib/libshutil.tex Doc/lib/libsmtplib.tex Doc/lib/libsocket.tex Doc/lib/libstdtypes.tex Doc/lib/libstruct.tex Doc/lib/libtarfile.tex Doc/lib/libtest.tex Doc/lib/libtime.tex Doc/lib/libzipfile.tex Doc/ref/ref3.tex Doc/ref/ref4.tex Doc/ref/ref6.tex Doc/tut/tut.tex Doc/whatsnew/whatsnew26.tex Grammar/Grammar INTBENCH Include/Python-ast.h Include/abstract.h Include/boolobject.h Include/ceval.h Include/dictobject.h Include/fileobject.h Include/graminit.h Include/intobject.h Include/longobject.h Include/object.h Include/opcode.h Lib/BaseHTTPServer.py Lib/Bastion.py Lib/CGIHTTPServer.py Lib/ConfigParser.py Lib/Cookie.py Lib/DocXMLRPCServer.py Lib/SimpleXMLRPCServer.py Lib/SocketServer.py Lib/StringIO.py Lib/UserDict.py Lib/UserString.py Lib/_LWPCookieJar.py Lib/_strptime.py Lib/_threading_local.py Lib/aifc.py Lib/asynchat.py Lib/asyncore.py Lib/atexit.py Lib/audiodev.py Lib/base64.py Lib/bdb.py Lib/bsddb/dbrecio.py Lib/bsddb/dbtables.py Lib/bsddb/test/test_all.py Lib/bsddb/test/test_associate.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_compat.py Lib/bsddb/test/test_dbshelve.py Lib/bsddb/test/test_dbtables.py Lib/bsddb/test/test_join.py Lib/bsddb/test/test_lock.py Lib/bsddb/test/test_queue.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_thread.py Lib/cProfile.py Lib/calendar.py Lib/cgi.py Lib/code.py Lib/compileall.py Lib/compiler/ast.py Lib/compiler/future.py Lib/compiler/misc.py Lib/compiler/pyassem.py Lib/compiler/pycodegen.py Lib/compiler/symbols.py Lib/compiler/syntax.py Lib/compiler/transformer.py Lib/compiler/visitor.py Lib/cookielib.py Lib/copy.py Lib/csv.py Lib/ctypes/__init__.py Lib/ctypes/test/__init__.py Lib/ctypes/test/test_as_parameter.py Lib/ctypes/test/test_byteswap.py Lib/ctypes/test/test_find.py Lib/ctypes/test/test_functions.py Lib/ctypes/test/test_keeprefs.py Lib/ctypes/test/test_loading.py Lib/ctypes/test/test_numbers.py Lib/ctypes/test/test_objects.py Lib/ctypes/test/test_pointers.py Lib/ctypes/test/test_prototypes.py Lib/ctypes/test/test_strings.py Lib/ctypes/test/test_win32.py Lib/ctypes/util.py Lib/ctypes/wintypes.py Lib/curses/has_key.py Lib/curses/textpad.py Lib/decimal.py Lib/difflib.py Lib/dis.py Lib/distutils/bcppcompiler.py Lib/distutils/ccompiler.py Lib/distutils/cmd.py Lib/distutils/command/bdist_rpm.py Lib/distutils/command/build_ext.py Lib/distutils/command/config.py Lib/distutils/command/install.py Lib/distutils/command/register.py Lib/distutils/command/upload.py Lib/distutils/core.py Lib/distutils/dist.py Lib/distutils/fancy_getopt.py Lib/distutils/filelist.py Lib/distutils/log.py Lib/distutils/mwerkscompiler.py Lib/distutils/spawn.py Lib/distutils/sysconfig.py Lib/distutils/tests/test_dist.py Lib/distutils/text_file.py Lib/distutils/versionpredicate.py Lib/doctest.py Lib/dumbdbm.py Lib/dummy_thread.py Lib/dummy_threading.py Lib/email/charset.py Lib/email/generator.py Lib/email/iterators.py Lib/email/test/test_email.py Lib/email/test/test_email_codecs.py Lib/email/test/test_email_codecs_renamed.py Lib/email/test/test_email_renamed.py Lib/encodings/__init__.py Lib/encodings/aliases.py Lib/encodings/punycode.py Lib/filecmp.py Lib/fileinput.py Lib/formatter.py Lib/fpformat.py Lib/ftplib.py Lib/getopt.py Lib/getpass.py Lib/gettext.py Lib/gopherlib.py Lib/gzip.py Lib/heapq.py Lib/hotshot/log.py Lib/hotshot/stones.py Lib/htmlentitydefs.py Lib/htmllib.py Lib/httplib.py Lib/idlelib/AutoCompleteWindow.py Lib/idlelib/CallTips.py Lib/idlelib/CodeContext.py Lib/idlelib/ColorDelegator.py Lib/idlelib/Delegator.py Lib/idlelib/EditorWindow.py Lib/idlelib/FileList.py Lib/idlelib/GrepDialog.py Lib/idlelib/IOBinding.py Lib/idlelib/MultiCall.py Lib/idlelib/NEWS.txt Lib/idlelib/Percolator.py Lib/idlelib/PyShell.py Lib/idlelib/ScrolledList.py Lib/idlelib/UndoDelegator.py Lib/idlelib/WidgetRedirector.py Lib/idlelib/WindowList.py Lib/idlelib/configHandler.py Lib/idlelib/configHelpSourceEdit.py Lib/idlelib/configSectionNameDialog.py Lib/idlelib/help.txt Lib/idlelib/keybindingDialog.py Lib/idlelib/rpc.py Lib/idlelib/run.py Lib/ihooks.py Lib/imaplib.py Lib/imghdr.py Lib/imputil.py Lib/lib-tk/Dialog.py Lib/lib-tk/FileDialog.py Lib/lib-tk/SimpleDialog.py Lib/lib-tk/Tkinter.py Lib/lib-tk/tkColorChooser.py Lib/lib-tk/tkFileDialog.py Lib/lib-tk/tkFont.py Lib/lib-tk/tkMessageBox.py Lib/lib-tk/tkSimpleDialog.py Lib/locale.py Lib/logging/__init__.py Lib/logging/config.py Lib/logging/handlers.py Lib/macurl2path.py Lib/mailbox.py Lib/mailcap.py Lib/mhlib.py Lib/mimetypes.py Lib/mimify.py Lib/modulefinder.py Lib/msilib/__init__.py Lib/netrc.py Lib/nntplib.py Lib/ntpath.py Lib/opcode.py Lib/optparse.py Lib/pdb.py Lib/pickle.py Lib/pickletools.py Lib/pipes.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-irix5/cddb.py Lib/plat-irix5/cdplayer.py Lib/plat-irix5/flp.py Lib/plat-irix5/panel.py Lib/plat-irix6/FILE.py Lib/plat-irix6/IN.py Lib/plat-irix6/WAIT.py Lib/plat-irix6/cddb.py Lib/plat-irix6/cdplayer.py Lib/plat-irix6/flp.py Lib/plat-irix6/panel.py Lib/plat-linux2/DLFCN.py Lib/plat-linux2/IN.py Lib/plat-linux2/TYPES.py Lib/plat-mac/Audio_mac.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/EasyDialogs.py Lib/plat-mac/FrameWork.py Lib/plat-mac/MiniAEFrame.py Lib/plat-mac/aepack.py Lib/plat-mac/aetools.py Lib/plat-mac/applesingle.py Lib/plat-mac/argvemulator.py Lib/plat-mac/bundlebuilder.py Lib/plat-mac/findertools.py Lib/plat-mac/gensuitemodule.py Lib/plat-mac/ic.py Lib/plat-mac/macfs.py Lib/plat-mac/macresource.py Lib/plat-mac/pimp.py Lib/plat-mac/plistlib.py Lib/plat-mac/videoreader.py Lib/plat-os2emx/IN.py Lib/plat-os2emx/_emx_link.py Lib/plat-riscos/rourl2path.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/popen2.py Lib/poplib.py Lib/pprint.py Lib/profile.py Lib/pstats.py Lib/pty.py Lib/py_compile.py Lib/pyclbr.py Lib/pydoc.py Lib/quopri.py Lib/random.py Lib/repr.py Lib/rexec.py Lib/rfc822.py Lib/robotparser.py Lib/runpy.py Lib/sgmllib.py Lib/shelve.py Lib/shlex.py Lib/shutil.py Lib/site.py Lib/smtpd.py Lib/smtplib.py Lib/sndhdr.py Lib/socket.py Lib/sqlite3/dbapi2.py Lib/sqlite3/test/dbapi.py Lib/sqlite3/test/factory.py Lib/sqlite3/test/regression.py Lib/sqlite3/test/types.py Lib/sre_compile.py Lib/sre_constants.py Lib/sre_parse.py Lib/stat.py Lib/string.py Lib/stringold.py Lib/subprocess.py Lib/sunau.py Lib/sunaudio.py Lib/symbol.py Lib/symtable.py Lib/tabnanny.py Lib/tarfile.py Lib/telnetlib.py Lib/test/badsyntax_future8.py Lib/test/badsyntax_future9.py Lib/test/crashers/bogus_sre_bytecode.py Lib/test/crashers/borrowed_ref_1.py Lib/test/crashers/borrowed_ref_2.py Lib/test/crashers/gc_inspection.py Lib/test/crashers/loosing_mro_ref.py Lib/test/crashers/modify_dict_attr.py Lib/test/crashers/nasty_eq_vs_dict.py Lib/test/crashers/weakref_in_del.py Lib/test/doctest_aliases.py Lib/test/fork_wait.py Lib/test/inspect_fodder2.py Lib/test/list_tests.py Lib/test/mapping_tests.py Lib/test/output/test_cProfile Lib/test/output/test_class Lib/test/output/test_new Lib/test/output/test_popen Lib/test/output/test_profile Lib/test/output/test_resource Lib/test/pickletester.py Lib/test/pydocfodder.py Lib/test/pystone.py Lib/test/regrtest.py Lib/test/reperf.py Lib/test/sample_doctest.py Lib/test/seq_tests.py Lib/test/sortperf.py Lib/test/string_tests.py Lib/test/test___all__.py Lib/test/test_al.py Lib/test/test_anydbm.py Lib/test/test_array.py Lib/test/test_ast.py Lib/test/test_asynchat.py Lib/test/test_atexit.py Lib/test/test_audioop.py Lib/test/test_bigmem.py Lib/test/test_binop.py Lib/test/test_bisect.py Lib/test/test_bool.py Lib/test/test_bsddb.py Lib/test/test_bsddb3.py Lib/test/test_builtin.py Lib/test/test_bytes.py Lib/test/test_capi.py Lib/test/test_cd.py Lib/test/test_cfgparser.py Lib/test/test_cgi.py Lib/test/test_cl.py Lib/test/test_class.py Lib/test/test_cmath.py Lib/test/test_code.py Lib/test/test_codecs.py Lib/test/test_compare.py Lib/test/test_compile.py Lib/test/test_compiler.py Lib/test/test_complex.py Lib/test/test_cookie.py Lib/test/test_cookielib.py Lib/test/test_copy.py Lib/test/test_copy_reg.py Lib/test/test_crypt.py Lib/test/test_csv.py Lib/test/test_curses.py Lib/test/test_datetime.py Lib/test/test_dbm.py Lib/test/test_decimal.py Lib/test/test_defaultdict.py Lib/test/test_deque.py Lib/test/test_descr.py Lib/test/test_descrtut.py Lib/test/test_dict.py Lib/test/test_dictviews.py Lib/test/test_dis.py Lib/test/test_dl.py Lib/test/test_doctest.py Lib/test/test_doctest.txt Lib/test/test_doctest2.py Lib/test/test_dumbdbm.py Lib/test/test_dummy_thread.py Lib/test/test_dummy_threading.py Lib/test/test_enumerate.py Lib/test/test_errno.py Lib/test/test_exceptions.py Lib/test/test_extcall.py Lib/test/test_fcntl.py Lib/test/test_file.py Lib/test/test_fileinput.py Lib/test/test_format.py Lib/test/test_funcattrs.py Lib/test/test_functools.py Lib/test/test_gc.py Lib/test/test_gdbm.py Lib/test/test_generators.py Lib/test/test_genexps.py Lib/test/test_getargs2.py Lib/test/test_getopt.py Lib/test/test_gl.py Lib/test/test_grammar.py Lib/test/test_grp.py Lib/test/test_gzip.py Lib/test/test_hash.py Lib/test/test_heapq.py Lib/test/test_hexoct.py Lib/test/test_imageop.py Lib/test/test_imgfile.py Lib/test/test_import.py Lib/test/test_importhooks.py Lib/test/test_index.py Lib/test/test_inspect.py Lib/test/test_isinstance.py Lib/test/test_iter.py Lib/test/test_iterlen.py Lib/test/test_itertools.py Lib/test/test_largefile.py Lib/test/test_linuxaudiodev.py Lib/test/test_list.py Lib/test/test_locale.py Lib/test/test_long.py Lib/test/test_long_future.py Lib/test/test_mailbox.py Lib/test/test_marshal.py Lib/test/test_mhlib.py Lib/test/test_minidom.py Lib/test/test_module.py Lib/test/test_multibytecodec.py Lib/test/test_multibytecodec_support.py Lib/test/test_mutants.py Lib/test/test_new.py Lib/test/test_normalization.py Lib/test/test_ntpath.py Lib/test/test_old_mailbox.py Lib/test/test_operations.py Lib/test/test_operator.py Lib/test/test_optparse.py Lib/test/test_ossaudiodev.py Lib/test/test_parser.py Lib/test/test_peepholer.py Lib/test/test_pep247.py Lib/test/test_pep277.py Lib/test/test_pep352.py Lib/test/test_pkg.py Lib/test/test_poll.py Lib/test/test_popen.py Lib/test/test_popen2.py Lib/test/test_posix.py Lib/test/test_posixpath.py Lib/test/test_pow.py Lib/test/test_pprint.py Lib/test/test_pty.py Lib/test/test_pwd.py Lib/test/test_pyclbr.py Lib/test/test_pyexpat.py Lib/test/test_queue.py Lib/test/test_random.py Lib/test/test_re.py Lib/test/test_repr.py Lib/test/test_resource.py Lib/test/test_rfc822.py Lib/test/test_rgbimg.py Lib/test/test_richcmp.py Lib/test/test_runpy.py Lib/test/test_sax.py Lib/test/test_scope.py Lib/test/test_select.py Lib/test/test_set.py Lib/test/test_signal.py Lib/test/test_site.py Lib/test/test_slice.py Lib/test/test_socket.py Lib/test/test_socket_ssl.py Lib/test/test_socketserver.py Lib/test/test_softspace.py Lib/test/test_sort.py Lib/test/test_strftime.py Lib/test/test_string.py Lib/test/test_strop.py Lib/test/test_strptime.py Lib/test/test_struct.py Lib/test/test_subprocess.py Lib/test/test_sundry.py Lib/test/test_support.py Lib/test/test_syntax.py Lib/test/test_tarfile.py Lib/test/test_thread.py Lib/test/test_threaded_import.py Lib/test/test_threadedtempfile.py Lib/test/test_threading.py Lib/test/test_time.py Lib/test/test_timeout.py Lib/test/test_tokenize.py Lib/test/test_trace.py Lib/test/test_traceback.py Lib/test/test_types.py Lib/test/test_unary.py Lib/test/test_unicode.py Lib/test/test_urllib2.py Lib/test/test_urllib2net.py Lib/test/test_userdict.py Lib/test/test_uu.py Lib/test/test_uuid.py Lib/test/test_weakref.py Lib/test/test_winreg.py Lib/test/test_with.py Lib/test/test_xdrlib.py Lib/test/test_xml_etree.py Lib/test/test_xml_etree_c.py Lib/test/test_xmlrpc.py Lib/test/test_xrange.py Lib/test/test_zipfile.py Lib/test/test_zipfile64.py Lib/test/test_zipimport.py Lib/test/test_zlib.py Lib/test/time_hashlib.py Lib/textwrap.py Lib/this.py Lib/threading.py Lib/timeit.py Lib/token.py Lib/tokenize.py Lib/trace.py Lib/types.py Lib/unittest.py Lib/urllib.py Lib/urllib2.py Lib/urlparse.py Lib/uu.py Lib/uuid.py Lib/warnings.py Lib/weakref.py Lib/webbrowser.py Lib/whichdb.py Lib/wsgiref/simple_server.py Lib/xdrlib.py Lib/xml/dom/NodeFilter.py Lib/xml/dom/minidom.py Lib/xml/dom/pulldom.py Lib/xml/etree/ElementTree.py Lib/xml/sax/handler.py Lib/xml/sax/saxutils.py Lib/xml/sax/xmlreader.py Lib/xmllib.py Lib/xmlrpclib.py Lib/zipfile.py Makefile.pre.in Misc/ACKS Misc/NEWS Modules/_csv.c Modules/_ctypes/_ctypes.c Modules/_ctypes/_ctypes_test.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/libffi_msvc/ffi.c Modules/_cursesmodule.c Modules/_randommodule.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 Modules/_sre.c Modules/_struct.c Modules/_testcapimodule.c Modules/_tkinter.c Modules/arraymodule.c Modules/bz2module.c Modules/cPickle.c Modules/cStringIO.c Modules/cjkcodecs/multibytecodec.c Modules/collectionsmodule.c Modules/datetimemodule.c Modules/dlmodule.c Modules/itertoolsmodule.c Modules/parsermodule.c Modules/posixmodule.c Modules/socketmodule.c Modules/socketmodule.h Modules/timemodule.c Objects/abstract.c Objects/boolobject.c Objects/complexobject.c Objects/dictnotes.txt Objects/dictobject.c Objects/enumobject.c Objects/exceptions.c Objects/fileobject.c Objects/floatobject.c Objects/frameobject.c Objects/intobject.c Objects/iterobject.c Objects/listobject.c Objects/longobject.c Objects/object.c Objects/setobject.c Objects/stringobject.c Objects/typeobject.c Objects/unicodeobject.c Objects/weakrefobject.c PC/_msi.c PCbuild/_bsddb.vcproj PCbuild/_elementtree.vcproj PCbuild/_msi.vcproj PCbuild/_socket.vcproj PCbuild/_sqlite3.vcproj PCbuild/_ssl.mak PCbuild/_testcapi.vcproj PCbuild/_tkinter.vcproj PCbuild/build_ssl.py PCbuild/bz2.vcproj PCbuild/pyexpat.vcproj PCbuild/python.vcproj PCbuild/pythoncore.vcproj PCbuild/pythonw.vcproj PCbuild/select.vcproj PCbuild/unicodedata.vcproj PCbuild/winsound.vcproj Parser/Python.asdl Parser/asdl_c.py Parser/tokenizer.c Python/Python-ast.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/compile.c Python/frozen.c Python/getargs.c Python/graminit.c Python/import.c Python/marshal.c Python/pythonrun.c Python/symtable.c Python/sysmodule.c Python/traceback.c Tools/compiler/ast.txt Tools/freeze Tools/freeze/bkfile.py Tools/freeze/freeze.py Tools/freeze/hello.py Tools/freeze/makeconfig.py Tools/freeze/makefreeze.py Tools/freeze/parsesetup.py Tools/freeze/winmakemakefile.py Tools/msi/uuids.py Tools/pybench/CommandLine.py Tools/pybench/Dict.py Tools/pybench/Exceptions.py Tools/pybench/Lookups.py Tools/pybench/pybench.py configure configure.in pyconfig.h.in setup.py Message-ID: <20070223173306.D2CB71E4008@bag.python.org> Author: thomas.wouters Date: Fri Feb 23 18:29:35 2007 New Revision: 53867 Added: python/branches/p3yk-noslice/BROKEN python/branches/p3yk-noslice/INTBENCH - copied unchanged from r53866, python/branches/p3yk/INTBENCH python/branches/p3yk-noslice/Lib/test/test_dictviews.py - copied unchanged from r53866, python/branches/p3yk/Lib/test/test_dictviews.py Removed: python/branches/p3yk-noslice/Lib/test/output/test_new python/branches/p3yk-noslice/Lib/test/output/test_popen python/branches/p3yk-noslice/Lib/test/output/test_resource python/branches/p3yk-noslice/Lib/test/test_softspace.py Modified: python/branches/p3yk-noslice/ (props changed) python/branches/p3yk-noslice/Doc/api/concrete.tex python/branches/p3yk-noslice/Doc/commontex/license.tex python/branches/p3yk-noslice/Doc/dist/dist.tex python/branches/p3yk-noslice/Doc/howto/TODO python/branches/p3yk-noslice/Doc/howto/curses.tex python/branches/p3yk-noslice/Doc/howto/doanddont.tex python/branches/p3yk-noslice/Doc/howto/regex.tex python/branches/p3yk-noslice/Doc/lib/emailgenerator.tex python/branches/p3yk-noslice/Doc/lib/libcollections.tex python/branches/p3yk-noslice/Doc/lib/libdis.tex python/branches/p3yk-noslice/Doc/lib/libexcs.tex python/branches/p3yk-noslice/Doc/lib/libfunctools.tex python/branches/p3yk-noslice/Doc/lib/libheapq.tex python/branches/p3yk-noslice/Doc/lib/libimageop.tex python/branches/p3yk-noslice/Doc/lib/libitertools.tex python/branches/p3yk-noslice/Doc/lib/liblocale.tex python/branches/p3yk-noslice/Doc/lib/liblogging.tex python/branches/p3yk-noslice/Doc/lib/libmailbox.tex python/branches/p3yk-noslice/Doc/lib/libos.tex python/branches/p3yk-noslice/Doc/lib/librandom.tex python/branches/p3yk-noslice/Doc/lib/libshutil.tex python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex python/branches/p3yk-noslice/Doc/lib/libsocket.tex python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex python/branches/p3yk-noslice/Doc/lib/libstruct.tex python/branches/p3yk-noslice/Doc/lib/libtarfile.tex python/branches/p3yk-noslice/Doc/lib/libtest.tex python/branches/p3yk-noslice/Doc/lib/libtime.tex python/branches/p3yk-noslice/Doc/lib/libzipfile.tex python/branches/p3yk-noslice/Doc/ref/ref3.tex python/branches/p3yk-noslice/Doc/ref/ref4.tex python/branches/p3yk-noslice/Doc/ref/ref6.tex python/branches/p3yk-noslice/Doc/tut/tut.tex python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex python/branches/p3yk-noslice/Grammar/Grammar python/branches/p3yk-noslice/Include/Python-ast.h python/branches/p3yk-noslice/Include/abstract.h python/branches/p3yk-noslice/Include/boolobject.h python/branches/p3yk-noslice/Include/ceval.h python/branches/p3yk-noslice/Include/dictobject.h python/branches/p3yk-noslice/Include/fileobject.h python/branches/p3yk-noslice/Include/graminit.h python/branches/p3yk-noslice/Include/intobject.h python/branches/p3yk-noslice/Include/longobject.h python/branches/p3yk-noslice/Include/object.h python/branches/p3yk-noslice/Include/opcode.h python/branches/p3yk-noslice/Lib/BaseHTTPServer.py python/branches/p3yk-noslice/Lib/Bastion.py python/branches/p3yk-noslice/Lib/CGIHTTPServer.py python/branches/p3yk-noslice/Lib/ConfigParser.py python/branches/p3yk-noslice/Lib/Cookie.py python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py python/branches/p3yk-noslice/Lib/SocketServer.py python/branches/p3yk-noslice/Lib/StringIO.py python/branches/p3yk-noslice/Lib/UserDict.py python/branches/p3yk-noslice/Lib/UserString.py python/branches/p3yk-noslice/Lib/_LWPCookieJar.py python/branches/p3yk-noslice/Lib/_strptime.py python/branches/p3yk-noslice/Lib/_threading_local.py python/branches/p3yk-noslice/Lib/aifc.py python/branches/p3yk-noslice/Lib/asynchat.py python/branches/p3yk-noslice/Lib/asyncore.py python/branches/p3yk-noslice/Lib/atexit.py python/branches/p3yk-noslice/Lib/audiodev.py python/branches/p3yk-noslice/Lib/base64.py python/branches/p3yk-noslice/Lib/bdb.py python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py python/branches/p3yk-noslice/Lib/bsddb/dbtables.py python/branches/p3yk-noslice/Lib/bsddb/test/test_all.py python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py python/branches/p3yk-noslice/Lib/bsddb/test/test_dbshelve.py python/branches/p3yk-noslice/Lib/bsddb/test/test_dbtables.py python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py python/branches/p3yk-noslice/Lib/bsddb/test/test_queue.py python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py python/branches/p3yk-noslice/Lib/cProfile.py python/branches/p3yk-noslice/Lib/calendar.py python/branches/p3yk-noslice/Lib/cgi.py python/branches/p3yk-noslice/Lib/code.py python/branches/p3yk-noslice/Lib/compileall.py python/branches/p3yk-noslice/Lib/compiler/ast.py python/branches/p3yk-noslice/Lib/compiler/future.py python/branches/p3yk-noslice/Lib/compiler/misc.py python/branches/p3yk-noslice/Lib/compiler/pyassem.py python/branches/p3yk-noslice/Lib/compiler/pycodegen.py python/branches/p3yk-noslice/Lib/compiler/symbols.py python/branches/p3yk-noslice/Lib/compiler/syntax.py python/branches/p3yk-noslice/Lib/compiler/transformer.py python/branches/p3yk-noslice/Lib/compiler/visitor.py python/branches/p3yk-noslice/Lib/cookielib.py python/branches/p3yk-noslice/Lib/copy.py python/branches/p3yk-noslice/Lib/csv.py python/branches/p3yk-noslice/Lib/ctypes/__init__.py python/branches/p3yk-noslice/Lib/ctypes/test/__init__.py python/branches/p3yk-noslice/Lib/ctypes/test/test_as_parameter.py python/branches/p3yk-noslice/Lib/ctypes/test/test_byteswap.py python/branches/p3yk-noslice/Lib/ctypes/test/test_find.py python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py python/branches/p3yk-noslice/Lib/ctypes/test/test_keeprefs.py python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py python/branches/p3yk-noslice/Lib/ctypes/test/test_objects.py python/branches/p3yk-noslice/Lib/ctypes/test/test_pointers.py python/branches/p3yk-noslice/Lib/ctypes/test/test_prototypes.py python/branches/p3yk-noslice/Lib/ctypes/test/test_strings.py python/branches/p3yk-noslice/Lib/ctypes/test/test_win32.py python/branches/p3yk-noslice/Lib/ctypes/util.py python/branches/p3yk-noslice/Lib/ctypes/wintypes.py python/branches/p3yk-noslice/Lib/curses/has_key.py python/branches/p3yk-noslice/Lib/curses/textpad.py python/branches/p3yk-noslice/Lib/decimal.py python/branches/p3yk-noslice/Lib/difflib.py python/branches/p3yk-noslice/Lib/dis.py python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py python/branches/p3yk-noslice/Lib/distutils/ccompiler.py python/branches/p3yk-noslice/Lib/distutils/cmd.py python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py python/branches/p3yk-noslice/Lib/distutils/command/config.py python/branches/p3yk-noslice/Lib/distutils/command/install.py python/branches/p3yk-noslice/Lib/distutils/command/register.py python/branches/p3yk-noslice/Lib/distutils/command/upload.py python/branches/p3yk-noslice/Lib/distutils/core.py python/branches/p3yk-noslice/Lib/distutils/dist.py python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py python/branches/p3yk-noslice/Lib/distutils/filelist.py python/branches/p3yk-noslice/Lib/distutils/log.py python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py python/branches/p3yk-noslice/Lib/distutils/spawn.py python/branches/p3yk-noslice/Lib/distutils/sysconfig.py python/branches/p3yk-noslice/Lib/distutils/tests/test_dist.py python/branches/p3yk-noslice/Lib/distutils/text_file.py python/branches/p3yk-noslice/Lib/distutils/versionpredicate.py python/branches/p3yk-noslice/Lib/doctest.py python/branches/p3yk-noslice/Lib/dumbdbm.py python/branches/p3yk-noslice/Lib/dummy_thread.py python/branches/p3yk-noslice/Lib/dummy_threading.py python/branches/p3yk-noslice/Lib/email/charset.py python/branches/p3yk-noslice/Lib/email/generator.py python/branches/p3yk-noslice/Lib/email/iterators.py python/branches/p3yk-noslice/Lib/email/test/test_email.py python/branches/p3yk-noslice/Lib/email/test/test_email_codecs.py python/branches/p3yk-noslice/Lib/email/test/test_email_codecs_renamed.py python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py python/branches/p3yk-noslice/Lib/encodings/__init__.py python/branches/p3yk-noslice/Lib/encodings/aliases.py python/branches/p3yk-noslice/Lib/encodings/punycode.py python/branches/p3yk-noslice/Lib/filecmp.py python/branches/p3yk-noslice/Lib/fileinput.py python/branches/p3yk-noslice/Lib/formatter.py python/branches/p3yk-noslice/Lib/fpformat.py python/branches/p3yk-noslice/Lib/ftplib.py python/branches/p3yk-noslice/Lib/getopt.py python/branches/p3yk-noslice/Lib/getpass.py python/branches/p3yk-noslice/Lib/gettext.py python/branches/p3yk-noslice/Lib/gopherlib.py python/branches/p3yk-noslice/Lib/gzip.py python/branches/p3yk-noslice/Lib/heapq.py python/branches/p3yk-noslice/Lib/hotshot/log.py python/branches/p3yk-noslice/Lib/hotshot/stones.py python/branches/p3yk-noslice/Lib/htmlentitydefs.py python/branches/p3yk-noslice/Lib/htmllib.py python/branches/p3yk-noslice/Lib/httplib.py python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py python/branches/p3yk-noslice/Lib/idlelib/CallTips.py python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py python/branches/p3yk-noslice/Lib/idlelib/ColorDelegator.py python/branches/p3yk-noslice/Lib/idlelib/Delegator.py python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py python/branches/p3yk-noslice/Lib/idlelib/FileList.py python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt python/branches/p3yk-noslice/Lib/idlelib/Percolator.py python/branches/p3yk-noslice/Lib/idlelib/PyShell.py python/branches/p3yk-noslice/Lib/idlelib/ScrolledList.py python/branches/p3yk-noslice/Lib/idlelib/UndoDelegator.py python/branches/p3yk-noslice/Lib/idlelib/WidgetRedirector.py python/branches/p3yk-noslice/Lib/idlelib/WindowList.py python/branches/p3yk-noslice/Lib/idlelib/configHandler.py python/branches/p3yk-noslice/Lib/idlelib/configHelpSourceEdit.py python/branches/p3yk-noslice/Lib/idlelib/configSectionNameDialog.py python/branches/p3yk-noslice/Lib/idlelib/help.txt python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py python/branches/p3yk-noslice/Lib/idlelib/rpc.py python/branches/p3yk-noslice/Lib/idlelib/run.py python/branches/p3yk-noslice/Lib/ihooks.py python/branches/p3yk-noslice/Lib/imaplib.py python/branches/p3yk-noslice/Lib/imghdr.py python/branches/p3yk-noslice/Lib/imputil.py python/branches/p3yk-noslice/Lib/lib-tk/Dialog.py python/branches/p3yk-noslice/Lib/lib-tk/FileDialog.py python/branches/p3yk-noslice/Lib/lib-tk/SimpleDialog.py python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py python/branches/p3yk-noslice/Lib/lib-tk/tkColorChooser.py python/branches/p3yk-noslice/Lib/lib-tk/tkFileDialog.py python/branches/p3yk-noslice/Lib/lib-tk/tkFont.py python/branches/p3yk-noslice/Lib/lib-tk/tkMessageBox.py python/branches/p3yk-noslice/Lib/lib-tk/tkSimpleDialog.py python/branches/p3yk-noslice/Lib/locale.py python/branches/p3yk-noslice/Lib/logging/__init__.py python/branches/p3yk-noslice/Lib/logging/config.py python/branches/p3yk-noslice/Lib/logging/handlers.py python/branches/p3yk-noslice/Lib/macurl2path.py python/branches/p3yk-noslice/Lib/mailbox.py python/branches/p3yk-noslice/Lib/mailcap.py python/branches/p3yk-noslice/Lib/mhlib.py python/branches/p3yk-noslice/Lib/mimetypes.py python/branches/p3yk-noslice/Lib/mimify.py python/branches/p3yk-noslice/Lib/modulefinder.py python/branches/p3yk-noslice/Lib/msilib/__init__.py python/branches/p3yk-noslice/Lib/netrc.py python/branches/p3yk-noslice/Lib/nntplib.py python/branches/p3yk-noslice/Lib/ntpath.py python/branches/p3yk-noslice/Lib/opcode.py python/branches/p3yk-noslice/Lib/optparse.py python/branches/p3yk-noslice/Lib/pdb.py python/branches/p3yk-noslice/Lib/pickle.py python/branches/p3yk-noslice/Lib/pickletools.py python/branches/p3yk-noslice/Lib/pipes.py python/branches/p3yk-noslice/Lib/plat-aix3/IN.py python/branches/p3yk-noslice/Lib/plat-aix4/IN.py python/branches/p3yk-noslice/Lib/plat-atheos/IN.py python/branches/p3yk-noslice/Lib/plat-atheos/TYPES.py python/branches/p3yk-noslice/Lib/plat-beos5/IN.py python/branches/p3yk-noslice/Lib/plat-freebsd2/IN.py python/branches/p3yk-noslice/Lib/plat-freebsd3/IN.py python/branches/p3yk-noslice/Lib/plat-irix5/IN.py python/branches/p3yk-noslice/Lib/plat-irix5/cddb.py python/branches/p3yk-noslice/Lib/plat-irix5/cdplayer.py python/branches/p3yk-noslice/Lib/plat-irix5/flp.py python/branches/p3yk-noslice/Lib/plat-irix5/panel.py python/branches/p3yk-noslice/Lib/plat-irix6/FILE.py python/branches/p3yk-noslice/Lib/plat-irix6/IN.py python/branches/p3yk-noslice/Lib/plat-irix6/WAIT.py python/branches/p3yk-noslice/Lib/plat-irix6/cddb.py python/branches/p3yk-noslice/Lib/plat-irix6/cdplayer.py python/branches/p3yk-noslice/Lib/plat-irix6/flp.py python/branches/p3yk-noslice/Lib/plat-irix6/panel.py python/branches/p3yk-noslice/Lib/plat-linux2/DLFCN.py python/branches/p3yk-noslice/Lib/plat-linux2/IN.py python/branches/p3yk-noslice/Lib/plat-linux2/TYPES.py python/branches/p3yk-noslice/Lib/plat-mac/Audio_mac.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/CarbonEvents.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Components.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Controls.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Dragconst.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Folders.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Fonts.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Icons.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/MacTextEditor.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/OSAconst.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QDOffscreen.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickDraw.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickTime.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Sound.py python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Windows.py python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py python/branches/p3yk-noslice/Lib/plat-mac/FrameWork.py python/branches/p3yk-noslice/Lib/plat-mac/MiniAEFrame.py python/branches/p3yk-noslice/Lib/plat-mac/aepack.py python/branches/p3yk-noslice/Lib/plat-mac/aetools.py python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py python/branches/p3yk-noslice/Lib/plat-mac/argvemulator.py python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py python/branches/p3yk-noslice/Lib/plat-mac/findertools.py python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py python/branches/p3yk-noslice/Lib/plat-mac/ic.py python/branches/p3yk-noslice/Lib/plat-mac/macfs.py python/branches/p3yk-noslice/Lib/plat-mac/macresource.py python/branches/p3yk-noslice/Lib/plat-mac/pimp.py python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py python/branches/p3yk-noslice/Lib/plat-mac/videoreader.py python/branches/p3yk-noslice/Lib/plat-os2emx/IN.py python/branches/p3yk-noslice/Lib/plat-os2emx/_emx_link.py python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py python/branches/p3yk-noslice/Lib/plat-sunos5/TYPES.py python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py python/branches/p3yk-noslice/Lib/platform.py python/branches/p3yk-noslice/Lib/popen2.py python/branches/p3yk-noslice/Lib/poplib.py python/branches/p3yk-noslice/Lib/pprint.py python/branches/p3yk-noslice/Lib/profile.py python/branches/p3yk-noslice/Lib/pstats.py python/branches/p3yk-noslice/Lib/pty.py python/branches/p3yk-noslice/Lib/py_compile.py python/branches/p3yk-noslice/Lib/pyclbr.py python/branches/p3yk-noslice/Lib/pydoc.py python/branches/p3yk-noslice/Lib/quopri.py python/branches/p3yk-noslice/Lib/random.py python/branches/p3yk-noslice/Lib/repr.py python/branches/p3yk-noslice/Lib/rexec.py python/branches/p3yk-noslice/Lib/rfc822.py python/branches/p3yk-noslice/Lib/robotparser.py python/branches/p3yk-noslice/Lib/runpy.py python/branches/p3yk-noslice/Lib/sgmllib.py python/branches/p3yk-noslice/Lib/shelve.py python/branches/p3yk-noslice/Lib/shlex.py python/branches/p3yk-noslice/Lib/shutil.py python/branches/p3yk-noslice/Lib/site.py python/branches/p3yk-noslice/Lib/smtpd.py python/branches/p3yk-noslice/Lib/smtplib.py python/branches/p3yk-noslice/Lib/sndhdr.py python/branches/p3yk-noslice/Lib/socket.py python/branches/p3yk-noslice/Lib/sqlite3/dbapi2.py python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py python/branches/p3yk-noslice/Lib/sqlite3/test/factory.py python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py python/branches/p3yk-noslice/Lib/sqlite3/test/types.py python/branches/p3yk-noslice/Lib/sre_compile.py python/branches/p3yk-noslice/Lib/sre_constants.py python/branches/p3yk-noslice/Lib/sre_parse.py python/branches/p3yk-noslice/Lib/stat.py python/branches/p3yk-noslice/Lib/string.py python/branches/p3yk-noslice/Lib/stringold.py python/branches/p3yk-noslice/Lib/subprocess.py python/branches/p3yk-noslice/Lib/sunau.py python/branches/p3yk-noslice/Lib/sunaudio.py python/branches/p3yk-noslice/Lib/symbol.py python/branches/p3yk-noslice/Lib/symtable.py python/branches/p3yk-noslice/Lib/tabnanny.py python/branches/p3yk-noslice/Lib/tarfile.py python/branches/p3yk-noslice/Lib/telnetlib.py python/branches/p3yk-noslice/Lib/test/badsyntax_future8.py python/branches/p3yk-noslice/Lib/test/badsyntax_future9.py python/branches/p3yk-noslice/Lib/test/crashers/bogus_sre_bytecode.py python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_1.py python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_2.py python/branches/p3yk-noslice/Lib/test/crashers/gc_inspection.py python/branches/p3yk-noslice/Lib/test/crashers/loosing_mro_ref.py python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py python/branches/p3yk-noslice/Lib/test/crashers/nasty_eq_vs_dict.py python/branches/p3yk-noslice/Lib/test/crashers/weakref_in_del.py python/branches/p3yk-noslice/Lib/test/doctest_aliases.py python/branches/p3yk-noslice/Lib/test/fork_wait.py python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py python/branches/p3yk-noslice/Lib/test/list_tests.py python/branches/p3yk-noslice/Lib/test/mapping_tests.py python/branches/p3yk-noslice/Lib/test/output/test_cProfile python/branches/p3yk-noslice/Lib/test/output/test_class python/branches/p3yk-noslice/Lib/test/output/test_profile python/branches/p3yk-noslice/Lib/test/pickletester.py python/branches/p3yk-noslice/Lib/test/pydocfodder.py python/branches/p3yk-noslice/Lib/test/pystone.py python/branches/p3yk-noslice/Lib/test/regrtest.py python/branches/p3yk-noslice/Lib/test/reperf.py python/branches/p3yk-noslice/Lib/test/sample_doctest.py python/branches/p3yk-noslice/Lib/test/seq_tests.py python/branches/p3yk-noslice/Lib/test/sortperf.py python/branches/p3yk-noslice/Lib/test/string_tests.py python/branches/p3yk-noslice/Lib/test/test___all__.py python/branches/p3yk-noslice/Lib/test/test_al.py python/branches/p3yk-noslice/Lib/test/test_anydbm.py python/branches/p3yk-noslice/Lib/test/test_array.py python/branches/p3yk-noslice/Lib/test/test_ast.py python/branches/p3yk-noslice/Lib/test/test_asynchat.py python/branches/p3yk-noslice/Lib/test/test_atexit.py python/branches/p3yk-noslice/Lib/test/test_audioop.py python/branches/p3yk-noslice/Lib/test/test_bigmem.py python/branches/p3yk-noslice/Lib/test/test_binop.py python/branches/p3yk-noslice/Lib/test/test_bisect.py python/branches/p3yk-noslice/Lib/test/test_bool.py python/branches/p3yk-noslice/Lib/test/test_bsddb.py python/branches/p3yk-noslice/Lib/test/test_bsddb3.py python/branches/p3yk-noslice/Lib/test/test_builtin.py python/branches/p3yk-noslice/Lib/test/test_bytes.py python/branches/p3yk-noslice/Lib/test/test_capi.py python/branches/p3yk-noslice/Lib/test/test_cd.py python/branches/p3yk-noslice/Lib/test/test_cfgparser.py python/branches/p3yk-noslice/Lib/test/test_cgi.py python/branches/p3yk-noslice/Lib/test/test_cl.py python/branches/p3yk-noslice/Lib/test/test_class.py python/branches/p3yk-noslice/Lib/test/test_cmath.py python/branches/p3yk-noslice/Lib/test/test_code.py python/branches/p3yk-noslice/Lib/test/test_codecs.py python/branches/p3yk-noslice/Lib/test/test_compare.py python/branches/p3yk-noslice/Lib/test/test_compile.py python/branches/p3yk-noslice/Lib/test/test_compiler.py python/branches/p3yk-noslice/Lib/test/test_complex.py python/branches/p3yk-noslice/Lib/test/test_cookie.py python/branches/p3yk-noslice/Lib/test/test_cookielib.py python/branches/p3yk-noslice/Lib/test/test_copy.py python/branches/p3yk-noslice/Lib/test/test_copy_reg.py python/branches/p3yk-noslice/Lib/test/test_crypt.py python/branches/p3yk-noslice/Lib/test/test_csv.py python/branches/p3yk-noslice/Lib/test/test_curses.py python/branches/p3yk-noslice/Lib/test/test_datetime.py python/branches/p3yk-noslice/Lib/test/test_dbm.py python/branches/p3yk-noslice/Lib/test/test_decimal.py python/branches/p3yk-noslice/Lib/test/test_defaultdict.py python/branches/p3yk-noslice/Lib/test/test_deque.py python/branches/p3yk-noslice/Lib/test/test_descr.py python/branches/p3yk-noslice/Lib/test/test_descrtut.py python/branches/p3yk-noslice/Lib/test/test_dict.py python/branches/p3yk-noslice/Lib/test/test_dis.py python/branches/p3yk-noslice/Lib/test/test_dl.py python/branches/p3yk-noslice/Lib/test/test_doctest.py python/branches/p3yk-noslice/Lib/test/test_doctest.txt python/branches/p3yk-noslice/Lib/test/test_doctest2.py python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py python/branches/p3yk-noslice/Lib/test/test_dummy_threading.py python/branches/p3yk-noslice/Lib/test/test_enumerate.py python/branches/p3yk-noslice/Lib/test/test_errno.py python/branches/p3yk-noslice/Lib/test/test_exceptions.py python/branches/p3yk-noslice/Lib/test/test_extcall.py python/branches/p3yk-noslice/Lib/test/test_fcntl.py python/branches/p3yk-noslice/Lib/test/test_file.py python/branches/p3yk-noslice/Lib/test/test_fileinput.py python/branches/p3yk-noslice/Lib/test/test_format.py python/branches/p3yk-noslice/Lib/test/test_funcattrs.py python/branches/p3yk-noslice/Lib/test/test_functools.py python/branches/p3yk-noslice/Lib/test/test_gc.py python/branches/p3yk-noslice/Lib/test/test_gdbm.py python/branches/p3yk-noslice/Lib/test/test_generators.py python/branches/p3yk-noslice/Lib/test/test_genexps.py python/branches/p3yk-noslice/Lib/test/test_getargs2.py python/branches/p3yk-noslice/Lib/test/test_getopt.py python/branches/p3yk-noslice/Lib/test/test_gl.py python/branches/p3yk-noslice/Lib/test/test_grammar.py python/branches/p3yk-noslice/Lib/test/test_grp.py python/branches/p3yk-noslice/Lib/test/test_gzip.py python/branches/p3yk-noslice/Lib/test/test_hash.py python/branches/p3yk-noslice/Lib/test/test_heapq.py python/branches/p3yk-noslice/Lib/test/test_hexoct.py python/branches/p3yk-noslice/Lib/test/test_imageop.py python/branches/p3yk-noslice/Lib/test/test_imgfile.py python/branches/p3yk-noslice/Lib/test/test_import.py python/branches/p3yk-noslice/Lib/test/test_importhooks.py python/branches/p3yk-noslice/Lib/test/test_index.py python/branches/p3yk-noslice/Lib/test/test_inspect.py python/branches/p3yk-noslice/Lib/test/test_isinstance.py python/branches/p3yk-noslice/Lib/test/test_iter.py python/branches/p3yk-noslice/Lib/test/test_iterlen.py python/branches/p3yk-noslice/Lib/test/test_itertools.py python/branches/p3yk-noslice/Lib/test/test_largefile.py python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py python/branches/p3yk-noslice/Lib/test/test_list.py python/branches/p3yk-noslice/Lib/test/test_locale.py python/branches/p3yk-noslice/Lib/test/test_long.py python/branches/p3yk-noslice/Lib/test/test_long_future.py python/branches/p3yk-noslice/Lib/test/test_mailbox.py python/branches/p3yk-noslice/Lib/test/test_marshal.py python/branches/p3yk-noslice/Lib/test/test_mhlib.py python/branches/p3yk-noslice/Lib/test/test_minidom.py python/branches/p3yk-noslice/Lib/test/test_module.py python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py python/branches/p3yk-noslice/Lib/test/test_mutants.py python/branches/p3yk-noslice/Lib/test/test_new.py python/branches/p3yk-noslice/Lib/test/test_normalization.py python/branches/p3yk-noslice/Lib/test/test_ntpath.py python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py python/branches/p3yk-noslice/Lib/test/test_operations.py python/branches/p3yk-noslice/Lib/test/test_operator.py python/branches/p3yk-noslice/Lib/test/test_optparse.py python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py python/branches/p3yk-noslice/Lib/test/test_parser.py python/branches/p3yk-noslice/Lib/test/test_peepholer.py python/branches/p3yk-noslice/Lib/test/test_pep247.py python/branches/p3yk-noslice/Lib/test/test_pep277.py python/branches/p3yk-noslice/Lib/test/test_pep352.py python/branches/p3yk-noslice/Lib/test/test_pkg.py python/branches/p3yk-noslice/Lib/test/test_poll.py python/branches/p3yk-noslice/Lib/test/test_popen.py python/branches/p3yk-noslice/Lib/test/test_popen2.py python/branches/p3yk-noslice/Lib/test/test_posix.py python/branches/p3yk-noslice/Lib/test/test_posixpath.py python/branches/p3yk-noslice/Lib/test/test_pow.py python/branches/p3yk-noslice/Lib/test/test_pprint.py python/branches/p3yk-noslice/Lib/test/test_pty.py python/branches/p3yk-noslice/Lib/test/test_pwd.py python/branches/p3yk-noslice/Lib/test/test_pyclbr.py python/branches/p3yk-noslice/Lib/test/test_pyexpat.py python/branches/p3yk-noslice/Lib/test/test_queue.py python/branches/p3yk-noslice/Lib/test/test_random.py python/branches/p3yk-noslice/Lib/test/test_re.py python/branches/p3yk-noslice/Lib/test/test_repr.py python/branches/p3yk-noslice/Lib/test/test_resource.py python/branches/p3yk-noslice/Lib/test/test_rfc822.py python/branches/p3yk-noslice/Lib/test/test_rgbimg.py python/branches/p3yk-noslice/Lib/test/test_richcmp.py python/branches/p3yk-noslice/Lib/test/test_runpy.py python/branches/p3yk-noslice/Lib/test/test_sax.py python/branches/p3yk-noslice/Lib/test/test_scope.py python/branches/p3yk-noslice/Lib/test/test_select.py python/branches/p3yk-noslice/Lib/test/test_set.py python/branches/p3yk-noslice/Lib/test/test_signal.py python/branches/p3yk-noslice/Lib/test/test_site.py python/branches/p3yk-noslice/Lib/test/test_slice.py python/branches/p3yk-noslice/Lib/test/test_socket.py python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py python/branches/p3yk-noslice/Lib/test/test_socketserver.py python/branches/p3yk-noslice/Lib/test/test_sort.py python/branches/p3yk-noslice/Lib/test/test_strftime.py python/branches/p3yk-noslice/Lib/test/test_string.py python/branches/p3yk-noslice/Lib/test/test_strop.py python/branches/p3yk-noslice/Lib/test/test_strptime.py python/branches/p3yk-noslice/Lib/test/test_struct.py python/branches/p3yk-noslice/Lib/test/test_subprocess.py python/branches/p3yk-noslice/Lib/test/test_sundry.py python/branches/p3yk-noslice/Lib/test/test_support.py python/branches/p3yk-noslice/Lib/test/test_syntax.py python/branches/p3yk-noslice/Lib/test/test_tarfile.py python/branches/p3yk-noslice/Lib/test/test_thread.py python/branches/p3yk-noslice/Lib/test/test_threaded_import.py python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py python/branches/p3yk-noslice/Lib/test/test_threading.py python/branches/p3yk-noslice/Lib/test/test_time.py python/branches/p3yk-noslice/Lib/test/test_timeout.py python/branches/p3yk-noslice/Lib/test/test_tokenize.py python/branches/p3yk-noslice/Lib/test/test_trace.py python/branches/p3yk-noslice/Lib/test/test_traceback.py python/branches/p3yk-noslice/Lib/test/test_types.py python/branches/p3yk-noslice/Lib/test/test_unary.py python/branches/p3yk-noslice/Lib/test/test_unicode.py python/branches/p3yk-noslice/Lib/test/test_urllib2.py python/branches/p3yk-noslice/Lib/test/test_urllib2net.py python/branches/p3yk-noslice/Lib/test/test_userdict.py python/branches/p3yk-noslice/Lib/test/test_uu.py python/branches/p3yk-noslice/Lib/test/test_uuid.py python/branches/p3yk-noslice/Lib/test/test_weakref.py python/branches/p3yk-noslice/Lib/test/test_winreg.py python/branches/p3yk-noslice/Lib/test/test_with.py python/branches/p3yk-noslice/Lib/test/test_xdrlib.py python/branches/p3yk-noslice/Lib/test/test_xml_etree.py python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py python/branches/p3yk-noslice/Lib/test/test_xrange.py python/branches/p3yk-noslice/Lib/test/test_zipfile.py python/branches/p3yk-noslice/Lib/test/test_zipfile64.py python/branches/p3yk-noslice/Lib/test/test_zipimport.py python/branches/p3yk-noslice/Lib/test/test_zlib.py python/branches/p3yk-noslice/Lib/test/time_hashlib.py python/branches/p3yk-noslice/Lib/textwrap.py python/branches/p3yk-noslice/Lib/this.py python/branches/p3yk-noslice/Lib/threading.py python/branches/p3yk-noslice/Lib/timeit.py python/branches/p3yk-noslice/Lib/token.py python/branches/p3yk-noslice/Lib/tokenize.py python/branches/p3yk-noslice/Lib/trace.py python/branches/p3yk-noslice/Lib/types.py python/branches/p3yk-noslice/Lib/unittest.py python/branches/p3yk-noslice/Lib/urllib.py python/branches/p3yk-noslice/Lib/urllib2.py python/branches/p3yk-noslice/Lib/urlparse.py python/branches/p3yk-noslice/Lib/uu.py python/branches/p3yk-noslice/Lib/uuid.py python/branches/p3yk-noslice/Lib/warnings.py python/branches/p3yk-noslice/Lib/weakref.py python/branches/p3yk-noslice/Lib/webbrowser.py python/branches/p3yk-noslice/Lib/whichdb.py python/branches/p3yk-noslice/Lib/wsgiref/simple_server.py python/branches/p3yk-noslice/Lib/xdrlib.py python/branches/p3yk-noslice/Lib/xml/dom/NodeFilter.py python/branches/p3yk-noslice/Lib/xml/dom/minidom.py python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py python/branches/p3yk-noslice/Lib/xml/sax/handler.py python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py python/branches/p3yk-noslice/Lib/xml/sax/xmlreader.py python/branches/p3yk-noslice/Lib/xmllib.py python/branches/p3yk-noslice/Lib/xmlrpclib.py python/branches/p3yk-noslice/Lib/zipfile.py python/branches/p3yk-noslice/Makefile.pre.in python/branches/p3yk-noslice/Misc/ACKS python/branches/p3yk-noslice/Misc/NEWS python/branches/p3yk-noslice/Modules/_csv.c python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c python/branches/p3yk-noslice/Modules/_ctypes/_ctypes_test.c python/branches/p3yk-noslice/Modules/_ctypes/callproc.c python/branches/p3yk-noslice/Modules/_ctypes/cfield.c python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffi.c python/branches/p3yk-noslice/Modules/_cursesmodule.c python/branches/p3yk-noslice/Modules/_randommodule.c python/branches/p3yk-noslice/Modules/_sqlite/cache.c python/branches/p3yk-noslice/Modules/_sqlite/cache.h python/branches/p3yk-noslice/Modules/_sqlite/connection.c python/branches/p3yk-noslice/Modules/_sqlite/connection.h python/branches/p3yk-noslice/Modules/_sqlite/cursor.c python/branches/p3yk-noslice/Modules/_sqlite/cursor.h python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.c python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.h python/branches/p3yk-noslice/Modules/_sqlite/module.c python/branches/p3yk-noslice/Modules/_sqlite/module.h python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.c python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.h python/branches/p3yk-noslice/Modules/_sqlite/row.c python/branches/p3yk-noslice/Modules/_sqlite/row.h python/branches/p3yk-noslice/Modules/_sqlite/statement.c python/branches/p3yk-noslice/Modules/_sqlite/statement.h python/branches/p3yk-noslice/Modules/_sqlite/util.c python/branches/p3yk-noslice/Modules/_sqlite/util.h python/branches/p3yk-noslice/Modules/_sre.c python/branches/p3yk-noslice/Modules/_struct.c python/branches/p3yk-noslice/Modules/_testcapimodule.c python/branches/p3yk-noslice/Modules/_tkinter.c python/branches/p3yk-noslice/Modules/arraymodule.c python/branches/p3yk-noslice/Modules/bz2module.c python/branches/p3yk-noslice/Modules/cPickle.c python/branches/p3yk-noslice/Modules/cStringIO.c python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c python/branches/p3yk-noslice/Modules/collectionsmodule.c python/branches/p3yk-noslice/Modules/datetimemodule.c python/branches/p3yk-noslice/Modules/dlmodule.c python/branches/p3yk-noslice/Modules/itertoolsmodule.c python/branches/p3yk-noslice/Modules/parsermodule.c python/branches/p3yk-noslice/Modules/posixmodule.c python/branches/p3yk-noslice/Modules/socketmodule.c python/branches/p3yk-noslice/Modules/socketmodule.h python/branches/p3yk-noslice/Modules/timemodule.c python/branches/p3yk-noslice/Objects/abstract.c python/branches/p3yk-noslice/Objects/boolobject.c python/branches/p3yk-noslice/Objects/complexobject.c python/branches/p3yk-noslice/Objects/dictnotes.txt python/branches/p3yk-noslice/Objects/dictobject.c python/branches/p3yk-noslice/Objects/enumobject.c python/branches/p3yk-noslice/Objects/exceptions.c python/branches/p3yk-noslice/Objects/fileobject.c python/branches/p3yk-noslice/Objects/floatobject.c python/branches/p3yk-noslice/Objects/frameobject.c python/branches/p3yk-noslice/Objects/intobject.c python/branches/p3yk-noslice/Objects/iterobject.c python/branches/p3yk-noslice/Objects/listobject.c python/branches/p3yk-noslice/Objects/longobject.c python/branches/p3yk-noslice/Objects/object.c python/branches/p3yk-noslice/Objects/setobject.c python/branches/p3yk-noslice/Objects/stringobject.c python/branches/p3yk-noslice/Objects/typeobject.c python/branches/p3yk-noslice/Objects/unicodeobject.c python/branches/p3yk-noslice/Objects/weakrefobject.c python/branches/p3yk-noslice/PC/_msi.c python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj python/branches/p3yk-noslice/PCbuild/_elementtree.vcproj python/branches/p3yk-noslice/PCbuild/_msi.vcproj python/branches/p3yk-noslice/PCbuild/_socket.vcproj python/branches/p3yk-noslice/PCbuild/_sqlite3.vcproj python/branches/p3yk-noslice/PCbuild/_ssl.mak python/branches/p3yk-noslice/PCbuild/_testcapi.vcproj python/branches/p3yk-noslice/PCbuild/_tkinter.vcproj python/branches/p3yk-noslice/PCbuild/build_ssl.py python/branches/p3yk-noslice/PCbuild/bz2.vcproj python/branches/p3yk-noslice/PCbuild/pyexpat.vcproj python/branches/p3yk-noslice/PCbuild/python.vcproj python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj python/branches/p3yk-noslice/PCbuild/pythonw.vcproj python/branches/p3yk-noslice/PCbuild/select.vcproj python/branches/p3yk-noslice/PCbuild/unicodedata.vcproj python/branches/p3yk-noslice/PCbuild/winsound.vcproj python/branches/p3yk-noslice/Parser/Python.asdl python/branches/p3yk-noslice/Parser/asdl_c.py python/branches/p3yk-noslice/Parser/tokenizer.c python/branches/p3yk-noslice/Python/Python-ast.c python/branches/p3yk-noslice/Python/ast.c python/branches/p3yk-noslice/Python/bltinmodule.c python/branches/p3yk-noslice/Python/ceval.c python/branches/p3yk-noslice/Python/compile.c python/branches/p3yk-noslice/Python/frozen.c python/branches/p3yk-noslice/Python/getargs.c python/branches/p3yk-noslice/Python/graminit.c python/branches/p3yk-noslice/Python/import.c python/branches/p3yk-noslice/Python/marshal.c python/branches/p3yk-noslice/Python/pythonrun.c python/branches/p3yk-noslice/Python/symtable.c python/branches/p3yk-noslice/Python/sysmodule.c python/branches/p3yk-noslice/Python/traceback.c python/branches/p3yk-noslice/Tools/compiler/ast.txt python/branches/p3yk-noslice/Tools/freeze/ (props changed) python/branches/p3yk-noslice/Tools/freeze/bkfile.py python/branches/p3yk-noslice/Tools/freeze/freeze.py python/branches/p3yk-noslice/Tools/freeze/hello.py python/branches/p3yk-noslice/Tools/freeze/makeconfig.py python/branches/p3yk-noslice/Tools/freeze/makefreeze.py python/branches/p3yk-noslice/Tools/freeze/parsesetup.py python/branches/p3yk-noslice/Tools/freeze/winmakemakefile.py python/branches/p3yk-noslice/Tools/msi/uuids.py python/branches/p3yk-noslice/Tools/pybench/CommandLine.py python/branches/p3yk-noslice/Tools/pybench/Dict.py python/branches/p3yk-noslice/Tools/pybench/Exceptions.py python/branches/p3yk-noslice/Tools/pybench/Lookups.py python/branches/p3yk-noslice/Tools/pybench/pybench.py python/branches/p3yk-noslice/configure python/branches/p3yk-noslice/configure.in python/branches/p3yk-noslice/pyconfig.h.in python/branches/p3yk-noslice/setup.py Log: Merge p3yk into p3yk-noslice branch. Merged revisions 53364-53866 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/p3yk ................ r53417 | guido.van.rossum | 2007-01-14 00:54:39 +0100 (Sun, 14 Jan 2007) | 2 lines Fix pybench so it works -- Larry Hastings. ................ r53421 | guido.van.rossum | 2007-01-14 04:31:43 +0100 (Sun, 14 Jan 2007) | 9 lines 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. ................ r53422 | guido.van.rossum | 2007-01-14 04:42:30 +0100 (Sun, 14 Jan 2007) | 2 lines News about int/long unification and except syntax change. ................ r53424 | guido.van.rossum | 2007-01-14 05:02:16 +0100 (Sun, 14 Jan 2007) | 3 lines Fix cPickle breakage due to last-minute change to the name of the 'long' type (it's not called 'int' :-). ................ r53433 | guido.van.rossum | 2007-01-14 17:55:36 +0100 (Sun, 14 Jan 2007) | 2 lines Honesty before all. ................ r53438 | guido.van.rossum | 2007-01-14 19:43:49 +0100 (Sun, 14 Jan 2007) | 2 lines Fix new bug in ftplib.py introduced by exception scope limitation. ................ r53439 | guido.van.rossum | 2007-01-14 19:52:06 +0100 (Sun, 14 Jan 2007) | 2 lines One more test breakage hits the dust. The test was clearly in the wrong. ................ r53443 | guido.van.rossum | 2007-01-15 01:07:32 +0100 (Mon, 15 Jan 2007) | 10 lines 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. ........ ................ r53444 | guido.van.rossum | 2007-01-15 01:14:39 +0100 (Mon, 15 Jan 2007) | 2 lines Fix repr.py -- it was triggering on the type name 'long', should be 'int'. ................ r53445 | guido.van.rossum | 2007-01-15 01:21:46 +0100 (Mon, 15 Jan 2007) | 3 lines Fix pickletools doctests -- all we get nowadays is longs. (Hmm... Shouldn't longs of certain sizes be pickled using 'I' opcodes? Later.) ................ r53446 | guido.van.rossum | 2007-01-15 01:31:49 +0100 (Mon, 15 Jan 2007) | 3 lines Fix the sqlite failure -- it was the usual, PyInt_Check -> PyInt_CheckExact. Clarify some OverflowError messages from the various PyLong_AsXXX methods. ................ r53448 | guido.van.rossum | 2007-01-15 01:38:25 +0100 (Mon, 15 Jan 2007) | 2 lines No more tests are broken AFAIK. ................ r53451 | thomas.wouters | 2007-01-15 16:49:28 +0100 (Mon, 15 Jan 2007) | 216 lines 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). ........ ................ r53452 | guido.van.rossum | 2007-01-15 17:59:06 +0100 (Mon, 15 Jan 2007) | 3 lines Rip out 'long' and 'L'-suffixed integer literals. (Rough first cut.) ................ r53453 | guido.van.rossum | 2007-01-15 18:02:51 +0100 (Mon, 15 Jan 2007) | 2 lines Fix L-suffixed literal straggler. ................ r53598 | brett.cannon | 2007-01-30 00:43:38 +0100 (Tue, 30 Jan 2007) | 2 lines Fix minor grammar typo. ................ r53599 | brett.cannon | 2007-01-30 00:44:37 +0100 (Tue, 30 Jan 2007) | 2 lines Add missing entry for PEP 3102 (keyword-only arguments). ................ r53600 | guido.van.rossum | 2007-01-30 01:00:40 +0100 (Tue, 30 Jan 2007) | 2 lines Update news about int/long unification. ................ r53610 | thomas.wouters | 2007-02-01 19:02:27 +0100 (Thu, 01 Feb 2007) | 180 lines Merged revisions 53451-53537 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53454 | brett.cannon | 2007-01-15 20:12:08 +0100 (Mon, 15 Jan 2007) | 3 lines Add a note for strptime that just because strftime supports some extra directive that is not documented that strptime will as well. ........ r53458 | vinay.sajip | 2007-01-16 10:50:07 +0100 (Tue, 16 Jan 2007) | 1 line Updated rotating file handlers to use _open(). ........ r53459 | marc-andre.lemburg | 2007-01-16 14:03:06 +0100 (Tue, 16 Jan 2007) | 2 lines Add news items for the recent pybench and platform changes. ........ r53460 | sjoerd.mullender | 2007-01-16 17:42:38 +0100 (Tue, 16 Jan 2007) | 4 lines Fixed ntpath.expandvars to not replace references to non-existing variables with nothing. Also added tests. This fixes bug #494589. ........ r53464 | neal.norwitz | 2007-01-17 07:23:51 +0100 (Wed, 17 Jan 2007) | 1 line Give Calvin Spealman access for python-dev summaries. ........ r53465 | neal.norwitz | 2007-01-17 09:37:26 +0100 (Wed, 17 Jan 2007) | 1 line Remove Calvin since he only has access to the website currently. ........ r53466 | thomas.heller | 2007-01-17 10:40:34 +0100 (Wed, 17 Jan 2007) | 2 lines Replace C++ comments with C comments. ........ r53472 | andrew.kuchling | 2007-01-17 20:55:06 +0100 (Wed, 17 Jan 2007) | 1 line [Part of bug #1599254] Add suggestion to Mailbox docs to use Maildir, and warn user to lock/unlock mailboxes when modifying them ........ r53475 | georg.brandl | 2007-01-17 22:09:04 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1637967: missing //= operator in list. ........ r53477 | georg.brandl | 2007-01-17 22:19:58 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1629125: fix wrong data type (int -> Py_ssize_t) in PyDict_Next docs. ........ r53481 | neal.norwitz | 2007-01-18 06:40:58 +0100 (Thu, 18 Jan 2007) | 1 line Try reverting part of r53145 that seems to cause the Windows buildbots to fail in test_uu.UUFileTest.test_encode ........ r53482 | fred.drake | 2007-01-18 06:42:30 +0100 (Thu, 18 Jan 2007) | 1 line add missing version entry ........ r53483 | neal.norwitz | 2007-01-18 07:20:55 +0100 (Thu, 18 Jan 2007) | 7 lines This test doesn't pass on Windows. The cause seems to be that chmod doesn't support the same funcationality as on Unix. I'm not sure if this fix is the best (or if it will even work)--it's a test to see if the buildbots start passing again. It might be better to not even run this test if it's windows (or non-posix). ........ r53488 | neal.norwitz | 2007-01-19 06:53:33 +0100 (Fri, 19 Jan 2007) | 1 line SF #1635217, Fix unbalanced paren ........ r53489 | martin.v.loewis | 2007-01-19 07:42:22 +0100 (Fri, 19 Jan 2007) | 3 lines Prefix AST symbols with _Py_. Fixes #1637022. Will backport. ........ r53497 | martin.v.loewis | 2007-01-19 19:01:38 +0100 (Fri, 19 Jan 2007) | 2 lines Add UUIDs for 2.5.1 and 2.5.2 ........ r53499 | raymond.hettinger | 2007-01-19 19:07:18 +0100 (Fri, 19 Jan 2007) | 1 line SF# 1635892: Fix docs for betavariate's input parameters . ........ r53503 | martin.v.loewis | 2007-01-20 15:05:39 +0100 (Sat, 20 Jan 2007) | 2 lines Merge 53501 and 53502 from 25 branch: Add /GS- for AMD64 and Itanium builds where missing. ........ r53504 | walter.doerwald | 2007-01-20 18:28:31 +0100 (Sat, 20 Jan 2007) | 2 lines Port test_resource.py to unittest. ........ r53505 | walter.doerwald | 2007-01-20 19:19:33 +0100 (Sat, 20 Jan 2007) | 2 lines Add argument tests an calls of resource.getrusage(). ........ r53506 | walter.doerwald | 2007-01-20 20:03:17 +0100 (Sat, 20 Jan 2007) | 2 lines resource.RUSAGE_BOTH might not exist. ........ r53507 | walter.doerwald | 2007-01-21 00:07:28 +0100 (Sun, 21 Jan 2007) | 2 lines Port test_new.py to unittest. ........ r53508 | martin.v.loewis | 2007-01-21 10:33:07 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1610575: Add support for _Bool to struct. ........ r53509 | georg.brandl | 2007-01-21 11:28:43 +0100 (Sun, 21 Jan 2007) | 3 lines Bug #1486663: don't reject keyword arguments for subclasses of builtin types. ........ r53511 | georg.brandl | 2007-01-21 11:35:10 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1627441: close sockets properly in urllib2. ........ r53517 | georg.brandl | 2007-01-22 20:40:21 +0100 (Mon, 22 Jan 2007) | 3 lines Use new email module names (#1637162, #1637159, #1637157). ........ r53518 | andrew.kuchling | 2007-01-22 21:26:40 +0100 (Mon, 22 Jan 2007) | 1 line Improve pattern used for mbox 'From' lines; add a simple test ........ r53519 | andrew.kuchling | 2007-01-22 21:27:50 +0100 (Mon, 22 Jan 2007) | 1 line Make comment match the code ........ r53522 | georg.brandl | 2007-01-22 22:10:33 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1249573: fix rfc822.parsedate not accepting a certain date format ........ r53524 | georg.brandl | 2007-01-22 22:23:41 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1627316: handle error in condition/ignore pdb commands more gracefully. ........ r53526 | lars.gustaebel | 2007-01-23 12:17:33 +0100 (Tue, 23 Jan 2007) | 4 lines Patch #1507247: tarfile.py: use current umask for intermediate directories. ........ r53527 | thomas.wouters | 2007-01-23 14:42:00 +0100 (Tue, 23 Jan 2007) | 13 lines SF patch #1630975: Fix crash when replacing sys.stdout in sitecustomize When running the interpreter in an environment that would cause it to set stdout/stderr/stdin's encoding, having a sitecustomize that would replace them with something other than PyFile objects would crash the interpreter. Fix it by simply ignoring the encoding-setting for non-files. This could do with a test, but I can think of no maintainable and portable way to test this bug, short of adding a sitecustomize.py to the buildsystem and have it always run with it (hmmm....) ........ r53528 | thomas.wouters | 2007-01-23 14:50:49 +0100 (Tue, 23 Jan 2007) | 4 lines Add news entry about last checkin (oops.) ........ r53531 | martin.v.loewis | 2007-01-23 22:11:47 +0100 (Tue, 23 Jan 2007) | 4 lines Make PyTraceBack_Here use the current thread, not the frame's thread state. Fixes #1579370. Will backport. ........ r53535 | brett.cannon | 2007-01-24 00:21:22 +0100 (Wed, 24 Jan 2007) | 5 lines Fix crasher for when an object's __del__ creates a new weakref to itself. Patch only fixes new-style classes; classic classes still buggy. Closes bug #1377858. Already backported. ........ r53536 | walter.doerwald | 2007-01-24 01:42:19 +0100 (Wed, 24 Jan 2007) | 2 lines Port test_popen.py to unittest. ........ ................ r53627 | thomas.wouters | 2007-02-03 22:49:06 +0100 (Sat, 03 Feb 2007) | 8 lines - Fix conversion glitch in test_pyclbr, which caused a test to not fail when it should. - Remove unneeded classic-class support from pydoc (which would otherwise cause test_pyclbr to fail.) ................ r53634 | thomas.wouters | 2007-02-05 02:24:16 +0100 (Mon, 05 Feb 2007) | 96 lines Merged revisions 53538-53622 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53545 | andrew.kuchling | 2007-01-24 21:06:41 +0100 (Wed, 24 Jan 2007) | 1 line Strengthen warning about using lock() ........ r53556 | thomas.heller | 2007-01-25 19:34:14 +0100 (Thu, 25 Jan 2007) | 3 lines Fix for #1643874: When calling SysAllocString, create a PyCObject which will eventually call SysFreeString to free the BSTR resource. ........ r53563 | andrew.kuchling | 2007-01-25 21:02:13 +0100 (Thu, 25 Jan 2007) | 1 line Add item ........ r53564 | brett.cannon | 2007-01-25 21:22:02 +0100 (Thu, 25 Jan 2007) | 8 lines Fix time.strptime's %U support. Basically rewrote the algorithm to be more generic so that one only has to shift certain values based on whether the week was specified to start on Monday or Sunday. Cut out a lot of edge case code compared to the previous version. Also broke algorithm out into its own function (that is private to the module). Fixes bug #1643943 (thanks Biran Nahas for the report). ........ r53570 | brett.cannon | 2007-01-26 00:30:39 +0100 (Fri, 26 Jan 2007) | 4 lines Remove specific mention of my name and email address from modules. Not really needed and all bug reports should go to the bug tracker, not directly to me. Plus I am not the only person to have edited these files at this point. ........ r53573 | fred.drake | 2007-01-26 17:28:44 +0100 (Fri, 26 Jan 2007) | 1 line fix typo (extraneous ")") ........ r53575 | georg.brandl | 2007-01-27 18:43:02 +0100 (Sat, 27 Jan 2007) | 4 lines Patch #1638243: the compiler package is now able to correctly compile a with statement; previously, executing code containing a with statement compiled by the compiler package crashed the interpreter. ........ r53578 | georg.brandl | 2007-01-27 18:59:42 +0100 (Sat, 27 Jan 2007) | 3 lines Patch #1634778: add missing encoding aliases for iso8859_15 and iso8859_16. ........ r53579 | georg.brandl | 2007-01-27 20:38:50 +0100 (Sat, 27 Jan 2007) | 2 lines Bug #1645944: os.access now returns bool but docstring is not updated ........ r53590 | brett.cannon | 2007-01-28 21:58:00 +0100 (Sun, 28 Jan 2007) | 2 lines Use the thread lock's context manager instead of a try/finally statement. ........ r53591 | brett.cannon | 2007-01-29 05:41:44 +0100 (Mon, 29 Jan 2007) | 2 lines Add a test for slicing an exception. ........ r53594 | andrew.kuchling | 2007-01-29 21:21:43 +0100 (Mon, 29 Jan 2007) | 1 line Minor edits to the curses HOWTO ........ r53596 | andrew.kuchling | 2007-01-29 21:55:40 +0100 (Mon, 29 Jan 2007) | 1 line Various minor edits ........ r53597 | andrew.kuchling | 2007-01-29 22:28:48 +0100 (Mon, 29 Jan 2007) | 1 line More edits ........ r53601 | tim.peters | 2007-01-30 04:03:46 +0100 (Tue, 30 Jan 2007) | 2 lines Whitespace normalization. ........ r53603 | georg.brandl | 2007-01-30 21:21:30 +0100 (Tue, 30 Jan 2007) | 2 lines Bug #1648191: typo in docs. ........ r53605 | brett.cannon | 2007-01-30 22:34:36 +0100 (Tue, 30 Jan 2007) | 8 lines No more raising of string exceptions! The next step of PEP 352 (for 2.6) causes raising a string exception to trigger a TypeError. Trying to catch a string exception raises a DeprecationWarning. References to string exceptions has been removed from the docs since they are now just an error. ........ r53618 | raymond.hettinger | 2007-02-01 22:02:59 +0100 (Thu, 01 Feb 2007) | 1 line Bug #1648179: set.update() not recognizing __iter__ overrides in dict subclasses. ........ ................ r53651 | martin.v.loewis | 2007-02-06 22:05:30 +0100 (Tue, 06 Feb 2007) | 2 lines Fix refcounting bugs related to CONVERT_BINOP. ................ r53652 | martin.v.loewis | 2007-02-06 22:30:59 +0100 (Tue, 06 Feb 2007) | 3 lines Remove bogus INCREF of ziptuple: it is a freshly-allocated tuple object. ................ r53685 | guido.van.rossum | 2007-02-09 06:32:43 +0100 (Fri, 09 Feb 2007) | 3 lines Essential changes for print function changes. Lib will be changed in a separate run. ................ r53686 | guido.van.rossum | 2007-02-09 06:37:30 +0100 (Fri, 09 Feb 2007) | 9 lines Fix most trivially-findable print statements. There's one major and one minor category still unfixed: doctests are the major category (and I hope to be able to augment the refactoring tool to refactor bona fide doctests soon); other code generating print statements in strings is the minor category. (Oh, and I don't know if the compiler package works.) ................ r53688 | guido.van.rossum | 2007-02-09 06:42:38 +0100 (Fri, 09 Feb 2007) | 2 lines Note that print is a function now. ................ r53701 | guido.van.rossum | 2007-02-09 21:13:25 +0100 (Fri, 09 Feb 2007) | 3 lines Fix a bunch of doctests with the -d option of refactor.py. We still have 27 failing tests (down from 39). ................ r53702 | guido.van.rossum | 2007-02-09 21:33:44 +0100 (Fri, 09 Feb 2007) | 2 lines Revert doubly-converted doctests. ................ r53703 | guido.van.rossum | 2007-02-09 21:50:08 +0100 (Fri, 09 Feb 2007) | 7 lines Fix an unfortunate mis-conversion: sometimes "print x," must be converted to "print(x, end=' ')", but other times it must be converted to "print(x, end='')". There's no easy way to find out, because it depends on whether x ends with a newline. I'm sure I'll find more like this. ................ r53704 | georg.brandl | 2007-02-09 22:28:07 +0100 (Fri, 09 Feb 2007) | 7 lines * Remove PRINT_ITEM(_TO), PRINT_NEWLINE(_TO) opcodes. * Fix some docstrings and one Print -> print. * Fix test_{class,code,descrtut,dis,extcall,parser,popen,pkg,subprocess,syntax,traceback}. These were the ones that generated code with a print statement. In most remaining failing tests there's an issue with the soft space. ................ r53705 | guido.van.rossum | 2007-02-09 22:54:58 +0100 (Fri, 09 Feb 2007) | 2 lines Some more tests pass now. (Also test_compiler.py with -u all.) ................ r53706 | guido.van.rossum | 2007-02-09 23:09:01 +0100 (Fri, 09 Feb 2007) | 2 lines Fix another test. ................ r53707 | guido.van.rossum | 2007-02-09 23:11:20 +0100 (Fri, 09 Feb 2007) | 2 lines Two tests fixed with one fix. ................ r53708 | guido.van.rossum | 2007-02-09 23:16:54 +0100 (Fri, 09 Feb 2007) | 2 lines Fix a bogus end=' ' here. ................ r53709 | guido.van.rossum | 2007-02-09 23:18:41 +0100 (Fri, 09 Feb 2007) | 2 lines More prints embedded in strings. ................ r53710 | guido.van.rossum | 2007-02-09 23:27:36 +0100 (Fri, 09 Feb 2007) | 3 lines Found another difference between old and new print: old print would suppress the softspace after \t. ................ r53711 | guido.van.rossum | 2007-02-09 23:28:28 +0100 (Fri, 09 Feb 2007) | 2 lines Trivial fix for test_profile.py. ................ r53712 | guido.van.rossum | 2007-02-09 23:36:02 +0100 (Fri, 09 Feb 2007) | 2 lines Fairly subtle fix for failing tests. ................ r53713 | guido.van.rossum | 2007-02-09 23:43:10 +0100 (Fri, 09 Feb 2007) | 2 lines Fix the roundtripping function. ................ r53714 | guido.van.rossum | 2007-02-09 23:43:47 +0100 (Fri, 09 Feb 2007) | 2 lines Redue the failure rate to 13 tests. Bah. ................ r53715 | guido.van.rossum | 2007-02-10 00:20:19 +0100 (Sat, 10 Feb 2007) | 4 lines Kill off softspace completely (except in formatter.py which seems to have a different feature with the same name). The change to test_doctest.txt reduces the doctest failures to 3. ................ r53716 | guido.van.rossum | 2007-02-10 00:27:01 +0100 (Sat, 10 Feb 2007) | 2 lines Fix test_frozen. ................ r53717 | guido.van.rossum | 2007-02-10 00:38:28 +0100 (Sat, 10 Feb 2007) | 2 lines Ignore *.py[co]. ................ r53718 | guido.van.rossum | 2007-02-10 00:39:59 +0100 (Sat, 10 Feb 2007) | 4 lines Fix the remaining doctest failures. One was a modified line that was echoed in an exception; the other two were softspace problems, fixed clumsily but effectively. ................ r53719 | guido.van.rossum | 2007-02-10 00:52:14 +0100 (Sat, 10 Feb 2007) | 2 lines News about softspace. ................ r53721 | guido.van.rossum | 2007-02-10 02:11:45 +0100 (Sat, 10 Feb 2007) | 2 lines Very preliminary work on dict views. ................ r53723 | guido.van.rossum | 2007-02-10 05:54:19 +0100 (Sat, 10 Feb 2007) | 2 lines Endow dict views with a proper length method. ................ r53724 | guido.van.rossum | 2007-02-10 19:55:06 +0100 (Sat, 10 Feb 2007) | 4 lines Implement __contains__ for dict_keys and dict_items. (Not for dict_values, where it can't be done faster than the default implementation which just iterates the elements.) ................ r53727 | guido.van.rossum | 2007-02-10 23:53:17 +0100 (Sat, 10 Feb 2007) | 2 lines Random change to make this work unchanged when dict.keys() returns a dict view. ................ r53732 | guido.van.rossum | 2007-02-11 07:12:03 +0100 (Sun, 11 Feb 2007) | 9 lines - PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone; and .keys(), .items(), .values() return dict views. The dict views aren't fully functional yet; in particular, they can't be compared to sets yet. but they are useful as "iterator wells". There are still 27 failing unit tests; I expect that many of these have fairly trivial fixes, but there are so many, I could use help. ................ r53734 | guido.van.rossum | 2007-02-11 08:05:21 +0100 (Sun, 11 Feb 2007) | 2 lines With the help of the improved fixer, test_with.py is now fixed. ................ r53738 | guido.van.rossum | 2007-02-11 19:44:55 +0100 (Sun, 11 Feb 2007) | 2 lines Make test_sax pass. ................ r53739 | guido.van.rossum | 2007-02-11 19:53:00 +0100 (Sun, 11 Feb 2007) | 2 lines Another fix. Partly reverted the tweaks done by the previous fix. ................ r53740 | guido.van.rossum | 2007-02-11 19:54:18 +0100 (Sun, 11 Feb 2007) | 2 lines Two more trivial fixes. ................ r53742 | guido.van.rossum | 2007-02-11 23:59:48 +0100 (Sun, 11 Feb 2007) | 2 lines Nailed test_weakref.py. Pfew, messy! ................ r53743 | georg.brandl | 2007-02-12 00:06:17 +0100 (Mon, 12 Feb 2007) | 3 lines Checkin the regenerated Python-ast.c and fix test_optparse. ................ r53746 | guido.van.rossum | 2007-02-12 01:07:01 +0100 (Mon, 12 Feb 2007) | 2 lines Make test_logging pass. ................ r53747 | guido.van.rossum | 2007-02-12 01:22:55 +0100 (Mon, 12 Feb 2007) | 2 lines Fix another unit test. ................ r53748 | guido.van.rossum | 2007-02-12 01:23:56 +0100 (Mon, 12 Feb 2007) | 2 lines Fix unittest. ................ r53749 | guido.van.rossum | 2007-02-12 03:23:40 +0100 (Mon, 12 Feb 2007) | 4 lines Make dict.keys() and dict.items() comparable to sets, using == and !=. (PEP 3106 requires subset comparisons too, those will come later if someone really wants them. :-) ................ r53759 | guido.van.rossum | 2007-02-13 06:46:39 +0100 (Tue, 13 Feb 2007) | 2 lines List of broken tests at this time. If you fix a test, please update this file. ................ r53773 | guido.van.rossum | 2007-02-13 20:55:23 +0100 (Tue, 13 Feb 2007) | 2 lines Get rid of some old TO TO items. ................ r53779 | guido.van.rossum | 2007-02-14 18:49:04 +0100 (Wed, 14 Feb 2007) | 2 lines Fix for test_dict.py, thanks to Eduardo O Padoan. ................ r53780 | guido.van.rossum | 2007-02-15 04:49:08 +0100 (Thu, 15 Feb 2007) | 6 lines Fix the damage to UserDict and its tests. Clearly this is not the right way to fix this; UserDict and MixinDict ought to be redesigned with the new dict API in mind. But I'm not claiming to be in charge of library redesign, I only want zero failing tests. ................ r53781 | guido.van.rossum | 2007-02-15 05:01:01 +0100 (Thu, 15 Feb 2007) | 2 lines Some more test now pass. ................ r53841 | brett.cannon | 2007-02-21 22:18:18 +0100 (Wed, 21 Feb 2007) | 2 lines Fix plistlib to work with dict views. ................ r53843 | brett.cannon | 2007-02-21 22:57:55 +0100 (Wed, 21 Feb 2007) | 2 lines Fix test_os from breakage due to dict views. ................ r53844 | brett.cannon | 2007-02-21 22:59:58 +0100 (Wed, 21 Feb 2007) | 2 lines Fix test_mutants for dict views. ................ r53845 | brett.cannon | 2007-02-21 23:05:37 +0100 (Wed, 21 Feb 2007) | 7 lines Fix xml.dom.minidom so it works again after the dict views introduction. There are some methods in minidom that return dict.keys() directly. There were left alone since the tests passed without touching them, but it might be prudent to just wrap them in a 'list' call to be safe for people expecting a list. ................ r53852 | brett.cannon | 2007-02-22 05:45:13 +0100 (Thu, 22 Feb 2007) | 7 lines Fix test_iterlen by returning the iterator of dict views. Problem is that iteritems and itervalues' previous object were both an iterator *and* and iterable. The tests expected an iterator but were given an iterable. Should the 2to3 conversion for iter(values|items|keys) change the code to ``iter(dict.keys())`` to be more compatible? ................ r53853 | brett.cannon | 2007-02-22 05:49:03 +0100 (Thu, 22 Feb 2007) | 2 lines Fix test_iter after the dict views conversion. ................ r53854 | brett.cannon | 2007-02-22 05:50:21 +0100 (Thu, 22 Feb 2007) | 2 lines Fix test_importhooks for dict views. ................ r53855 | brett.cannon | 2007-02-22 06:04:32 +0100 (Thu, 22 Feb 2007) | 3 lines Fix dumbdbm and test_dumbdbm to work with dict views. Bug in dumbdbm was from dict views not being iterators but just iterables. ................ r53856 | brett.cannon | 2007-02-22 06:05:21 +0100 (Thu, 22 Feb 2007) | 2 lines Remove test_dumbdbm as failing. ................ r53857 | brett.cannon | 2007-02-22 07:12:19 +0100 (Thu, 22 Feb 2007) | 3 lines Fix obvious problems from switch to dict views. Some tests still fail over some reference count issue (I think). ................ r53858 | brett.cannon | 2007-02-22 07:40:59 +0100 (Thu, 22 Feb 2007) | 2 lines Fix test_bsddb3 (along with something bsddb) to work with dict views. ................ r53859 | guido.van.rossum | 2007-02-23 00:55:25 +0100 (Fri, 23 Feb 2007) | 5 lines Fix the last two tests. Thanks to Brett for fixing so many before! I see some tracebacks from threads when testing test_bsddbd3 (on OSX) but the test claims to pass, so I'm ignoring these. ................ r53866 | thomas.wouters | 2007-02-23 16:07:44 +0100 (Fri, 23 Feb 2007) | 294 lines Merged revisions 53623-53858 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53624 | peter.astrand | 2007-02-02 20:06:36 +0100 (Fri, 02 Feb 2007) | 1 line We had several if statements checking the value of a fd. This is unsafe, since valid fds might be zero. We should check for not None instead. ........ r53635 | kurt.kaiser | 2007-02-05 07:03:18 +0100 (Mon, 05 Feb 2007) | 2 lines Add 'raw' support to configHandler. Patch 1650174 Tal Einat. ........ r53641 | kurt.kaiser | 2007-02-06 00:02:16 +0100 (Tue, 06 Feb 2007) | 5 lines 1. Calltips now 'handle' tuples in the argument list (display '' :) Suggested solution by Christos Georgiou, Bug 791968. 2. Clean up tests, were not failing when they should have been. 4. Remove some camelcase and an unneeded try/except block. ........ r53644 | kurt.kaiser | 2007-02-06 04:21:40 +0100 (Tue, 06 Feb 2007) | 2 lines Clean up ModifiedInterpreter.runcode() structure ........ r53646 | peter.astrand | 2007-02-06 16:37:50 +0100 (Tue, 06 Feb 2007) | 1 line Applied patch 1124861.3.patch to solve bug #1124861: Automatically create pipes on Windows, if GetStdHandle fails. Will backport. ........ r53648 | lars.gustaebel | 2007-02-06 19:38:13 +0100 (Tue, 06 Feb 2007) | 4 lines Patch #1652681: create nonexistent files in append mode and allow appending to empty files. ........ r53649 | kurt.kaiser | 2007-02-06 20:09:43 +0100 (Tue, 06 Feb 2007) | 4 lines Updated patch (CodeContext.061217.patch) to [ 1362975 ] CodeContext - Improved text indentation Tal Einat 16Dec06 ........ r53650 | kurt.kaiser | 2007-02-06 20:21:19 +0100 (Tue, 06 Feb 2007) | 2 lines narrow exception per [ 1540849 ] except too broad ........ r53653 | kurt.kaiser | 2007-02-07 04:39:41 +0100 (Wed, 07 Feb 2007) | 4 lines [ 1621265 ] Auto-completion list placement Move AC window below input line unless not enough space, then put it above. Patch: Tal Einat ........ r53654 | kurt.kaiser | 2007-02-07 09:07:13 +0100 (Wed, 07 Feb 2007) | 2 lines Handle AttributeError during calltip lookup ........ r53656 | raymond.hettinger | 2007-02-07 21:08:22 +0100 (Wed, 07 Feb 2007) | 3 lines SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses ........ r53658 | raymond.hettinger | 2007-02-07 22:04:20 +0100 (Wed, 07 Feb 2007) | 1 line SF: 1397711 Set docs conflated immutable and hashable ........ r53660 | raymond.hettinger | 2007-02-07 22:42:17 +0100 (Wed, 07 Feb 2007) | 1 line Check for a common user error with defaultdict(). ........ r53662 | raymond.hettinger | 2007-02-07 23:24:07 +0100 (Wed, 07 Feb 2007) | 1 line Bug #1575169: operator.isSequenceType() now returns False for subclasses of dict. ........ r53664 | raymond.hettinger | 2007-02-08 00:49:03 +0100 (Thu, 08 Feb 2007) | 1 line Silence compiler warning ........ r53666 | raymond.hettinger | 2007-02-08 01:07:32 +0100 (Thu, 08 Feb 2007) | 1 line Do not let overflows in enumerate() and count() pass silently. ........ r53668 | raymond.hettinger | 2007-02-08 01:50:39 +0100 (Thu, 08 Feb 2007) | 1 line Bypass set specific optimizations for set and frozenset subclasses. ........ r53670 | raymond.hettinger | 2007-02-08 02:42:35 +0100 (Thu, 08 Feb 2007) | 1 line Fix docstring bug ........ r53671 | martin.v.loewis | 2007-02-08 10:13:36 +0100 (Thu, 08 Feb 2007) | 3 lines Bug #1653736: Complain about keyword arguments to time.isoformat. Will backport to 2.5. ........ r53679 | kurt.kaiser | 2007-02-08 23:58:18 +0100 (Thu, 08 Feb 2007) | 6 lines Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented; mouse and cursor selection in ACWindow implemented; double Tab inserts current selection and closes ACW (similar to double-click and Return); scroll wheel now works in ACW. Added AutoComplete instructions to IDLE Help. ........ r53689 | martin.v.loewis | 2007-02-09 13:19:32 +0100 (Fri, 09 Feb 2007) | 3 lines Bug #1653736: Properly discard third argument to slot_nb_inplace_power. Will backport. ........ r53691 | martin.v.loewis | 2007-02-09 13:36:48 +0100 (Fri, 09 Feb 2007) | 4 lines Bug #1600860: Search for shared python library in LIBDIR, not lib/python/config, on "linux" and "gnu" systems. Will backport. ........ r53693 | martin.v.loewis | 2007-02-09 13:58:49 +0100 (Fri, 09 Feb 2007) | 2 lines Update broken link. Will backport to 2.5. ........ r53697 | georg.brandl | 2007-02-09 19:48:41 +0100 (Fri, 09 Feb 2007) | 2 lines Bug #1656078: typo in in profile docs. ........ r53731 | brett.cannon | 2007-02-11 06:36:00 +0100 (Sun, 11 Feb 2007) | 3 lines Change a very minor inconsistency (that is purely cosmetic) in the AST definition. ........ r53735 | skip.montanaro | 2007-02-11 19:24:37 +0100 (Sun, 11 Feb 2007) | 1 line fix trace.py --ignore-dir ........ r53741 | brett.cannon | 2007-02-11 20:44:41 +0100 (Sun, 11 Feb 2007) | 3 lines Check in changed Python-ast.c from a cosmetic change to Python.asdl (in r53731). ........ r53751 | brett.cannon | 2007-02-12 04:51:02 +0100 (Mon, 12 Feb 2007) | 5 lines Modify Parser/asdl_c.py so that the __version__ number for Python/Python-ast.c is specified at the top of the file. Also add a note that Python/Python-ast.c needs to be committed separately after a change to the AST grammar to capture the revision number of the change (which is what __version__ is set to). ........ r53752 | lars.gustaebel | 2007-02-12 10:25:53 +0100 (Mon, 12 Feb 2007) | 3 lines Bug #1656581: Point out that external file objects are supposed to be at position 0. ........ r53754 | martin.v.loewis | 2007-02-12 13:21:10 +0100 (Mon, 12 Feb 2007) | 3 lines Patch 1463026: Support default namespace in XMLGenerator. Fixes #847665. Will backport. ........ r53757 | armin.rigo | 2007-02-12 17:23:24 +0100 (Mon, 12 Feb 2007) | 4 lines Fix the line to what is my guess at the original author's meaning. (The line has no effect anyway, but is present because it's customary call the base class __init__). ........ r53763 | martin.v.loewis | 2007-02-13 09:34:45 +0100 (Tue, 13 Feb 2007) | 3 lines Patch #685268: Consider a package's __path__ in imputil. Will backport. ........ r53765 | martin.v.loewis | 2007-02-13 10:49:38 +0100 (Tue, 13 Feb 2007) | 2 lines Patch #698833: Support file decryption in zipfile. ........ r53766 | martin.v.loewis | 2007-02-13 11:10:39 +0100 (Tue, 13 Feb 2007) | 3 lines Patch #1517891: Make 'a' create the file if it doesn't exist. Fixes #1514451. ........ r53767 | martin.v.loewis | 2007-02-13 13:08:24 +0100 (Tue, 13 Feb 2007) | 3 lines Bug #1658794: Remove extraneous 'this'. Will backport to 2.5. ........ r53769 | martin.v.loewis | 2007-02-13 13:14:19 +0100 (Tue, 13 Feb 2007) | 3 lines Patch #1657276: Make NETLINK_DNRTMSG conditional. Will backport. ........ r53771 | lars.gustaebel | 2007-02-13 17:09:24 +0100 (Tue, 13 Feb 2007) | 4 lines Patch #1647484: Renamed GzipFile's filename attribute to name. The filename attribute is still accessible as a property that emits a DeprecationWarning. ........ r53772 | lars.gustaebel | 2007-02-13 17:24:00 +0100 (Tue, 13 Feb 2007) | 3 lines Strip the '.gz' extension from the filename that is written to the gzip header. ........ r53774 | martin.v.loewis | 2007-02-14 11:07:37 +0100 (Wed, 14 Feb 2007) | 2 lines Patch #1432399: Add HCI sockets. ........ r53775 | martin.v.loewis | 2007-02-14 12:30:07 +0100 (Wed, 14 Feb 2007) | 2 lines Update 1432399 to removal of _BT_SOCKADDR_MEMB. ........ r53776 | martin.v.loewis | 2007-02-14 12:30:56 +0100 (Wed, 14 Feb 2007) | 3 lines Ignore directory time stamps when considering whether to rerun libffi configure. ........ r53778 | lars.gustaebel | 2007-02-14 15:45:12 +0100 (Wed, 14 Feb 2007) | 4 lines A missing binary mode in AppendTest caused failures in Windows Buildbot. ........ r53782 | martin.v.loewis | 2007-02-15 10:51:35 +0100 (Thu, 15 Feb 2007) | 2 lines Patch #1397848: add the reasoning behind no-resize-on-shrinkage. ........ r53783 | georg.brandl | 2007-02-15 11:37:59 +0100 (Thu, 15 Feb 2007) | 2 lines Make functools.wraps() docs a bit clearer. ........ r53785 | georg.brandl | 2007-02-15 12:29:04 +0100 (Thu, 15 Feb 2007) | 2 lines Patch #1494140: Add documentation for the new struct.Struct object. ........ r53787 | georg.brandl | 2007-02-15 12:29:55 +0100 (Thu, 15 Feb 2007) | 2 lines Add missing \versionadded. ........ r53800 | brett.cannon | 2007-02-15 23:54:39 +0100 (Thu, 15 Feb 2007) | 11 lines Update the encoding package's search function to use absolute imports when calling __import__. This helps make the expected search locations for encoding modules be more explicit. One could use an explicit value for __path__ when making the call to __import__ to force the exact location searched for encodings. This would give the most strict search path possible if one is worried about malicious code being imported. The unfortunate side-effect of that is that if __path__ was modified on 'encodings' on purpose in a safe way it would not be picked up in future __import__ calls. ........ r53801 | brett.cannon | 2007-02-16 20:33:01 +0100 (Fri, 16 Feb 2007) | 2 lines Make the __import__ call in encodings.__init__ absolute with a level 0 call. ........ r53809 | vinay.sajip | 2007-02-16 23:36:24 +0100 (Fri, 16 Feb 2007) | 1 line Minor fix for currentframe (SF #1652788). ........ r53818 | raymond.hettinger | 2007-02-19 03:03:19 +0100 (Mon, 19 Feb 2007) | 3 lines Extend work on revision 52962: Eliminate redundant calls to PyObject_Hash(). ........ r53820 | raymond.hettinger | 2007-02-19 05:08:43 +0100 (Mon, 19 Feb 2007) | 1 line Add merge() function to heapq. ........ r53821 | raymond.hettinger | 2007-02-19 06:28:28 +0100 (Mon, 19 Feb 2007) | 1 line Add tie-breaker count to preserve sort stability. ........ r53822 | raymond.hettinger | 2007-02-19 07:59:32 +0100 (Mon, 19 Feb 2007) | 1 line Use C heapreplace() instead of slower _siftup() in pure python. ........ r53823 | raymond.hettinger | 2007-02-19 08:30:21 +0100 (Mon, 19 Feb 2007) | 1 line Add test for merge stability ........ r53824 | raymond.hettinger | 2007-02-19 10:14:10 +0100 (Mon, 19 Feb 2007) | 1 line Provide an example of defaultdict with non-zero constant factory function. ........ r53825 | lars.gustaebel | 2007-02-19 10:54:47 +0100 (Mon, 19 Feb 2007) | 2 lines Moved misplaced news item. ........ r53826 | martin.v.loewis | 2007-02-19 11:55:19 +0100 (Mon, 19 Feb 2007) | 3 lines Patch #1490190: posixmodule now includes os.chflags() and os.lchflags() functions on platforms where the underlying system calls are available. ........ r53827 | raymond.hettinger | 2007-02-19 19:15:04 +0100 (Mon, 19 Feb 2007) | 1 line Fixup docstrings for merge(). ........ r53829 | raymond.hettinger | 2007-02-19 21:44:04 +0100 (Mon, 19 Feb 2007) | 1 line Fixup set/dict interoperability. ........ r53837 | raymond.hettinger | 2007-02-21 06:20:38 +0100 (Wed, 21 Feb 2007) | 1 line Add itertools.izip_longest(). ........ r53838 | raymond.hettinger | 2007-02-21 18:22:05 +0100 (Wed, 21 Feb 2007) | 1 line Remove filler struct item and fix leak. ........ ................ Added: python/branches/p3yk-noslice/BROKEN ============================================================================== --- (empty file) +++ python/branches/p3yk-noslice/BROKEN Fri Feb 23 18:29:35 2007 @@ -0,0 +1 @@ + test_exceptions (needs slice object support) Modified: python/branches/p3yk-noslice/Doc/api/concrete.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/api/concrete.tex (original) +++ python/branches/p3yk-noslice/Doc/api/concrete.tex Fri Feb 23 18:29:35 2007 @@ -2082,7 +2082,7 @@ \begin{verbatim} PyObject *key, *value; -int pos = 0; +Py_ssize_t pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { /* do something interesting with the values... */ @@ -2097,7 +2097,7 @@ \begin{verbatim} PyObject *key, *value; -int pos = 0; +Py_ssize_t pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { int i = PyInt_AS_LONG(value) + 1; Modified: python/branches/p3yk-noslice/Doc/commontex/license.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/commontex/license.tex (original) +++ python/branches/p3yk-noslice/Doc/commontex/license.tex Fri Feb 23 18:29:35 2007 @@ -50,6 +50,7 @@ \linev{2.4.1}{2.4}{2005}{PSF}{yes} \linev{2.4.2}{2.4.1}{2005}{PSF}{yes} \linev{2.4.3}{2.4.2}{2006}{PSF}{yes} + \linev{2.4.4}{2.4.3}{2006}{PSF}{yes} \linev{2.5}{2.4}{2006}{PSF}{yes} \end{tablev} Modified: python/branches/p3yk-noslice/Doc/dist/dist.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/dist/dist.tex (original) +++ python/branches/p3yk-noslice/Doc/dist/dist.tex Fri Feb 23 18:29:35 2007 @@ -692,7 +692,7 @@ \begin{tableii}{l|l}{code}{Provides Expression}{Explanation} \lineii{mypkg} {Provide \code{mypkg}, using the distribution version} - \lineii{mypkg (1.1} {Provide \code{mypkg} version 1.1, regardless of the + \lineii{mypkg (1.1)} {Provide \code{mypkg} version 1.1, regardless of the distribution version} \end{tableii} Modified: python/branches/p3yk-noslice/Doc/howto/TODO ============================================================================== --- python/branches/p3yk-noslice/Doc/howto/TODO (original) +++ python/branches/p3yk-noslice/Doc/howto/TODO Fri Feb 23 18:29:35 2007 @@ -1,7 +1,7 @@ Short-term tasks: - Quick revision pass to make HOWTOs match the current state of Python: -curses doanddont regex sockets sorting + Quick revision pass to make HOWTOs match the current state of Python +doanddont regex sockets Medium-term tasks: Revisit the regex howto. Modified: python/branches/p3yk-noslice/Doc/howto/curses.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/howto/curses.tex (original) +++ python/branches/p3yk-noslice/Doc/howto/curses.tex Fri Feb 23 18:29:35 2007 @@ -2,7 +2,7 @@ \title{Curses Programming with Python} -\release{2.01} +\release{2.02} \author{A.M. Kuchling, Eric S. Raymond} \authoraddress{\email{amk at amk.ca}, \email{esr at thyrsus.com}} @@ -147,10 +147,10 @@ In Python you can avoid these complications and make debugging much easier by importing the module \module{curses.wrapper}. It supplies a -function \function{wrapper} that takes a hook argument. It does the +\function{wrapper()} function that takes a callable. It does the initializations described above, and also initializes colors if color -support is present. It then runs your hook, and then finally -deinitializes appropriately. The hook is called inside a try-catch +support is present. It then runs your provided callable and finally +deinitializes appropriately. The callable is called inside a try-catch clause which catches exceptions, performs curses deinitialization, and then passes the exception upwards. Thus, your terminal won't be left in a funny state on exception. @@ -159,7 +159,7 @@ Windows are the basic abstraction in curses. A window object represents a rectangular area of the screen, and supports various - methods to display text, erase it, allow the user to input strings, +methods to display text, erase it, allow the user to input strings, and so forth. The \code{stdscr} object returned by the \function{initscr()} function @@ -223,14 +223,14 @@ The \function{refresh()} call displays a section of the pad in the rectangle extending from coordinate (5,5) to coordinate (20,75) on the -screen;the upper left corner of the displayed section is coordinate +screen; the upper left corner of the displayed section is coordinate (0,0) on the pad. Beyond that difference, pads are exactly like ordinary windows and support the same methods. If you have multiple windows and pads on screen there is a more efficient way to go, which will prevent annoying screen flicker at -refresh time. Use the methods \method{noutrefresh()} and/or -\method{noutrefresh()} of each window to update the data structure +refresh time. Use the \method{noutrefresh()} method +of each window to update the data structure representing the desired state of the screen; then change the physical screen to match the desired state in one go with the function \function{doupdate()}. The normal \method{refresh()} method calls @@ -254,9 +254,9 @@ \begin{tableii}{|c|l|}{textrm}{Form}{Description} \lineii{\var{str} or \var{ch}}{Display the string \var{str} or -character \var{ch}} +character \var{ch} at the current position} \lineii{\var{str} or \var{ch}, \var{attr}}{Display the string \var{str} or -character \var{ch}, using attribute \var{attr}} +character \var{ch}, using attribute \var{attr} at the current position} \lineii{\var{y}, \var{x}, \var{str} or \var{ch}} {Move to position \var{y,x} within the window, and display \var{str} or \var{ch}} @@ -271,7 +271,7 @@ The \function{addstr()} function takes a Python string as the value to be displayed, while the \function{addch()} functions take a character, -which can be either a Python string of length 1, or an integer. If +which can be either a Python string of length 1 or an integer. If it's a string, you're limited to displaying characters between 0 and 255. SVr4 curses provides constants for extension characters; these constants are integers greater than 255. For example, @@ -331,15 +331,15 @@ provide it, The most common such terminal is probably the Linux console, followed by color xterms. -To use color, you must call the \function{start_color()} function -soon after calling \function{initscr()}, to initialize the default -color set (the \function{curses.wrapper.wrapper()} function does this +To use color, you must call the \function{start_color()} function soon +after calling \function{initscr()}, to initialize the default color +set (the \function{curses.wrapper.wrapper()} function does this automatically). Once that's done, the \function{has_colors()} function returns TRUE if the terminal in use can actually display -color. (Note from AMK: curses uses the American spelling -'color', instead of the Canadian/British spelling 'colour'. If you're -like me, you'll have to resign yourself to misspelling it for the sake -of these functions.) +color. (Note: curses uses the American spelling 'color', instead of +the Canadian/British spelling 'colour'. If you're used to the British +spelling, you'll have to resign yourself to misspelling it for the +sake of these functions.) The curses library maintains a finite number of color pairs, containing a foreground (or text) color and a background color. You @@ -400,18 +400,19 @@ lack. The most common way to get input to a window is to use its -\method{getch()} method. that pauses, and waits for the user to hit -a key, displaying it if \function{echo()} has been called earlier. -You can optionally specify a coordinate to which the cursor should be -moved before pausing. +\method{getch()} method. \method{getch()} pauses and waits for the +user to hit a key, displaying it if \function{echo()} has been called +earlier. You can optionally specify a coordinate to which the cursor +should be moved before pausing. It's possible to change this behavior with the method \method{nodelay()}. After \method{nodelay(1)}, \method{getch()} for -the window becomes non-blocking and returns ERR (-1) when no input is -ready. There's also a \function{halfdelay()} function, which can be -used to (in effect) set a timer on each \method{getch()}; if no input -becomes available within the number of milliseconds specified as the -argument to \function{halfdelay()}, curses throws an exception. +the window becomes non-blocking and returns \code{curses.ERR} (a value +of -1) when no input is ready. There's also a \function{halfdelay()} +function, which can be used to (in effect) set a timer on each +\method{getch()}; if no input becomes available within the number of +milliseconds specified as the argument to \function{halfdelay()}, +curses raises an exception. The \method{getch()} method returns an integer; if it's between 0 and 255, it represents the ASCII code of the key pressed. Values greater Modified: python/branches/p3yk-noslice/Doc/howto/doanddont.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/howto/doanddont.tex (original) +++ python/branches/p3yk-noslice/Doc/howto/doanddont.tex Fri Feb 23 18:29:35 2007 @@ -32,7 +32,7 @@ \subsubsection{Inside Function Definitions} \code{from module import *} is {\em invalid} inside function definitions. -While many versions of Python do no check for the invalidity, it does not +While many versions of Python do not check for the invalidity, it does not make it more valid, no more then having a smart lawyer makes a man innocent. Do not use it like that ever. Even in versions where it was accepted, it made the function execution slower, because the compiler could not be certain Modified: python/branches/p3yk-noslice/Doc/howto/regex.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/howto/regex.tex (original) +++ python/branches/p3yk-noslice/Doc/howto/regex.tex Fri Feb 23 18:29:35 2007 @@ -34,17 +34,18 @@ The \module{re} module was added in Python 1.5, and provides Perl-style regular expression patterns. Earlier versions of Python came with the \module{regex} module, which provided Emacs-style -patterns. \module{regex} module was removed in Python 2.5. +patterns. The \module{regex} module was removed completely in Python 2.5. -Regular expressions (or REs) are essentially a tiny, highly -specialized programming language embedded inside Python and made -available through the \module{re} module. Using this little language, -you specify the rules for the set of possible strings that you want to -match; this set might contain English sentences, or e-mail addresses, -or TeX commands, or anything you like. You can then ask questions -such as ``Does this string match the pattern?'', or ``Is there a match -for the pattern anywhere in this string?''. You can also use REs to -modify a string or to split it apart in various ways. +Regular expressions (called REs, or regexes, or regex patterns) are +essentially a tiny, highly specialized programming language embedded +inside Python and made available through the \module{re} module. +Using this little language, you specify the rules for the set of +possible strings that you want to match; this set might contain +English sentences, or e-mail addresses, or TeX commands, or anything +you like. You can then ask questions such as ``Does this string match +the pattern?'', or ``Is there a match for the pattern anywhere in this +string?''. You can also use REs to modify a string or to split it +apart in various ways. Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For @@ -80,11 +81,12 @@ would let this RE match \samp{Test} or \samp{TEST} as well; more about this later.) -There are exceptions to this rule; some characters are -special, and don't match themselves. Instead, they signal that some -out-of-the-ordinary thing should be matched, or they affect other -portions of the RE by repeating them. Much of this document is -devoted to discussing various metacharacters and what they do. +There are exceptions to this rule; some characters are special +\dfn{metacharacters}, and don't match themselves. Instead, they +signal that some out-of-the-ordinary thing should be matched, or they +affect other portions of the RE by repeating them or changing their +meaning. Much of this document is devoted to discussing various +metacharacters and what they do. Here's a complete list of the metacharacters; their meanings will be discussed in the rest of this HOWTO. @@ -111,9 +113,10 @@ usually a metacharacter, but inside a character class it's stripped of its special nature. -You can match the characters not within a range by \dfn{complementing} -the set. This is indicated by including a \character{\^} as the first -character of the class; \character{\^} elsewhere will simply match the +You can match the characters not listed within the class by +\dfn{complementing} the set. This is indicated by including a +\character{\^} as the first character of the class; \character{\^} +outside a character class will simply match the \character{\^} character. For example, \verb|[^5]| will match any character except \character{5}. @@ -176,7 +179,7 @@ For example, \regexp{ca*t} will match \samp{ct} (0 \samp{a} characters), \samp{cat} (1 \samp{a}), \samp{caaat} (3 \samp{a} characters), and so forth. The RE engine has various internal -limitations stemming from the size of C's \code{int} type, that will +limitations stemming from the size of C's \code{int} type that will prevent it from matching over 2 billion \samp{a} characters; you probably don't have enough memory to construct a string that large, so you shouldn't run into that limit. @@ -238,9 +241,9 @@ You can omit either \var{m} or \var{n}; in that case, a reasonable value is assumed for the missing value. Omitting \var{m} is -interpreted as a lower limit of 0, while omitting \var{n} results in an -upper bound of infinity --- actually, the 2 billion limit mentioned -earlier, but that might as well be infinity. +interpreted as a lower limit of 0, while omitting \var{n} results in +an upper bound of infinity --- actually, the upper bound is the +2-billion limit mentioned earlier, but that might as well be infinity. Readers of a reductionist bent may notice that the three other qualifiers can all be expressed using this notation. \regexp{\{0,\}} is the same @@ -285,7 +288,7 @@ no need to bloat the language specification by including them.) Instead, the \module{re} module is simply a C extension module included with Python, just like the \module{socket} or \module{zlib} -module. +modules. Putting REs in strings keeps the Python language simpler, but has one disadvantage which is the topic of the next section. @@ -326,7 +329,7 @@ a string literal prefixed with \character{r}, so \code{r"\e n"} is a two-character string containing \character{\e} and \character{n}, while \code{"\e n"} is a one-character string containing a newline. -Frequently regular expressions will be expressed in Python +Regular expressions will often be written in Python code using this raw string notation. \begin{tableii}{c|c}{code}{Regular String}{Raw string} @@ -368,9 +371,9 @@ \file{redemo.py} can be quite useful when trying to debug a complicated RE. Phil Schwartz's \ulink{Kodos}{http://www.phil-schwartz.com/kodos.spy} is also an interactive -tool for developing and testing RE patterns. This HOWTO will use the -standard Python interpreter for its examples. +tool for developing and testing RE patterns. +This HOWTO uses the standard Python interpreter for its examples. First, run the Python interpreter, import the \module{re} module, and compile a RE: @@ -401,7 +404,7 @@ later use. \begin{verbatim} ->>> m = p.match( 'tempo') +>>> m = p.match('tempo') >>> print m <_sre.SRE_Match object at 80c4f68> \end{verbatim} @@ -472,9 +475,9 @@ \end{verbatim} \method{findall()} has to create the entire list before it can be -returned as the result. In Python 2.2, the \method{finditer()} method -is also available, returning a sequence of \class{MatchObject} instances -as an iterator. +returned as the result. The \method{finditer()} method returns a +sequence of \class{MatchObject} instances as an +iterator.\footnote{Introduced in Python 2.2.2.} \begin{verbatim} >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...') @@ -491,13 +494,13 @@ \subsection{Module-Level Functions} -You don't have to produce a \class{RegexObject} and call its methods; +You don't have to create a \class{RegexObject} and call its methods; the \module{re} module also provides top-level functions called -\function{match()}, \function{search()}, \function{sub()}, and so -forth. These functions take the same arguments as the corresponding -\class{RegexObject} method, with the RE string added as the first -argument, and still return either \code{None} or a \class{MatchObject} -instance. +\function{match()}, \function{search()}, \function{findall()}, +\function{sub()}, and so forth. These functions take the same +arguments as the corresponding \class{RegexObject} method, with the RE +string added as the first argument, and still return either +\code{None} or a \class{MatchObject} instance. \begin{verbatim} >>> print re.match(r'From\s+', 'Fromage amk') @@ -514,7 +517,7 @@ Should you use these module-level functions, or should you get the \class{RegexObject} and call its methods yourself? That choice depends on how frequently the RE will be used, and on your personal -coding style. If a RE is being used at only one point in the code, +coding style. If the RE is being used at only one point in the code, then the module functions are probably more convenient. If a program contains a lot of regular expressions, or re-uses the same ones in several locations, then it might be worthwhile to collect all the @@ -537,7 +540,7 @@ Compilation flags let you modify some aspects of how regular expressions work. Flags are available in the \module{re} module under -two names, a long name such as \constant{IGNORECASE}, and a short, +two names, a long name such as \constant{IGNORECASE} and a short, one-letter form such as \constant{I}. (If you're familiar with Perl's pattern modifiers, the one-letter forms use the same letters; the short form of \constant{re.VERBOSE} is \constant{re.X}, for example.) @@ -617,7 +620,7 @@ format them. When this flag has been specified, whitespace within the RE string is ignored, except when the whitespace is in a character class or preceded by an unescaped backslash; this lets you organize -and indent the RE more clearly. It also enables you to put comments +and indent the RE more clearly. This flag also lets you put comments within a RE that will be ignored by the engine; comments are marked by a \character{\#} that's neither in a character class or preceded by an unescaped backslash. @@ -629,18 +632,19 @@ charref = re.compile(r""" &[#] # Start of a numeric entity reference ( - [0-9]+[^0-9] # Decimal form - | 0[0-7]+[^0-7] # Octal form - | x[0-9a-fA-F]+[^0-9a-fA-F] # Hexadecimal form + 0[0-7]+ # Octal form + | [0-9]+ # Decimal form + | x[0-9a-fA-F]+ # Hexadecimal form ) + ; # Trailing semicolon """, re.VERBOSE) \end{verbatim} Without the verbose setting, the RE would look like this: \begin{verbatim} -charref = re.compile("&#([0-9]+[^0-9]" - "|0[0-7]+[^0-7]" - "|x[0-9a-fA-F]+[^0-9a-fA-F])") +charref = re.compile("&#(0[0-7]+" + "|[0-9]+" + "|x[0-9a-fA-F]+);") \end{verbatim} In the above example, Python's automatic concatenation of string @@ -722,12 +726,12 @@ \item[\regexp{\e A}] Matches only at the start of the string. When not in \constant{MULTILINE} mode, \regexp{\e A} and \regexp{\^} are -effectively the same. In \constant{MULTILINE} mode, however, they're -different; \regexp{\e A} still matches only at the beginning of the +effectively the same. In \constant{MULTILINE} mode, they're +different: \regexp{\e A} still matches only at the beginning of the string, but \regexp{\^} may match at any location inside the string that follows a newline character. -\item[\regexp{\e Z}]Matches only at the end of the string. +\item[\regexp{\e Z}] Matches only at the end of the string. \item[\regexp{\e b}] Word boundary. This is a zero-width assertion that matches only at the @@ -782,14 +786,23 @@ strings by writing a RE divided into several subgroups which match different components of interest. For example, an RFC-822 header line is divided into a header name and a value, separated by a -\character{:}. This can be handled by writing a regular expression +\character{:}, like this: + +\begin{verbatim} +From: author at example.com +User-Agent: Thunderbird 1.5.0.9 (X11/20061227) +MIME-Version: 1.0 +To: editor at example.com +\end{verbatim} + +This can be handled by writing a regular expression which matches an entire header line, and has one group which matches the header name, and another group which matches the header's value. Groups are marked by the \character{(}, \character{)} metacharacters. \character{(} and \character{)} have much the same meaning as they do in mathematical expressions; they group together the expressions -contained inside them. For example, you can repeat the contents of a +contained inside them, and you can repeat the contents of a group with a repeating qualifier, such as \regexp{*}, \regexp{+}, \regexp{?}, or \regexp{\{\var{m},\var{n}\}}. For example, \regexp{(ab)*} will match zero or more repetitions of \samp{ab}. @@ -881,12 +894,13 @@ syntax for regular expression extensions, so we'll look at that first. Perl 5 added several additional features to standard regular -expressions, and the Python \module{re} module supports most of them. -It would have been difficult to choose new single-keystroke -metacharacters or new special sequences beginning with \samp{\e} to -represent the new features without making Perl's regular expressions -confusingly different from standard REs. If you chose \samp{\&} as a -new metacharacter, for example, old expressions would be assuming that +expressions, and the Python \module{re} module supports most of them. +It would have been difficult to choose new +single-keystroke metacharacters or new special sequences beginning +with \samp{\e} to represent the new features without making Perl's +regular expressions confusingly different from standard REs. If you +chose \samp{\&} as a new metacharacter, for example, old expressions +would be assuming that \samp{\&} was a regular character and wouldn't have escaped it by writing \regexp{\e \&} or \regexp{[\&]}. @@ -913,15 +927,15 @@ to the features that simplify working with groups in complex REs. Since groups are numbered from left to right and a complex expression may use many groups, it can become difficult to keep track of the -correct numbering, and modifying such a complex RE is annoying. -Insert a new group near the beginning, and you change the numbers of +correct numbering. Modifying such a complex RE is annoying, too: +insert a new group near the beginning and you change the numbers of everything that follows it. -First, sometimes you'll want to use a group to collect a part of a -regular expression, but aren't interested in retrieving the group's -contents. You can make this fact explicit by using a non-capturing -group: \regexp{(?:...)}, where you can put any other regular -expression inside the parentheses. +Sometimes you'll want to use a group to collect a part of a regular +expression, but aren't interested in retrieving the group's contents. +You can make this fact explicit by using a non-capturing group: +\regexp{(?:...)}, where you can replace the \regexp{...} +with any other regular expression. \begin{verbatim} >>> m = re.match("([abc])+", "abc") @@ -937,23 +951,23 @@ capturing group; you can put anything inside it, repeat it with a repetition metacharacter such as \samp{*}, and nest it within other groups (capturing or non-capturing). \regexp{(?:...)} is particularly -useful when modifying an existing group, since you can add new groups +useful when modifying an existing pattern, since you can add new groups without changing how all the other groups are numbered. It should be mentioned that there's no performance difference in searching between capturing and non-capturing groups; neither form is any faster than the other. -The second, and more significant, feature is named groups; instead of +A more significant feature is named groups: instead of referring to them by numbers, groups can be referenced by a name. The syntax for a named group is one of the Python-specific extensions: \regexp{(?P<\var{name}>...)}. \var{name} is, obviously, the name of -the group. Except for associating a name with a group, named groups -also behave identically to capturing groups. The \class{MatchObject} -methods that deal with capturing groups all accept either integers, to -refer to groups by number, or a string containing the group name. -Named groups are still given numbers, so you can retrieve information -about a group in two ways: +the group. Named groups also behave exactly like capturing groups, +and additionally associate a name with a group. The +\class{MatchObject} methods that deal with capturing groups all accept +either integers that refer to the group by number or strings that +contain the desired group's name. Named groups are still given +numbers, so you can retrieve information about a group in two ways: \begin{verbatim} >>> p = re.compile(r'(?P\b\w+\b)') @@ -980,11 +994,11 @@ It's obviously much easier to retrieve \code{m.group('zonem')}, instead of having to remember to retrieve group 9. -Since the syntax for backreferences, in an expression like -\regexp{(...)\e 1}, refers to the number of the group there's +The syntax for backreferences in an expression such as +\regexp{(...)\e 1} refers to the number of the group. There's naturally a variant that uses the group name instead of the number. -This is also a Python extension: \regexp{(?P=\var{name})} indicates -that the contents of the group called \var{name} should again be found +This is another Python extension: \regexp{(?P=\var{name})} indicates +that the contents of the group called \var{name} should again be matched at the current point. The regular expression for finding doubled words, \regexp{(\e b\e w+)\e s+\e 1} can also be written as \regexp{(?P\e b\e w+)\e s+(?P=word)}: @@ -1014,11 +1028,11 @@ \emph{doesn't} match at the current position in the string. \end{itemize} -An example will help make this concrete by demonstrating a case -where a lookahead is useful. Consider a simple pattern to match a -filename and split it apart into a base name and an extension, -separated by a \samp{.}. For example, in \samp{news.rc}, \samp{news} -is the base name, and \samp{rc} is the filename's extension. +To make this concrete, let's look at a case where a lookahead is +useful. Consider a simple pattern to match a filename and split it +apart into a base name and an extension, separated by a \samp{.}. For +example, in \samp{news.rc}, \samp{news} is the base name, and +\samp{rc} is the filename's extension. The pattern to match this is quite simple: @@ -1065,12 +1079,12 @@ exclude both \samp{bat} and \samp{exe} as extensions, the pattern would get even more complicated and confusing. -A negative lookahead cuts through all this: +A negative lookahead cuts through all this confusion: \regexp{.*[.](?!bat\$).*\$} % $ -The lookahead means: if the expression \regexp{bat} doesn't match at +The negative lookahead means: if the expression \regexp{bat} doesn't match at this point, try the rest of the pattern; if \regexp{bat\$} does match, the whole pattern will fail. The trailing \regexp{\$} is required to ensure that something like \samp{sample.batch}, where the extension @@ -1087,7 +1101,7 @@ \section{Modifying Strings} Up to this point, we've simply performed searches against a static -string. Regular expressions are also commonly used to modify a string +string. Regular expressions are also commonly used to modify strings in various ways, using the following \class{RegexObject} methods: \begin{tableii}{c|l}{code}{Method/Attribute}{Purpose} Modified: python/branches/p3yk-noslice/Doc/lib/emailgenerator.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/emailgenerator.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/emailgenerator.tex Fri Feb 23 18:29:35 2007 @@ -33,7 +33,7 @@ line. This is the only guaranteed portable way to avoid having such lines be mistaken for a \UNIX{} mailbox format envelope header separator (see \ulink{WHY THE CONTENT-LENGTH FORMAT IS BAD} -{http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html} +{http://www.jwz.org/doc/content-length.html} for details). \var{mangle_from_} defaults to \code{True}, but you might want to set this to \code{False} if you are not writing \UNIX{} mailbox format files. Modified: python/branches/p3yk-noslice/Doc/lib/libcollections.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libcollections.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libcollections.tex Fri Feb 23 18:29:35 2007 @@ -311,16 +311,20 @@ When a letter is first encountered, it is missing from the mapping, so the \member{default_factory} function calls \function{int()} to supply a default count of zero. The increment operation then builds up the count for each -letter. This technique makes counting simpler and faster than an equivalent -technique using \method{dict.get()}: +letter. -\begin{verbatim} ->>> d = {} ->>> for k in s: - d[k] = d.get(k, 0) + 1 +The function \function{int()} which always returns zero is just a special +case of constant functions. A faster and more flexible way to create +constant functions is to use \function{itertools.repeat()} which can supply +any constant value (not just zero): ->>> d.items() -[('i', 4), ('p', 2), ('s', 4), ('m', 1)] +\begin{verbatim} +>>> def constant_factory(value): +... return itertools.repeat(value).next +>>> d = defaultdict(constant_factory('')) +>>> d.update(name='John', action='ran') +>>> '%(name)s %(action)s to %(object)s' % d +'John ran to ' \end{verbatim} Setting the \member{default_factory} to \class{set} makes the Modified: python/branches/p3yk-noslice/Doc/lib/libdis.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libdis.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libdis.tex Fri Feb 23 18:29:35 2007 @@ -300,27 +300,6 @@ expression statement is terminated with \code{POP_STACK}. \end{opcodedesc} -\begin{opcodedesc}{PRINT_ITEM}{} -Prints TOS to the file-like object bound to \code{sys.stdout}. There -is one such instruction for each item in the \keyword{print} statement. -\end{opcodedesc} - -\begin{opcodedesc}{PRINT_ITEM_TO}{} -Like \code{PRINT_ITEM}, but prints the item second from TOS to the -file-like object at TOS. This is used by the extended print statement. -\end{opcodedesc} - -\begin{opcodedesc}{PRINT_NEWLINE}{} -Prints a new line on \code{sys.stdout}. This is generated as the -last operation of a \keyword{print} statement, unless the statement -ends with a comma. -\end{opcodedesc} - -\begin{opcodedesc}{PRINT_NEWLINE_TO}{} -Like \code{PRINT_NEWLINE}, but prints the new line on the file-like -object on the TOS. This is used by the extended print statement. -\end{opcodedesc} - \begin{opcodedesc}{BREAK_LOOP}{} Terminates a loop due to a \keyword{break} statement. \end{opcodedesc} Modified: python/branches/p3yk-noslice/Doc/lib/libexcs.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libexcs.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libexcs.tex Fri Feb 23 18:29:35 2007 @@ -10,22 +10,6 @@ provided in the built-in namespace as well as the \module{exceptions} module. -\begin{notice} -In past versions of Python string exceptions were supported. In -Python 1.5 and newer versions, all standard exceptions have been -converted to class objects and users are encouraged to do the same. -String exceptions will raise a \code{DeprecationWarning} in Python 2.5 and -newer. -In future versions, support for string exceptions will be removed. - -Two distinct string objects with the same value are considered different -exceptions. This is done to force programmers to use exception names -rather than their string value when specifying exception handlers. -The string value of all built-in exceptions is their name, but this is -not a requirement for user-defined exceptions or exceptions defined by -library modules. -\end{notice} - For class exceptions, in a \keyword{try}\stindex{try} statement with an \keyword{except}\stindex{except} clause that mentions a particular class, that clause also handles any exception classes derived from Modified: python/branches/p3yk-noslice/Doc/lib/libfunctools.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libfunctools.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libfunctools.tex Fri Feb 23 18:29:35 2007 @@ -66,15 +66,16 @@ \begin{funcdesc}{update_wrapper} {wrapper, wrapped\optional{, assigned}\optional{, updated}} -Update a wrapper function to look like the wrapped function. The optional -arguments are tuples to specify which attributes of the original +Update a \var{wrapper} function to look like the \var{wrapped} function. +The optional arguments are tuples to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function and which attributes of the wrapper function are updated with the corresponding attributes from the original function. The default values for these arguments are the module level constants -\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's name, -module and documentation string) and \var{WRAPPER_UPDATES} (which -updates the wrapper function's instance dictionary). +\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's +\var{__name__}, \var{__module__} and \var{__doc__}, the documentation string) +and \var{WRAPPER_UPDATES} (which updates the wrapper function's \var{__dict__}, +i.e. the instance dictionary). The main intended use for this function is in decorator functions which wrap the decorated function and return the wrapper. If the @@ -98,6 +99,7 @@ ... >>> @my_decorator ... def example(): + ... """Docstring""" ... print 'Called example function' ... >>> example() @@ -105,9 +107,12 @@ Called example function >>> example.__name__ 'example' + >>> example.__doc__ + 'Docstring' \end{verbatim} Without the use of this decorator factory, the name of the example -function would have been \code{'wrapper'}. +function would have been \code{'wrapper'}, and the docstring of the +original \function{example()} would have been lost. \end{funcdesc} Modified: python/branches/p3yk-noslice/Doc/lib/libheapq.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libheapq.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libheapq.tex Fri Feb 23 18:29:35 2007 @@ -88,7 +88,18 @@ >>> \end{verbatim} -The module also offers two general purpose functions based on heaps. +The module also offers three general purpose functions based on heaps. + +\begin{funcdesc}{merge}{*iterables} +Merge multiple sorted inputs into a single sorted output (for example, merge +timestamped entries from multiple log files). Returns an iterator over +over the sorted values. + +Similar to \code{sorted(itertools.chain(*iterables))} but returns an iterable, +does not pull the data into memory all at once, and assumes that each of the +input streams is already sorted (smallest to largest). +\versionadded{2.6} +\end{funcdesc} \begin{funcdesc}{nlargest}{n, iterable\optional{, key}} Return a list with the \var{n} largest elements from the dataset defined @@ -110,7 +121,7 @@ \versionchanged[Added the optional \var{key} argument]{2.5} \end{funcdesc} -Both functions perform best for smaller values of \var{n}. For larger +The latter two functions perform best for smaller values of \var{n}. For larger values, it is more efficient to use the \function{sorted()} function. Also, when \code{n==1}, it is more efficient to use the builtin \function{min()} and \function{max()} functions. Modified: python/branches/p3yk-noslice/Doc/lib/libimageop.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libimageop.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libimageop.tex Fri Feb 23 18:29:35 2007 @@ -19,7 +19,7 @@ \begin{funcdesc}{crop}{image, psize, width, height, x0, y0, x1, y1} -Return the selected part of \var{image}, which should by +Return the selected part of \var{image}, which should be \var{width} by \var{height} in size and consist of pixels of \var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like the \function{gl.lrectread()} parameters, i.e.\ the boundary is Modified: python/branches/p3yk-noslice/Doc/lib/libitertools.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libitertools.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libitertools.tex Fri Feb 23 18:29:35 2007 @@ -302,6 +302,33 @@ don't care about trailing, unmatched values from the longer iterables. \end{funcdesc} +\begin{funcdesc}{izip_longest}{*iterables\optional{, fillvalue}} + Make an iterator that aggregates elements from each of the iterables. + If the iterables are of uneven length, missing values are filled-in + with \var{fillvalue}. Iteration continues until the longest iterable + is exhausted. Equivalent to: + + \begin{verbatim} + def izip_longest(*args, **kwds): + fillvalue = kwds.get('fillvalue') + def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): + yield counter() # yields the fillvalue, or raises IndexError + fillers = repeat(fillvalue) + iters = [chain(it, sentinel(), fillers) for it in args] + try: + for tup in izip(*iters): + yield tup + except IndexError: + pass + \end{verbatim} + + If one of the iterables is potentially infinite, then the + \function{izip_longest()} function should be wrapped with something + that limits the number of calls (for example \function{islice()} or + \function{take()}). + \versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{repeat}{object\optional{, times}} Make an iterator that returns \var{object} over and over again. Runs indefinitely unless the \var{times} argument is specified. Modified: python/branches/p3yk-noslice/Doc/lib/liblocale.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/liblocale.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/liblocale.tex Fri Feb 23 18:29:35 2007 @@ -481,7 +481,7 @@ locale settings. When a call to the \function{setlocale()} function changes the \constant{LC_CTYPE} settings, the variables \code{string.lowercase}, \code{string.uppercase} and -\code{string.letters} are recalculated. Note that this code that uses +\code{string.letters} are recalculated. Note that code that uses these variable through `\keyword{from} ... \keyword{import} ...', e.g.\ \code{from string import letters}, is not affected by subsequent \function{setlocale()} calls. Modified: python/branches/p3yk-noslice/Doc/lib/liblogging.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/liblogging.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/liblogging.tex Fri Feb 23 18:29:35 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-noslice/Doc/lib/libmailbox.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libmailbox.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libmailbox.tex Fri Feb 23 18:29:35 2007 @@ -25,22 +25,29 @@ A mailbox, which may be inspected and modified. \end{classdesc*} +The \class{Mailbox} class defines an interface and +is not intended to be instantiated. Instead, format-specific +subclasses should inherit from \class{Mailbox} and your code +should instantiate a particular subclass. + The \class{Mailbox} interface is dictionary-like, with small keys -corresponding to messages. Keys are issued by the \class{Mailbox} instance -with which they will be used and are only meaningful to that \class{Mailbox} -instance. A key continues to identify a message even if the corresponding -message is modified, such as by replacing it with another message. Messages may -be added to a \class{Mailbox} instance using the set-like method -\method{add()} and removed using a \code{del} statement or the set-like methods -\method{remove()} and \method{discard()}. +corresponding to messages. Keys are issued by the \class{Mailbox} +instance with which they will be used and are only meaningful to that +\class{Mailbox} instance. A key continues to identify a message even +if the corresponding message is modified, such as by replacing it with +another message. + +Messages may be added to a \class{Mailbox} instance using the set-like +method \method{add()} and removed using a \code{del} statement or the +set-like methods \method{remove()} and \method{discard()}. \class{Mailbox} interface semantics differ from dictionary semantics in some -noteworthy ways. Each time a message is requested, a new representation -(typically a \class{Message} instance) is generated, based upon the current -state of the mailbox. Similarly, when a message is added to a \class{Mailbox} -instance, the provided message representation's contents are copied. In neither -case is a reference to the message representation kept by the \class{Mailbox} -instance. +noteworthy ways. Each time a message is requested, a new +representation (typically a \class{Message} instance) is generated +based upon the current state of the mailbox. Similarly, when a message +is added to a \class{Mailbox} instance, the provided message +representation's contents are copied. In neither case is a reference +to the message representation kept by the \class{Mailbox} instance. The default \class{Mailbox} iterator iterates over message representations, not keys as the default dictionary iterator does. Moreover, modification of a @@ -51,9 +58,18 @@ \exception{KeyError} exception if the corresponding message is subsequently removed. -\class{Mailbox} itself is intended to define an interface and to be inherited -from by format-specific subclasses but is not intended to be instantiated. -Instead, you should instantiate a subclass. +\begin{notice}[warning] +Be very cautious when modifying mailboxes that might be +simultaneously changed by some other process. The safest mailbox +format to use for such tasks is Maildir; try to avoid using +single-file formats such as mbox for concurrent writing. If you're +modifying a mailbox, you +\emph{must} lock it by calling the \method{lock()} and +\method{unlock()} methods \emph{before} reading any messages in the file +or making any changes by adding or deleting a message. Failing to +lock the mailbox runs the risk of losing messages or corrupting the entire +mailbox. +\end{notice} \class{Mailbox} instances have the following methods: @@ -202,15 +218,16 @@ \begin{methoddesc}{flush}{} Write any pending changes to the filesystem. For some \class{Mailbox} -subclasses, changes are always written immediately and this method does -nothing. +subclasses, changes are always written immediately and \method{flush()} does +nothing, but you should still make a habit of calling this method. \end{methoddesc} \begin{methoddesc}{lock}{} Acquire an exclusive advisory lock on the mailbox so that other processes know not to modify it. An \exception{ExternalClashError} is raised if the lock is not available. The particular locking mechanisms used depend upon the mailbox -format. +format. You should \emph{always} lock the mailbox before making any +modifications to its contents. \end{methoddesc} \begin{methoddesc}{unlock}{} @@ -1373,36 +1390,55 @@ \begin{verbatim} import mailbox destination = mailbox.MH('~/Mail') +destination.lock() for message in mailbox.Babyl('~/RMAIL'): destination.add(MHMessage(message)) +destination.flush() +destination.unlock() \end{verbatim} -An example of sorting mail from numerous mailing lists, being careful to avoid -mail corruption due to concurrent modification by other programs, mail loss due -to interruption of the program, or premature termination due to malformed -messages in the mailbox: +This example sorts mail from several mailing lists into different +mailboxes, being careful to avoid mail corruption due to concurrent +modification by other programs, mail loss due to interruption of the +program, or premature termination due to malformed messages in the +mailbox: \begin{verbatim} import mailbox import email.Errors + list_names = ('python-list', 'python-dev', 'python-bugs') + boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names) -inbox = mailbox.Maildir('~/Maildir', None) +inbox = mailbox.Maildir('~/Maildir', factory=None) + for key in inbox.iterkeys(): try: message = inbox[key] except email.Errors.MessageParseError: continue # The message is malformed. Just leave it. + for name in list_names: list_id = message['list-id'] if list_id and name in list_id: + # Get mailbox to use box = boxes[name] + + # Write copy to disk before removing original. + # If there's a crash, you might duplicate a message, but + # that's better than losing a message completely. box.lock() box.add(message) - box.flush() # Write copy to disk before removing original. + box.flush() box.unlock() + + # Remove original message + inbox.lock() inbox.discard(key) + inbox.flush() + inbox.unlock() break # Found destination, so stop looking. + for box in boxes.itervalues(): box.close() \end{verbatim} Modified: python/branches/p3yk-noslice/Doc/lib/libos.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libos.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libos.tex Fri Feb 23 18:29:35 2007 @@ -758,6 +758,26 @@ \versionadded{2.3} \end{funcdesc} +\begin{funcdesc}{chflags}{path, flags} +Set the flags of \var{path} to the numeric \var{flags}. +\var{flags} may take a combination (bitwise OR) of the following values +(as defined in the \module{stat} module): +\begin{itemize} + \item \code{UF_NODUMP} + \item \code{UF_IMMUTABLE} + \item \code{UF_APPEND} + \item \code{UF_OPAQUE} + \item \code{UF_NOUNLINK} + \item \code{SF_ARCHIVED} + \item \code{SF_IMMUTABLE} + \item \code{SF_APPEND} + \item \code{SF_NOUNLINK} + \item \code{SF_SNAPSHOT} +\end{itemize} +Availability: Macintosh, \UNIX. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{chroot}{path} Change the root directory of the current process to \var{path}. Availability: Macintosh, \UNIX. @@ -804,6 +824,13 @@ Availability: Macintosh, \UNIX. \end{funcdesc} +\begin{funcdesc}{lchflags}{path, flags} +Set the flags of \var{path} to the numeric \var{flags}, like +\function{chflags()}, but do not follow symbolic links. +Availability: \UNIX. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{lchown}{path, uid, gid} Change the owner and group id of \var{path} to the numeric \var{uid} and gid. This function will not follow symbolic links. Modified: python/branches/p3yk-noslice/Doc/lib/librandom.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/librandom.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/librandom.tex Fri Feb 23 18:29:35 2007 @@ -185,7 +185,7 @@ \begin{funcdesc}{betavariate}{alpha, beta} Beta distribution. Conditions on the parameters are - \code{\var{alpha} > -1} and \code{\var{beta} > -1}. + \code{\var{alpha} > 0} and \code{\var{beta} > 0}. Returned values range between 0 and 1. \end{funcdesc} Modified: python/branches/p3yk-noslice/Doc/lib/libshutil.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libshutil.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libshutil.tex Fri Feb 23 18:29:35 2007 @@ -44,8 +44,8 @@ \end{funcdesc} \begin{funcdesc}{copystat}{src, dst} - Copy the permission bits, last access time, and last modification - time from \var{src} to \var{dst}. The file contents, owner, and + Copy the permission bits, last access time, last modification time, + and flags from \var{src} to \var{dst}. The file contents, owner, and group are unaffected. \var{src} and \var{dst} are path names given as strings. \end{funcdesc} Modified: python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex Fri Feb 23 18:29:35 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-noslice/Doc/lib/libsocket.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libsocket.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libsocket.tex Fri Feb 23 18:29:35 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-noslice/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex Fri Feb 23 18:29:35 2007 @@ -1212,7 +1212,7 @@ \label{types-set}} \obindex{set} -A \dfn{set} object is an unordered collection of immutable values. +A \dfn{set} object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. Modified: python/branches/p3yk-noslice/Doc/lib/libstruct.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libstruct.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libstruct.tex Fri Feb 23 18:29:35 2007 @@ -29,6 +29,15 @@ exactly. \end{funcdesc} +\begin{funcdesc}{pack_into}{fmt, buffer, offset, v1, v2, \moreargs} + Pack the values \code{\var{v1}, \var{v2}, \textrm{\ldots}} according to the given + format, write the packed bytes into the writable \var{buffer} starting at + \var{offset}. + Note that the offset is not an optional argument. + + \versionadded{2.5} +\end{funcdesc} + \begin{funcdesc}{unpack}{fmt, string} Unpack the string (presumably packed by \code{pack(\var{fmt}, \textrm{\ldots})}) according to the given format. The result is a @@ -37,6 +46,16 @@ (\code{len(\var{string})} must equal \code{calcsize(\var{fmt})}). \end{funcdesc} +\begin{funcdesc}{unpack_from}{fmt, buffer\optional{,offset \code{= 0}}} + Unpack the \var{buffer} according to tthe given format. + The result is a tuple even if it contains exactly one item. The + \var{buffer} must contain at least the amount of data required by the + format (\code{len(buffer[offset:])} must be at least + \code{calcsize(\var{fmt})}). + + \versionadded{2.5} +\end{funcdesc} + \begin{funcdesc}{calcsize}{fmt} Return the size of the struct (and hence of the string) corresponding to the given format. @@ -50,14 +69,15 @@ \lineiv{c}{\ctype{char}}{string of length 1}{} \lineiv{b}{\ctype{signed char}}{integer}{} \lineiv{B}{\ctype{unsigned char}}{integer}{} + \lineiv{t}{\ctype{_Bool}}{bool}{(1)} \lineiv{h}{\ctype{short}}{integer}{} \lineiv{H}{\ctype{unsigned short}}{integer}{} \lineiv{i}{\ctype{int}}{integer}{} \lineiv{I}{\ctype{unsigned int}}{long}{} \lineiv{l}{\ctype{long}}{integer}{} \lineiv{L}{\ctype{unsigned long}}{long}{} - \lineiv{q}{\ctype{long long}}{long}{(1)} - \lineiv{Q}{\ctype{unsigned long long}}{long}{(1)} + \lineiv{q}{\ctype{long long}}{long}{(2)} + \lineiv{Q}{\ctype{unsigned long long}}{long}{(2)} \lineiv{f}{\ctype{float}}{float}{} \lineiv{d}{\ctype{double}}{float}{} \lineiv{s}{\ctype{char[]}}{string}{} @@ -70,6 +90,11 @@ \begin{description} \item[(1)] + The \character{t} conversion code corresponds to the \ctype{_Bool} type + defined by C99. If this type is not available, it is simulated using a + \ctype{char}. In standard mode, it is always represented by one byte. + \versionadded{2.6} +\item[(2)] The \character{q} and \character{Q} conversion codes are available in native mode only if the platform C compiler supports C \ctype{long long}, or, on Windows, \ctype{__int64}. They are always available in standard @@ -118,6 +143,12 @@ meaning a Python long integer will be used to hold the pointer; other platforms use 32-bit pointers and will use a Python integer. +For the \character{t} format character, the return value is either +\constant{True} or \constant{False}. When packing, the truth value +of the argument object is used. Either 0 or 1 in the native or standard +bool representation will be packed, and any non-zero value will be True +when unpacking. + By default, C numbers are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). @@ -151,6 +182,7 @@ \ctype{long long} (\ctype{__int64} on Windows) is 8 bytes; \ctype{float} and \ctype{double} are 32-bit and 64-bit IEEE floating point numbers, respectively. +\ctype{_Bool} is 1 byte. Note the difference between \character{@} and \character{=}: both use native byte order, but the size and alignment of the latter is @@ -195,3 +227,43 @@ \seemodule{array}{Packed binary storage of homogeneous data.} \seemodule{xdrlib}{Packing and unpacking of XDR data.} \end{seealso} + +\subsection{Struct Objects \label{struct-objects}} + +The \module{struct} module also defines the following type: + +\begin{classdesc}{Struct}{format} + Return a new Struct object which writes and reads binary data according to + the format string \var{format}. Creating a Struct object once and calling + its methods is more efficient than calling the \module{struct} functions + with the same format since the format string only needs to be compiled once. + + \versionadded{2.5} +\end{classdesc} + +Compiled Struct objects support the following methods and attributes: + +\begin{methoddesc}[Struct]{pack}{v1, v2, \moreargs} + Identical to the \function{pack()} function, using the compiled format. + (\code{len(result)} will equal \member{self.size}.) +\end{methoddesc} + +\begin{methoddesc}[Struct]{pack_into}{buffer, offset, v1, v2, \moreargs} + Identical to the \function{pack_into()} function, using the compiled format. +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack}{string} + Identical to the \function{unpack()} function, using the compiled format. + (\code{len(string)} must equal \member{self.size}). +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack_from}{buffer\optional{,offset + \code{= 0}}} + Identical to the \function{unpack_from()} function, using the compiled format. + (\code{len(buffer[offset:])} must be at least \member{self.size}). +\end{methoddesc} + +\begin{memberdesc}[Struct]{format} + The format string used to construct this Struct object. +\end{memberdesc} + Modified: python/branches/p3yk-noslice/Doc/lib/libtarfile.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libtarfile.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libtarfile.tex Fri Feb 23 18:29:35 2007 @@ -36,7 +36,8 @@ \lineii{'r:'}{Open for reading exclusively without compression.} \lineii{'r:gz'}{Open for reading with gzip compression.} \lineii{'r:bz2'}{Open for reading with bzip2 compression.} - \lineii{'a' or 'a:'}{Open for appending with no compression.} + \lineii{'a' or 'a:'}{Open for appending with no compression. The file + is created if it does not exist.} \lineii{'w' or 'w:'}{Open for uncompressed writing.} \lineii{'w:gz'}{Open for gzip compressed writing.} \lineii{'w:bz2'}{Open for bzip2 compressed writing.} @@ -48,8 +49,8 @@ avoid this. If a compression method is not supported, \exception{CompressionError} is raised. - If \var{fileobj} is specified, it is used as an alternative to - a file object opened for \var{name}. + If \var{fileobj} is specified, it is used as an alternative to a file + object opened for \var{name}. It is supposed to be at position 0. For special purposes, there is a second format for \var{mode}: \code{'filemode|[compression]'}. \function{open()} will return a @@ -160,6 +161,7 @@ If \var{fileobj} is given, it is used for reading or writing data. If it can be determined, \var{mode} is overridden by \var{fileobj}'s mode. + \var{fileobj} will be used from position 0. \begin{notice} \var{fileobj} is not closed, when \class{TarFile} is closed. \end{notice} Modified: python/branches/p3yk-noslice/Doc/lib/libtest.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libtest.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libtest.tex Fri Feb 23 18:29:35 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-noslice/Doc/lib/libtime.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libtime.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libtime.tex Fri Feb 23 18:29:35 2007 @@ -324,6 +324,12 @@ it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones). + +Only the directives specified in the documentation are supported. Because +\code{strftime()} is implemented per platform it can sometimes offer more +directives than those listed. But \code{strptime()} is independent of any +platform and thus does not necessarily support all directives available that +are not documented as supported. \end{funcdesc} \begin{datadesc}{struct_time} Modified: python/branches/p3yk-noslice/Doc/lib/libzipfile.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libzipfile.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libzipfile.tex Fri Feb 23 18:29:35 2007 @@ -17,8 +17,10 @@ {PKZIP Application Note}. This module does not currently handle ZIP files which have appended -comments, or multi-disk ZIP files. It can handle ZIP files that use the -ZIP64 extensions (that is ZIP files that are more than 4 GByte in size). +comments, or multi-disk ZIP files. It can handle ZIP files that use +the ZIP64 extensions (that is ZIP files that are more than 4 GByte in +size). It supports decryption of encrypted files in ZIP archives, but +it cannot currently create an encrypted file. The available attributes of this module are: @@ -99,6 +101,8 @@ \end{verbatim} also works, and at least \program{WinZip} can read such files. + If \var{mode} is \code{a} and the file does not exist at all, + it is created. \var{compression} is the ZIP compression method to use when writing the archive, and should be \constant{ZIP_STORED} or \constant{ZIP_DEFLATED}; unrecognized values will cause @@ -112,6 +116,9 @@ ZIP file would require ZIP64 extensions. ZIP64 extensions are disabled by default because the default \program{zip} and \program{unzip} commands on \UNIX{} (the InfoZIP utilities) don't support these extensions. + + \versionchanged[If the file does not exist, it is created if the + mode is 'a']{2.6} \end{classdesc} \begin{methoddesc}{close}{} @@ -138,9 +145,18 @@ Print a table of contents for the archive to \code{sys.stdout}. \end{methoddesc} -\begin{methoddesc}{read}{name} +\begin{methoddesc}{setpassword}{pwd} + Set \var{pwd} as default password to extract encrypted files. + \versionadded{2.6} +\end{methoddesc} + +\begin{methoddesc}{read}{name\optional{, pwd}} Return the bytes of the file in the archive. The archive must be - open for read or append. + open for read or append. \var{pwd} is the password used for encrypted + files and, if specified, it will override the default password set with + \method{setpassword()}. + + \versionchanged[\var{pwd} was added]{2.6} \end{methoddesc} \begin{methoddesc}{testzip}{} Modified: python/branches/p3yk-noslice/Doc/ref/ref3.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/ref/ref3.tex (original) +++ python/branches/p3yk-noslice/Doc/ref/ref3.tex Fri Feb 23 18:29:35 2007 @@ -1997,8 +1997,8 @@ \methodline[numeric object]{__ixor__}{self, other} \methodline[numeric object]{__ior__}{self, other} These methods are called to implement the augmented arithmetic -operations (\code{+=}, \code{-=}, \code{*=}, \code{/=}, \code{\%=}, -\code{**=}, \code{<<=}, \code{>>=}, \code{\&=}, +operations (\code{+=}, \code{-=}, \code{*=}, \code{/=}, \code{//=}, +\code{\%=}, \code{**=}, \code{<<=}, \code{>>=}, \code{\&=}, \code{\textasciicircum=}, \code{|=}). These methods should attempt to do the operation in-place (modifying \var{self}) and return the result (which could be, but does not have to be, \var{self}). If a specific method Modified: python/branches/p3yk-noslice/Doc/ref/ref4.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/ref/ref4.tex (original) +++ python/branches/p3yk-noslice/Doc/ref/ref4.tex Fri Feb 23 18:29:35 2007 @@ -197,10 +197,6 @@ value can be raised along with the identifying string which can be passed to the handler. -\deprecated{2.5}{String exceptions should not be used in new code. -They will not be supported in a future version of Python. Old code -should be rewritten to use class exceptions instead.} - \begin{notice}[warning] Messages to exceptions are not part of the Python API. Their contents may change from one version of Python to the next without warning and should not Modified: python/branches/p3yk-noslice/Doc/ref/ref6.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/ref/ref6.tex (original) +++ python/branches/p3yk-noslice/Doc/ref/ref6.tex Fri Feb 23 18:29:35 2007 @@ -12,7 +12,6 @@ \productioncont{| \token{augmented_assignment_stmt}} \productioncont{| \token{pass_stmt}} \productioncont{| \token{del_stmt}} - \productioncont{| \token{print_stmt}} \productioncont{| \token{return_stmt}} \productioncont{| \token{yield_stmt}} \productioncont{| \token{raise_stmt}} @@ -370,60 +369,6 @@ \indexii{attribute}{deletion} -\section{The \keyword{print} statement \label{print}} -\stindex{print} - -\begin{productionlist} - \production{print_stmt} - {"print" ( \optional{\token{expression} ("," \token{expression})* \optional{","}}} - \productioncont{| ">>" \token{expression} - \optional{("," \token{expression})+ \optional{","}} )} -\end{productionlist} - -\keyword{print} evaluates each expression in turn and writes the -resulting object to standard output (see below). If an object is not -a string, it is first converted to a string using the rules for string -conversions. The (resulting or original) string is then written. A -space is written before each object is (converted and) written, unless -the output system believes it is positioned at the beginning of a -line. This is the case (1) when no characters have yet been written -to standard output, (2) when the last character written to standard -output is \character{\e n}, or (3) when the last write operation on -standard output was not a \keyword{print} statement. (In some cases -it may be functional to write an empty string to standard output for -this reason.) \note{Objects which act like file objects but which are -not the built-in file objects often do not properly emulate this -aspect of the file object's behavior, so it is best not to rely on -this.} -\index{output} -\indexii{writing}{values} - -A \character{\e n} character is written at the end, unless the -\keyword{print} statement ends with a comma. This is the only action -if the statement contains just the keyword \keyword{print}. -\indexii{trailing}{comma} -\indexii{newline}{suppression} - -Standard output is defined as the file object named \code{stdout} -in the built-in module \module{sys}. If no such object exists, or if -it does not have a \method{write()} method, a \exception{RuntimeError} -exception is raised. -\indexii{standard}{output} -\refbimodindex{sys} -\withsubitem{(in module sys)}{\ttindex{stdout}} -\exindex{RuntimeError} - -\keyword{print} also has an extended\index{extended print statement} -form, defined by the second portion of the syntax described above. -This form is sometimes referred to as ``\keyword{print} chevron.'' -In this form, the first expression after the \code{>>} must -evaluate to a ``file-like'' object, specifically an object that has a -\method{write()} method as described above. With this extended form, -the subsequent expressions are printed to this file object. If the -first expression evaluates to \code{None}, then \code{sys.stdout} is -used as the file for output. - - \section{The \keyword{return} statement \label{return}} \stindex{return} Modified: python/branches/p3yk-noslice/Doc/tut/tut.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/tut/tut.tex (original) +++ python/branches/p3yk-noslice/Doc/tut/tut.tex Fri Feb 23 18:29:35 2007 @@ -1991,7 +1991,7 @@ There is a way to remove an item from a list given its index instead of its value: the \keyword{del} statement. This differs from the -\method{pop()}) method which returns a value. The \keyword{del} +\method{pop()} method which returns a value. The \keyword{del} statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example: Modified: python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex (original) +++ python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex Fri Feb 23 18:29:35 2007 @@ -72,6 +72,12 @@ This class supports an interface identical to the existing \class{SMTP} class. (Contributed by Monty Taylor.) +\item The \module{test.test_support} module now contains a +\function{EnvironmentVarGuard} context manager that +supports temporarily changing environment variables and +automatically restores them to their old values. +(Contributed by Brett Cannon.) + \end{itemize} Modified: python/branches/p3yk-noslice/Grammar/Grammar ============================================================================== --- python/branches/p3yk-noslice/Grammar/Grammar (original) +++ python/branches/p3yk-noslice/Grammar/Grammar Fri Feb 23 18:29:35 2007 @@ -38,15 +38,13 @@ stmt: simple_stmt | compound_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE -small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | +small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | assert_stmt) expr_stmt: testlist (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=') # For normal assignments, additional restrictions enforced by the interpreter -print_stmt: 'print' ( [ test (',' test)* [','] ] | - '>>' test [ (',' test)+ [','] ] ) del_stmt: 'del' exprlist pass_stmt: 'pass' flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt Modified: python/branches/p3yk-noslice/Include/Python-ast.h ============================================================================== --- python/branches/p3yk-noslice/Include/Python-ast.h (original) +++ python/branches/p3yk-noslice/Include/Python-ast.h Fri Feb 23 18:29:35 2007 @@ -1,4 +1,4 @@ -/* File automatically generated by Parser/asdl_c.py */ +/* File automatically generated by Parser/asdl_c.py. */ #include "asdl.h" @@ -62,12 +62,11 @@ }; enum _stmt_kind {FunctionDef_kind=1, ClassDef_kind=2, Return_kind=3, - Delete_kind=4, Assign_kind=5, AugAssign_kind=6, Print_kind=7, - For_kind=8, While_kind=9, If_kind=10, With_kind=11, - Raise_kind=12, TryExcept_kind=13, TryFinally_kind=14, - Assert_kind=15, Import_kind=16, ImportFrom_kind=17, - Global_kind=18, Expr_kind=19, Pass_kind=20, Break_kind=21, - Continue_kind=22}; + Delete_kind=4, Assign_kind=5, AugAssign_kind=6, For_kind=7, + While_kind=8, If_kind=9, With_kind=10, Raise_kind=11, + TryExcept_kind=12, TryFinally_kind=13, Assert_kind=14, + Import_kind=15, ImportFrom_kind=16, Global_kind=17, + Expr_kind=18, Pass_kind=19, Break_kind=20, Continue_kind=21}; struct _stmt { enum _stmt_kind kind; union { @@ -105,12 +104,6 @@ } AugAssign; struct { - expr_ty dest; - asdl_seq *values; - bool nl; - } Print; - - struct { expr_ty target; expr_ty iter; asdl_seq *body; @@ -366,97 +359,154 @@ }; -mod_ty Module(asdl_seq * body, PyArena *arena); -mod_ty Interactive(asdl_seq * body, PyArena *arena); -mod_ty Expression(expr_ty body, PyArena *arena); -mod_ty Suite(asdl_seq * body, PyArena *arena); -stmt_ty FunctionDef(identifier name, arguments_ty args, asdl_seq * body, - asdl_seq * decorators, expr_ty returns, int lineno, int - col_offset, PyArena *arena); -stmt_ty ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int - lineno, int col_offset, PyArena *arena); -stmt_ty Return(expr_ty value, int lineno, int col_offset, PyArena *arena); -stmt_ty Delete(asdl_seq * targets, int lineno, int col_offset, PyArena *arena); -stmt_ty Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, - PyArena *arena); -stmt_ty AugAssign(expr_ty target, operator_ty op, expr_ty value, int lineno, - int col_offset, PyArena *arena); -stmt_ty Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int - col_offset, PyArena *arena); -stmt_ty For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, - int lineno, int col_offset, PyArena *arena); -stmt_ty While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int - col_offset, PyArena *arena); -stmt_ty If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int - col_offset, PyArena *arena); -stmt_ty With(expr_ty context_expr, expr_ty optional_vars, asdl_seq * body, int - lineno, int col_offset, PyArena *arena); -stmt_ty Raise(expr_ty type, expr_ty inst, expr_ty tback, int lineno, int - col_offset, PyArena *arena); -stmt_ty TryExcept(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, int - lineno, int col_offset, PyArena *arena); -stmt_ty TryFinally(asdl_seq * body, asdl_seq * finalbody, int lineno, int +#define Module(a0, a1) _Py_Module(a0, a1) +mod_ty _Py_Module(asdl_seq * body, PyArena *arena); +#define Interactive(a0, a1) _Py_Interactive(a0, a1) +mod_ty _Py_Interactive(asdl_seq * body, PyArena *arena); +#define Expression(a0, a1) _Py_Expression(a0, a1) +mod_ty _Py_Expression(expr_ty body, PyArena *arena); +#define Suite(a0, a1) _Py_Suite(a0, a1) +mod_ty _Py_Suite(asdl_seq * body, PyArena *arena); +#define FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) _Py_FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) +stmt_ty _Py_FunctionDef(identifier name, arguments_ty args, asdl_seq * body, + asdl_seq * decorators, expr_ty returns, int lineno, int + col_offset, PyArena *arena); +#define ClassDef(a0, a1, a2, a3, a4, a5) _Py_ClassDef(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int + lineno, int col_offset, PyArena *arena); +#define Return(a0, a1, a2, a3) _Py_Return(a0, a1, a2, a3) +stmt_ty _Py_Return(expr_ty value, int lineno, int col_offset, PyArena *arena); +#define Delete(a0, a1, a2, a3) _Py_Delete(a0, a1, a2, a3) +stmt_ty _Py_Delete(asdl_seq * targets, int lineno, int col_offset, PyArena + *arena); +#define Assign(a0, a1, a2, a3, a4) _Py_Assign(a0, a1, a2, a3, a4) +stmt_ty _Py_Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, PyArena *arena); -stmt_ty Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, PyArena - *arena); -stmt_ty Import(asdl_seq * names, int lineno, int col_offset, PyArena *arena); -stmt_ty ImportFrom(identifier module, asdl_seq * names, int level, int lineno, - int col_offset, PyArena *arena); -stmt_ty Global(asdl_seq * names, int lineno, int col_offset, PyArena *arena); -stmt_ty Expr(expr_ty value, int lineno, int col_offset, PyArena *arena); -stmt_ty Pass(int lineno, int col_offset, PyArena *arena); -stmt_ty Break(int lineno, int col_offset, PyArena *arena); -stmt_ty Continue(int lineno, int col_offset, PyArena *arena); -expr_ty BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset, - PyArena *arena); -expr_ty BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int - col_offset, PyArena *arena); -expr_ty UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset, - PyArena *arena); -expr_ty Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset, - PyArena *arena); -expr_ty IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int - col_offset, PyArena *arena); -expr_ty Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, - PyArena *arena); -expr_ty Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena); -expr_ty ListComp(expr_ty elt, asdl_seq * generators, int lineno, int +#define AugAssign(a0, a1, a2, a3, a4, a5) _Py_AugAssign(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_AugAssign(expr_ty target, operator_ty op, expr_ty value, int + lineno, int col_offset, PyArena *arena); +#define For(a0, a1, a2, a3, a4, a5, a6) _Py_For(a0, a1, a2, a3, a4, a5, a6) +stmt_ty _Py_For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * + orelse, int lineno, int col_offset, PyArena *arena); +#define While(a0, a1, a2, a3, a4, a5) _Py_While(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, + int col_offset, PyArena *arena); +#define If(a0, a1, a2, a3, a4, a5) _Py_If(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, + int col_offset, PyArena *arena); +#define With(a0, a1, a2, a3, a4, a5) _Py_With(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_With(expr_ty context_expr, expr_ty optional_vars, asdl_seq * body, + int lineno, int col_offset, PyArena *arena); +#define Raise(a0, a1, a2, a3, a4, a5) _Py_Raise(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_Raise(expr_ty type, expr_ty inst, expr_ty tback, int lineno, int + col_offset, PyArena *arena); +#define TryExcept(a0, a1, a2, a3, a4, a5) _Py_TryExcept(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_TryExcept(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, + int lineno, int col_offset, PyArena *arena); +#define TryFinally(a0, a1, a2, a3, a4) _Py_TryFinally(a0, a1, a2, a3, a4) +stmt_ty _Py_TryFinally(asdl_seq * body, asdl_seq * finalbody, int lineno, int + col_offset, PyArena *arena); +#define Assert(a0, a1, a2, a3, a4) _Py_Assert(a0, a1, a2, a3, a4) +stmt_ty _Py_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, + PyArena *arena); +#define Import(a0, a1, a2, a3) _Py_Import(a0, a1, a2, a3) +stmt_ty _Py_Import(asdl_seq * names, int lineno, int col_offset, PyArena + *arena); +#define ImportFrom(a0, a1, a2, a3, a4, a5) _Py_ImportFrom(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_ImportFrom(identifier module, asdl_seq * names, int level, int + lineno, int col_offset, PyArena *arena); +#define Global(a0, a1, a2, a3) _Py_Global(a0, a1, a2, a3) +stmt_ty _Py_Global(asdl_seq * names, int lineno, int col_offset, PyArena + *arena); +#define Expr(a0, a1, a2, a3) _Py_Expr(a0, a1, a2, a3) +stmt_ty _Py_Expr(expr_ty value, int lineno, int col_offset, PyArena *arena); +#define Pass(a0, a1, a2) _Py_Pass(a0, a1, a2) +stmt_ty _Py_Pass(int lineno, int col_offset, PyArena *arena); +#define Break(a0, a1, a2) _Py_Break(a0, a1, a2) +stmt_ty _Py_Break(int lineno, int col_offset, PyArena *arena); +#define Continue(a0, a1, a2) _Py_Continue(a0, a1, a2) +stmt_ty _Py_Continue(int lineno, int col_offset, PyArena *arena); +#define BoolOp(a0, a1, a2, a3, a4) _Py_BoolOp(a0, a1, a2, a3, a4) +expr_ty _Py_BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset, + PyArena *arena); +#define BinOp(a0, a1, a2, a3, a4, a5) _Py_BinOp(a0, a1, a2, a3, a4, a5) +expr_ty _Py_BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int + col_offset, PyArena *arena); +#define UnaryOp(a0, a1, a2, a3, a4) _Py_UnaryOp(a0, a1, a2, a3, a4) +expr_ty _Py_UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset, + PyArena *arena); +#define Lambda(a0, a1, a2, a3, a4) _Py_Lambda(a0, a1, a2, a3, a4) +expr_ty _Py_Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset, + PyArena *arena); +#define IfExp(a0, a1, a2, a3, a4, a5) _Py_IfExp(a0, a1, a2, a3, a4, a5) +expr_ty _Py_IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int + col_offset, PyArena *arena); +#define Dict(a0, a1, a2, a3, a4) _Py_Dict(a0, a1, a2, a3, a4) +expr_ty _Py_Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, PyArena *arena); -expr_ty GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int +#define Set(a0, a1, a2, a3) _Py_Set(a0, a1, a2, a3) +expr_ty _Py_Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena); +#define ListComp(a0, a1, a2, a3, a4) _Py_ListComp(a0, a1, a2, a3, a4) +expr_ty _Py_ListComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena); -expr_ty Yield(expr_ty value, int lineno, int col_offset, PyArena *arena); -expr_ty Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, int - lineno, int col_offset, PyArena *arena); -expr_ty Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty - starargs, expr_ty kwargs, int lineno, int col_offset, PyArena - *arena); -expr_ty Num(object n, int lineno, int col_offset, PyArena *arena); -expr_ty Str(string s, int lineno, int col_offset, PyArena *arena); -expr_ty Ellipsis(int lineno, int col_offset, PyArena *arena); -expr_ty Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int - lineno, int col_offset, PyArena *arena); -expr_ty Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int - lineno, int col_offset, PyArena *arena); -expr_ty Name(identifier id, expr_context_ty ctx, int lineno, int col_offset, - PyArena *arena); -expr_ty List(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, - PyArena *arena); -expr_ty Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, - PyArena *arena); -slice_ty Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena); -slice_ty ExtSlice(asdl_seq * dims, PyArena *arena); -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, 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, - asdl_seq * kw_defaults, PyArena *arena); -arg_ty SimpleArg(identifier arg, expr_ty annotation, PyArena *arena); -arg_ty NestedArgs(asdl_seq * args, PyArena *arena); -keyword_ty keyword(identifier arg, expr_ty value, PyArena *arena); -alias_ty alias(identifier name, identifier asname, PyArena *arena); +#define GeneratorExp(a0, a1, a2, a3, a4) _Py_GeneratorExp(a0, a1, a2, a3, a4) +expr_ty _Py_GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int + col_offset, PyArena *arena); +#define Yield(a0, a1, a2, a3) _Py_Yield(a0, a1, a2, a3) +expr_ty _Py_Yield(expr_ty value, int lineno, int col_offset, PyArena *arena); +#define Compare(a0, a1, a2, a3, a4, a5) _Py_Compare(a0, a1, a2, a3, a4, a5) +expr_ty _Py_Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, + int lineno, int col_offset, PyArena *arena); +#define Call(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Call(a0, a1, a2, a3, a4, a5, a6, a7) +expr_ty _Py_Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty + starargs, expr_ty kwargs, int lineno, int col_offset, PyArena + *arena); +#define Num(a0, a1, a2, a3) _Py_Num(a0, a1, a2, a3) +expr_ty _Py_Num(object n, int lineno, int col_offset, PyArena *arena); +#define Str(a0, a1, a2, a3) _Py_Str(a0, a1, a2, a3) +expr_ty _Py_Str(string s, int lineno, int col_offset, PyArena *arena); +#define Ellipsis(a0, a1, a2) _Py_Ellipsis(a0, a1, a2) +expr_ty _Py_Ellipsis(int lineno, int col_offset, PyArena *arena); +#define Attribute(a0, a1, a2, a3, a4, a5) _Py_Attribute(a0, a1, a2, a3, a4, a5) +expr_ty _Py_Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int + lineno, int col_offset, PyArena *arena); +#define Subscript(a0, a1, a2, a3, a4, a5) _Py_Subscript(a0, a1, a2, a3, a4, a5) +expr_ty _Py_Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int + lineno, int col_offset, PyArena *arena); +#define Name(a0, a1, a2, a3, a4) _Py_Name(a0, a1, a2, a3, a4) +expr_ty _Py_Name(identifier id, expr_context_ty ctx, int lineno, int + col_offset, PyArena *arena); +#define List(a0, a1, a2, a3, a4) _Py_List(a0, a1, a2, a3, a4) +expr_ty _Py_List(asdl_seq * elts, expr_context_ty ctx, int lineno, int + col_offset, PyArena *arena); +#define Tuple(a0, a1, a2, a3, a4) _Py_Tuple(a0, a1, a2, a3, a4) +expr_ty _Py_Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int + col_offset, PyArena *arena); +#define Slice(a0, a1, a2, a3) _Py_Slice(a0, a1, a2, a3) +slice_ty _Py_Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena); +#define ExtSlice(a0, a1) _Py_ExtSlice(a0, a1) +slice_ty _Py_ExtSlice(asdl_seq * dims, PyArena *arena); +#define Index(a0, a1) _Py_Index(a0, a1) +slice_ty _Py_Index(expr_ty value, PyArena *arena); +#define comprehension(a0, a1, a2, a3) _Py_comprehension(a0, a1, a2, a3) +comprehension_ty _Py_comprehension(expr_ty target, expr_ty iter, asdl_seq * + ifs, PyArena *arena); +#define excepthandler(a0, a1, a2, a3, a4, a5) _Py_excepthandler(a0, a1, a2, a3, a4, a5) +excepthandler_ty _Py_excepthandler(expr_ty type, identifier name, asdl_seq * + body, int lineno, int col_offset, PyArena + *arena); +#define arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8) _Py_arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8) +arguments_ty _Py_arguments(asdl_seq * args, identifier vararg, expr_ty + varargannotation, asdl_seq * kwonlyargs, identifier + kwarg, expr_ty kwargannotation, asdl_seq * defaults, + asdl_seq * kw_defaults, PyArena *arena); +#define SimpleArg(a0, a1, a2) _Py_SimpleArg(a0, a1, a2) +arg_ty _Py_SimpleArg(identifier arg, expr_ty annotation, PyArena *arena); +#define NestedArgs(a0, a1) _Py_NestedArgs(a0, a1) +arg_ty _Py_NestedArgs(asdl_seq * args, PyArena *arena); +#define keyword(a0, a1, a2) _Py_keyword(a0, a1, a2) +keyword_ty _Py_keyword(identifier arg, expr_ty value, PyArena *arena); +#define alias(a0, a1, a2) _Py_alias(a0, a1, a2) +alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); PyObject* PyAST_mod2obj(mod_ty t); Modified: python/branches/p3yk-noslice/Include/abstract.h ============================================================================== --- python/branches/p3yk-noslice/Include/abstract.h (original) +++ python/branches/p3yk-noslice/Include/abstract.h Fri Feb 23 18:29:35 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 @@ -1127,37 +1127,28 @@ */ - /* Implemented as macro: + PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o); - PyObject *PyMapping_Keys(PyObject *o); - - On success, return a list of the keys in object o. On - failure, return NULL. This is equivalent to the Python - expression: o.keys(). + /* + On success, return a list or tuple of the keys in object o. + On failure, return NULL. */ -#define PyMapping_Keys(O) PyObject_CallMethod(O,"keys",NULL) - - /* Implemented as macro: - PyObject *PyMapping_Values(PyObject *o); + PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o); - On success, return a list of the values in object o. On - failure, return NULL. This is equivalent to the Python - expression: o.values(). + /* + On success, return a list or tuple of the values in object o. + On failure, return NULL. */ -#define PyMapping_Values(O) PyObject_CallMethod(O,"values",NULL) - - /* Implemented as macro: - PyObject *PyMapping_Items(PyObject *o); + PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o); - On success, return a list of the items in object o, where - each item is a tuple containing a key-value pair. On - failure, return NULL. This is equivalent to the Python - expression: o.items(). + /* + On success, return a list or tuple of the items in object o, + where each item is a tuple containing a key-value pair. + On failure, return NULL. */ -#define PyMapping_Items(O) PyObject_CallMethod(O,"items",NULL) PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key); Modified: python/branches/p3yk-noslice/Include/boolobject.h ============================================================================== --- python/branches/p3yk-noslice/Include/boolobject.h (original) +++ python/branches/p3yk-noslice/Include/boolobject.h Fri Feb 23 18:29:35 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-noslice/Include/ceval.h ============================================================================== --- python/branches/p3yk-noslice/Include/ceval.h (original) +++ python/branches/p3yk-noslice/Include/ceval.h Fri Feb 23 18:29:35 2007 @@ -40,8 +40,6 @@ flag was set, else return 0. */ PyAPI_FUNC(int) PyEval_MergeCompilerFlags(PyCompilerFlags *cf); -PyAPI_FUNC(int) Py_FlushLine(void); - PyAPI_FUNC(int) Py_AddPendingCall(int (*func)(void *), void *arg); PyAPI_FUNC(int) Py_MakePendingCalls(void); Modified: python/branches/p3yk-noslice/Include/dictobject.h ============================================================================== --- python/branches/p3yk-noslice/Include/dictobject.h (original) +++ python/branches/p3yk-noslice/Include/dictobject.h Fri Feb 23 18:29:35 2007 @@ -100,12 +100,15 @@ PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); PyAPI_FUNC(int) PyDict_Next( PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); +PyAPI_FUNC(int) _PyDict_Next( + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp); PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp); PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key); +PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, long hash); /* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */ PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other); Modified: python/branches/p3yk-noslice/Include/fileobject.h ============================================================================== --- python/branches/p3yk-noslice/Include/fileobject.h (original) +++ python/branches/p3yk-noslice/Include/fileobject.h Fri Feb 23 18:29:35 2007 @@ -13,7 +13,6 @@ PyObject *f_name; PyObject *f_mode; int (*f_close)(FILE *); - int f_softspace; /* Flag used by 'print' command */ int f_binary; /* Flag which indicates whether the file is open in binary (1) or text (0) mode */ char* f_buf; /* Allocated readahead buffer */ @@ -41,7 +40,6 @@ PyAPI_FUNC(PyObject *) PyFile_Name(PyObject *); PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int); PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int); -PyAPI_FUNC(int) PyFile_SoftSpace(PyObject *, int); PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *); PyAPI_FUNC(int) PyObject_AsFileDescriptor(PyObject *); Modified: python/branches/p3yk-noslice/Include/graminit.h ============================================================================== --- python/branches/p3yk-noslice/Include/graminit.h (original) +++ python/branches/p3yk-noslice/Include/graminit.h Fri Feb 23 18:29:35 2007 @@ -18,71 +18,70 @@ #define small_stmt 273 #define expr_stmt 274 #define augassign 275 -#define print_stmt 276 -#define del_stmt 277 -#define pass_stmt 278 -#define flow_stmt 279 -#define break_stmt 280 -#define continue_stmt 281 -#define return_stmt 282 -#define yield_stmt 283 -#define raise_stmt 284 -#define import_stmt 285 -#define import_name 286 -#define import_from 287 -#define import_as_name 288 -#define dotted_as_name 289 -#define import_as_names 290 -#define dotted_as_names 291 -#define dotted_name 292 -#define global_stmt 293 -#define assert_stmt 294 -#define compound_stmt 295 -#define if_stmt 296 -#define while_stmt 297 -#define for_stmt 298 -#define try_stmt 299 -#define with_stmt 300 -#define with_var 301 -#define except_clause 302 -#define suite 303 -#define testlist_safe 304 -#define old_test 305 -#define old_lambdef 306 -#define test 307 -#define or_test 308 -#define and_test 309 -#define not_test 310 -#define comparison 311 -#define comp_op 312 -#define expr 313 -#define xor_expr 314 -#define and_expr 315 -#define shift_expr 316 -#define arith_expr 317 -#define term 318 -#define factor 319 -#define power 320 -#define atom 321 -#define listmaker 322 -#define testlist_gexp 323 -#define lambdef 324 -#define trailer 325 -#define subscriptlist 326 -#define subscript 327 -#define sliceop 328 -#define exprlist 329 -#define testlist 330 -#define dictsetmaker 331 -#define classdef 332 -#define arglist 333 -#define argument 334 -#define list_iter 335 -#define list_for 336 -#define list_if 337 -#define gen_iter 338 -#define gen_for 339 -#define gen_if 340 -#define testlist1 341 -#define encoding_decl 342 -#define yield_expr 343 +#define del_stmt 276 +#define pass_stmt 277 +#define flow_stmt 278 +#define break_stmt 279 +#define continue_stmt 280 +#define return_stmt 281 +#define yield_stmt 282 +#define raise_stmt 283 +#define import_stmt 284 +#define import_name 285 +#define import_from 286 +#define import_as_name 287 +#define dotted_as_name 288 +#define import_as_names 289 +#define dotted_as_names 290 +#define dotted_name 291 +#define global_stmt 292 +#define assert_stmt 293 +#define compound_stmt 294 +#define if_stmt 295 +#define while_stmt 296 +#define for_stmt 297 +#define try_stmt 298 +#define with_stmt 299 +#define with_var 300 +#define except_clause 301 +#define suite 302 +#define testlist_safe 303 +#define old_test 304 +#define old_lambdef 305 +#define test 306 +#define or_test 307 +#define and_test 308 +#define not_test 309 +#define comparison 310 +#define comp_op 311 +#define expr 312 +#define xor_expr 313 +#define and_expr 314 +#define shift_expr 315 +#define arith_expr 316 +#define term 317 +#define factor 318 +#define power 319 +#define atom 320 +#define listmaker 321 +#define testlist_gexp 322 +#define lambdef 323 +#define trailer 324 +#define subscriptlist 325 +#define subscript 326 +#define sliceop 327 +#define exprlist 328 +#define testlist 329 +#define dictsetmaker 330 +#define classdef 331 +#define arglist 332 +#define argument 333 +#define list_iter 334 +#define list_for 335 +#define list_if 336 +#define gen_iter 337 +#define gen_for 338 +#define gen_if 339 +#define testlist1 340 +#define encoding_decl 341 +#define yield_expr 342 Modified: python/branches/p3yk-noslice/Include/intobject.h ============================================================================== --- python/branches/p3yk-noslice/Include/intobject.h (original) +++ python/branches/p3yk-noslice/Include/intobject.h Fri Feb 23 18:29:35 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-noslice/Include/longobject.h ============================================================================== --- python/branches/p3yk-noslice/Include/longobject.h (original) +++ python/branches/p3yk-noslice/Include/longobject.h Fri Feb 23 18:29:35 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-noslice/Include/object.h ============================================================================== --- python/branches/p3yk-noslice/Include/object.h (original) +++ python/branches/p3yk-noslice/Include/object.h Fri Feb 23 18:29:35 2007 @@ -368,7 +368,7 @@ /* Generic operations on objects */ PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int); -PyAPI_FUNC(void) _Py_Break(void); +PyAPI_FUNC(void) _Py_BreakPoint(void); PyAPI_FUNC(void) _PyObject_Dump(PyObject *); PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *); PyAPI_FUNC(PyObject *) _PyObject_Str(PyObject *); Modified: python/branches/p3yk-noslice/Include/opcode.h ============================================================================== --- python/branches/p3yk-noslice/Include/opcode.h (original) +++ python/branches/p3yk-noslice/Include/opcode.h Fri Feb 23 18:29:35 2007 @@ -52,10 +52,7 @@ #define GET_ITER 68 #define PRINT_EXPR 70 -#define PRINT_ITEM 71 -#define PRINT_NEWLINE 72 -#define PRINT_ITEM_TO 73 -#define PRINT_NEWLINE_TO 74 + #define INPLACE_LSHIFT 75 #define INPLACE_RSHIFT 76 #define INPLACE_AND 77 Modified: python/branches/p3yk-noslice/Lib/BaseHTTPServer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/BaseHTTPServer.py (original) +++ python/branches/p3yk-noslice/Lib/BaseHTTPServer.py Fri Feb 23 18:29:35 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 % @@ -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. @@ -570,7 +570,7 @@ httpd = ServerClass(server_address, HandlerClass) sa = httpd.socket.getsockname() - print "Serving HTTP on", sa[0], "port", sa[1], "..." + print("Serving HTTP on", sa[0], "port", sa[1], "...") httpd.serve_forever() Modified: python/branches/p3yk-noslice/Lib/Bastion.py ============================================================================== --- python/branches/p3yk-noslice/Lib/Bastion.py (original) +++ python/branches/p3yk-noslice/Lib/Bastion.py Fri Feb 23 18:29:35 2007 @@ -165,7 +165,7 @@ print "accessible" \n""" exec(testcode) - print '='*20, "Using rexec:", '='*20 + print('='*20, "Using rexec:", '='*20) import rexec r = rexec.RExec() m = r.add_module('__main__') Modified: python/branches/p3yk-noslice/Lib/CGIHTTPServer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/CGIHTTPServer.py (original) +++ python/branches/p3yk-noslice/Lib/CGIHTTPServer.py Fri Feb 23 18:29:35 2007 @@ -107,7 +107,7 @@ """Execute a CGI script.""" path = self.path dir, rest = self.cgi_info - + i = path.find('/', len(dir) + 1) while i >= 0: nextdir = path[:i] Modified: python/branches/p3yk-noslice/Lib/ConfigParser.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ConfigParser.py (original) +++ python/branches/p3yk-noslice/Lib/ConfigParser.py Fri Feb 23 18:29:35 2007 @@ -214,7 +214,7 @@ def sections(self): """Return a list of section names, excluding [DEFAULT]""" # self._sections will never have [DEFAULT] in it - return self._sections.keys() + return list(self._sections.keys()) def add_section(self, section): """Create a new section in the configuration. @@ -242,7 +242,7 @@ opts.update(self._defaults) if '__name__' in opts: del opts['__name__'] - return opts.keys() + return list(opts.keys()) def read(self, filenames): """Read and parse a filename or a list of filenames. @@ -547,7 +547,7 @@ if vars: for key, value in vars.items(): d[self.optionxform(key)] = value - options = d.keys() + options = list(d.keys()) if "__name__" in options: options.remove("__name__") if raw: Modified: python/branches/p3yk-noslice/Lib/Cookie.py ============================================================================== --- python/branches/p3yk-noslice/Lib/Cookie.py (original) +++ python/branches/p3yk-noslice/Lib/Cookie.py Fri Feb 23 18:29:35 2007 @@ -80,9 +80,9 @@ >>> C = Cookie.SmartCookie() >>> C["rocky"] = "road" >>> C["rocky"]["path"] = "/cookie" - >>> print C.output(header="Cookie:") + >>> print(C.output(header="Cookie:")) Cookie: rocky=road; Path=/cookie - >>> print C.output(attrs=[], header="Cookie:") + >>> print(C.output(attrs=[], header="Cookie:")) Cookie: rocky=road The load() method of a Cookie extracts cookies from a string. In a @@ -100,7 +100,7 @@ >>> C = Cookie.SmartCookie() >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') - >>> print C + >>> print(C) Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" Each element of the Cookie also supports all of the RFC 2109 @@ -110,7 +110,7 @@ >>> C = Cookie.SmartCookie() >>> C["oreo"] = "doublestuff" >>> C["oreo"]["path"] = "/" - >>> print C + >>> print(C) Set-Cookie: oreo=doublestuff; Path=/ Each dictionary element has a 'value' attribute, which gives you @@ -198,7 +198,7 @@ fact, this simply returns a SmartCookie. >>> C = Cookie.Cookie() - >>> print C.__class__.__name__ + >>> print(C.__class__.__name__) SmartCookie @@ -488,8 +488,7 @@ # Now add any defined attributes if attrs is None: attrs = self._reserved - items = self.items() - items.sort() + items = sorted(self.items()) for K,V in items: if V == "": continue if K not in attrs: continue @@ -582,8 +581,7 @@ def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"): """Return a string suitable for HTTP.""" result = [] - items = self.items() - items.sort() + items = sorted(self.items()) for K,V in items: result.append( V.output(attrs, header) ) return sep.join(result) @@ -593,8 +591,7 @@ def __repr__(self): L = [] - items = self.items() - items.sort() + items = sorted(self.items()) for K,V in items: L.append( '%s=%s' % (K,repr(V.value) ) ) return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L)) @@ -602,8 +599,7 @@ def js_output(self, attrs=None): """Return a string suitable for JavaScript.""" result = [] - items = self.items() - items.sort() + items = sorted(self.items()) for K,V in items: result.append( V.js_output(attrs) ) return _nulljoin(result) Modified: python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py (original) +++ python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py Fri Feb 23 18:29:35 2007 @@ -270,9 +270,9 @@ response = self.generate_html_documentation() - print 'Content-Type: text/html' - print 'Content-Length: %d' % len(response) - print + print('Content-Type: text/html') + print('Content-Length: %d' % len(response)) + print() sys.stdout.write(response) def __init__(self): Modified: python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py (original) +++ python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py Fri Feb 23 18:29:35 2007 @@ -543,9 +543,9 @@ response = self._marshaled_dispatch(request_text) - print 'Content-Type: text/xml' - print 'Content-Length: %d' % len(response) - print + print('Content-Type: text/xml') + print('Content-Length: %d' % len(response)) + print() sys.stdout.write(response) def handle_get(self): @@ -565,10 +565,10 @@ 'message' : message, 'explain' : explain } - print 'Status: %d %s' % (code, message) - print 'Content-Type: text/html' - print 'Content-Length: %d' % len(response) - print + print('Status: %d %s' % (code, message)) + print('Content-Type: text/html') + print('Content-Length: %d' % len(response)) + print() sys.stdout.write(response) def handle_request(self, request_text = None): @@ -590,7 +590,7 @@ self.handle_xmlrpc(request_text) if __name__ == '__main__': - print 'Running XML-RPC server on port 8000' + print('Running XML-RPC server on port 8000') server = SimpleXMLRPCServer(("localhost", 8000)) server.register_function(pow) server.register_function(lambda x,y: x+y, 'add') Modified: python/branches/p3yk-noslice/Lib/SocketServer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/SocketServer.py (original) +++ python/branches/p3yk-noslice/Lib/SocketServer.py Fri Feb 23 18:29:35 2007 @@ -263,12 +263,12 @@ The default is to print a traceback and continue. """ - print '-'*40 - print 'Exception happened during processing of request from', - print client_address + print('-'*40) + print('Exception happened during processing of request from', end=' ') + print(client_address) import traceback traceback.print_exc() # XXX But this goes to stderr! - print '-'*40 + print('-'*40) class TCPServer(BaseServer): Modified: python/branches/p3yk-noslice/Lib/StringIO.py ============================================================================== --- python/branches/p3yk-noslice/Lib/StringIO.py (original) +++ python/branches/p3yk-noslice/Lib/StringIO.py Fri Feb 23 18:29:35 2007 @@ -60,7 +60,6 @@ self.buflist = [] self.pos = 0 self.closed = False - self.softspace = 0 def __iter__(self): return self @@ -291,14 +290,14 @@ if f.getvalue() != text: raise RuntimeError, 'write failed' length = f.tell() - print 'File length =', length + print('File length =', length) f.seek(len(lines[0])) f.write(lines[1]) f.seek(0) - print 'First line =', repr(f.readline()) - print 'Position =', f.tell() + print('First line =', repr(f.readline())) + print('Position =', f.tell()) line = f.readline() - print 'Second line =', repr(line) + print('Second line =', repr(line)) f.seek(-len(line), 1) line2 = f.read(len(line)) if line != line2: @@ -310,13 +309,13 @@ line2 = f.read() if line != line2: raise RuntimeError, 'bad result after seek back from EOF' - print 'Read', len(list), 'more lines' - print 'File length =', f.tell() + print('Read', len(list), 'more lines') + print('File length =', f.tell()) if f.tell() != length: raise RuntimeError, 'bad length' f.truncate(length/2) f.seek(0, 2) - print 'Truncated length =', f.tell() + print('Truncated length =', f.tell()) if f.tell() != length/2: raise RuntimeError, 'truncate did not adjust length' f.close() Modified: python/branches/p3yk-noslice/Lib/UserDict.py ============================================================================== --- python/branches/p3yk-noslice/Lib/UserDict.py (original) +++ python/branches/p3yk-noslice/Lib/UserDict.py Fri Feb 23 18:29:35 2007 @@ -42,9 +42,6 @@ return c def keys(self): return self.data.keys() def items(self): return self.data.items() - def iteritems(self): return self.data.iteritems() - def iterkeys(self): return self.data.iterkeys() - def itervalues(self): return self.data.itervalues() def values(self): return self.data.values() def update(self, dict=None, **kwargs): if dict is None: @@ -91,6 +88,8 @@ # methods, progressively more efficiency comes with defining # __contains__(), __iter__(), and iteritems(). + # XXX It would make more sense to expect __iter__ to be primitive. + # second level definitions support higher levels def __iter__(self): for k in self.keys(): @@ -103,11 +102,11 @@ return True # third level takes advantage of second level definitions + def iterkeys(self): + return self.__iter__() def iteritems(self): for k in self: yield (k, self[k]) - def iterkeys(self): - return self.__iter__() # fourth level uses definitions from lower levels def itervalues(self): @@ -118,7 +117,7 @@ def items(self): return list(self.iteritems()) def clear(self): - for key in self.keys(): + for key in list(self.iterkeys()): del self[key] def setdefault(self, key, default=None): try: @@ -152,6 +151,9 @@ elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups for k, v in other.iteritems(): self[k] = v + elif hasattr(other, 'items'): # items may also save memory and lookups + for k, v in other.items(): + self[k] = v elif hasattr(other, 'keys'): for k in other.keys(): self[k] = other[k] Modified: python/branches/p3yk-noslice/Lib/UserString.py ============================================================================== --- python/branches/p3yk-noslice/Lib/UserString.py (original) +++ python/branches/p3yk-noslice/Lib/UserString.py Fri Feb 23 18:29:35 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-noslice/Lib/_LWPCookieJar.py ============================================================================== --- python/branches/p3yk-noslice/Lib/_LWPCookieJar.py (original) +++ python/branches/p3yk-noslice/Lib/_LWPCookieJar.py Fri Feb 23 18:29:35 2007 @@ -37,8 +37,7 @@ if cookie.comment: h.append(("comment", cookie.comment)) if cookie.comment_url: h.append(("commenturl", cookie.comment_url)) - keys = cookie._rest.keys() - keys.sort() + keys = sorted(cookie._rest.keys()) for k in keys: h.append((k, str(cookie._rest[k]))) Modified: python/branches/p3yk-noslice/Lib/_strptime.py ============================================================================== --- python/branches/p3yk-noslice/Lib/_strptime.py (original) +++ python/branches/p3yk-noslice/Lib/_strptime.py Fri Feb 23 18:29:35 2007 @@ -22,9 +22,6 @@ except: from dummy_thread import allocate_lock as _thread_allocate_lock -__author__ = "Brett Cannon" -__email__ = "brett at python.org" - __all__ = ['strptime'] def _getlang(): @@ -273,11 +270,31 @@ _CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache _regex_cache = {} +def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon): + """Calculate the Julian day based on the year, week of the year, and day of + the week, with week_start_day representing whether the week of the year + assumes the week starts on Sunday or Monday (6 or 0).""" + first_weekday = datetime_date(year, 1, 1).weekday() + # If we are dealing with the %U directive (week starts on Sunday), it's + # easier to just shift the view to Sunday being the first day of the + # week. + if not week_starts_Mon: + first_weekday = (first_weekday + 1) % 7 + day_of_week = (day_of_week + 1) % 7 + # Need to watch out for a week 0 (when the first day of the year is not + # the same as that specified by %U or %W). + week_0_length = (7 - first_weekday) % 7 + if week_of_year == 0: + return 1 + day_of_week - first_weekday + else: + days_to_week = week_0_length + (7 * (week_of_year - 1)) + return 1 + days_to_week + day_of_week + + def strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a time struct based on the input string and the format string.""" global _TimeRE_cache, _regex_cache - _cache_lock.acquire() - try: + with _cache_lock: time_re = _TimeRE_cache locale_time = time_re.locale_time if _getlang() != locale_time.lang: @@ -302,8 +319,6 @@ except IndexError: raise ValueError("stray %% in format '%s'" % format) _regex_cache[format] = format_regex - finally: - _cache_lock.release() found = format_regex.match(data_string) if not found: raise ValueError("time data %r does not match format %r" % @@ -323,7 +338,7 @@ # values weekday = julian = -1 found_dict = found.groupdict() - for group_key in found_dict.iterkeys(): + for group_key in found_dict.keys(): # Directives not explicitly handled below: # c, x, X # handled by making out of other directives @@ -385,10 +400,10 @@ elif group_key in ('U', 'W'): week_of_year = int(found_dict[group_key]) if group_key == 'U': - # U starts week on Sunday + # U starts week on Sunday. week_of_year_start = 6 else: - # W starts week on Monday + # W starts week on Monday. week_of_year_start = 0 elif group_key == 'Z': # Since -1 is default value only need to worry about setting tz if @@ -406,42 +421,20 @@ tz = value break # If we know the week of the year and what day of that week, we can figure - # out the Julian day of the year - # Calculations below assume 0 is a Monday + # out the Julian day of the year. if julian == -1 and week_of_year != -1 and weekday != -1: - # Calculate how many days in week 0 - first_weekday = datetime_date(year, 1, 1).weekday() - preceeding_days = 7 - first_weekday - if preceeding_days == 7: - preceeding_days = 0 - # Adjust for U directive so that calculations are not dependent on - # directive used to figure out week of year - if weekday == 6 and week_of_year_start == 6: - week_of_year -= 1 - # If a year starts and ends on a Monday but a week is specified to - # start on a Sunday we need to up the week to counter-balance the fact - # that with %W that first Monday starts week 1 while with %U that is - # week 0 and thus shifts everything by a week - if weekday == 0 and first_weekday == 0 and week_of_year_start == 6: - week_of_year += 1 - # If in week 0, then just figure out how many days from Jan 1 to day of - # week specified, else calculate by multiplying week of year by 7, - # adding in days in week 0, and the number of days from Monday to the - # day of the week - if week_of_year == 0: - julian = 1 + weekday - first_weekday - else: - days_to_week = preceeding_days + (7 * (week_of_year - 1)) - julian = 1 + days_to_week + weekday + week_starts_Mon = True if week_of_year_start == 0 else False + julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, + week_starts_Mon) # Cannot pre-calculate datetime_date() since can change in Julian - #calculation and thus could have different value for the day of the week - #calculation + # calculation and thus could have different value for the day of the week + # calculation. if julian == -1: # Need to add 1 to result since first day of the year is 1, not 0. julian = datetime_date(year, month, day).toordinal() - \ datetime_date(year, 1, 1).toordinal() + 1 else: # Assume that if they bothered to include Julian day it will - #be accurate + # be accurate. datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal()) year = datetime_result.year month = datetime_result.month Modified: python/branches/p3yk-noslice/Lib/_threading_local.py ============================================================================== --- python/branches/p3yk-noslice/Lib/_threading_local.py (original) +++ python/branches/p3yk-noslice/Lib/_threading_local.py Fri Feb 23 18:29:35 2007 @@ -28,8 +28,7 @@ >>> log = [] >>> def f(): - ... items = mydata.__dict__.items() - ... items.sort() + ... items = sorted(mydata.__dict__.items()) ... log.append(items) ... mydata.number = 11 ... log.append(mydata.number) Modified: python/branches/p3yk-noslice/Lib/aifc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/aifc.py (original) +++ python/branches/p3yk-noslice/Lib/aifc.py Fri Feb 23 18:29:35 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) @@ -453,7 +453,7 @@ kludge = 0 if chunk.chunksize == 18: kludge = 1 - print 'Warning: bad COMM chunk size' + print('Warning: bad COMM chunk size') chunk.chunksize = 23 #DEBUG end self._comptype = chunk.read(4) @@ -518,11 +518,11 @@ # a position 0 and name '' self._markers.append((id, pos, name)) except EOFError: - print 'Warning: MARK chunk contains only', - print len(self._markers), - if len(self._markers) == 1: print 'marker', - else: print 'markers', - print 'instead of', nmarkers + print('Warning: MARK chunk contains only', end=' ') + print(len(self._markers), end=' ') + if len(self._markers) == 1: print('marker', end=' ') + else: print('markers', end=' ') + print('instead of', nmarkers) class Aifc_write: # Variables used in this class: @@ -939,16 +939,16 @@ sys.argv.append('/usr/demos/data/audio/bach.aiff') fn = sys.argv[1] f = open(fn, 'r') - print "Reading", fn - print "nchannels =", f.getnchannels() - print "nframes =", f.getnframes() - print "sampwidth =", f.getsampwidth() - print "framerate =", f.getframerate() - print "comptype =", f.getcomptype() - print "compname =", f.getcompname() + print("Reading", fn) + print("nchannels =", f.getnchannels()) + print("nframes =", f.getnframes()) + print("sampwidth =", f.getsampwidth()) + print("framerate =", f.getframerate()) + print("comptype =", f.getcomptype()) + print("compname =", f.getcompname()) if sys.argv[2:]: gn = sys.argv[2] - print "Writing", gn + print("Writing", gn) g = open(gn, 'w') g.setparams(f.getparams()) while 1: @@ -958,4 +958,4 @@ g.writeframes(data) g.close() f.close() - print "Done." + print("Done.") Modified: python/branches/p3yk-noslice/Lib/asynchat.py ============================================================================== --- python/branches/p3yk-noslice/Lib/asynchat.py (original) +++ python/branches/p3yk-noslice/Lib/asynchat.py Fri Feb 23 18:29:35 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-noslice/Lib/asyncore.py ============================================================================== --- python/branches/p3yk-noslice/Lib/asyncore.py (original) +++ python/branches/p3yk-noslice/Lib/asyncore.py Fri Feb 23 18:29:35 2007 @@ -373,7 +373,7 @@ def log_info(self, message, type='info'): if __debug__ or type != 'info': - print '%s: %s' % (type, message) + print('%s: %s' % (type, message)) def handle_read_event(self): if self.accepting: Modified: python/branches/p3yk-noslice/Lib/atexit.py ============================================================================== --- python/branches/p3yk-noslice/Lib/atexit.py (original) +++ python/branches/p3yk-noslice/Lib/atexit.py Fri Feb 23 18:29:35 2007 @@ -26,7 +26,7 @@ exc_info = sys.exc_info() except: import traceback - print >> sys.stderr, "Error in atexit._run_exitfuncs:" + print("Error in atexit._run_exitfuncs:", file=sys.stderr) traceback.print_exc() exc_info = sys.exc_info() @@ -53,11 +53,11 @@ if __name__ == "__main__": def x1(): - print "running x1" + print("running x1") def x2(n): - print "running x2(%r)" % (n,) + print("running x2(%r)" % (n,)) def x3(n, kwd=None): - print "running x3(%r, kwd=%r)" % (n, kwd) + print("running x3(%r, kwd=%r)" % (n, kwd)) register(x1) register(x2, 12) Modified: python/branches/p3yk-noslice/Lib/audiodev.py ============================================================================== --- python/branches/p3yk-noslice/Lib/audiodev.py (original) +++ python/branches/p3yk-noslice/Lib/audiodev.py Fri Feb 23 18:29:35 2007 @@ -240,7 +240,7 @@ fn = 'f:just samples:just.aif' import aifc af = aifc.open(fn, 'r') - print fn, af.getparams() + print(fn, af.getparams()) p = AudioDev() p.setoutrate(af.getframerate()) p.setsampwidth(af.getsampwidth()) @@ -249,7 +249,7 @@ while 1: data = af.readframes(BUFSIZ) if not data: break - print len(data) + print(len(data)) p.writeframes(data) p.wait() Modified: python/branches/p3yk-noslice/Lib/base64.py ============================================================================== --- python/branches/p3yk-noslice/Lib/base64.py (original) +++ python/branches/p3yk-noslice/Lib/base64.py Fri Feb 23 18:29:35 2007 @@ -126,10 +126,8 @@ 8: 'I', 17: 'R', 26: '2', } -_b32tab = _b32alphabet.items() -_b32tab.sort() -_b32tab = [v for k, v in _b32tab] -_b32rev = dict([(v, long(k)) for k, v in _b32alphabet.items()]) +_b32tab = [v for k, v in sorted(_b32alphabet.items())] +_b32rev = dict([(v, int(k)) for k, v in _b32alphabet.items()]) def b32encode(s): @@ -330,11 +328,11 @@ opts, args = getopt.getopt(sys.argv[1:], 'deut') except getopt.error as msg: sys.stdout = sys.stderr - print msg - print """usage: %s [-d|-e|-u|-t] [file|-] + print(msg) + print("""usage: %s [-d|-e|-u|-t] [file|-] -d, -u: decode -e: encode (default) - -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0] + -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]) sys.exit(2) func = encode for o, a in opts: @@ -352,7 +350,7 @@ s0 = "Aladdin:open sesame" s1 = encodestring(s0) s2 = decodestring(s1) - print s0, repr(s1), s2 + print(s0, repr(s1), s2) if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/bdb.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bdb.py (original) +++ python/branches/p3yk-noslice/Lib/bdb.py Fri Feb 23 18:29:35 2007 @@ -58,7 +58,7 @@ return self.trace_dispatch if event == 'c_return': return self.trace_dispatch - print 'bdb.Bdb.dispatch: unknown debugging event:', repr(event) + print('bdb.Bdb.dispatch: unknown debugging event:', repr(event)) return self.trace_dispatch def dispatch_line(self, frame): @@ -483,17 +483,17 @@ disp = disp + 'yes ' else: disp = disp + 'no ' - print >>out, '%-4dbreakpoint %s at %s:%d' % (self.number, disp, - self.file, self.line) + print('%-4dbreakpoint %s at %s:%d' % (self.number, disp, + self.file, self.line), file=out) if self.cond: - print >>out, '\tstop only if %s' % (self.cond,) + print('\tstop only if %s' % (self.cond,), file=out) if self.ignore: - print >>out, '\tignore next %d hits' % (self.ignore) + print('\tignore next %d hits' % (self.ignore), file=out) if (self.hits): if (self.hits > 1): ss = 's' else: ss = '' - print >>out, ('\tbreakpoint already hit %d time%s' % - (self.hits, ss)) + print(('\tbreakpoint already hit %d time%s' % + (self.hits, ss)), file=out) # -----------end of Breakpoint class---------- @@ -582,27 +582,27 @@ def user_call(self, frame, args): name = frame.f_code.co_name if not name: name = '???' - print '+++ call', name, args + print('+++ call', name, args) def user_line(self, frame): import linecache name = frame.f_code.co_name if not name: name = '???' fn = self.canonic(frame.f_code.co_filename) line = linecache.getline(fn, frame.f_lineno) - print '+++', fn, frame.f_lineno, name, ':', line.strip() + print('+++', fn, frame.f_lineno, name, ':', line.strip()) def user_return(self, frame, retval): - print '+++ return', retval + print('+++ return', retval) def user_exception(self, frame, exc_stuff): - print '+++ exception', exc_stuff + print('+++ exception', exc_stuff) self.set_continue() def foo(n): - print 'foo(', n, ')' + print('foo(', n, ')') x = bar(n*10) - print 'bar returned', x + print('bar returned', x) def bar(a): - print 'bar(', a, ')' + print('bar(', a, ')') return a/2 def test(): Modified: python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py Fri Feb 23 18:29:35 2007 @@ -39,7 +39,6 @@ self.len = None self.pos = 0 self.closed = 0 - self.softspace = 0 def close(self): if not self.closed: Modified: python/branches/p3yk-noslice/Lib/bsddb/dbtables.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/dbtables.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/dbtables.py Fri Feb 23 18:29:35 2007 @@ -208,12 +208,12 @@ def _db_print(self) : """Print the database to stdout for debugging""" - print "******** Printing raw database for debugging ********" + print("******** Printing raw database for debugging ********") cur = self.db.cursor() try: key, data = cur.first() while 1: - print repr({key: data}) + print(repr({key: data})) next = cur.next() if next: key, data = next @@ -546,7 +546,7 @@ self.__load_column_info(table) if columns is None: columns = self.tablecolumns[table] - for column in (columns + conditions.keys()): + for column in (columns + list(conditions.keys())): if not self.__tablecolumns[table].count(column): raise TableDBError, "unknown column: %r" % (column,) @@ -580,7 +580,7 @@ # leave all unknown condition callables alone as equals return 0 - conditionlist = conditions.items() + conditionlist = list(conditions.items()) conditionlist.sort(cmp_conditions) # Apply conditions to column data to find what we want Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_all.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_all.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_all.py Fri Feb 23 18:29:35 2007 @@ -22,15 +22,15 @@ def print_versions(): - print - print '-=' * 38 - print db.DB_VERSION_STRING - print 'bsddb.db.version(): %s' % (db.version(), ) - print 'bsddb.db.__version__: %s' % db.__version__ - print 'bsddb.db.cvsid: %s' % db.cvsid - print 'python version: %s' % sys.version - print 'My pid: %s' % os.getpid() - print '-=' * 38 + print() + print('-=' * 38) + print(db.DB_VERSION_STRING) + print('bsddb.db.version(): %s' % (db.version(), )) + print('bsddb.db.__version__: %s' % db.__version__) + print('bsddb.db.cvsid: %s' % db.cvsid) + print('python version: %s' % sys.version) + print('My pid: %s' % os.getpid()) + print('-=' * 38) class PrintInfoFakeTest(unittest.TestCase): Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py Fri Feb 23 18:29:35 2007 @@ -114,9 +114,9 @@ def test00_associateDBError(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test00_associateDBError..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test00_associateDBError..." % \ + self.__class__.__name__) dupDB = db.DB(self.env) dupDB.set_flags(db.DB_DUP) @@ -207,9 +207,9 @@ def test01_associateWithDB(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_associateWithDB..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_associateWithDB..." % \ + self.__class__.__name__) self.createDB() @@ -227,9 +227,9 @@ def test02_associateAfterDB(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_associateAfterDB..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_associateAfterDB..." % \ + self.__class__.__name__) self.createDB() self.addDataToDB(self.getDB()) @@ -257,7 +257,7 @@ vals[1].index('unknown') if verbose: - print "Primary key traversal:" + print("Primary key traversal:") self.cur = self.getDB().cursor(txn) count = 0 rec = self.cur.first() @@ -268,13 +268,13 @@ assert rec[0] and type(rec[0]) == type(0) count = count + 1 if verbose: - print rec + print(rec) rec = self.cur.next() assert count == len(musicdata) # all items accounted for if verbose: - print "Secondary key traversal:" + print("Secondary key traversal:") self.cur = secDB.cursor(txn) count = 0 @@ -294,7 +294,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) rec = self.cur.next() # all items accounted for EXCEPT for 1 with "Blues" genre assert count == len(musicdata)-1 @@ -304,7 +304,7 @@ def getGenre(self, priKey, priData): assert type(priData) == type("") if verbose: - print 'getGenre key: %r data: %r' % (priKey, priData) + print('getGenre key: %r data: %r' % (priKey, priData)) genre = string.split(priData, '|')[2] if genre == 'Blues': return db.DB_DONOTINDEX @@ -343,9 +343,9 @@ def test13_associate_in_transaction(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test13_associateAutoCommit..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test13_associateAutoCommit..." % \ + self.__class__.__name__) txn = self.env.txn_begin() try: @@ -389,7 +389,7 @@ def getGenre(self, priKey, priData): assert type(priData) == type(()) if verbose: - print 'getGenre key: %r data: %r' % (priKey, priData) + print('getGenre key: %r data: %r' % (priKey, priData)) genre = priData[2] if genre == 'Blues': return db.DB_DONOTINDEX Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py Fri Feb 23 18:29:35 2007 @@ -31,10 +31,10 @@ def test00_version(self): info = db.version() if verbose: - print '\n', '-=' * 20 - print 'bsddb.db.version(): %s' % (info, ) - print db.DB_VERSION_STRING - print '-=' * 20 + print('\n', '-=' * 20) + print('bsddb.db.version(): %s' % (info, )) + print(db.DB_VERSION_STRING) + print('-=' * 20) assert info == (db.DB_VERSION_MAJOR, db.DB_VERSION_MINOR, db.DB_VERSION_PATCH) @@ -131,7 +131,7 @@ num = len(d) if verbose: - print "created %d records" % num + print("created %d records" % num) def makeData(self, key): @@ -145,13 +145,13 @@ d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_GetsAndPuts..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_GetsAndPuts..." % self.__class__.__name__) for key in ['0001', '0100', '0400', '0700', '0999']: data = d.get(key) if verbose: - print data + print(data) assert d.get('0321') == '0321-0321-0321-0321-0321' @@ -164,7 +164,7 @@ d.delete('abcd') except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) else: self.fail("expected exception") @@ -183,7 +183,7 @@ d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE) except db.DBKeyExistError as val: assert val[0] == db.DB_KEYEXIST - if verbose: print val + if verbose: print(val) else: self.fail("expected exception") @@ -212,7 +212,7 @@ rec = d.get_both('0555', '0555-0555-0555-0555-0555') if verbose: - print rec + print(rec) assert d.get_both('0555', 'bad data') == None @@ -227,7 +227,7 @@ s = d.stat() assert type(s) == type({}) if verbose: - print 'd.stat() returned this dictionary:' + print('d.stat() returned this dictionary:') pprint(s) @@ -237,15 +237,15 @@ d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_DictionaryMethods..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_DictionaryMethods..." % \ + self.__class__.__name__) for key in ['0002', '0101', '0401', '0701', '0998']: data = d[key] assert data == self.makeData(key) if verbose: - print data + print(data) assert len(d) == self._numKeys keys = d.keys() @@ -263,7 +263,7 @@ assert len(keys) == self._numKeys+1 if verbose: - print "the first 10 keys are:" + print("the first 10 keys are:") pprint(keys[:10]) assert d['new record'] == 'a replacement record' @@ -278,7 +278,7 @@ assert len(items[0]) == 2 if verbose: - print "the first 10 items are:" + print("the first 10 items are:") pprint(items[:10]) values = d.values() @@ -286,7 +286,7 @@ assert type(values) == type([]) if verbose: - print "the first 10 values are:" + print("the first 10 values are:") pprint(values[:10]) @@ -295,9 +295,9 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0): if verbose: - print '\n', '-=' * 30 - print "Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \ - (self.__class__.__name__, get_raises_error, set_raises_error) + print('\n', '-=' * 30) + print("Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \ + (self.__class__.__name__, get_raises_error, set_raises_error)) if self.env and self.dbopenflags & db.DB_AUTO_COMMIT: txn = self.env.txn_begin() @@ -310,13 +310,13 @@ while rec is not None: count = count + 1 if verbose and count % 100 == 0: - print rec + print(rec) try: rec = c.next() except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) rec = None else: self.fail("unexpected DBNotFoundError") @@ -330,13 +330,13 @@ while rec is not None: count = count + 1 if verbose and count % 100 == 0: - print rec + print(rec) try: rec = c.prev() except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) rec = None else: self.fail("unexpected DBNotFoundError") @@ -359,7 +359,7 @@ n = c.set('bad key') except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) else: if set_raises_error: self.fail("expected exception") @@ -373,7 +373,7 @@ n = c.get_both('0404', 'bad data') except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) else: if get_raises_error: self.fail("expected exception") @@ -383,16 +383,16 @@ if self.d.get_type() == db.DB_BTREE: rec = c.set_range('011') if verbose: - print "searched for '011', found: ", rec + print("searched for '011', found: ", rec) rec = c.set_range('011',dlen=0,doff=0) if verbose: - print "searched (partial) for '011', found: ", rec + print("searched (partial) for '011', found: ", rec) if rec[1] != '': self.fail('expected empty data portion') ev = c.set_range('empty value') if verbose: - print "search for 'empty value' returned", ev + print("search for 'empty value' returned", ev) if ev[1] != '': self.fail('empty value lookup failed') c.set('0499') @@ -402,7 +402,7 @@ except db.DBKeyEmptyError as val: if get_raises_error: assert val[0] == db.DB_KEYEMPTY - if verbose: print val + if verbose: print(val) else: self.fail("unexpected DBKeyEmptyError") else: @@ -441,13 +441,13 @@ for method, args in methods_to_test.items(): try: if verbose: - print "attempting to use a closed cursor's %s method" % \ - method + print("attempting to use a closed cursor's %s method" % \ + method) # a bug may cause a NULL pointer dereference... getattr(c, method)(*args) except db.DBError as val: assert val[0] == 0 - if verbose: print val + if verbose: print(val) else: self.fail("no exception raised when using a buggy cursor's" "%s method" % method) @@ -466,9 +466,9 @@ def test03b_SimpleCursorWithoutGetReturnsNone0(self): # same test but raise exceptions instead of returning None if verbose: - print '\n', '-=' * 30 - print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ + self.__class__.__name__) old = self.d.set_get_returns_none(0) assert old == 2 @@ -477,9 +477,9 @@ def test03b_SimpleCursorWithGetReturnsNone1(self): # same test but raise exceptions instead of returning None if verbose: - print '\n', '-=' * 30 - print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ + self.__class__.__name__) old = self.d.set_get_returns_none(1) self.test03_SimpleCursorStuff(get_raises_error=0, set_raises_error=1) @@ -488,9 +488,9 @@ def test03c_SimpleCursorGetReturnsNone2(self): # same test but raise exceptions instead of returning None if verbose: - print '\n', '-=' * 30 - print "Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \ + self.__class__.__name__) old = self.d.set_get_returns_none(1) assert old == 2 @@ -503,9 +503,9 @@ def test04_PartialGetAndPut(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test04_PartialGetAndPut..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test04_PartialGetAndPut..." % \ + self.__class__.__name__) key = "partialTest" data = "1" * 1000 + "2" * 1000 @@ -533,8 +533,8 @@ def test05_GetSize(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test05_GetSize..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test05_GetSize..." % self.__class__.__name__) for i in range(1, 50000, 500): key = "size%s" % i @@ -553,8 +553,8 @@ d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test99_Truncate..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test99_Truncate..." % self.__class__.__name__) d.put("abcde", "ABCDE"); num = d.truncate() @@ -598,8 +598,8 @@ return if verbose: - print '\n', '-=' * 30 - print "Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__) # can't rename or remove an open DB self.d.close() @@ -647,8 +647,8 @@ def test06_Transactions(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test06_Transactions..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test06_Transactions..." % self.__class__.__name__) assert d.get('new rec', txn=self.txn) == None d.put('new rec', 'this is a new record', self.txn) @@ -671,7 +671,7 @@ while rec is not None: count = count + 1 if verbose and count % 100 == 0: - print rec + print(rec) rec = c.next() assert count == self._numKeys+1 @@ -696,7 +696,7 @@ assert logs != None for log in logs: if verbose: - print 'log file: ' + log + print('log file: ' + log) if db.version() >= (4,2): logs = self.env.log_archive(db.DB_ARCH_REMOVE) assert not logs @@ -712,8 +712,8 @@ d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test07_TxnTruncate..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test07_TxnTruncate..." % self.__class__.__name__) d.put("abcde", "ABCDE"); txn = self.env.txn_begin() @@ -762,21 +762,21 @@ def test07_RecnoInBTree(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test07_RecnoInBTree..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test07_RecnoInBTree..." % self.__class__.__name__) rec = d.get(200) assert type(rec) == type(()) assert len(rec) == 2 if verbose: - print "Record #200 is ", rec + print("Record #200 is ", rec) c = d.cursor() c.set('0200') num = c.get_recno() assert type(num) == type(1) if verbose: - print "recno of d['0200'] is ", num + print("recno of d['0200'] is ", num) rec = c.current() assert c.set_recno(num) == rec @@ -796,9 +796,9 @@ def test08_DuplicateKeys(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test08_DuplicateKeys..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test08_DuplicateKeys..." % \ + self.__class__.__name__) d.put("dup0", "before") for x in "The quick brown fox jumped over the lazy dog.".split(): @@ -808,7 +808,7 @@ data = d.get("dup1") assert data == "The" if verbose: - print data + print(data) c = d.cursor() rec = c.set("dup1") @@ -827,14 +827,14 @@ rec = c.set('dup1') while rec is not None: if verbose: - print rec + print(rec) rec = c.next_dup() c.set('dup1') rec = c.next_nodup() assert rec[0] != 'dup1' if verbose: - print rec + print(rec) c.close() @@ -869,8 +869,8 @@ def test09_MultiDB(self): d1 = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test09_MultiDB..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test09_MultiDB..." % self.__class__.__name__) d2 = db.DB(self.env) d2.open(self.filename, "second", self.dbtype, @@ -910,7 +910,7 @@ while rec is not None: count = count + 1 if verbose and (count % 50) == 0: - print rec + print(rec) rec = c1.next() assert count == self._numKeys @@ -919,7 +919,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) rec = c2.next() assert count == 9 @@ -928,7 +928,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) rec = c3.next() assert count == 52 Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py Fri Feb 23 18:29:35 2007 @@ -37,7 +37,7 @@ def test03_rnopen(self): data = string.split("The quick brown fox jumped over the lazy dog.") if verbose: - print "\nTesting: rnopen" + print("\nTesting: rnopen") f = rnopen(self.filename, 'c') for x in range(len(data)): @@ -45,7 +45,7 @@ getTest = (f[1], f[2], f[3]) if verbose: - print '%s %s %s' % getTest + print('%s %s %s' % getTest) assert getTest[1] == 'quick', 'data mismatch!' @@ -73,7 +73,7 @@ rec = f.first() while rec: if verbose: - print rec + print(rec) try: rec = f.next() except KeyError: @@ -89,17 +89,17 @@ def do_bthash_test(self, factory, what): if verbose: - print '\nTesting: ', what + print('\nTesting: ', what) f = factory(self.filename, 'c') if verbose: - print 'creation...' + print('creation...') # truth test if f: - if verbose: print "truth test: true" + if verbose: print("truth test: true") else: - if verbose: print "truth test: false" + if verbose: print("truth test: false") f['0'] = '' f['a'] = 'Guido' @@ -109,10 +109,10 @@ # 'e' intentionally left out f['f'] = 'Python' if verbose: - print '%s %s %s' % (f['a'], f['b'], f['c']) + print('%s %s %s' % (f['a'], f['b'], f['c'])) if verbose: - print 'key ordering...' + print('key ordering...') start = f.set_location(f.first()[0]) if start != ('0', ''): self.fail("incorrect first() result: "+repr(start)) @@ -124,7 +124,7 @@ f.previous() break if verbose: - print rec + print(rec) assert f.has_key('f'), 'Error, missing key!' @@ -147,9 +147,9 @@ # truth test try: if f: - if verbose: print "truth test: true" + if verbose: print("truth test: true") else: - if verbose: print "truth test: false" + if verbose: print("truth test: false") except db.DBError: pass else: @@ -158,16 +158,16 @@ del f if verbose: - print 'modification...' + print('modification...') f = factory(self.filename, 'w') f['d'] = 'discovered' if verbose: - print 'access...' + print('access...') for key in f.keys(): word = f[key] if verbose: - print word + print(word) def noRec(f): rec = f['no such key'] Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_dbshelve.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_dbshelve.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_dbshelve.py Fri Feb 23 18:29:35 2007 @@ -79,8 +79,8 @@ def test01_basics(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_basics..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_basics..." % self.__class__.__name__) self.populateDB(self.d) self.d.sync() @@ -94,9 +94,9 @@ f = d.fd() if verbose: - print "length:", l - print "keys:", k - print "stats:", s + print("length:", l) + print("keys:", k) + print("stats:", s) assert 0 == d.has_key('bad key') assert 1 == d.has_key('IA') @@ -113,7 +113,7 @@ value = d[key] values.append(value) if verbose: - print "%s: %s" % (key, value) + print("%s: %s" % (key, value)) self.checkrec(key, value) dbvalues = sorted(d.values(), key=lambda x: (str(type(x)), x)) @@ -144,8 +144,8 @@ def test02_cursors(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_cursors..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_cursors..." % self.__class__.__name__) self.populateDB(self.d) d = self.d @@ -156,7 +156,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) key, value = rec self.checkrec(key, value) rec = c.next() @@ -170,7 +170,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) key, value = rec self.checkrec(key, value) rec = c.prev() Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_dbtables.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_dbtables.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_dbtables.py Fri Feb 23 18:29:35 2007 @@ -76,6 +76,7 @@ values = self.tdb.Select( tabname, [colname], conditions={colname: None}) + values = list(values) colval = pickle.loads(values[0][colname]) assert(colval > 3.141 and colval < 3.142) @@ -102,6 +103,7 @@ values = self.tdb.Select(tabname, [col2], conditions={col0: lambda x: pickle.loads(x) >= 8}) + values = list(values) assert len(values) == 2 if values[0]['Species'] == 'Penguin' : @@ -110,7 +112,7 @@ assert values[1]['Species'] == 'Penguin' else : if verbose: - print "values= %r" % (values,) + print("values= %r" % (values,)) raise "Wrong values returned!" def test03(self): @@ -120,15 +122,15 @@ except dbtables.TableDBError: pass if verbose: - print '...before CreateTable...' + print('...before CreateTable...') self.tdb._db_print() self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e']) if verbose: - print '...after CreateTable...' + print('...after CreateTable...') self.tdb._db_print() self.tdb.Drop(tabname) if verbose: - print '...after Drop...' + print('...after Drop...') self.tdb._db_print() self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e']) @@ -179,11 +181,13 @@ values = self.tdb.Select( tabname, ['a', 'd', 'b'], conditions={'e': dbtables.PrefixCond('Fuzzy')}) + values = list(values) assert len(values) == 1 assert values[0]['d'] == None values = self.tdb.Select(tabname, ['b'], conditions={'c': lambda c: c == 'meep'}) + values = list(values) assert len(values) == 1 assert values[0]['b'] == "bad" @@ -272,6 +276,7 @@ values = self.tdb.Select( tabname, ['p', 'e'], conditions={'e': dbtables.PrefixCond('the l')}) + values = list(values) assert len(values) == 2, values assert values[0]['e'] == values[1]['e'], values assert values[0]['p'] != values[1]['p'], values @@ -279,6 +284,7 @@ values = self.tdb.Select( tabname, ['d', 'a'], conditions={'a': dbtables.LikeCond('%aardvark%')}) + values = list(values) assert len(values) == 1, values assert values[0]['d'] == "is for dog", values assert values[0]['a'] == "is for aardvark", values @@ -290,6 +296,7 @@ 'd':dbtables.ExactCond('is for dog'), 'c':dbtables.PrefixCond('is for'), 'p':lambda s: not s}) + values = list(values) assert len(values) == 1, values assert values[0]['d'] == "is for dog", values assert values[0]['a'] == "is for aardvark", values @@ -354,6 +361,7 @@ values = self.tdb.Select( tabname, None, conditions={'Type': dbtables.ExactCond('Unknown')}) + values = list(values) assert len(values) == 1, values assert values[0]['Name'] == None, values assert values[0]['Access'] == None, values @@ -362,6 +370,7 @@ values = self.tdb.Select( tabname, None, conditions={'Name': dbtables.ExactCond('Nifty.MP3')}) + values = list(values) assert len(values) == 1, values assert values[0]['Type'] == "MP3", values assert values[0]['Access'] == "2", values @@ -369,6 +378,7 @@ # Make sure change applied only to select conditions values = self.tdb.Select( tabname, None, conditions={'Name': dbtables.LikeCond('%doc%')}) + values = list(values) assert len(values) == 1, values assert values[0]['Type'] == "Word", values assert values[0]['Access'] == "9", values Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py Fri Feb 23 18:29:35 2007 @@ -65,9 +65,9 @@ def test01_join(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_join..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_join..." % \ + self.__class__.__name__) # create and populate primary index priDB = db.DB(self.env) Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py Fri Feb 23 18:29:35 2007 @@ -49,27 +49,27 @@ def test01_simple(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_simple..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_simple..." % self.__class__.__name__) anID = self.env.lock_id() if verbose: - print "locker ID: %s" % anID + print("locker ID: %s" % anID) lock = self.env.lock_get(anID, "some locked thing", db.DB_LOCK_WRITE) if verbose: - print "Aquired lock: %s" % lock + print("Aquired lock: %s" % lock) time.sleep(1) self.env.lock_put(lock) if verbose: - print "Released lock: %s" % lock + print("Released lock: %s" % lock) def test02_threaded(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_threaded..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_threaded..." % self.__class__.__name__) threads = [] threads.append(Thread(target = self.theThread, @@ -113,17 +113,17 @@ anID = self.env.lock_id() if verbose: - print "%s: locker ID: %s" % (name, anID) + print("%s: locker ID: %s" % (name, anID)) lock = self.env.lock_get(anID, "some locked thing", lockType) if verbose: - print "%s: Aquired %s lock: %s" % (name, lt, lock) + print("%s: Aquired %s lock: %s" % (name, lt, lock)) time.sleep(sleepTime) self.env.lock_put(lock) if verbose: - print "%s: Released %s lock: %s" % (name, lt, lock) + print("%s: Released %s lock: %s" % (name, lt, lock)) #---------------------------------------------------------------------- Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_queue.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_queue.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_queue.py Fri Feb 23 18:29:35 2007 @@ -34,15 +34,15 @@ # Basic Queue tests using the deprecated DBCursor.consume method. if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_basic..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_basic..." % self.__class__.__name__) d = db.DB() d.set_re_len(40) # Queues must be fixed length d.open(self.filename, db.DB_QUEUE, db.DB_CREATE) if verbose: - print "before appends" + '-' * 30 + print("before appends" + '-' * 30) pprint(d.stat()) for x in string.letters: @@ -58,7 +58,7 @@ assert len(d) == 55 if verbose: - print "before close" + '-' * 30 + print("before close" + '-' * 30) pprint(d.stat()) d.close() @@ -67,25 +67,25 @@ d.open(self.filename) if verbose: - print "after open" + '-' * 30 + print("after open" + '-' * 30) pprint(d.stat()) d.append("one more") c = d.cursor() if verbose: - print "after append" + '-' * 30 + print("after append" + '-' * 30) pprint(d.stat()) rec = c.consume() while rec: if verbose: - print rec + print(rec) rec = c.consume() c.close() if verbose: - print "after consume loop" + '-' * 30 + print("after consume loop" + '-' * 30) pprint(d.stat()) assert len(d) == 0, \ @@ -101,12 +101,12 @@ # (No cursor needed) if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_basicPost32..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_basicPost32..." % self.__class__.__name__) if db.version() < (3, 2, 0): if verbose: - print "Test not run, DB not new enough..." + print("Test not run, DB not new enough...") return d = db.DB() @@ -114,7 +114,7 @@ d.open(self.filename, db.DB_QUEUE, db.DB_CREATE) if verbose: - print "before appends" + '-' * 30 + print("before appends" + '-' * 30) pprint(d.stat()) for x in string.letters: @@ -130,7 +130,7 @@ assert len(d) == 55 if verbose: - print "before close" + '-' * 30 + print("before close" + '-' * 30) pprint(d.stat()) d.close() @@ -140,23 +140,23 @@ #d.set_get_returns_none(true) if verbose: - print "after open" + '-' * 30 + print("after open" + '-' * 30) pprint(d.stat()) d.append("one more") if verbose: - print "after append" + '-' * 30 + print("after append" + '-' * 30) pprint(d.stat()) rec = d.consume() while rec: if verbose: - print rec + print(rec) rec = d.consume() if verbose: - print "after consume loop" + '-' * 30 + print("after consume loop" + '-' * 30) pprint(d.stat()) d.close() Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py Fri Feb 23 18:29:35 2007 @@ -45,9 +45,9 @@ assert type(recno) == type(0) assert recno >= 1 if verbose: - print recno, + print(recno, end=' ') - if verbose: print + if verbose: print() stat = d.stat() if verbose: @@ -56,7 +56,7 @@ for recno in range(1, len(d)+1): data = d[recno] if verbose: - print data + print(data) assert type(data) == type("") assert data == d.get(recno) @@ -65,7 +65,7 @@ data = d[0] # This should raise a KeyError!?!?! except db.DBInvalidArgError as val: assert val[0] == db.EINVAL - if verbose: print val + if verbose: print(val) else: self.fail("expected exception") @@ -94,7 +94,7 @@ keys = d.keys() if verbose: - print keys + print(keys) assert type(keys) == type([]) assert type(keys[0]) == type(123) assert len(keys) == len(d) @@ -120,23 +120,23 @@ data = d.get_both(26, "z" * 60) assert data == "z" * 60 if verbose: - print data + print(data) fd = d.fd() if verbose: - print fd + print(fd) c = d.cursor() rec = c.first() while rec: if verbose: - print rec + print(rec) rec = c.next() c.set(50) rec = c.current() if verbose: - print rec + print(rec) c.put(-1, "a replacement record", db.DB_CURRENT) @@ -144,18 +144,18 @@ rec = c.current() assert rec == (50, "a replacement record") if verbose: - print rec + print(rec) rec = c.set_range(30) if verbose: - print rec + print(rec) # test that non-existant key lookups work (and that # DBC_set_range doesn't have a memleak under valgrind) rec = c.set_range(999999) assert rec == None if verbose: - print rec + print(rec) c.close() d.close() @@ -182,7 +182,7 @@ self.fail("unexpected DBKeyEmptyError exception") else: assert val[0] == db.DB_KEYEMPTY - if verbose: print val + if verbose: print(val) else: if not get_returns_none: self.fail("expected exception") @@ -190,7 +190,7 @@ rec = c.set(40) while rec: if verbose: - print rec + print(rec) rec = c.next() c.close() @@ -227,9 +227,9 @@ text = open(source, 'r').read() text = text.strip() if verbose: - print text - print data - print text.split('\n') + print(text) + print(data) + print(text.split('\n')) assert text.split('\n') == data @@ -247,8 +247,8 @@ text = open(source, 'r').read() text = text.strip() if verbose: - print text - print text.split('\n') + print(text) + print(text.split('\n')) assert text.split('\n') == \ "The quick reddish-brown fox jumped over the comatose dog".split() @@ -269,7 +269,7 @@ d.append('bad' * 20) except db.DBInvalidArgError as val: assert val[0] == db.EINVAL - if verbose: print val + if verbose: print(val) else: self.fail("expected exception") @@ -277,7 +277,7 @@ rec = c.first() while rec: if verbose: - print rec + print(rec) rec = c.next() c.close() Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py Fri Feb 23 18:29:35 2007 @@ -93,9 +93,9 @@ def test01_1WriterMultiReaders(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_1WriterMultiReaders..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_1WriterMultiReaders..." % \ + self.__class__.__name__) threads = [] for x in range(self.writers): @@ -123,17 +123,17 @@ start = howMany * writerNum stop = howMany * (writerNum + 1) - 1 if verbose: - print "%s: creating records %d - %d" % (name, start, stop) + print("%s: creating records %d - %d" % (name, start, stop)) for x in range(start, stop): key = '%04d' % x dbutils.DeadlockWrap(d.put, key, self.makeData(key), max_retries=12) if verbose and x % 100 == 0: - print "%s: records %d - %d finished" % (name, start, x) + print("%s: records %d - %d finished" % (name, start, x)) if verbose: - print "%s: finished creating records" % name + print("%s: finished creating records" % name) ## # Each write-cursor will be exclusive, the only one that can update the DB... ## if verbose: print "%s: deleting a few records" % name @@ -147,7 +147,7 @@ ## c.close() if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) def readerThread(self, d, readerNum): time.sleep(0.01 * readerNum) @@ -163,12 +163,12 @@ self.assertEqual(self.makeData(key), data) rec = c.next() if verbose: - print "%s: found %d records" % (name, count) + print("%s: found %d records" % (name, count)) c.close() time.sleep(0.05) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) class BTreeConcurrentDataStore(ConcurrentDataStoreBase): @@ -199,8 +199,8 @@ def test02_SimpleLocks(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_SimpleLocks..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_SimpleLocks..." % self.__class__.__name__) threads = [] for x in range(self.writers): @@ -226,7 +226,7 @@ start = howMany * writerNum stop = howMany * (writerNum + 1) - 1 if verbose: - print "%s: creating records %d - %d" % (name, start, stop) + print("%s: creating records %d - %d" % (name, start, stop)) # create a bunch of records for x in xrange(start, stop): @@ -235,7 +235,7 @@ max_retries=12) if verbose and x % 100 == 0: - print "%s: records %d - %d finished" % (name, start, x) + print("%s: records %d - %d finished" % (name, start, x)) # do a bit or reading too if random() <= 0.05: @@ -249,22 +249,22 @@ dbutils.DeadlockWrap(d.sync, max_retries=12) except db.DBIncompleteError as val: if verbose: - print "could not complete sync()..." + print("could not complete sync()...") # read them back, deleting a few for x in xrange(start, stop): key = '%04d' % x data = dbutils.DeadlockWrap(d.get, key, max_retries=12) if verbose and x % 100 == 0: - print "%s: fetched record (%s, %s)" % (name, key, data) + print("%s: fetched record (%s, %s)" % (name, key, data)) self.assertEqual(data, self.makeData(key)) if random() <= 0.10: dbutils.DeadlockWrap(d.delete, key, max_retries=12) if verbose: - print "%s: deleted record %s" % (name, key) + print("%s: deleted record %s" % (name, key)) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) def readerThread(self, d, readerNum): time.sleep(0.01 * readerNum) @@ -280,12 +280,12 @@ self.assertEqual(self.makeData(key), data) rec = dbutils.DeadlockWrap(c.next, max_retries=10) if verbose: - print "%s: found %d records" % (name, count) + print("%s: found %d records" % (name, count)) c.close() time.sleep(0.05) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) class BTreeSimpleThreaded(SimpleThreadedBase): @@ -318,9 +318,9 @@ def test03_ThreadedTransactions(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test03_ThreadedTransactions..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test03_ThreadedTransactions..." % \ + self.__class__.__name__) threads = [] for x in range(self.writers): @@ -357,12 +357,12 @@ key = '%04d' % x d.put(key, self.makeData(key), txn) if verbose and x % 100 == 0: - print "%s: records %d - %d finished" % (name, start, x) + print("%s: records %d - %d finished" % (name, start, x)) txn.commit() finished = True except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: - print "%s: Aborting transaction (%s)" % (name, val[1]) + print("%s: Aborting transaction (%s)" % (name, val[1])) txn.abort() time.sleep(0.05) @@ -371,16 +371,16 @@ start = howMany * writerNum stop = howMany * (writerNum + 1) - 1 if verbose: - print "%s: creating records %d - %d" % (name, start, stop) + print("%s: creating records %d - %d" % (name, start, stop)) step = 100 for x in range(start, stop, step): self.doWrite(d, name, x, min(stop, x+step)) if verbose: - print "%s: finished creating records" % name + print("%s: finished creating records" % name) if verbose: - print "%s: deleting a few records" % name + print("%s: deleting a few records" % name) finished = False while not finished: @@ -397,15 +397,15 @@ txn.commit() finished = True if verbose: - print "%s: deleted records %s" % (name, recs) + print("%s: deleted records %s" % (name, recs)) except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: - print "%s: Aborting transaction (%s)" % (name, val[1]) + print("%s: Aborting transaction (%s)" % (name, val[1])) txn.abort() time.sleep(0.05) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) def readerThread(self, d, readerNum): time.sleep(0.01 * readerNum + 0.05) @@ -424,13 +424,13 @@ key, data = rec self.assertEqual(self.makeData(key), data) rec = c.next() - if verbose: print "%s: found %d records" % (name, count) + if verbose: print("%s: found %d records" % (name, count)) c.close() txn.commit() finished = True except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: - print "%s: Aborting transaction (%s)" % (name, val[1]) + print("%s: Aborting transaction (%s)" % (name, val[1])) c.close() txn.abort() time.sleep(0.05) @@ -438,7 +438,7 @@ time.sleep(0.05) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) def deadlockThread(self): self.doLockDetect = True @@ -448,8 +448,8 @@ aborted = self.env.lock_detect( db.DB_LOCK_RANDOM, db.DB_LOCK_CONFLICT) if verbose and aborted: - print "deadlock: Aborted %d deadlocked transaction(s)" \ - % aborted + print("deadlock: Aborted %d deadlocked transaction(s)" \ + % aborted) except db.DBError: pass @@ -497,7 +497,7 @@ suite.addTest(unittest.makeSuite(HashThreadedNoWaitTransactions)) else: - print "Threads not available, skipping thread tests." + print("Threads not available, skipping thread tests.") return suite Modified: python/branches/p3yk-noslice/Lib/cProfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/cProfile.py (original) +++ python/branches/p3yk-noslice/Lib/cProfile.py Fri Feb 23 18:29:35 2007 @@ -58,8 +58,8 @@ # Backwards compatibility. def help(): - print "Documentation for the profile/cProfile modules can be found " - print "in the Python Library Reference, section 'The Python Profiler'." + print("Documentation for the profile/cProfile modules can be found ") + print("in the Python Library Reference, section 'The Python Profiler'.") # ____________________________________________________________ Modified: python/branches/p3yk-noslice/Lib/calendar.py ============================================================================== --- python/branches/p3yk-noslice/Lib/calendar.py (original) +++ python/branches/p3yk-noslice/Lib/calendar.py Fri Feb 23 18:29:35 2007 @@ -261,7 +261,7 @@ """ Print a single week (no newline). """ - print self.week(theweek, width), + print(self.week(theweek, width), end=' ') def formatday(self, day, weekday, width): """ @@ -308,7 +308,7 @@ """ Print a month's calendar. """ - print self.formatmonth(theyear, themonth, w, l), + print(self.formatmonth(theyear, themonth, w, l), end=' ') def formatmonth(self, theyear, themonth, w=0, l=0): """ @@ -365,7 +365,7 @@ def pryear(self, theyear, w=0, l=0, c=6, m=3): """Print a year's calendar.""" - print self.formatyear(theyear, w, l, c, m) + print(self.formatyear(theyear, w, l, c, m)) class HTMLCalendar(Calendar): @@ -584,7 +584,7 @@ def format(cols, colwidth=_colwidth, spacing=_spacing): """Prints multi-column formatting for year calendars""" - print formatstring(cols, colwidth, spacing) + print(formatstring(cols, colwidth, spacing)) def formatstring(cols, colwidth=_colwidth, spacing=_spacing): @@ -668,9 +668,9 @@ encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: - print cal.formatyearpage(datetime.date.today().year, **optdict) + print(cal.formatyearpage(datetime.date.today().year, **optdict)) elif len(args) == 2: - print cal.formatyearpage(int(args[1]), **optdict) + print(cal.formatyearpage(int(args[1]), **optdict)) else: parser.error("incorrect number of arguments") sys.exit(1) @@ -694,7 +694,7 @@ sys.exit(1) if options.encoding: result = result.encode(options.encoding) - print result + print(result) if __name__ == "__main__": Modified: python/branches/p3yk-noslice/Lib/cgi.py ============================================================================== --- python/branches/p3yk-noslice/Lib/cgi.py (original) +++ python/branches/p3yk-noslice/Lib/cgi.py Fri Feb 23 18:29:35 2007 @@ -901,8 +901,8 @@ the script in HTML form. """ - print "Content-type: text/html" - print + print("Content-type: text/html") + print() sys.stderr = sys.stdout try: form = FieldStorage() # Replace with other classes to test those @@ -915,12 +915,12 @@ exec("testing print_exception() -- italics?") def g(f=f): f() - print "

What follows is a test, not an actual exception:

" + print("

What follows is a test, not an actual exception:

") g() except: print_exception() - print "

Second try with a small maxlen...

" + print("

Second try with a small maxlen...

") global maxlen maxlen = 50 @@ -937,67 +937,67 @@ if type is None: type, value, tb = sys.exc_info() import traceback - print - print "

Traceback (most recent call last):

" + print() + print("

Traceback (most recent call last):

") list = traceback.format_tb(tb, limit) + \ traceback.format_exception_only(type, value) - print "
%s%s
" % ( + print("
%s%s
" % ( escape("".join(list[:-1])), escape(list[-1]), - ) + )) del tb def print_environ(environ=os.environ): """Dump the shell environment as HTML.""" keys = environ.keys() keys.sort() - print - print "

Shell Environment:

" - print "
" + print() + print("

Shell Environment:

") + print("
") for key in keys: - print "
", escape(key), "
", escape(environ[key]) - print "
" - print + print("
", escape(key), "
", escape(environ[key])) + print("
") + print() def print_form(form): """Dump the contents of a form as HTML.""" keys = form.keys() keys.sort() - print - print "

Form Contents:

" + print() + print("

Form Contents:

") if not keys: - print "

No form fields." - print "

" + print("

No form fields.") + print("

") for key in keys: - print "
" + escape(key) + ":", + print("
" + escape(key) + ":", end=' ') value = form[key] - print "" + escape(repr(type(value))) + "" - print "
" + escape(repr(value)) - print "
" - print + print("" + escape(repr(type(value))) + "") + print("
" + escape(repr(value))) + print("
") + print() def print_directory(): """Dump the current directory as HTML.""" - print - print "

Current Working Directory:

" + print() + print("

Current Working Directory:

") try: pwd = os.getcwd() except os.error as msg: - print "os.error:", escape(str(msg)) + print("os.error:", escape(str(msg))) else: - print escape(pwd) - print + print(escape(pwd)) + print() def print_arguments(): - print - print "

Command Line Arguments:

" - print - print sys.argv - print + print() + print("

Command Line Arguments:

") + print() + print(sys.argv) + print() def print_environ_usage(): """Dump a list of environment variables used by CGI as HTML.""" - print """ + print("""

These environment variables could have been set:

  • AUTH_TYPE @@ -1036,7 +1036,7 @@
  • HTTP_REFERER
  • HTTP_USER_AGENT
-""" +""") # Utilities Modified: python/branches/p3yk-noslice/Lib/code.py ============================================================================== --- python/branches/p3yk-noslice/Lib/code.py (original) +++ python/branches/p3yk-noslice/Lib/code.py Fri Feb 23 18:29:35 2007 @@ -12,19 +12,6 @@ __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] -def softspace(file, newvalue): - oldvalue = 0 - try: - oldvalue = file.softspace - except AttributeError: - pass - try: - file.softspace = newvalue - except (AttributeError, TypeError): - # "attribute-less object" or "read-only attributes" - pass - return oldvalue - class InteractiveInterpreter: """Base class for InteractiveConsole. @@ -105,9 +92,6 @@ raise except: self.showtraceback() - else: - if softspace(sys.stdout, 0): - print def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. Modified: python/branches/p3yk-noslice/Lib/compileall.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compileall.py (original) +++ python/branches/p3yk-noslice/Lib/compileall.py Fri Feb 23 18:29:35 2007 @@ -33,11 +33,11 @@ """ if not quiet: - print 'Listing', dir, '...' + print('Listing', dir, '...') try: names = os.listdir(dir) except os.error: - print "Can't list", dir + print("Can't list", dir) names = [] names.sort() success = 1 @@ -60,18 +60,18 @@ except os.error: ctime = 0 if (ctime > ftime) and not force: continue if not quiet: - print 'Compiling', fullname, '...' + print('Compiling', fullname, '...') try: ok = py_compile.compile(fullname, None, dfile, True) except KeyboardInterrupt: raise KeyboardInterrupt except py_compile.PyCompileError as err: if quiet: - print 'Compiling', fullname, '...' - print err.msg + print('Compiling', fullname, '...') + print(err.msg) success = 0 except IOError as e: - print "Sorry", e + print("Sorry", e) success = 0 else: if ok == 0: @@ -98,7 +98,7 @@ success = 1 for dir in sys.path: if (not dir or dir == os.curdir) and skip_curdir: - print 'Skipping current directory' + print('Skipping current directory') else: success = success and compile_dir(dir, maxlevels, None, force, quiet=quiet) @@ -110,16 +110,16 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:') except getopt.error as msg: - print msg - print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ - "[-x regexp] [directory ...]" - print "-l: don't recurse down" - print "-f: force rebuild even if timestamps are up-to-date" - print "-q: quiet operation" - print "-d destdir: purported directory name for error messages" - print " if no directory arguments, -l sys.path is assumed" - print "-x regexp: skip files matching the regular expression regexp" - print " the regexp is search for in the full path of the file" + print(msg) + print("usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ + "[-x regexp] [directory ...]") + print("-l: don't recurse down") + print("-f: force rebuild even if timestamps are up-to-date") + print("-q: quiet operation") + print("-d destdir: purported directory name for error messages") + print(" if no directory arguments, -l sys.path is assumed") + print("-x regexp: skip files matching the regular expression regexp") + print(" the regexp is search for in the full path of the file") sys.exit(2) maxlevels = 10 ddir = None @@ -136,7 +136,7 @@ rx = re.compile(a) if ddir: if len(args) != 1: - print "-d destdir require exactly one directory argument" + print("-d destdir require exactly one directory argument") sys.exit(2) success = 1 try: @@ -148,7 +148,7 @@ else: success = compile_path() except KeyboardInterrupt: - print "\n[interrupt]" + print("\n[interrupt]") success = 0 return success Modified: python/branches/p3yk-noslice/Lib/compiler/ast.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/ast.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/ast.py Fri Feb 23 18:29:35 2007 @@ -998,50 +998,6 @@ def __repr__(self): return "Power((%s, %s))" % (repr(self.left), repr(self.right)) -class Print(Node): - def __init__(self, nodes, dest, lineno=None): - self.nodes = nodes - self.dest = dest - self.lineno = lineno - - def getChildren(self): - children = [] - children.extend(flatten(self.nodes)) - children.append(self.dest) - return tuple(children) - - def getChildNodes(self): - nodelist = [] - nodelist.extend(flatten_nodes(self.nodes)) - if self.dest is not None: - nodelist.append(self.dest) - return tuple(nodelist) - - def __repr__(self): - return "Print(%s, %s)" % (repr(self.nodes), repr(self.dest)) - -class Printnl(Node): - def __init__(self, nodes, dest, lineno=None): - self.nodes = nodes - self.dest = dest - self.lineno = lineno - - def getChildren(self): - children = [] - children.extend(flatten(self.nodes)) - children.append(self.dest) - return tuple(children) - - def getChildNodes(self): - nodelist = [] - nodelist.extend(flatten_nodes(self.nodes)) - if self.dest is not None: - nodelist.append(self.dest) - return tuple(nodelist) - - def __repr__(self): - return "Printnl(%s, %s)" % (repr(self.nodes), repr(self.dest)) - class Raise(Node): def __init__(self, expr1, expr2, expr3, lineno=None): self.expr1 = expr1 @@ -1381,6 +1337,6 @@ def __repr__(self): return "Yield(%s)" % (repr(self.value),) -for name, obj in globals().items(): +for name, obj in list(globals().items()): if isinstance(obj, type) and issubclass(obj, Node): nodes[name.lower()] = obj Modified: python/branches/p3yk-noslice/Lib/compiler/future.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/future.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/future.py Fri Feb 23 18:29:35 2007 @@ -65,9 +65,9 @@ from compiler import parseFile, walk for file in sys.argv[1:]: - print file + print(file) tree = parseFile(file) v = FutureParser() walk(tree, v) - print v.found - print + print(v.found) + print() Modified: python/branches/p3yk-noslice/Lib/compiler/misc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/misc.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/misc.py Fri Feb 23 18:29:35 2007 @@ -18,7 +18,7 @@ def add(self, elt): self.elts[elt] = elt def elements(self): - return self.elts.keys() + return list(self.elts.keys()) def has_elt(self, elt): return elt in self.elts def remove(self, elt): Modified: python/branches/p3yk-noslice/Lib/compiler/pyassem.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/pyassem.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/pyassem.py Fri Feb 23 18:29:35 2007 @@ -19,10 +19,10 @@ def startBlock(self, block): if self._debug: if self.current: - print "end", repr(self.current) - print " next", self.current.next - print " ", self.current.get_children() - print repr(block) + print("end", repr(self.current)) + print(" next", self.current.next) + print(" ", self.current.get_children()) + print(repr(block)) self.current = block def nextBlock(self, block=None): @@ -68,7 +68,7 @@ def emit(self, *inst): if self._debug: - print "\t", inst + print("\t", inst) if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']: self.current.addOutEdge(self.exit) if len(inst) == 2 and isinstance(inst[1], Block): @@ -400,12 +400,12 @@ for t in self.insts: opname = t[0] if opname == "SET_LINENO": - print + print() if len(t) == 1: - print "\t", "%3d" % pc, opname + print("\t", "%3d" % pc, opname) pc = pc + 1 else: - print "\t", "%3d" % pc, opname, t[1] + print("\t", "%3d" % pc, opname, t[1]) pc = pc + 3 if io: sys.stdout = save @@ -504,7 +504,7 @@ if name in cells] for name in self.cellvars: del cells[name] - self.cellvars = self.cellvars + cells.keys() + self.cellvars = self.cellvars + list(cells.keys()) self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): @@ -573,7 +573,7 @@ # similarly for other opcodes... - for name, obj in locals().items(): + for name, obj in list(locals().items()): if name[:9] == "_convert_": opname = name[9:] _converters[opname] = obj @@ -601,8 +601,8 @@ try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: - print opname, oparg - print self.opnum[opname], lo, hi + print(opname, oparg) + print(self.opnum[opname], lo, hi) raise self.stage = DONE @@ -744,7 +744,7 @@ for i in insts: opname = i[0] if debug: - print i, + print(i, end=' ') delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta @@ -763,7 +763,7 @@ if depth > maxDepth: maxDepth = depth if debug: - print depth, maxDepth + print(depth, maxDepth) return maxDepth effect = { @@ -772,8 +772,7 @@ 'LIST_APPEND': -2, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, - # PRINT_EXPR? - 'PRINT_ITEM': -1, + 'PRINT_EXPR': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'BUILD_CLASS': -2, Modified: python/branches/p3yk-noslice/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/pycodegen.py Fri Feb 23 18:29:35 2007 @@ -112,7 +112,7 @@ gen = ModuleCodeGenerator(tree) if display: import pprint - print pprint.pprint(tree) + print(pprint.pprint(tree)) self.code = gen.getCode() def dump(self, f): @@ -914,6 +914,8 @@ self.emit('LOAD_CONST', None) self.nextBlock(final) self.setups.push((END_FINALLY, final)) + self._implicitNameOp('LOAD', exitvar) + self._implicitNameOp('DELETE', exitvar) self.emit('WITH_CLEANUP') self.emit('END_FINALLY') self.setups.pop() @@ -1016,7 +1018,7 @@ self.set_lineno(node) self.delName(node.name) else: - print "oops", node.flags + print("oops", node.flags) def visitAssAttr(self, node): self.visit(node.expr) @@ -1025,8 +1027,8 @@ elif node.flags == 'OP_DELETE': self.emit('DELETE_ATTR', self.mangle(node.attrname)) else: - print "warning: unexpected flags:", node.flags - print node + print("warning: unexpected flags:", node.flags) + print(node) def _visitAssSequence(self, node, op='UNPACK_SEQUENCE'): if findOp(node) != 'OP_DELETE': @@ -1111,29 +1113,6 @@ opcode = callfunc_opcode_info[have_star, have_dstar] self.emit(opcode, kw << 8 | pos) - def visitPrint(self, node, newline=0): - self.set_lineno(node) - if node.dest: - self.visit(node.dest) - for child in node.nodes: - if node.dest: - self.emit('DUP_TOP') - self.visit(child) - if node.dest: - self.emit('ROT_TWO') - self.emit('PRINT_ITEM_TO') - else: - self.emit('PRINT_ITEM') - if node.dest and not newline: - self.emit('POP_TOP') - - def visitPrintnl(self, node): - self.visitPrint(node, newline=1) - if node.dest: - self.emit('PRINT_NEWLINE_TO') - else: - self.emit('PRINT_NEWLINE') - def visitReturn(self, node): self.set_lineno(node) self.visit(node.value) Modified: python/branches/p3yk-noslice/Lib/compiler/symbols.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/symbols.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/symbols.py Fri Feb 23 18:29:35 2007 @@ -76,12 +76,12 @@ return self.children def DEBUG(self): - print >> sys.stderr, self.name, self.nested and "nested" or "" - print >> sys.stderr, "\tglobals: ", self.globals - print >> sys.stderr, "\tcells: ", self.cells - print >> sys.stderr, "\tdefs: ", self.defs - print >> sys.stderr, "\tuses: ", self.uses - print >> sys.stderr, "\tfrees:", self.frees + print(self.name, self.nested and "nested" or "", file=sys.stderr) + print("\tglobals: ", self.globals, file=sys.stderr) + print("\tcells: ", self.cells, file=sys.stderr) + print("\tdefs: ", self.defs, file=sys.stderr) + print("\tuses: ", self.uses, file=sys.stderr) + print("\tfrees:", self.frees, file=sys.stderr) def check_name(self, name): """Return scope of name. @@ -429,7 +429,7 @@ if not (s.startswith('_[') or s.startswith('.'))] for file in sys.argv[1:]: - print file + print(file) f = open(file) buf = f.read() f.close() @@ -443,10 +443,10 @@ names2 = s.scopes[tree].get_names() if not list_eq(mod_names, names2): - print - print "oops", file - print sorted(mod_names) - print sorted(names2) + print() + print("oops", file) + print(sorted(mod_names)) + print(sorted(names2)) sys.exit(-1) d = {} @@ -460,11 +460,11 @@ l = [sc for sc in scopes if sc.name == s.get_name()] if len(l) > 1: - print "skipping", s.get_name() + print("skipping", s.get_name()) else: if not list_eq(get_names(s.get_namespace()), l[0].get_names()): - print s.get_name() - print sorted(get_names(s.get_namespace())) - print sorted(l[0].get_names()) + print(s.get_name()) + print(sorted(get_names(s.get_namespace()))) + print(sorted(l[0].get_names())) sys.exit(-1) Modified: python/branches/p3yk-noslice/Lib/compiler/syntax.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/syntax.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/syntax.py Fri Feb 23 18:29:35 2007 @@ -32,7 +32,7 @@ def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: - print "%s:%s: %s" % (node.filename, node.lineno, msg) + print("%s:%s: %s" % (node.filename, node.lineno, msg)) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) Modified: python/branches/p3yk-noslice/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/transformer.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/transformer.py Fri Feb 23 18:29:35 2007 @@ -86,7 +86,7 @@ try: return nodes[kind](*args[1:]) except TypeError: - print nodes[kind], len(args), args + print(nodes[kind], len(args), args) raise else: raise WalkerError, "Can't find appropriate Node type: %s" % str(args) @@ -387,26 +387,6 @@ return AugAssign(lval, op[1], exprNode, lineno=op[2]) raise WalkerError, "can't get here" - def print_stmt(self, nodelist): - # print ([ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ]) - items = [] - if len(nodelist) == 1: - start = 1 - dest = None - elif nodelist[1][0] == token.RIGHTSHIFT: - assert len(nodelist) == 3 \ - or nodelist[3][0] == token.COMMA - dest = self.com_node(nodelist[2]) - start = 4 - else: - dest = None - start = 1 - for i in range(start, len(nodelist), 2): - items.append(self.com_node(nodelist[i])) - if nodelist[-1][0] == token.COMMA: - return Print(items, dest, lineno=nodelist[0][2]) - return Printnl(items, dest, lineno=nodelist[0][2]) - def del_stmt(self, nodelist): return self.com_assign(nodelist[1], OP_DELETE) @@ -1018,7 +998,7 @@ if nodelist[2][0] == token.COLON: var = None else: - var = self.com_node(nodelist[2]) + var = self.com_assign(nodelist[2][2], OP_ASSIGN) return With(expr, var, body, lineno=nodelist[0][2]) def com_with_var(self, nodelist): @@ -1458,7 +1438,6 @@ symbol.simple_stmt, symbol.compound_stmt, symbol.expr_stmt, - symbol.print_stmt, symbol.del_stmt, symbol.pass_stmt, symbol.break_stmt, Modified: python/branches/p3yk-noslice/Lib/compiler/visitor.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/visitor.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/visitor.py Fri Feb 23 18:29:35 2007 @@ -79,20 +79,20 @@ meth = getattr(self.visitor, 'visit' + className, 0) self._cache[node.__class__] = meth if self.VERBOSE > 1: - print "dispatch", className, (meth and meth.__name__ or '') + print("dispatch", className, (meth and meth.__name__ or '')) if meth: meth(node, *args) elif self.VERBOSE > 0: klass = node.__class__ if klass not in self.examples: self.examples[klass] = klass - print - print self.visitor - print klass + print() + print(self.visitor) + print(klass) for attr in dir(node): if attr[0] != '_': - print "\t", "%-12.12s" % attr, getattr(node, attr) - print + print("\t", "%-12.12s" % attr, getattr(node, attr)) + print() return self.default(node, *args) # XXX this is an API change @@ -107,7 +107,7 @@ return walker.visitor def dumpNode(node): - print node.__class__ + print(node.__class__) for attr in dir(node): if attr[0] != '_': - print "\t", "%-10.10s" % attr, getattr(node, attr) + print("\t", "%-10.10s" % attr, getattr(node, attr)) Modified: python/branches/p3yk-noslice/Lib/cookielib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/cookielib.py (original) +++ python/branches/p3yk-noslice/Lib/cookielib.py Fri Feb 23 18:29:35 2007 @@ -1171,8 +1171,7 @@ def vals_sorted_by_key(adict): - keys = adict.keys() - keys.sort() + keys = sorted(adict.keys()) return map(adict.get, keys) def deepvalues(mapping): @@ -1318,26 +1317,26 @@ self._cookies_lock.acquire() try: - self._policy._now = self._now = int(time.time()) + self._policy._now = self._now = int(time.time()) + + cookies = self._cookies_for_request(request) - cookies = self._cookies_for_request(request) + 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 - 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._cookies_lock.release() self.clear_expired_cookies() @@ -1609,7 +1608,7 @@ if self._policy.set_ok(cookie, request): self.set_cookie(cookie) - + finally: self._cookies_lock.release() @@ -1632,14 +1631,14 @@ _debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() try: - self._policy._now = self._now = int(time.time()) + 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) + 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() + self._cookies_lock.release() def clear(self, domain=None, path=None, name=None): """Clear some cookies. @@ -1677,11 +1676,11 @@ """ self._cookies_lock.acquire() try: - for cookie in self: - if cookie.discard: - self.clear(cookie.domain, cookie.path, cookie.name) + for cookie in self: + if cookie.discard: + self.clear(cookie.domain, cookie.path, cookie.name) finally: - self._cookies_lock.release() + self._cookies_lock.release() def clear_expired_cookies(self): """Discard all expired cookies. @@ -1695,12 +1694,12 @@ """ self._cookies_lock.acquire() try: - now = time.time() - for cookie in self: - if cookie.is_expired(now): - self.clear(cookie.domain, cookie.path, cookie.name) + 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() + self._cookies_lock.release() def __iter__(self): return deepvalues(self._cookies) @@ -1774,16 +1773,16 @@ self._cookies_lock.acquire() try: - old_state = copy.deepcopy(self._cookies) - self._cookies = {} - try: - self.load(filename, ignore_discard, ignore_expires) - except (LoadError, IOError): - self._cookies = old_state - raise + 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() + self._cookies_lock.release() from _LWPCookieJar import LWPCookieJar, lwp_cookie_str from _MozillaCookieJar import MozillaCookieJar Modified: python/branches/p3yk-noslice/Lib/copy.py ============================================================================== --- python/branches/p3yk-noslice/Lib/copy.py (original) +++ python/branches/p3yk-noslice/Lib/copy.py Fri Feb 23 18:29:35 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: @@ -230,7 +230,7 @@ def _deepcopy_dict(x, memo): y = {} memo[id(x)] = y - for key, value in x.iteritems(): + for key, value in x.items(): y[deepcopy(key, memo)] = deepcopy(value, memo) return y d[dict] = _deepcopy_dict @@ -302,7 +302,7 @@ if state is not None: y.__dict__.update(state) if slotstate is not None: - for key, value in slotstate.iteritems(): + for key, value in slotstate.items(): setattr(y, key, value) return y @@ -315,14 +315,14 @@ 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 + print(l1==l) l1 = map(copy, l) - print l1==l + print(l1==l) l1 = deepcopy(l) - print l1==l + print(l1==l) class C: def __init__(self, arg=None): self.a = 1 @@ -337,7 +337,7 @@ def __getstate__(self): return {'a': self.a, 'arg': self.arg} def __setstate__(self, state): - for key, value in state.iteritems(): + for key, value in state.items(): setattr(self, key, value) def __deepcopy__(self, memo=None): new = self.__class__(deepcopy(self.arg, memo)) @@ -346,26 +346,26 @@ c = C('argument sketch') l.append(c) l2 = copy(l) - print l == l2 - print l - print l2 + print(l == l2) + print(l) + print(l2) l2 = deepcopy(l) - print l == l2 - print l - print l2 + print(l == l2) + print(l) + print(l2) l.append({l[1]: l, 'xyz': l[2]}) l3 = copy(l) import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) + print(map(repr.repr, l)) + print(map(repr.repr, l1)) + print(map(repr.repr, l2)) + print(map(repr.repr, l3)) l3 = deepcopy(l) import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) + print(map(repr.repr, l)) + print(map(repr.repr, l1)) + print(map(repr.repr, l2)) + print(map(repr.repr, l3)) if __name__ == '__main__': _test() Modified: python/branches/p3yk-noslice/Lib/csv.py ============================================================================== --- python/branches/p3yk-noslice/Lib/csv.py (original) +++ python/branches/p3yk-noslice/Lib/csv.py Fri Feb 23 18:29:35 2007 @@ -278,7 +278,7 @@ charFrequency[char] = metaFrequency for char in charFrequency.keys(): - items = charFrequency[char].items() + items = list(charFrequency[char].items()) if len(items) == 1 and items[0][0] == 0: continue # get the mode of the frequencies @@ -308,7 +308,7 @@ consistency -= 0.01 if len(delims) == 1: - delim = delims.keys()[0] + delim = list(delims.keys())[0] skipinitialspace = (data[0].count(delim) == data[0].count("%c " % delim)) return (delim, skipinitialspace) @@ -367,9 +367,9 @@ if len(row) != columns: continue # skip rows that have irregular number of columns - for col in columnTypes.keys(): + for col in list(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-noslice/Lib/ctypes/__init__.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/__init__.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/__init__.py Fri Feb 23 18:29:35 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 @@ -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 @@ -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 = {} @@ -257,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 @@ -328,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-noslice/Lib/ctypes/test/__init__.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/__init__.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/__init__.py Fri Feb 23 18:29:35 2007 @@ -41,7 +41,7 @@ hasattr(package.__loader__, '_files')): path = package.__name__.replace(".", os.path.sep) mask = os.path.join(path, mask) - for fnm in package.__loader__._files.iterkeys(): + for fnm in package.__loader__._files.keys(): if fnmatch.fnmatchcase(fnm, mask): yield os.path.splitext(fnm)[0].replace(os.path.sep, ".") else: @@ -60,10 +60,10 @@ except ResourceDenied as detail: skipped.append(modname) if verbosity > 1: - print >> sys.stderr, "Skipped %s: %s" % (modname, detail) + print("Skipped %s: %s" % (modname, detail), file=sys.stderr) continue except Exception as detail: - print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail) + print("Warning: could not import %s: %s" % (modname, detail), file=sys.stderr) continue for name in dir(mod): if name.startswith("_"): @@ -74,7 +74,7 @@ return skipped, tests def usage(): - print __doc__ + print(__doc__) return 1 def test_with_refcounts(runner, verbosity, testcase): @@ -106,9 +106,9 @@ cleanup() refcounts[i] = sys.gettotalrefcount() - rc if filter(None, refcounts): - print "%s leaks:\n\t" % testcase, refcounts + print("%s leaks:\n\t" % testcase, refcounts) elif verbosity: - print "%s: ok." % testcase + print("%s: ok." % testcase) class TestRunner(unittest.TextTestRunner): def run(self, test, skipped): @@ -166,7 +166,7 @@ try: sys.gettotalrefcount except AttributeError: - print >> sys.stderr, "-r flag requires Python debug build" + print("-r flag requires Python debug build", file=sys.stderr) return -1 search_leaks = True elif flag == "-u": Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_as_parameter.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_as_parameter.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_as_parameter.py Fri Feb 23 18:29:35 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-noslice/Lib/ctypes/test/test_byteswap.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_byteswap.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_byteswap.py Fri Feb 23 18:29:35 2007 @@ -15,7 +15,7 @@ class Test(unittest.TestCase): def X_test(self): - print >> sys.stderr, sys.byteorder + print(sys.byteorder, file=sys.stderr) for i in range(32): bits = BITS() setattr(bits, "i%s" % i, 1) Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_find.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_find.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_find.py Fri Feb 23 18:29:35 2007 @@ -22,12 +22,12 @@ ## print, for debugging if is_resource_enabled("printing"): if lib_gl or lib_glu or lib_glut or lib_gle: - print "OpenGL libraries:" + print("OpenGL libraries:") for item in (("GL", lib_gl), ("GLU", lib_glu), ("glut", lib_glut), ("gle", lib_gle)): - print "\t", item + print("\t", item) # On some systems, loading the OpenGL libraries needs the RTLD_GLOBAL mode. Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py Fri Feb 23 18:29:35 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-noslice/Lib/ctypes/test/test_keeprefs.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_keeprefs.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_keeprefs.py Fri Feb 23 18:29:35 2007 @@ -100,13 +100,13 @@ x = X() i = c_char_p("abc def") from sys import getrefcount as grc - print "2?", grc(i) + print("2?", grc(i)) x.p = pointer(i) - print "3?", grc(i) + print("3?", grc(i)) for i in range(320): c_int(99) x.p[0] - print x.p[0] + print(x.p[0]) ## del x ## print "2?", grc(i) ## del i @@ -115,14 +115,14 @@ for i in range(320): c_int(99) x.p[0] - print x.p[0] - print x.p.contents + print(x.p[0]) + print(x.p.contents) ## print x._objects x.p[0] = "spam spam" ## print x.p[0] - print "+" * 42 - print x._objects + print("+" * 42) + print(x._objects) class PointerToStructure(unittest.TestCase): def test(self): Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py Fri Feb 23 18:29:35 2007 @@ -15,7 +15,7 @@ libc_name = find_library("c") if is_resource_enabled("printing"): - print "libc_name is", libc_name + print("libc_name is", libc_name) class LoaderTest(unittest.TestCase): @@ -44,8 +44,8 @@ if os.name in ("nt", "ce"): def test_load_library(self): if is_resource_enabled("printing"): - print find_library("kernel32") - print find_library("user32") + print(find_library("kernel32")) + print(find_library("user32")) if os.name == "nt": windll.kernel32.GetModuleHandleW Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py Fri Feb 23 18:29:35 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 @@ -192,7 +192,7 @@ for i in items: func(); func(); func(); func(); func() stop = clock() - print "%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)) + print("%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))) def check_perf(): # Construct 5 objects Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_objects.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_objects.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_objects.py Fri Feb 23 18:29:35 2007 @@ -13,7 +13,7 @@ >>> from ctypes import * >>> array = (c_char_p * 5)() ->>> print array._objects +>>> print(array._objects) None >>> @@ -34,14 +34,14 @@ ... _fields_ = [("x", c_int), ("y", c_int), ("array", c_char_p * 5)] ... >>> x = X() ->>> print x._objects +>>> print(x._objects) None >>> The'array' attribute of the 'x' object shares part of the memory buffer of 'x' ('_b_base_' is either None, or the root object owning the memory block): ->>> print x.array._b_base_ # doctest: +ELLIPSIS +>>> print(x.array._b_base_) # doctest: +ELLIPSIS >>> Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_pointers.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_pointers.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_pointers.py Fri Feb 23 18:29:35 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-noslice/Lib/ctypes/test/test_prototypes.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_prototypes.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_prototypes.py Fri Feb 23 18:29:35 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-noslice/Lib/ctypes/test/test_strings.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_strings.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_strings.py Fri Feb 23 18:29:35 2007 @@ -189,7 +189,7 @@ for i in items: func(arg); func(arg); func(arg); func(arg); func(arg) stop = clock() - print "%20s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)) + print("%20s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))) def check_perf(): # Construct 5 objects Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_win32.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_win32.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_win32.py Fri Feb 23 18:29:35 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-noslice/Lib/ctypes/util.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/util.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/util.py Fri Feb 23 18:29:35 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 @@ -103,15 +125,15 @@ def test(): from ctypes import cdll if os.name == "nt": - print cdll.msvcrt - print cdll.load("msvcrt") - print find_library("msvcrt") + print(cdll.msvcrt) + print(cdll.load("msvcrt")) + print(find_library("msvcrt")) if os.name == "posix": # find and load_version - print find_library("m") - print find_library("c") - print find_library("bz2") + print(find_library("m")) + print(find_library("c")) + print(find_library("bz2")) # getattr ## print cdll.m @@ -119,14 +141,14 @@ # load if sys.platform == "darwin": - print cdll.LoadLibrary("libm.dylib") - print cdll.LoadLibrary("libcrypto.dylib") - print cdll.LoadLibrary("libSystem.dylib") - print cdll.LoadLibrary("System.framework/System") + print(cdll.LoadLibrary("libm.dylib")) + print(cdll.LoadLibrary("libcrypto.dylib")) + print(cdll.LoadLibrary("libSystem.dylib")) + print(cdll.LoadLibrary("System.framework/System")) else: - print cdll.LoadLibrary("libm.so") - print cdll.LoadLibrary("libcrypt.so") - print find_library("crypt") + print(cdll.LoadLibrary("libm.so")) + print(cdll.LoadLibrary("libcrypt.so")) + print(find_library("crypt")) if __name__ == "__main__": test() Modified: python/branches/p3yk-noslice/Lib/ctypes/wintypes.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/wintypes.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/wintypes.py Fri Feb 23 18:29:35 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-noslice/Lib/curses/has_key.py ============================================================================== --- python/branches/p3yk-noslice/Lib/curses/has_key.py (original) +++ python/branches/p3yk-noslice/Lib/curses/has_key.py Fri Feb 23 18:29:35 2007 @@ -189,4 +189,4 @@ % (_curses.keyname( key ), system, python) ) finally: _curses.endwin() - for i in L: print i + for i in L: print(i) Modified: python/branches/p3yk-noslice/Lib/curses/textpad.py ============================================================================== --- python/branches/p3yk-noslice/Lib/curses/textpad.py (original) +++ python/branches/p3yk-noslice/Lib/curses/textpad.py Fri Feb 23 18:29:35 2007 @@ -170,4 +170,4 @@ return Textbox(win).edit() str = curses.wrapper(test_editbox) - print 'Contents of text box:', repr(str) + print('Contents of text box:', repr(str)) Modified: python/branches/p3yk-noslice/Lib/decimal.py ============================================================================== --- python/branches/p3yk-noslice/Lib/decimal.py (original) +++ python/branches/p3yk-noslice/Lib/decimal.py Fri Feb 23 18:29:35 2007 @@ -56,31 +56,31 @@ >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41") Decimal("-2.20") >>> dig = Decimal(1) ->>> print dig / Decimal(3) +>>> print(dig / Decimal(3)) 0.333333333 >>> getcontext().prec = 18 ->>> print dig / Decimal(3) +>>> print(dig / Decimal(3)) 0.333333333333333333 ->>> print dig.sqrt() +>>> print(dig.sqrt()) 1 ->>> print Decimal(3).sqrt() +>>> print(Decimal(3).sqrt()) 1.73205080756887729 ->>> print Decimal(3) ** 123 +>>> print(Decimal(3) ** 123) 4.85192780976896427E+58 >>> inf = Decimal(1) / Decimal(0) ->>> print inf +>>> print(inf) Infinity >>> neginf = Decimal(-1) / Decimal(0) ->>> print neginf +>>> print(neginf) -Infinity ->>> print neginf + inf +>>> print(neginf + inf) NaN ->>> print neginf * inf +>>> print(neginf * inf) -Infinity ->>> print dig / 0 +>>> print(dig / 0) Infinity >>> getcontext().traps[DivisionByZero] = 1 ->>> print dig / 0 +>>> print(dig / 0) Traceback (most recent call last): ... ... @@ -88,29 +88,29 @@ decimal.DivisionByZero: x / 0 >>> c = Context() >>> c.traps[InvalidOperation] = 0 ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 0 >>> c.divide(Decimal(0), Decimal(0)) Decimal("NaN") >>> c.traps[InvalidOperation] = 1 ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 1 >>> c.flags[InvalidOperation] = 0 ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 0 ->>> print c.divide(Decimal(0), Decimal(0)) +>>> print(c.divide(Decimal(0), Decimal(0))) Traceback (most recent call last): ... ... ... decimal.InvalidOperation: 0 / 0 ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 1 >>> c.flags[InvalidOperation] = 0 >>> c.traps[InvalidOperation] = 0 ->>> print c.divide(Decimal(0), Decimal(0)) +>>> print(c.divide(Decimal(0), Decimal(0))) NaN ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 1 >>> """ @@ -483,19 +483,19 @@ # as the doctest module doesn't understand __future__ statements """ >>> from __future__ import with_statement - >>> print getcontext().prec + >>> print(getcontext().prec) 28 >>> with localcontext(): ... ctx = getcontext() - ... ctx.prec() += 2 - ... print ctx.prec - ... + ... ctx.prec += 2 + ... print(ctx.prec) + ... 30 >>> with localcontext(ExtendedContext): - ... print getcontext().prec - ... + ... print(getcontext().prec) + ... 9 - >>> print getcontext().prec + >>> print(getcontext().prec) 28 """ if ctx is None: ctx = getcontext() @@ -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-noslice/Lib/difflib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/difflib.py (original) +++ python/branches/p3yk-noslice/Lib/difflib.py Fri Feb 23 18:29:35 2007 @@ -76,7 +76,7 @@ sequences. As a rule of thumb, a .ratio() value over 0.6 means the sequences are close matches: - >>> print round(s.ratio(), 3) + >>> print(round(s.ratio(), 3)) 0.866 >>> @@ -84,7 +84,7 @@ .get_matching_blocks() is handy: >>> for block in s.get_matching_blocks(): - ... print "a[%d] and b[%d] match for %d elements" % block + ... print("a[%d] and b[%d] match for %d elements" % block) a[0] and b[0] match for 8 elements a[8] and b[17] match for 21 elements a[29] and b[38] match for 0 elements @@ -97,7 +97,7 @@ use .get_opcodes(): >>> for opcode in s.get_opcodes(): - ... print "%6s a[%d:%d] b[%d:%d]" % opcode + ... print("%6s a[%d:%d] b[%d:%d]" % opcode) equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:29] b[17:38] @@ -331,7 +331,7 @@ junkdict = {} if isjunk: for d in populardict, b2j: - for elt in d.keys(): + for elt in list(d.keys()): if isjunk(elt): junkdict[elt] = 1 del d[elt] @@ -545,8 +545,8 @@ >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): - ... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % - ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])) + ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % + ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) @@ -832,7 +832,7 @@ As a single multi-line string it looks like this: - >>> print ''.join(result), + >>> print(''.join(result), end="") 1. Beautiful is better than ugly. - 2. Explicit is better than implicit. - 3. Simple is better than complex. @@ -889,8 +889,9 @@ Example: - >>> print ''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1), + >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1))), + ... end="") - one ? ^ + ore @@ -950,7 +951,7 @@ >>> d = Differ() >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1, ... ['abcdefGhijkl\n'], 0, 1) - >>> print ''.join(results), + >>> print(''.join(results), end="") - abcDefghiJkl ? ^ ^ ^ + abcdefGhijkl @@ -1058,7 +1059,7 @@ >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n', ... ' ^ ^ ^ ', '+ ^ ^ ^ ') - >>> for line in results: print repr(line) + >>> for line in results: print(repr(line)) ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' @@ -1164,7 +1165,7 @@ ... 'zero one tree four'.split(), 'Original', 'Current', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003', ... lineterm=''): - ... print line + ... print(line) --- Original Sat Jan 26 23:30:50 1991 +++ Current Fri Jun 06 10:20:52 2003 @@ -1,4 +1,4 @@ @@ -1223,9 +1224,10 @@ Example: - >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1), + >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1), ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')), + ... end="") *** Original Sat Jan 26 23:30:50 1991 --- Current Fri Jun 06 10:22:46 2003 *************** @@ -1295,7 +1297,7 @@ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) - >>> print ''.join(diff), + >>> print(''.join(diff), end="") - one ? ^ + ore @@ -1992,11 +1994,11 @@ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> diff = list(diff) - >>> print ''.join(restore(diff, 1)), + >>> print(''.join(restore(diff, 1)), end="") one two three - >>> print ''.join(restore(diff, 2)), + >>> print(''.join(restore(diff, 2)), end="") ore tree emu Modified: python/branches/p3yk-noslice/Lib/dis.py ============================================================================== --- python/branches/p3yk-noslice/Lib/dis.py (original) +++ python/branches/p3yk-noslice/Lib/dis.py Fri Feb 23 18:29:35 2007 @@ -30,12 +30,12 @@ types.FunctionType, types.CodeType, types.ClassType): - print "Disassembly of %s:" % name + print("Disassembly of %s:" % name) try: dis(x1) except TypeError as msg: - print "Sorry:", msg - print + print("Sorry:", msg) + print() elif hasattr(x, 'co_code'): disassemble(x) elif isinstance(x, str): @@ -69,40 +69,40 @@ op = ord(c) if i in linestarts: if i > 0: - print - print "%3d" % linestarts[i], + print() + print("%3d" % linestarts[i], end=' ') else: - print ' ', + print(' ', end=' ') - if i == lasti: print '-->', - else: print ' ', - if i in labels: print '>>', - else: print ' ', - print repr(i).rjust(4), - print opname[op].ljust(20), + if i == lasti: print('-->', end=' ') + else: print(' ', end=' ') + if i in labels: print('>>', end=' ') + else: print(' ', end=' ') + print(repr(i).rjust(4), end=' ') + print(opname[op].ljust(20), end=' ') i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg extended_arg = 0 i = i+2 if op == EXTENDED_ARG: - extended_arg = oparg*65536L - print repr(oparg).rjust(5), + extended_arg = oparg*65536 + print(repr(oparg).rjust(5), end=' ') if op in hasconst: - print '(' + repr(co.co_consts[oparg]) + ')', + print('(' + repr(co.co_consts[oparg]) + ')', end=' ') elif op in hasname: - print '(' + co.co_names[oparg] + ')', + print('(' + co.co_names[oparg] + ')', end=' ') elif op in hasjrel: - print '(to ' + repr(i + oparg) + ')', + print('(to ' + repr(i + oparg) + ')', end=' ') elif op in haslocal: - print '(' + co.co_varnames[oparg] + ')', + print('(' + co.co_varnames[oparg] + ')', end=' ') elif op in hascompare: - print '(' + cmp_op[oparg] + ')', + print('(' + cmp_op[oparg] + ')', end=' ') elif op in hasfree: if free is None: free = co.co_cellvars + co.co_freevars - print '(' + free[oparg] + ')', - print + print('(' + free[oparg] + ')', end=' ') + print() def disassemble_string(code, lasti=-1, varnames=None, names=None, constants=None): @@ -112,37 +112,37 @@ while i < n: c = code[i] op = ord(c) - if i == lasti: print '-->', - else: print ' ', - if i in labels: print '>>', - else: print ' ', - print repr(i).rjust(4), - print opname[op].ljust(15), + if i == lasti: print('-->', end=' ') + else: print(' ', end=' ') + if i in labels: print('>>', end=' ') + else: print(' ', end=' ') + print(repr(i).rjust(4), end=' ') + print(opname[op].ljust(15), end=' ') i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 - print repr(oparg).rjust(5), + print(repr(oparg).rjust(5), end=' ') if op in hasconst: if constants: - print '(' + repr(constants[oparg]) + ')', + print('(' + repr(constants[oparg]) + ')', end=' ') else: - print '(%d)'%oparg, + print('(%d)'%oparg, end=' ') elif op in hasname: if names is not None: - print '(' + names[oparg] + ')', + print('(' + names[oparg] + ')', end=' ') else: - print '(%d)'%oparg, + print('(%d)'%oparg, end=' ') elif op in hasjrel: - print '(to ' + repr(i + oparg) + ')', + print('(to ' + repr(i + oparg) + ')', end=' ') elif op in haslocal: if varnames: - print '(' + varnames[oparg] + ')', + print('(' + varnames[oparg] + ')', end=' ') else: - print '(%d)' % oparg, + print('(%d)' % oparg, end=' ') elif op in hascompare: - print '(' + cmp_op[oparg] + ')', - print + print('(' + cmp_op[oparg] + ')', end=' ') + print() disco = disassemble # XXX For backwards compatibility Modified: python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py Fri Feb 23 18:29:35 2007 @@ -392,7 +392,7 @@ try: self.spawn(pp_args) except DistutilsExecError as msg: - print msg + print(msg) raise CompileError, msg # preprocess() Modified: python/branches/p3yk-noslice/Lib/distutils/ccompiler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/ccompiler.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/ccompiler.py Fri Feb 23 18:29:35 2007 @@ -1026,7 +1026,7 @@ def debug_print (self, msg): from distutils.debug import DEBUG if DEBUG: - print msg + print(msg) def warn (self, msg): sys.stderr.write ("warning: %s\n" % msg) Modified: python/branches/p3yk-noslice/Lib/distutils/cmd.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/cmd.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/cmd.py Fri Feb 23 18:29:35 2007 @@ -163,14 +163,14 @@ from distutils.fancy_getopt import longopt_xlate if header is None: header = "command options for '%s':" % self.get_command_name() - print indent + header + print(indent + header) indent = indent + " " for (option, _, _) in self.user_options: option = string.translate(option, longopt_xlate) if option[-1] == "=": option = option[:-1] value = getattr(self, option) - print indent + "%s = %s" % (option, value) + print(indent + "%s = %s" % (option, value)) def run (self): @@ -199,7 +199,7 @@ """ from distutils.debug import DEBUG if DEBUG: - print msg + print(msg) sys.stdout.flush() @@ -475,4 +475,4 @@ if __name__ == "__main__": - print "ok" + print("ok") Modified: python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py Fri Feb 23 18:29:35 2007 @@ -267,11 +267,11 @@ def run (self): if DEBUG: - print "before _get_package_data():" - print "vendor =", self.vendor - print "packager =", self.packager - print "doc_files =", self.doc_files - print "changelog =", self.changelog + print("before _get_package_data():") + print("vendor =", self.vendor) + print("packager =", self.packager) + print("doc_files =", self.doc_files) + print("changelog =", self.changelog) # make directories if self.spec_only: Modified: python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py Fri Feb 23 18:29:35 2007 @@ -185,9 +185,7 @@ # for extensions under Cygwin and AtheOS Python's library directory must be # appended to library_dirs - if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos' or \ - ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')) and - sysconfig.get_config_var('Py_ENABLE_SHARED')): + if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos': if string.find(sys.executable, sys.exec_prefix) != -1: # building third party extensions self.library_dirs.append(os.path.join(sys.prefix, "lib", @@ -197,6 +195,17 @@ # building python standard extensions self.library_dirs.append('.') + # for extensions under Linux with a shared Python library, + # Python's library directory must be appended to library_dirs + if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \ + and sysconfig.get_config_var('Py_ENABLE_SHARED'): + if string.find(sys.executable, sys.exec_prefix) != -1: + # building third party extensions + self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) + else: + # building python standard extensions + self.library_dirs.append('.') + # The argument parsing will result in self.define being a string, but # it has to be a list of 2-tuples. All the preprocessor symbols # specified by the 'define' option will be set to '1'. Multiple Modified: python/branches/p3yk-noslice/Lib/distutils/command/config.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/command/config.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/command/config.py Fri Feb 23 18:29:35 2007 @@ -359,9 +359,9 @@ def dump_file (filename, head=None): if head is None: - print filename + ":" + print(filename + ":") else: - print head + print(head) file = open(filename) sys.stdout.write(file.read()) Modified: python/branches/p3yk-noslice/Lib/distutils/command/install.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/command/install.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/command/install.py Fri Feb 23 18:29:35 2007 @@ -292,7 +292,7 @@ if DEBUG: from pprint import pprint - print "config vars:" + print("config vars:") pprint(self.config_vars) # Expand "~" and configuration variables in the installation @@ -347,7 +347,7 @@ def dump_dirs (self, msg): if DEBUG: from distutils.fancy_getopt import longopt_xlate - print msg + ":" + print(msg + ":") for opt in self.user_options: opt_name = opt[0] if opt_name[-1] == "=": @@ -359,7 +359,7 @@ else: opt_name = string.translate(opt_name, longopt_xlate) val = getattr(self, opt_name) - print " %s: %s" % (opt_name, val) + print(" %s: %s" % (opt_name, val)) def finalize_unix (self): Modified: python/branches/p3yk-noslice/Lib/distutils/command/register.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/command/register.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/command/register.py Fri Feb 23 18:29:35 2007 @@ -86,14 +86,14 @@ ''' Fetch the list of classifiers from the server. ''' response = urllib2.urlopen(self.repository+'?:action=list_classifiers') - print response.read() + print(response.read()) def verify_metadata(self): ''' Send the metadata to the package index server to be checked. ''' # send the info to the server and report the result (code, result) = self.post_to_server(self.build_post_data('verify')) - print 'Server response (%s): %s'%(code, result) + print('Server response (%s): %s'%(code, result)) def send_metadata(self): ''' Send the metadata to the package index server. @@ -128,7 +128,7 @@ if os.environ.has_key('HOME'): rc = os.path.join(os.environ['HOME'], '.pypirc') if os.path.exists(rc): - print 'Using PyPI login from %s'%rc + print('Using PyPI login from %s'%rc) config = ConfigParser.ConfigParser() config.read(rc) username = config.get('server-login', 'username') @@ -138,17 +138,17 @@ # get the user's login info choices = '1 2 3 4'.split() while choice not in choices: - print '''We need to know who you are, so please choose either: + print('''We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit -Your selection [default 1]: ''', +Your selection [default 1]: ''', end=' ') choice = raw_input() if not choice: choice = '1' elif choice not in choices: - print 'Please choose one of the four options!' + print('Please choose one of the four options!') if choice == '1': # get the username and password @@ -165,13 +165,13 @@ # send the info to the server and report the result code, result = self.post_to_server(self.build_post_data('submit'), auth) - print 'Server response (%s): %s'%(code, result) + print('Server response (%s): %s'%(code, result)) # possibly save the login if os.environ.has_key('HOME') and config is None and code == 200: rc = os.path.join(os.environ['HOME'], '.pypirc') - print 'I can store your PyPI login so future submissions will be faster.' - print '(the login will be stored in %s)'%rc + print('I can store your PyPI login so future submissions will be faster.') + print('(the login will be stored in %s)'%rc) choice = 'X' while choice.lower() not in 'yn': choice = raw_input('Save your login (y/N)?') @@ -200,22 +200,22 @@ if data['password'] != data['confirm']: data['password'] = '' data['confirm'] = None - print "Password and confirm don't match!" + print("Password and confirm don't match!") while not data['email']: data['email'] = raw_input(' EMail: ') code, result = self.post_to_server(data) if code != 200: - print 'Server response (%s): %s'%(code, result) + print('Server response (%s): %s'%(code, result)) else: - print 'You will receive an email shortly.' - print 'Follow the instructions in it to complete registration.' + print('You will receive an email shortly.') + print('Follow the instructions in it to complete registration.') elif choice == '3': data = {':action': 'password_reset'} data['email'] = '' while not data['email']: data['email'] = raw_input('Your email address: ') code, result = self.post_to_server(data) - print 'Server response (%s): %s'%(code, result) + print('Server response (%s): %s'%(code, result)) def build_post_data(self, action): # figure the data to send - the metadata plus some additional @@ -295,5 +295,5 @@ data = result.read() result = 200, 'OK' if self.show_response: - print '-'*75, data, '-'*75 + print('-'*75, data, '-'*75) return result Modified: python/branches/p3yk-noslice/Lib/distutils/command/upload.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/command/upload.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/command/upload.py Fri Feb 23 18:29:35 2007 @@ -196,4 +196,4 @@ self.announce('Upload failed (%s): %s' % (r.status, r.reason), log.ERROR) if self.show_response: - print '-'*75, r.read(), '-'*75 + print('-'*75, r.read(), '-'*75) Modified: python/branches/p3yk-noslice/Lib/distutils/core.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/core.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/core.py Fri Feb 23 18:29:35 2007 @@ -125,7 +125,7 @@ dist.parse_config_files() if DEBUG: - print "options (after parsing config files):" + print("options (after parsing config files):") dist.dump_option_dicts() if _setup_stop_after == "config": @@ -139,7 +139,7 @@ raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg if DEBUG: - print "options (after parsing command line):" + print("options (after parsing command line):") dist.dump_option_dicts() if _setup_stop_after == "commandline": Modified: python/branches/p3yk-noslice/Lib/distutils/dist.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/dist.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/dist.py Fri Feb 23 18:29:35 2007 @@ -290,22 +290,22 @@ commands.sort() if header is not None: - print indent + header + print(indent + header) indent = indent + " " if not commands: - print indent + "no commands known yet" + print(indent + "no commands known yet") return for cmd_name in commands: opt_dict = self.command_options.get(cmd_name) if opt_dict is None: - print indent + "no option dict for '%s' command" % cmd_name + print(indent + "no option dict for '%s' command" % cmd_name) else: - print indent + "option dict for '%s' command:" % cmd_name + print(indent + "option dict for '%s' command:" % cmd_name) out = pformat(opt_dict) for line in string.split(out, "\n"): - print indent + " " + line + print(indent + " " + line) # dump_option_dicts () @@ -365,11 +365,11 @@ if filenames is None: filenames = self.find_config_files() - if DEBUG: print "Distribution.parse_config_files():" + if DEBUG: print("Distribution.parse_config_files():") parser = ConfigParser() for filename in filenames: - if DEBUG: print " reading", filename + if DEBUG: print(" reading", filename) parser.read(filename) for section in parser.sections(): options = parser.options(section) @@ -636,14 +636,14 @@ options = self.global_options parser.set_option_table(options) parser.print_help(self.common_usage + "\nGlobal options:") - print + print() if display_options: parser.set_option_table(self.display_options) parser.print_help( "Information display options (just display " + "information, ignore any commands)") - print + print() for command in self.commands: if type(command) is ClassType and issubclass(command, Command): @@ -657,9 +657,9 @@ else: parser.set_option_table(klass.user_options) parser.print_help("Options for '%s' command:" % klass.__name__) - print + print() - print gen_usage(self.script_name) + print(gen_usage(self.script_name)) return # _show_help () @@ -678,8 +678,8 @@ # we ignore "foo bar"). if self.help_commands: self.print_commands() - print - print gen_usage(self.script_name) + print() + print(gen_usage(self.script_name)) return 1 # If user supplied any of the "display metadata" options, then @@ -695,12 +695,12 @@ opt = translate_longopt(opt) value = getattr(self.metadata, "get_"+opt)() if opt in ['keywords', 'platforms']: - print string.join(value, ',') + print(string.join(value, ',')) elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'): - print string.join(value, '\n') + print(string.join(value, '\n')) else: - print value + print(value) any_display_options = 1 return any_display_options @@ -712,7 +712,7 @@ 'print_commands()'. """ - print header + ":" + print(header + ":") for cmd in commands: klass = self.cmdclass.get(cmd) @@ -723,7 +723,7 @@ except AttributeError: description = "(no description available)" - print " %-*s %s" % (max_length, cmd, description) + print(" %-*s %s" % (max_length, cmd, description)) # print_command_list () @@ -757,7 +757,7 @@ "Standard commands", max_length) if extra_commands: - print + print() self.print_command_list(extra_commands, "Extra commands", max_length) @@ -862,8 +862,8 @@ cmd_obj = self.command_obj.get(command) if not cmd_obj and create: if DEBUG: - print "Distribution.get_command_obj(): " \ - "creating '%s' command object" % command + print("Distribution.get_command_obj(): " \ + "creating '%s' command object" % command) klass = self.get_command_class(command) cmd_obj = self.command_obj[command] = klass(self) @@ -893,9 +893,9 @@ if option_dict is None: option_dict = self.get_option_dict(command_name) - if DEBUG: print " setting options for '%s' command:" % command_name + if DEBUG: print(" setting options for '%s' command:" % command_name) for (option, (source, value)) in option_dict.items(): - if DEBUG: print " %s = %s (from %s)" % (option, value, source) + if DEBUG: print(" %s = %s (from %s)" % (option, value, source)) try: bool_opts = map(translate_longopt, command_obj.boolean_options) except AttributeError: @@ -1219,4 +1219,4 @@ if __name__ == "__main__": dist = Distribution() - print "ok" + print("ok") Modified: python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py Fri Feb 23 18:29:35 2007 @@ -497,6 +497,6 @@ say, "How should I know?"].)""" for w in (10, 20, 30, 40): - print "width: %d" % w - print string.join(wrap_text(text, w), "\n") - print + print("width: %d" % w) + print(string.join(wrap_text(text, w), "\n")) + print() Modified: python/branches/p3yk-noslice/Lib/distutils/filelist.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/filelist.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/filelist.py Fri Feb 23 18:29:35 2007 @@ -53,7 +53,7 @@ """ from distutils.debug import DEBUG if DEBUG: - print msg + print(msg) # -- List-like methods --------------------------------------------- Modified: python/branches/p3yk-noslice/Lib/distutils/log.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/log.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/log.py Fri Feb 23 18:29:35 2007 @@ -23,9 +23,9 @@ if not args: # msg may contain a '%'. If args is empty, # don't even try to string-format - print msg + print(msg) else: - print msg % args + print(msg % args) sys.stdout.flush() def log(self, level, msg, *args): Modified: python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py Fri Feb 23 18:29:35 2007 @@ -160,9 +160,9 @@ settings['libraries'] = libraries settings['extrasearchdirs'] = sourcefiledirs + include_dirs + library_dirs if self.dry_run: - print 'CALLING LINKER IN', os.getcwd() + print('CALLING LINKER IN', os.getcwd()) for key, value in settings.items(): - print '%20.20s %s'%(key, value) + print('%20.20s %s'%(key, value)) return # Build the export file exportfilename = os.path.join(build_temp, exportname) Modified: python/branches/p3yk-noslice/Lib/distutils/spawn.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/spawn.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/spawn.py Fri Feb 23 18:29:35 2007 @@ -109,7 +109,7 @@ "command '%s' failed: %s" % (cmd[0], exc[-1]) if rc != 0: # and this reflects the command running but failing - print "command '%s' failed with exit status %d" % (cmd[0], rc) + print("command '%s' failed with exit status %d" % (cmd[0], rc)) raise DistutilsExecError, \ "command '%s' failed with exit status %d" % (cmd[0], rc) Modified: python/branches/p3yk-noslice/Lib/distutils/sysconfig.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/sysconfig.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/sysconfig.py Fri Feb 23 18:29:35 2007 @@ -271,7 +271,7 @@ # do variable interpolation here while notdone: - for name in notdone.keys(): + for name in list(notdone): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: Modified: python/branches/p3yk-noslice/Lib/distutils/tests/test_dist.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/tests/test_dist.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/tests/test_dist.py Fri Feb 23 18:29:35 2007 @@ -74,8 +74,8 @@ sys.argv.append("build") f = open(TESTFN, "w") try: - print >>f, "[global]" - print >>f, "command_packages = foo.bar, splat" + print("[global]", file=f) + print("command_packages = foo.bar, splat", file=f) f.close() d = self.create_distribution([TESTFN]) self.assertEqual(d.get_command_packages(), Modified: python/branches/p3yk-noslice/Lib/distutils/text_file.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/text_file.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/text_file.py Fri Feb 23 18:29:35 2007 @@ -342,13 +342,13 @@ result = file.readlines () # result = string.join (result, '') if result == expected_result: - print "ok %d (%s)" % (count, description) + print("ok %d (%s)" % (count, description)) else: - print "not ok %d (%s):" % (count, description) - print "** expected:" - print expected_result - print "** received:" - print result + print("not ok %d (%s):" % (count, description)) + print("** expected:") + print(expected_result) + print("** received:") + print(result) filename = "test.txt" Modified: python/branches/p3yk-noslice/Lib/distutils/versionpredicate.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/versionpredicate.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/versionpredicate.py Fri Feb 23 18:29:35 2007 @@ -40,7 +40,7 @@ The str() of a `VersionPredicate` provides a normalized human-readable version of the expression:: - >>> print v + >>> print(v) pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3) The `satisfied_by()` method can be used to determine with a given Modified: python/branches/p3yk-noslice/Lib/doctest.py ============================================================================== --- python/branches/p3yk-noslice/Lib/doctest.py (original) +++ python/branches/p3yk-noslice/Lib/doctest.py Fri Feb 23 18:29:35 2007 @@ -240,16 +240,10 @@ # that a trailing newline is missing. if result and not result.endswith("\n"): result += "\n" - # Prevent softspace from screwing up the next test case, in - # case they used print with a trailing comma in an example. - if hasattr(self, "softspace"): - del self.softspace return result - def truncate(self, size=None): + def truncate(self, size=None): StringIO.truncate(self, size) - if hasattr(self, "softspace"): - del self.softspace # Worst-case linear-time ellipsis matching. def _ellipsis_match(want, got): @@ -855,7 +849,7 @@ add them to `tests`. """ if self._verbose: - print 'Finding tests in %s' % name + print('Finding tests in %s' % name) # If we've already processed this object, then ignore it. if id(obj) in seen: @@ -1012,7 +1006,7 @@ >>> runner = DocTestRunner(verbose=False) >>> tests.sort(key = lambda test: test.name) >>> for test in tests: - ... print test.name, '->', runner.run(test) + ... print(test.name, '->', runner.run(test)) _TestClass -> (0, 2) _TestClass.__init__ -> (0, 2) _TestClass.get -> (0, 2) @@ -1384,28 +1378,28 @@ failed.append(x) if verbose: if notests: - print len(notests), "items had no tests:" + print(len(notests), "items had no tests:") notests.sort() for thing in notests: - print " ", thing + print(" ", thing) if passed: - print len(passed), "items passed all tests:" + print(len(passed), "items passed all tests:") passed.sort() for thing, count in passed: - print " %3d tests in %s" % (count, thing) + print(" %3d tests in %s" % (count, thing)) if failed: - print self.DIVIDER - print len(failed), "items had failures:" + print(self.DIVIDER) + print(len(failed), "items had failures:") failed.sort() for thing, (f, t) in failed: - print " %3d of %3d in %s" % (f, t, thing) + print(" %3d of %3d in %s" % (f, t, thing)) if verbose: - print totalt, "tests in", len(self._name2ft), "items." - print totalt - totalf, "passed and", totalf, "failed." + print(totalt, "tests in", len(self._name2ft), "items.") + print(totalt - totalf, "passed and", totalf, "failed.") if totalf: - print "***Test Failed***", totalf, "failures." + print("***Test Failed***", totalf, "failures.") elif verbose: - print "Test passed." + print("Test passed.") return totalf, totalt #///////////////////////////////////////////////////////////////// @@ -1415,8 +1409,8 @@ d = self._name2ft for name, (f, t) in other._name2ft.items(): if name in d: - print "*** DocTestRunner.merge: '" + name + "' in both" \ - " testers; summing outcomes." + print("*** DocTestRunner.merge: '" + name + "' in both" \ + " testers; summing outcomes.") f2, t2 = d[name] f = f + f2 t = t + t2 @@ -1985,10 +1979,10 @@ def runstring(self, s, name): test = DocTestParser().get_doctest(s, self.globs, name, None, None) if self.verbose: - print "Running string", name + print("Running string", name) (f,t) = self.testrunner.run(test) if self.verbose: - print f, "of", t, "examples failed in string", name + print(f, "of", t, "examples failed in string", name) return (f,t) def rundoc(self, object, name=None, module=None): @@ -2419,7 +2413,7 @@ ... Ho hum ... ''' - >>> print script_from_examples(text) + >>> print(script_from_examples(text)) # Here are examples of simple math. # # Python has super accurate integer addition @@ -2512,7 +2506,7 @@ try: execfile(srcfilename, globs, globs) except: - print sys.exc_info()[1] + print(sys.exc_info()[1]) pdb.post_mortem(sys.exc_info()[2]) else: # Note that %r is vital here. '%s' instead can, e.g., cause @@ -2554,7 +2548,7 @@ """val -> _TestClass object with associated value val. >>> t = _TestClass(123) - >>> print t.get() + >>> print(t.get()) 123 """ @@ -2574,7 +2568,7 @@ """get() -> return TestClass's associated value. >>> x = _TestClass(-42) - >>> print x.get() + >>> print(x.get()) -42 """ @@ -2606,7 +2600,7 @@ "blank lines": r""" Blank lines can be marked with : - >>> print 'foo\n\nbar\n' + >>> print('foo\n\nbar\n') foo bar @@ -2616,14 +2610,14 @@ "ellipsis": r""" If the ellipsis flag is used, then '...' can be used to elide substrings in the desired output: - >>> print range(1000) #doctest: +ELLIPSIS + >>> print(range(1000)) #doctest: +ELLIPSIS [0, 1, 2, ..., 999] """, "whitespace normalization": r""" If the whitespace normalization flag is used, then differences in whitespace are ignored. - >>> print range(30) #doctest: +NORMALIZE_WHITESPACE + >>> print(range(30)) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] Modified: python/branches/p3yk-noslice/Lib/dumbdbm.py ============================================================================== --- python/branches/p3yk-noslice/Lib/dumbdbm.py (original) +++ python/branches/p3yk-noslice/Lib/dumbdbm.py Fri Feb 23 18:29:35 2007 @@ -109,7 +109,7 @@ f = self._open(self._dirfile, 'w') self._chmod(self._dirfile) - for key, pos_and_siz_pair in self._index.iteritems(): + for key, pos_and_siz_pair in self._index.items(): f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -202,7 +202,7 @@ return key in self._index def iterkeys(self): - return self._index.iterkeys() + return iter(self._index.keys()) __iter__ = iterkeys def __len__(self): @@ -243,5 +243,5 @@ else: # Turn off any bits that are set in the umask mode = mode & (~um) - + return _Database(file, mode) Modified: python/branches/p3yk-noslice/Lib/dummy_thread.py ============================================================================== --- python/branches/p3yk-noslice/Lib/dummy_thread.py (original) +++ python/branches/p3yk-noslice/Lib/dummy_thread.py Fri Feb 23 18:29:35 2007 @@ -11,11 +11,8 @@ import dummy_thread as thread """ -__author__ = "Brett Cannon" -__email__ = "brett at python.org" - -# Exports only things specified by thread documentation -# (skipping obsolete synonyms allocate(), start_new(), exit_thread()) +# Exports only things specified by thread documentation; +# skipping obsolete synonyms allocate(), start_new(), exit_thread(). __all__ = ['error', 'start_new_thread', 'exit', 'get_ident', 'allocate_lock', 'interrupt_main', 'LockType'] Modified: python/branches/p3yk-noslice/Lib/dummy_threading.py ============================================================================== --- python/branches/p3yk-noslice/Lib/dummy_threading.py (original) +++ python/branches/p3yk-noslice/Lib/dummy_threading.py Fri Feb 23 18:29:35 2007 @@ -5,11 +5,6 @@ directly imported it would have made all subsequent imports succeed regardless of whether ``thread`` was available which is not desired. -:Author: Brett Cannon -:Contact: brett at python.org - -XXX: Try to get rid of ``_dummy_threading``. - """ from sys import modules as sys_modules Modified: python/branches/p3yk-noslice/Lib/email/charset.py ============================================================================== --- python/branches/p3yk-noslice/Lib/email/charset.py (original) +++ python/branches/p3yk-noslice/Lib/email/charset.py Fri Feb 23 18:29:35 2007 @@ -46,6 +46,7 @@ 'iso-8859-13': (QP, QP, None), 'iso-8859-14': (QP, QP, None), 'iso-8859-15': (QP, QP, None), + 'iso-8859-16': (QP, QP, None), 'windows-1252':(QP, QP, None), 'viscii': (QP, QP, None), 'us-ascii': (None, None, None), @@ -81,6 +82,8 @@ 'latin-8': 'iso-8859-14', 'latin_9': 'iso-8859-15', 'latin-9': 'iso-8859-15', + 'latin_10':'iso-8859-16', + 'latin-10':'iso-8859-16', 'cp949': 'ks_c_5601-1987', 'euc_jp': 'euc-jp', 'euc_kr': 'euc-kr', Modified: python/branches/p3yk-noslice/Lib/email/generator.py ============================================================================== --- python/branches/p3yk-noslice/Lib/email/generator.py (original) +++ python/branches/p3yk-noslice/Lib/email/generator.py Fri Feb 23 18:29:35 2007 @@ -80,7 +80,7 @@ ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) - print >> self._fp, ufrom + print(ufrom, file=self._fp) self._write(msg) def clone(self, fp): @@ -140,13 +140,13 @@ def _write_headers(self, msg): for h, v in msg.items(): - print >> self._fp, '%s:' % h, + print('%s:' % h, end=' ', file=self._fp) if self._maxheaderlen == 0: # Explicit no-wrapping - print >> self._fp, v + print(v, file=self._fp) elif isinstance(v, Header): # Header instances know what to do - print >> self._fp, v.encode() + print(v.encode(), file=self._fp) elif _is8bitstring(v): # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this @@ -154,14 +154,14 @@ # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. - print >> self._fp, v + print(v, file=self._fp) else: # Header's got lots of smarts, so use it. - print >> self._fp, Header( + print(Header( v, maxlinelen=self._maxheaderlen, - header_name=h, continuation_ws='\t').encode() + header_name=h, continuation_ws='\t').encode(), file=self._fp) # A blank line always separates headers from body - print >> self._fp + print(file=self._fp) # # Handlers for writing types and subtypes @@ -215,9 +215,9 @@ msg.set_boundary(boundary) # If there's a preamble, write it out, with a trailing CRLF if msg.preamble is not None: - print >> self._fp, msg.preamble + print(msg.preamble, file=self._fp) # dash-boundary transport-padding CRLF - print >> self._fp, '--' + boundary + print('--' + boundary, file=self._fp) # body-part if msgtexts: self._fp.write(msgtexts.pop(0)) @@ -226,13 +226,13 @@ # --> CRLF body-part for body_part in msgtexts: # delimiter transport-padding CRLF - print >> self._fp, '\n--' + boundary + print('\n--' + boundary, file=self._fp) # body-part self._fp.write(body_part) # close-delimiter transport-padding self._fp.write('\n--' + boundary + '--') if msg.epilogue is not None: - print >> self._fp + print(file=self._fp) self._fp.write(msg.epilogue) def _handle_message_delivery_status(self, msg): @@ -308,12 +308,12 @@ for part in msg.walk(): maintype = part.get_content_maintype() if maintype == 'text': - print >> self, part.get_payload(decode=True) + print(part.get_payload(decode=True), file=self) elif maintype == 'multipart': # Just skip this pass else: - print >> self, self._fmt % { + print(self._fmt % { 'type' : part.get_content_type(), 'maintype' : part.get_content_maintype(), 'subtype' : part.get_content_subtype(), @@ -322,7 +322,7 @@ '[no description]'), 'encoding' : part.get('Content-Transfer-Encoding', '[no encoding]'), - } + }, file=self) Modified: python/branches/p3yk-noslice/Lib/email/iterators.py ============================================================================== --- python/branches/p3yk-noslice/Lib/email/iterators.py (original) +++ python/branches/p3yk-noslice/Lib/email/iterators.py Fri Feb 23 18:29:35 2007 @@ -63,11 +63,11 @@ if fp is None: fp = sys.stdout tab = ' ' * (level * 4) - print >> fp, tab + msg.get_content_type(), + print(tab + msg.get_content_type(), end='', file=fp) if include_default: - print >> fp, '[%s]' % msg.get_default_type() + print(' [%s]' % msg.get_default_type(), file=fp) else: - print >> fp + print(file=fp) if msg.is_multipart(): for subpart in msg.get_payload(): _structure(subpart, fp, level+1, include_default) Modified: python/branches/p3yk-noslice/Lib/email/test/test_email.py ============================================================================== --- python/branches/p3yk-noslice/Lib/email/test/test_email.py (original) +++ python/branches/p3yk-noslice/Lib/email/test/test_email.py Fri Feb 23 18:29:35 2007 @@ -54,10 +54,9 @@ if first != second: sfirst = str(first) ssecond = str(second) - diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) - fp = StringIO() - print >> fp, NL, NL.join(diff) - raise self.failureException, fp.getvalue() + diff = difflib.ndiff(sfirst.splitlines(True), + ssecond.splitlines(True)) + raise self.failureException(NL + "".join(diff)) def _msgobj(self, filename): fp = openfile(findfile(filename)) Modified: python/branches/p3yk-noslice/Lib/email/test/test_email_codecs.py ============================================================================== --- python/branches/p3yk-noslice/Lib/email/test/test_email_codecs.py (original) +++ python/branches/p3yk-noslice/Lib/email/test/test_email_codecs.py Fri Feb 23 18:29:35 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-noslice/Lib/email/test/test_email_codecs_renamed.py ============================================================================== --- python/branches/p3yk-noslice/Lib/email/test/test_email_codecs_renamed.py (original) +++ python/branches/p3yk-noslice/Lib/email/test/test_email_codecs_renamed.py Fri Feb 23 18:29:35 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-noslice/Lib/email/test/test_email_renamed.py ============================================================================== --- python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py (original) +++ python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py Fri Feb 23 18:29:35 2007 @@ -55,10 +55,9 @@ if first != second: sfirst = str(first) ssecond = str(second) - diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) - fp = StringIO() - print >> fp, NL, NL.join(diff) - raise self.failureException, fp.getvalue() + diff = difflib.ndiff(sfirst.splitlines(True), + ssecond.splitlines(True)) + raise self.failureException(NL + "".join(diff)) def _msgobj(self, filename): fp = openfile(findfile(filename)) Modified: python/branches/p3yk-noslice/Lib/encodings/__init__.py ============================================================================== --- python/branches/p3yk-noslice/Lib/encodings/__init__.py (original) +++ python/branches/p3yk-noslice/Lib/encodings/__init__.py Fri Feb 23 18:29:35 2007 @@ -93,8 +93,10 @@ if not modname or '.' in modname: continue try: - mod = __import__('encodings.' + modname, - globals(), locals(), _import_tail) + # Import is absolute to prevent the possibly malicious import of a + # module with side-effects that is not in the 'encodings' package. + mod = __import__('encodings.' + modname, fromlist=_import_tail, + level=0) except ImportError: pass else: Modified: python/branches/p3yk-noslice/Lib/encodings/aliases.py ============================================================================== --- python/branches/p3yk-noslice/Lib/encodings/aliases.py (original) +++ python/branches/p3yk-noslice/Lib/encodings/aliases.py Fri Feb 23 18:29:35 2007 @@ -301,6 +301,8 @@ # iso8859_13 codec 'iso_8859_13' : 'iso8859_13', + 'l7' : 'iso8859_13', + 'latin7' : 'iso8859_13', # iso8859_14 codec 'iso_8859_14' : 'iso8859_14', @@ -312,6 +314,8 @@ # iso8859_15 codec 'iso_8859_15' : 'iso8859_15', + 'l9' : 'iso8859_15', + 'latin9' : 'iso8859_15', # iso8859_16 codec 'iso_8859_16' : 'iso8859_16', Modified: python/branches/p3yk-noslice/Lib/encodings/punycode.py ============================================================================== --- python/branches/p3yk-noslice/Lib/encodings/punycode.py (original) +++ python/branches/p3yk-noslice/Lib/encodings/punycode.py Fri Feb 23 18:29:35 2007 @@ -17,8 +17,7 @@ base.append(c) else: extended[c] = 1 - extended = extended.keys() - extended.sort() + extended = sorted(extended.keys()) return "".join(base).encode("ascii"),extended def selective_len(str, max): Modified: python/branches/p3yk-noslice/Lib/filecmp.py ============================================================================== --- python/branches/p3yk-noslice/Lib/filecmp.py (original) +++ python/branches/p3yk-noslice/Lib/filecmp.py Fri Feb 23 18:29:35 2007 @@ -187,44 +187,44 @@ def phase4_closure(self): # Recursively call phase4() on subdirectories self.phase4() - for sd in self.subdirs.itervalues(): + for sd in self.subdirs.values(): sd.phase4_closure() def report(self): # Print a report on the differences between a and b # Output format is purposely lousy - print 'diff', self.left, self.right + print('diff', self.left, self.right) if self.left_only: self.left_only.sort() - print 'Only in', self.left, ':', self.left_only + print('Only in', self.left, ':', self.left_only) if self.right_only: self.right_only.sort() - print 'Only in', self.right, ':', self.right_only + print('Only in', self.right, ':', self.right_only) if self.same_files: self.same_files.sort() - print 'Identical files :', self.same_files + print('Identical files :', self.same_files) if self.diff_files: self.diff_files.sort() - print 'Differing files :', self.diff_files + print('Differing files :', self.diff_files) if self.funny_files: self.funny_files.sort() - print 'Trouble with common files :', self.funny_files + print('Trouble with common files :', self.funny_files) if self.common_dirs: self.common_dirs.sort() - print 'Common subdirectories :', self.common_dirs + print('Common subdirectories :', self.common_dirs) if self.common_funny: self.common_funny.sort() - print 'Common funny cases :', self.common_funny + print('Common funny cases :', self.common_funny) def report_partial_closure(self): # Print reports on self and on subdirs self.report() - for sd in self.subdirs.itervalues(): - print + for sd in self.subdirs.values(): + print() sd.report() def report_full_closure(self): # Report on self and subdirs recursively self.report() - for sd in self.subdirs.itervalues(): - print + for sd in self.subdirs.values(): + print() sd.report_full_closure() methodmap = dict(subdirs=phase4, Modified: python/branches/p3yk-noslice/Lib/fileinput.py ============================================================================== --- python/branches/p3yk-noslice/Lib/fileinput.py (original) +++ python/branches/p3yk-noslice/Lib/fileinput.py Fri Feb 23 18:29:35 2007 @@ -405,9 +405,9 @@ for line in input(args, inplace=inplace, backup=backup): if line[-1:] == '\n': line = line[:-1] if line[-1:] == '\r': line = line[:-1] - print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(), - isfirstline() and "*" or "", line) - print "%d: %s[%d]" % (lineno(), filename(), filelineno()) + print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(), + isfirstline() and "*" or "", line)) + print("%d: %s[%d]" % (lineno(), filename(), filelineno())) if __name__ == '__main__': _test() Modified: python/branches/p3yk-noslice/Lib/formatter.py ============================================================================== --- python/branches/p3yk-noslice/Lib/formatter.py (original) +++ python/branches/p3yk-noslice/Lib/formatter.py Fri Feb 23 18:29:35 2007 @@ -323,37 +323,37 @@ """ def new_alignment(self, align): - print "new_alignment(%r)" % (align,) + print("new_alignment(%r)" % (align,)) def new_font(self, font): - print "new_font(%r)" % (font,) + print("new_font(%r)" % (font,)) def new_margin(self, margin, level): - print "new_margin(%r, %d)" % (margin, level) + print("new_margin(%r, %d)" % (margin, level)) def new_spacing(self, spacing): - print "new_spacing(%r)" % (spacing,) + print("new_spacing(%r)" % (spacing,)) def new_styles(self, styles): - print "new_styles(%r)" % (styles,) + print("new_styles(%r)" % (styles,)) def send_paragraph(self, blankline): - print "send_paragraph(%r)" % (blankline,) + print("send_paragraph(%r)" % (blankline,)) def send_line_break(self): - print "send_line_break()" + print("send_line_break()") def send_hor_rule(self, *args, **kw): - print "send_hor_rule()" + print("send_hor_rule()") def send_label_data(self, data): - print "send_label_data(%r)" % (data,) + print("send_label_data(%r)" % (data,)) def send_flowing_data(self, data): - print "send_flowing_data(%r)" % (data,) + print("send_flowing_data(%r)" % (data,)) def send_literal_data(self, data): - print "send_literal_data(%r)" % (data,) + print("send_literal_data(%r)" % (data,)) class DumbWriter(NullWriter): Modified: python/branches/p3yk-noslice/Lib/fpformat.py ============================================================================== --- python/branches/p3yk-noslice/Lib/fpformat.py (original) +++ python/branches/p3yk-noslice/Lib/fpformat.py Fri Feb 23 18:29:35 2007 @@ -137,6 +137,6 @@ try: while 1: x, digs = input('Enter (x, digs): ') - print x, fix(x, digs), sci(x, digs) + print(x, fix(x, digs), sci(x, digs)) except (EOFError, KeyboardInterrupt): pass Modified: python/branches/p3yk-noslice/Lib/ftplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ftplib.py (original) +++ python/branches/p3yk-noslice/Lib/ftplib.py Fri Feb 23 18:29:35 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 @@ -136,7 +137,7 @@ '''Get the welcome message from the server. (this is read and squirreled away by connect())''' if self.debugging: - print '*welcome*', self.sanitize(self.welcome) + print('*welcome*', self.sanitize(self.welcome)) return self.welcome def set_debuglevel(self, level): @@ -166,12 +167,12 @@ # Internal: send one line to the server, appending CRLF def putline(self, line): line = line + CRLF - if self.debugging > 1: print '*put*', self.sanitize(line) + if self.debugging > 1: print('*put*', self.sanitize(line)) self.sock.sendall(line) # Internal: send one command to the server (through putline()) def putcmd(self, line): - if self.debugging: print '*cmd*', self.sanitize(line) + if self.debugging: print('*cmd*', self.sanitize(line)) self.putline(line) # Internal: return one line from the server, stripping CRLF. @@ -179,7 +180,7 @@ def getline(self): line = self.file.readline() if self.debugging > 1: - print '*get*', self.sanitize(line) + print('*get*', self.sanitize(line)) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] @@ -205,7 +206,7 @@ # Raise various errors if the response indicates an error def getresp(self): resp = self.getmultiline() - if self.debugging: print '*resp*', self.sanitize(resp) + if self.debugging: print('*resp*', self.sanitize(resp)) self.lastresp = resp[:3] c = resp[:1] if c in ('1', '2', '3'): @@ -229,7 +230,7 @@ IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.''' line = 'ABOR' + CRLF - if self.debugging > 1: print '*put urgent*', self.sanitize(line) + if self.debugging > 1: print('*put urgent*', self.sanitize(line)) self.sock.sendall(line, MSG_OOB) resp = self.getmultiline() if resp[:3] not in ('426', '226'): @@ -332,7 +333,7 @@ # 1xx or error messages for LIST), so we just discard # this response. if resp[0] == '2': - resp = self.getresp() + resp = self.getresp() if resp[0] != '1': raise error_reply, resp else: @@ -342,7 +343,7 @@ resp = self.sendcmd(cmd) # See above. if resp[0] == '2': - resp = self.getresp() + resp = self.getresp() if resp[0] != '1': raise error_reply, resp conn, sockaddr = sock.accept() @@ -408,7 +409,7 @@ fp = conn.makefile('rb') while 1: line = fp.readline() - if self.debugging > 2: print '*retr*', repr(line) + if self.debugging > 2: print('*retr*', repr(line)) if not line: break if line[-2:] == CRLF: @@ -513,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.''' @@ -563,7 +564,7 @@ try: return int(s) except (OverflowError, ValueError): - return long(s) + return int(s) _227_re = None @@ -635,7 +636,7 @@ def print_line(line): '''Default retrlines callback to print a line.''' - print line + print(line) def ftpcp(source, sourcename, target, targetname = '', type = 'I'): @@ -774,7 +775,7 @@ ''' if len(sys.argv) < 2: - print test.__doc__ + print(test.__doc__) sys.exit(0) debugging = 0 Modified: python/branches/p3yk-noslice/Lib/getopt.py ============================================================================== --- python/branches/p3yk-noslice/Lib/getopt.py (original) +++ python/branches/p3yk-noslice/Lib/getopt.py Fri Feb 23 18:29:35 2007 @@ -208,4 +208,4 @@ if __name__ == '__main__': import sys - print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) + print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])) Modified: python/branches/p3yk-noslice/Lib/getpass.py ============================================================================== --- python/branches/p3yk-noslice/Lib/getpass.py (original) +++ python/branches/p3yk-noslice/Lib/getpass.py Fri Feb 23 18:29:35 2007 @@ -67,7 +67,7 @@ def default_getpass(prompt='Password: ', stream=None): - print >>sys.stderr, "Warning: Problem with getpass. Passwords may be echoed." + print("Warning: Problem with getpass. Passwords may be echoed.", file=sys.stderr) return _raw_input(prompt, stream) Modified: python/branches/p3yk-noslice/Lib/gettext.py ============================================================================== --- python/branches/p3yk-noslice/Lib/gettext.py (original) +++ python/branches/p3yk-noslice/Lib/gettext.py Fri Feb 23 18:29:35 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-noslice/Lib/gopherlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/gopherlib.py (original) +++ python/branches/p3yk-noslice/Lib/gopherlib.py Fri Feb 23 18:29:35 2007 @@ -103,7 +103,7 @@ while 1: line = f.readline() if not line: - print '(Unexpected EOF from server)' + print('(Unexpected EOF from server)') break if line[-2:] == CRLF: line = line[:-2] @@ -112,17 +112,17 @@ if line == '.': break if not line: - print '(Empty line from server)' + print('(Empty line from server)') continue gtype = line[0] parts = line[1:].split(TAB) if len(parts) < 4: - print '(Bad line from server: %r)' % (line,) + print('(Bad line from server: %r)' % (line,)) continue if len(parts) > 4: if parts[4:] != ['+']: - print '(Extra info from server:', - print parts[4:], ')' + print('(Extra info from server:', end=' ') + print(parts[4:], ')') else: parts.append('') parts.insert(0, gtype) @@ -140,7 +140,7 @@ while 1: line = f.readline() if not line: - print '(Unexpected EOF from server)' + print('(Unexpected EOF from server)') break if line[-2:] == CRLF: line = line[:-2] @@ -196,13 +196,13 @@ f = send_selector(selector, host) if type == A_TEXT: lines = get_textfile(f) - for item in lines: print item + for item in lines: print(item) elif type in (A_MENU, A_INDEX): entries = get_directory(f) - for item in entries: print item + for item in entries: print(item) else: data = get_binary(f) - print 'binary data:', len(data), 'bytes:', repr(data[:100])[:40] + print('binary data:', len(data), 'bytes:', repr(data[:100])[:40]) # Run the test when run as script if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/gzip.py ============================================================================== --- python/branches/p3yk-noslice/Lib/gzip.py (original) +++ python/branches/p3yk-noslice/Lib/gzip.py Fri Feb 23 18:29:35 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("' def _init_write(self, filename): - if filename[-3:] != '.gz': - filename = filename + '.gz' - self.filename = filename + self.name = filename self.crc = zlib.crc32("") self.size = 0 self.writebuf = [] @@ -143,12 +149,14 @@ def _write_gzip_header(self): self.fileobj.write('\037\213') # magic header self.fileobj.write('\010') # compression method - fname = self.filename[:-3] + fname = self.name + if fname.endswith(".gz"): + fname = fname[:-3] flags = 0 if fname: flags = FNAME self.fileobj.write(chr(flags)) - write32u(self.fileobj, long(time.time())) + write32u(self.fileobj, int(time.time())) self.fileobj.write('\002') self.fileobj.write('\377') if fname: @@ -470,7 +478,7 @@ g = sys.stdout else: if arg[-3:] != ".gz": - print "filename doesn't end in .gz:", repr(arg) + print("filename doesn't end in .gz:", repr(arg)) continue f = open(arg, "rb") g = __builtin__.open(arg[:-3], "wb") Modified: python/branches/p3yk-noslice/Lib/heapq.py ============================================================================== --- python/branches/p3yk-noslice/Lib/heapq.py (original) +++ python/branches/p3yk-noslice/Lib/heapq.py Fri Feb 23 18:29:35 2007 @@ -126,8 +126,8 @@ From all times, sorting has always been a Great Art! :-) """ -__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'nlargest', - 'nsmallest'] +__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', + 'nlargest', 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee from operator import itemgetter, neg @@ -308,6 +308,41 @@ except ImportError: pass +def merge(*iterables): + '''Merge multiple sorted inputs into a single sorted output. + + Similar to sorted(itertools.chain(*iterables)) but returns an iterable, + does not pull the data into memory all at once, and assumes that each of + the input streams is already sorted (smallest to largest). + + >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) + [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] + + ''' + _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration + + h = [] + h_append = h.append + for itnum, it in enumerate(map(iter, iterables)): + try: + next = it.next + h_append([next(), itnum, next]) + except _StopIteration: + pass + heapify(h) + + while 1: + try: + while 1: + v, itnum, next = s = h[0] # raises IndexError when h is empty + yield v + s[0] = next() # raises StopIteration when exhausted + _heapreplace(h, s) # restore heap condition + except _StopIteration: + _heappop(h) # remove empty iterator + except IndexError: + return + # Extend the implementations of nsmallest and nlargest to use a key= argument _nsmallest = nsmallest def nsmallest(n, iterable, key=None): @@ -340,4 +375,7 @@ sort = [] while heap: sort.append(heappop(heap)) - print sort + print(sort) + + import doctest + doctest.testmod() Modified: python/branches/p3yk-noslice/Lib/hotshot/log.py ============================================================================== --- python/branches/p3yk-noslice/Lib/hotshot/log.py (original) +++ python/branches/p3yk-noslice/Lib/hotshot/log.py Fri Feb 23 18:29:35 2007 @@ -159,7 +159,7 @@ try: filename = self._filemap[fileno] except KeyError: - print "Could not identify fileId", fileno + print("Could not identify fileId", fileno) return 1 if filename is None: return 1 Modified: python/branches/p3yk-noslice/Lib/hotshot/stones.py ============================================================================== --- python/branches/p3yk-noslice/Lib/hotshot/stones.py (original) +++ python/branches/p3yk-noslice/Lib/hotshot/stones.py Fri Feb 23 18:29:35 2007 @@ -10,9 +10,9 @@ benchtime, stones = p.runcall(test.pystone.pystones) p.close() - print "Pystone(%s) time for %d passes = %g" % \ - (test.pystone.__version__, test.pystone.LOOPS, benchtime) - print "This machine benchmarks at %g pystones/second" % stones + print("Pystone(%s) time for %d passes = %g" % \ + (test.pystone.__version__, test.pystone.LOOPS, benchtime)) + print("This machine benchmarks at %g pystones/second" % stones) stats = hotshot.stats.load(logfile) stats.strip_dirs() Modified: python/branches/p3yk-noslice/Lib/htmlentitydefs.py ============================================================================== --- python/branches/p3yk-noslice/Lib/htmlentitydefs.py (original) +++ python/branches/p3yk-noslice/Lib/htmlentitydefs.py Fri Feb 23 18:29:35 2007 @@ -263,7 +263,7 @@ # (or a character reference if the character is outside the Latin-1 range) entitydefs = {} -for (name, codepoint) in name2codepoint.iteritems(): +for (name, codepoint) in name2codepoint.items(): codepoint2name[codepoint] = name if codepoint <= 0xff: entitydefs[name] = chr(codepoint) Modified: python/branches/p3yk-noslice/Lib/htmllib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/htmllib.py (original) +++ python/branches/p3yk-noslice/Lib/htmllib.py Fri Feb 23 18:29:35 2007 @@ -464,7 +464,7 @@ try: f = open(file, 'r') except IOError as msg: - print file, ":", msg + print(file, ":", msg) sys.exit(1) data = f.read() Modified: python/branches/p3yk-noslice/Lib/httplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/httplib.py (original) +++ python/branches/p3yk-noslice/Lib/httplib.py Fri Feb 23 18:29:35 2007 @@ -342,7 +342,7 @@ # Initialize with Simple-Response defaults line = self.fp.readline() if self.debuglevel > 0: - print "reply:", repr(line) + print("reply:", repr(line)) if not line: # Presumably, the server closed the connection before # sending a valid response. @@ -391,7 +391,7 @@ if not skip: break if self.debuglevel > 0: - print "header:", skip + print("header:", skip) self.status = status self.reason = reason.strip() @@ -414,7 +414,7 @@ self.msg = HTTPMessage(self.fp, 0) if self.debuglevel > 0: for hdr in self.msg.headers: - print "header:", hdr, + print("header:", hdr, end=' ') # don't let the msg keep an fp self.msg.fp = None @@ -611,7 +611,7 @@ """Return list of (header, value) tuples.""" if self.msg is None: raise ResponseNotReady() - return self.msg.items() + return list(self.msg.items()) class HTTPConnection: @@ -665,11 +665,11 @@ try: self.sock = socket.socket(af, socktype, proto) if self.debuglevel > 0: - print "connect: (%s, %s)" % (self.host, self.port) + print("connect: (%s, %s)" % (self.host, self.port)) self.sock.connect(sa) except socket.error as msg: if self.debuglevel > 0: - print 'connect fail:', (self.host, self.port) + print('connect fail:', (self.host, self.port)) if self.sock: self.sock.close() self.sock = None @@ -702,11 +702,11 @@ # NOTE: we DO propagate the error, though, because we cannot simply # ignore the error... the caller will know if they can retry. if self.debuglevel > 0: - print "send:", repr(str) + print("send:", repr(str)) try: blocksize=8192 if hasattr(str,'read') : - if self.debuglevel > 0: print "sendIng a read()able" + if self.debuglevel > 0: print("sendIng a read()able") data=str.read(blocksize) while data: self.sock.sendall(data) @@ -898,11 +898,11 @@ thelen = str(os.fstat(body.fileno()).st_size) except (AttributeError, OSError): # Don't send a length if this failed - if self.debuglevel > 0: print "Cannot stat!!" - + if self.debuglevel > 0: print("Cannot stat!!") + if thelen is not None: self.putheader('Content-Length',thelen) - for hdr, value in headers.iteritems(): + for hdr, value in headers.items(): self.putheader(hdr, value) self.endheaders() @@ -1408,13 +1408,13 @@ h.putrequest('GET', selector) h.endheaders() status, reason, headers = h.getreply() - print 'status =', status - print 'reason =', reason - print "read", len(h.getfile().read()) - print + print('status =', status) + print('reason =', reason) + print("read", len(h.getfile().read())) + print() if headers: - for header in headers.headers: print header.strip() - print + for header in headers.headers: print(header.strip()) + print() # minimal test that code to extract host from url works class HTTP11(HTTP): @@ -1431,20 +1431,20 @@ for host, selector in (('sourceforge.net', '/projects/python'), ): - print "https://%s%s" % (host, selector) + print("https://%s%s" % (host, selector)) hs = HTTPS() hs.set_debuglevel(dl) hs.connect(host) hs.putrequest('GET', selector) hs.endheaders() status, reason, headers = hs.getreply() - print 'status =', status - print 'reason =', reason - print "read", len(hs.getfile().read()) - print + print('status =', status) + print('reason =', reason) + print("read", len(hs.getfile().read())) + print() if headers: - for header in headers.headers: print header.strip() - print + for header in headers.headers: print(header.strip()) + print() if __name__ == '__main__': test() Modified: python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py Fri Feb 23 18:29:35 2007 @@ -10,13 +10,14 @@ KEYPRESS_VIRTUAL_EVENT_NAME = "<>" # We need to bind event beyond so that the function will be called # before the default specific IDLE function -KEYPRESS_SEQUENCES = ("", "", "", - "", "", "", "") +KEYPRESS_SEQUENCES = ("", "", "", "", + "", "", "", "", + "", "") KEYRELEASE_VIRTUAL_EVENT_NAME = "<>" KEYRELEASE_SEQUENCE = "" -LISTUPDATE_SEQUENCE = "" +LISTUPDATE_SEQUENCE = "" WINCONFIG_SEQUENCE = "" -DOUBLECLICK_SEQUENCE = "" +DOUBLECLICK_SEQUENCE = "" class AutoCompleteWindow: @@ -49,6 +50,8 @@ # event ids self.hideid = self.keypressid = self.listupdateid = self.winconfigid \ = self.keyreleaseid = self.doubleclickid = None + # Flag set if last keypress was a tab + self.lastkey_was_tab = False def _change_start(self, newstart): i = 0 @@ -118,11 +121,6 @@ i = 0 while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]: i += 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) @@ -206,7 +204,7 @@ self.keyrelease_event) self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE) self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, - self.listupdate_event) + self.listselect_event) self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event) self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, self.doubleclick_event) @@ -215,24 +213,34 @@ if not self.is_active(): return # Position the completion list window + text = self.widget + text.see(self.startindex) + x, y, cx, cy = text.bbox(self.startindex) acw = self.autocompletewindow - self.widget.see(self.startindex) - x, y, cx, cy = self.widget.bbox(self.startindex) - acw.wm_geometry("+%d+%d" % (x + self.widget.winfo_rootx(), - y + self.widget.winfo_rooty() \ - -acw.winfo_height())) - + acw_width, acw_height = acw.winfo_width(), acw.winfo_height() + text_width, text_height = text.winfo_width(), text.winfo_height() + new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width)) + new_y = text.winfo_rooty() + y + if (text_height - (y + cy) >= acw_height # enough height below + or y < acw_height): # not enough height above + # place acw below current line + new_y += cy + else: + # place acw above current line + new_y -= acw_height + acw.wm_geometry("+%d+%d" % (new_x, new_y)) def hide_event(self, event): if not self.is_active(): return self.hide_window() - def listupdate_event(self, event): + def listselect_event(self, event): if not self.is_active(): return self.userwantswindow = True - self._selection_changed() + cursel = int(self.listbox.curselection()[0]) + self._change_start(self.completions[cursel]) def doubleclick_event(self, event): # Put the selected completion in the text, and close the list @@ -248,7 +256,8 @@ state = event.mc_state else: state = 0 - + if keysym != "Tab": + self.lastkey_was_tab = False if (len(keysym) == 1 or keysym in ("underscore", "BackSpace") or (self.mode==AutoComplete.COMPLETE_FILES and keysym in ("period", "minus"))) \ @@ -330,13 +339,21 @@ self.listbox.select_clear(cursel) self.listbox.select_set(newsel) self._selection_changed() + self._change_start(self.completions[newsel]) return "break" elif (keysym == "Tab" and not state): - # The user wants a completion, but it is handled by AutoComplete - # (not AutoCompleteWindow), so ignore. - self.userwantswindow = True - return + if self.lastkey_was_tab: + # two tabs in a row; insert current selection and close acw + cursel = int(self.listbox.curselection()[0]) + self._change_start(self.completions[cursel]) + self.hide_window() + return "break" + else: + # first tab; let AutoComplete handle the completion + self.userwantswindow = True + self.lastkey_was_tab = True + return elif any(s in keysym for s in ("Shift", "Control", "Alt", "Meta", "Command", "Option")): Modified: python/branches/p3yk-noslice/Lib/idlelib/CallTips.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/CallTips.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/CallTips.py Fri Feb 23 18:29:35 2007 @@ -3,7 +3,9 @@ Call Tips are floating windows which display function, class, and method parameter and docstring information when you type an opening parenthesis, and which disappear when you type a closing parenthesis. + """ +import re import sys import types @@ -89,6 +91,8 @@ two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. + To find methods, fetch_tip must be fed a fully qualified name. + """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt @@ -108,7 +112,7 @@ namespace.update(__main__.__dict__) try: return eval(name, namespace) - except: + except (NameError, AttributeError): return None def _find_constructor(class_ob): @@ -124,39 +128,37 @@ def get_arg_text(ob): """Get a string describing the arguments for the given object""" - argText = "" + arg_text = "" if ob is not None: - argOffset = 0 + arg_offset = 0 if type(ob) in (types.ClassType, types.TypeType): # Look for the highest __init__ in the class chain. fob = _find_constructor(ob) if fob is None: fob = lambda: None else: - argOffset = 1 + arg_offset = 1 elif type(ob)==types.MethodType: # bit of a hack for methods - turn it into a function # but we drop the "self" param. fob = ob.im_func - argOffset = 1 + arg_offset = 1 else: fob = ob - # Try and build one for Python defined functions + # Try to build one for Python defined functions if type(fob) in [types.FunctionType, types.LambdaType]: - try: - realArgs = fob.func_code.co_varnames[argOffset:fob.func_code.co_argcount] - defaults = fob.func_defaults or [] - defaults = list(map(lambda name: "=%s" % repr(name), defaults)) - defaults = [""] * (len(realArgs)-len(defaults)) + defaults - items = map(lambda arg, dflt: arg+dflt, realArgs, defaults) - if fob.func_code.co_flags & 0x4: - items.append("...") - if fob.func_code.co_flags & 0x8: - items.append("***") - argText = ", ".join(items) - argText = "(%s)" % argText - except: - pass + argcount = fob.func_code.co_argcount + real_args = fob.func_code.co_varnames[arg_offset:argcount] + defaults = fob.func_defaults or [] + defaults = list(map(lambda name: "=%s" % repr(name), defaults)) + defaults = [""] * (len(real_args) - len(defaults)) + defaults + items = map(lambda arg, dflt: arg + dflt, real_args, defaults) + if fob.func_code.co_flags & 0x4: + items.append("...") + if fob.func_code.co_flags & 0x8: + items.append("***") + arg_text = ", ".join(items) + arg_text = "(%s)" % re.sub("\.\d+", "", arg_text) # See if we can use the docstring doc = getattr(ob, "__doc__", "") if doc: @@ -164,10 +166,10 @@ pos = doc.find("\n") if pos < 0 or pos > 70: pos = 70 - if argText: - argText += "\n" - argText += doc[:pos] - return argText + if arg_text: + arg_text += "\n" + arg_text += doc[:pos] + return arg_text ################################################# # @@ -181,16 +183,18 @@ def t4(*args): "(...)" def t5(a, *args): "(a, ...)" def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)" + def t7((a, b), c, (d, e)): "(, c, )" - class TC: - "(a=None, ...)" - def __init__(self, a=None, *b): "(a=None, ...)" + class TC(object): + "(ai=None, ...)" + def __init__(self, ai=None, *b): "(ai=None, ...)" def t1(self): "()" - def t2(self, a, b=None): "(a, b=None)" - def t3(self, a, *args): "(a, ...)" + def t2(self, ai, b=None): "(ai, b=None)" + def t3(self, ai, *args): "(ai, ...)" def t4(self, *args): "(...)" - def t5(self, a, *args): "(a, ...)" - def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)" + def t5(self, ai, *args): "(ai, ...)" + def t6(self, ai, b=None, *args, **kw): "(ai, b=None, ..., ***)" + def t7(self, (ai, b), c, (d, e)): "(, c, )" def test(tests): ct = CallTips() @@ -198,15 +202,20 @@ for t in tests: expected = t.__doc__ + "\n" + t.__doc__ name = t.__name__ - arg_text = ct.fetch_tip(name) + # exercise fetch_tip(), not just get_arg_text() + try: + qualified_name = "%s.%s" % (t.im_class.__name__, name) + except AttributeError: + qualified_name = name + arg_text = ct.fetch_tip(qualified_name) if arg_text != expected: failed.append(t) - print "%s - expected %s, but got %s" % (t, expected, - get_arg_text(entity)) - print "%d of %d tests failed" % (len(failed), len(tests)) + fmt = "%s - expected %s, but got %s" + print(fmt % (t.__name__, expected, get_arg_text(t))) + print("%d of %d tests failed" % (len(failed), len(tests))) tc = TC() - tests = (t1, t2, t3, t4, t5, t6, - TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6) + tests = (t1, t2, t3, t4, t5, t6, t7, + TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6, tc.t7) test(tests) Modified: python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py Fri Feb 23 18:29:35 2007 @@ -10,6 +10,7 @@ """ import Tkinter +from Tkconstants import TOP, LEFT, X, W, SUNKEN from configHandler import idleConf import re from sys import maxint as INFINITY @@ -24,7 +25,6 @@ class CodeContext: menudefs = [('options', [('!Code Conte_xt', '<>')])] - context_depth = idleConf.GetOption("extensions", "CodeContext", "numlines", type="int", default=3) bgcolor = idleConf.GetOption("extensions", "CodeContext", @@ -54,66 +54,33 @@ def toggle_code_context_event(self, event=None): if not self.label: - # The following code attempts to figure out the required border - # width and vertical padding required for the CodeContext widget - # to be perfectly aligned with the text in the main Text widget. - # This is done by retrieving the appropriate attributes from the - # editwin.text and editwin.text_frame widgets. + # Calculate the border width and horizontal padding required to + # align the context with the text in the main Text widget. # # All values are passed through int(str()), since some - # values may be pixel objects, which can't simply be added added - # to ints. - # - # This code is considered somewhat unstable since it relies on - # some of Tk's inner workings. However its effect is merely - # cosmetic; failure will only cause the CodeContext text to be - # somewhat misaligned with the text in the main Text widget. - # - # To avoid possible errors, all references to the inner workings - # of Tk are executed inside try/except blocks. - - widgets_for_width_calc = self.editwin.text, self.editwin.text_frame - - # calculate the required vertical padding + # values may be pixel objects, which can't simply be added to ints. + widgets = self.editwin.text, self.editwin.text_frame + # Calculate the required vertical padding padx = 0 - for widget in widgets_for_width_calc: - try: - # retrieve the "padx" attribte from widget's pack info - padx += int(str( widget.pack_info()['padx'] )) - except: - pass - try: - # retrieve the widget's "padx" attribte - padx += int(str( widget.cget('padx') )) - except: - pass - - # calculate the required border width - border_width = 0 - for widget in widgets_for_width_calc: - try: - # retrieve the widget's "border" attribte - border_width += int(str( widget.cget('border') )) - except: - pass - + for widget in widgets: + padx += int(str( widget.pack_info()['padx'] )) + padx += int(str( widget.cget('padx') )) + # Calculate the required border width + border = 0 + for widget in widgets: + border += int(str( widget.cget('border') )) self.label = Tkinter.Label(self.editwin.top, text="\n" * (self.context_depth - 1), - anchor="w", justify="left", + anchor=W, justify=LEFT, font=self.textfont, bg=self.bgcolor, fg=self.fgcolor, width=1, #don't request more than we get - padx=padx, #line up with text widget - border=border_width, #match border width - relief="sunken", - ) - - # CodeContext's label widget is packed before and above the - # text_frame widget, thus ensuring that it will appear directly - # above it. - self.label.pack(side="top", fill="x", expand=False, + padx=padx, border=border, + relief=SUNKEN) + # Pack the label widget before and above the text_frame widget, + # thus ensuring that it will appear directly above text_frame + self.label.pack(side=TOP, fill=X, expand=False, before=self.editwin.text_frame) - else: self.label.destroy() self.label = None @@ -190,7 +157,6 @@ stopindent) self.info.extend(lines) self.topvisible = new_topvisible - # empty lines in context pane: context_strings = [""] * max(0, self.context_depth - len(self.info)) # followed by the context hint lines: Modified: python/branches/p3yk-noslice/Lib/idlelib/ColorDelegator.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/ColorDelegator.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/ColorDelegator.py Fri Feb 23 18:29:35 2007 @@ -72,7 +72,7 @@ "hit": idleConf.GetHighlight(theme, "hit"), } - if DEBUG: print 'tagdefs',self.tagdefs + if DEBUG: print('tagdefs',self.tagdefs) def insert(self, index, chars, tags=None): index = self.index(index) @@ -91,13 +91,13 @@ def notify_range(self, index1, index2=None): self.tag_add("TODO", index1, index2) if self.after_id: - if DEBUG: print "colorizing already scheduled" + if DEBUG: print("colorizing already scheduled") return if self.colorizing: self.stop_colorizing = True - if DEBUG: print "stop colorizing" + if DEBUG: print("stop colorizing") if self.allow_colorizing: - if DEBUG: print "schedule colorizing" + if DEBUG: print("schedule colorizing") self.after_id = self.after(1, self.recolorize) close_when_done = None # Window to be closed when done colorizing @@ -106,7 +106,7 @@ if self.after_id: after_id = self.after_id self.after_id = None - if DEBUG: print "cancel scheduled recolorizer" + if DEBUG: print("cancel scheduled recolorizer") self.after_cancel(after_id) self.allow_colorizing = False self.stop_colorizing = True @@ -120,42 +120,42 @@ if self.after_id: after_id = self.after_id self.after_id = None - if DEBUG: print "cancel scheduled recolorizer" + if DEBUG: print("cancel scheduled recolorizer") self.after_cancel(after_id) if self.allow_colorizing and self.colorizing: - if DEBUG: print "stop colorizing" + if DEBUG: print("stop colorizing") self.stop_colorizing = True self.allow_colorizing = not self.allow_colorizing if self.allow_colorizing and not self.colorizing: self.after_id = self.after(1, self.recolorize) if DEBUG: - print "auto colorizing turned",\ - self.allow_colorizing and "on" or "off" + print("auto colorizing turned",\ + self.allow_colorizing and "on" or "off") return "break" def recolorize(self): self.after_id = None if not self.delegate: - if DEBUG: print "no delegate" + if DEBUG: print("no delegate") return if not self.allow_colorizing: - if DEBUG: print "auto colorizing is off" + if DEBUG: print("auto colorizing is off") return if self.colorizing: - if DEBUG: print "already colorizing" + if DEBUG: print("already colorizing") return try: self.stop_colorizing = False self.colorizing = True - if DEBUG: print "colorizing..." + if DEBUG: print("colorizing...") t0 = time.clock() self.recolorize_main() t1 = time.clock() - if DEBUG: print "%.3f seconds" % (t1-t0) + if DEBUG: print("%.3f seconds" % (t1-t0)) finally: self.colorizing = False if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): - if DEBUG: print "reschedule colorizing" + if DEBUG: print("reschedule colorizing") self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done @@ -240,7 +240,7 @@ self.tag_add("TODO", next) self.update() if self.stop_colorizing: - if DEBUG: print "colorizing stopped" + if DEBUG: print("colorizing stopped") return def removecolors(self): Modified: python/branches/p3yk-noslice/Lib/idlelib/Delegator.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/Delegator.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/Delegator.py Fri Feb 23 18:29:35 2007 @@ -23,7 +23,7 @@ def cachereport(self): keys = self.__cache.keys() keys.sort() - print keys + print(keys) def setdelegate(self, delegate): self.resetcache() Modified: python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py Fri Feb 23 18:29:35 2007 @@ -819,7 +819,7 @@ def close(self): reply = self.maybesave() - if reply != "cancel": + if str(reply) != "cancel": self._close() return reply @@ -859,7 +859,7 @@ try: self.load_extension(name) except: - print "Failed to load extension", repr(name) + print("Failed to load extension", repr(name)) import traceback traceback.print_exc() @@ -870,7 +870,7 @@ try: mod = __import__(name, globals(), locals(), []) except ImportError: - print "\nFailed to import extension: ", name + print("\nFailed to import extension: ", name) return cls = getattr(mod, name) keydefs = idleConf.GetExtensionBindings(name) Modified: python/branches/p3yk-noslice/Lib/idlelib/FileList.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/FileList.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/FileList.py Fri Feb 23 18:29:35 2007 @@ -54,7 +54,7 @@ try: key = self.inversedict[edit] except KeyError: - print "Don't know this EditorWindow object. (close)" + print("Don't know this EditorWindow object. (close)") return if key: del self.dict[key] @@ -67,7 +67,7 @@ try: key = self.inversedict[edit] except KeyError: - print "Don't know this EditorWindow object. (rename)" + print("Don't know this EditorWindow object. (rename)") return filename = edit.io.filename if not filename: Modified: python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py Fri Feb 23 18:29:35 2007 @@ -77,13 +77,13 @@ list.sort() self.close() pat = self.engine.getpat() - print "Searching %r in %s ..." % (pat, path) + print("Searching %r in %s ..." % (pat, path)) hits = 0 for fn in list: try: f = open(fn) except IOError as msg: - print msg + print(msg) continue lineno = 0 while 1: @@ -102,16 +102,16 @@ s = "" else: s = "s" - print "Found", hits, "hit%s." % s - print "(Hint: right-click to open locations.)" + print("Found", hits, "hit%s." % s) + print("(Hint: right-click to open locations.)") else: - print "No hits." + print("No hits.") def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) except os.error as msg: - print msg + print(msg) return [] list = [] subdirs = [] Modified: python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py Fri Feb 23 18:29:35 2007 @@ -209,7 +209,7 @@ # gets set to "not modified" at every new prompt. try: interp = self.editwin.interp - except: + except AttributeError: interp = None if not self.filename and self.get_saved() and not interp: self.editwin.flist.open(filename, self.loadfile) Modified: python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py Fri Feb 23 18:29:35 2007 @@ -388,7 +388,7 @@ text.pack() def bindseq(seq, n=[0]): def handler(event): - print seq + print(seq) text.bind("<>"%n[0], handler) text.event_add("<>"%n[0], seq) n[0] += 1 Modified: python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt (original) +++ python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt Fri Feb 23 18:29:35 2007 @@ -3,6 +3,19 @@ *Release date: XX-XXX-200X* +- Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented; + mouse and cursor selection in ACWindow implemented; double Tab inserts + current selection and closes ACW (similar to double-click and Return); scroll + wheel now works in ACW. Added AutoComplete instructions to IDLE Help. + +- AutoCompleteWindow moved below input line, will move above if there + isn't enough space. Patch 1621265 Tal Einat + +- Calltips now 'handle' tuples in the argument list (display '' :) + Suggested solution by Christos Georgiou, Bug 791968. + +- Add 'raw' support to configHandler. Patch 1650174 Tal Einat. + - Avoid hang when encountering a duplicate in a completion list. Bug 1571112. - Patch #1362975: Rework CodeContext indentation algorithm to Modified: python/branches/p3yk-noslice/Lib/idlelib/Percolator.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/Percolator.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/Percolator.py Fri Feb 23 18:29:35 2007 @@ -58,10 +58,10 @@ self.name = name Delegator.__init__(self, None) def insert(self, *args): - print self.name, ": insert", args + print(self.name, ": insert", args) self.delegate.insert(*args) def delete(self, *args): - print self.name, ": delete", args + print(self.name, ": delete", args) self.delegate.delete(*args) root = Tk() root.wm_protocol("WM_DELETE_WINDOW", root.quit) Modified: python/branches/p3yk-noslice/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/PyShell.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/PyShell.py Fri Feb 23 18:29:35 2007 @@ -19,8 +19,8 @@ try: from Tkinter import * except ImportError: - print>>sys.__stderr__, "** IDLE can't import Tkinter. " \ - "Your Python may not be configured for Tk. **" + print("** IDLE can't import Tkinter. " \ + "Your Python may not be configured for Tk. **", file=sys.__stderr__) sys.exit(1) import tkMessageBox @@ -504,14 +504,14 @@ console = self.tkconsole.console if how == "OK": if what is not None: - print >>console, repr(what) + print(repr(what), file=console) elif how == "EXCEPTION": if self.tkconsole.getvar("<>"): self.remote_stack_viewer() elif how == "ERROR": errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n" - print >>sys.__stderr__, errmsg, what - print >>console, errmsg, what + print(errmsg, what, file=sys.__stderr__) + print(errmsg, what, file=console) # we received a response to the currently active seq number: try: self.tkconsole.endexecuting() @@ -576,8 +576,8 @@ except (OverflowError, SyntaxError): self.tkconsole.resetoutput() tkerr = self.tkconsole.stderr - print>>tkerr, '*** Error in script or command!\n' - print>>tkerr, 'Traceback (most recent call last):' + print('*** Error in script or command!\n', file=tkerr) + print('Traceback (most recent call last):', file=tkerr) InteractiveInterpreter.showsyntaxerror(self, filename) self.tkconsole.showprompt() else: @@ -706,35 +706,36 @@ debugger = self.debugger try: self.tkconsole.beginexecuting() - try: - if not debugger and self.rpcclt is not None: - self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", - (code,), {}) - elif debugger: - debugger.run(code, self.locals) - else: - exec(code, self.locals) - except SystemExit: - if not self.tkconsole.closing: - if tkMessageBox.askyesno( - "Exit?", - "Do you want to exit altogether?", - default="yes", - master=self.tkconsole.text): - raise - else: - self.showtraceback() - else: + if not debugger and self.rpcclt is not None: + self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", + (code,), {}) + elif debugger: + debugger.run(code, self.locals) + else: + exec(code, self.locals) + except SystemExit: + if not self.tkconsole.closing: + if tkMessageBox.askyesno( + "Exit?", + "Do you want to exit altogether?", + default="yes", + master=self.tkconsole.text): raise - except: - if use_subprocess: - # When run w/o subprocess, both user and IDLE errors - # are printed here; skip message in that case. - print >> self.tkconsole.stderr, \ - "IDLE internal error in runcode()" + else: + else: + raise + except: + if use_subprocess: + print("IDLE internal error in runcode()", + file=self.tkconsole.stderr) self.showtraceback() - if use_subprocess: - self.tkconsole.endexecuting() + self.tkconsole.endexecuting() + else: + if self.tkconsole.canceled: + self.tkconsole.canceled = False + print("KeyboardInterrupt", file=self.tkconsole.stderr) + else: + self.showtraceback() finally: if not use_subprocess: try: @@ -1224,7 +1225,6 @@ self.text.insert("end-1c", "\n") self.text.mark_set("iomark", "end-1c") self.set_line_and_column() - sys.stdout.softspace = 0 def write(self, s, tags=()): try: @@ -1243,7 +1243,6 @@ def __init__(self, shell, tags, encoding=None): self.shell = shell self.tags = tags - self.softspace = 0 self.encoding = encoding def write(self, s): @@ -1349,7 +1348,7 @@ if os.path.isfile(script): pass else: - print "No script file: ", script + print("No script file: ", script) sys.exit() enable_shell = True if o == '-s': Modified: python/branches/p3yk-noslice/Lib/idlelib/ScrolledList.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/ScrolledList.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/ScrolledList.py Fri Feb 23 18:29:35 2007 @@ -124,8 +124,8 @@ root.protocol("WM_DELETE_WINDOW", root.destroy) class MyScrolledList(ScrolledList): def fill_menu(self): self.menu.add_command(label="pass") - def on_select(self, index): print "select", self.get(index) - def on_double(self, index): print "double", self.get(index) + def on_select(self, index): print("select", self.get(index)) + def on_double(self, index): print("double", self.get(index)) s = MyScrolledList(root) for i in range(30): s.append("item %02d" % i) Modified: python/branches/p3yk-noslice/Lib/idlelib/UndoDelegator.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/UndoDelegator.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/UndoDelegator.py Fri Feb 23 18:29:35 2007 @@ -38,10 +38,10 @@ def dump_event(self, event): from pprint import pprint pprint(self.undolist[:self.pointer]) - print "pointer:", self.pointer, - print "saved:", self.saved, - print "can_merge:", self.can_merge, - print "get_saved():", self.get_saved() + print("pointer:", self.pointer, end=' ') + print("saved:", self.saved, end=' ') + print("can_merge:", self.can_merge, end=' ') + print("get_saved():", self.get_saved()) pprint(self.undolist[self.pointer:]) return "break" Modified: python/branches/p3yk-noslice/Lib/idlelib/WidgetRedirector.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/WidgetRedirector.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/WidgetRedirector.py Fri Feb 23 18:29:35 2007 @@ -83,7 +83,7 @@ redir = WidgetRedirector(text) global orig_insert def my_insert(*args): - print "insert", args + print("insert", args) orig_insert(*args) orig_insert = redir.register("insert", my_insert) root.mainloop() Modified: python/branches/p3yk-noslice/Lib/idlelib/WindowList.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/WindowList.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/WindowList.py Fri Feb 23 18:29:35 2007 @@ -46,7 +46,7 @@ callback() except: t, v, tb = sys.exc_info() - print "warning: callback failed in WindowList", t, ":", v + print("warning: callback failed in WindowList", t, ":", v) registry = WindowList() Modified: python/branches/p3yk-noslice/Lib/idlelib/configHandler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/configHandler.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/configHandler.py Fri Feb 23 18:29:35 2007 @@ -39,22 +39,19 @@ self.file=cfgFile ConfigParser.__init__(self,defaults=cfgDefaults) - def Get(self, section, option, type=None, default=None): + def Get(self, section, option, type=None, default=None, raw=False): """ Get an option value for given section/option or return default. If type is specified, return as type. """ + if not self.has_option(section, option): + return default if type=='bool': - getVal=self.getboolean + return self.getboolean(section, option) elif type=='int': - getVal=self.getint - else: - getVal=self.get - if self.has_option(section,option): - #return getVal(section, option, raw, vars, default) - return getVal(section, option) + return self.getint(section, option) else: - return default + return self.get(section, option, raw=raw) def GetOptionList(self,section): """ @@ -219,7 +216,7 @@ return userDir def GetOption(self, configType, section, option, default=None, type=None, - warn_on_default=True): + warn_on_default=True, raw=False): """ Get an option value for given config type and given general configuration section/option or return a default. If type is specified, @@ -233,9 +230,11 @@ """ if self.userCfg[configType].has_option(section,option): - return self.userCfg[configType].Get(section, option, type=type) + return self.userCfg[configType].Get(section, option, + type=type, raw=raw) elif self.defaultCfg[configType].has_option(section,option): - return self.defaultCfg[configType].Get(section, option, type=type) + return self.defaultCfg[configType].Get(section, option, + type=type, raw=raw) else: #returning default, print warning if warn_on_default: warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n' @@ -679,18 +678,18 @@ ### module test if __name__ == '__main__': def dumpCfg(cfg): - print '\n',cfg,'\n' + print('\n',cfg,'\n') for key in cfg.keys(): sections=cfg[key].sections() - print key - print sections + print(key) + print(sections) for section in sections: options=cfg[key].options(section) - print section - print options + print(section) + print(options) for option in options: - print option, '=', cfg[key].Get(section,option) + print(option, '=', cfg[key].Get(section,option)) dumpCfg(idleConf.defaultCfg) dumpCfg(idleConf.userCfg) - print idleConf.userCfg['main'].Get('Theme','name') + print(idleConf.userCfg['main'].Get('Theme','name')) #print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal') Modified: python/branches/p3yk-noslice/Lib/idlelib/configHelpSourceEdit.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/configHelpSourceEdit.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/configHelpSourceEdit.py Fri Feb 23 18:29:35 2007 @@ -164,6 +164,6 @@ def run(): keySeq = '' dlg = GetHelpSourceDialog(root, 'Get Help Source') - print dlg.result + print(dlg.result) Button(root,text='Dialog', command=run).pack() root.mainloop() Modified: python/branches/p3yk-noslice/Lib/idlelib/configSectionNameDialog.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/configSectionNameDialog.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/configSectionNameDialog.py Fri Feb 23 18:29:35 2007 @@ -92,6 +92,6 @@ keySeq='' dlg=GetCfgSectionNameDialog(root,'Get Name', 'The information here should need to be word wrapped. Test.') - print dlg.result + print(dlg.result) Button(root,text='Dialog',command=run).pack() root.mainloop() Modified: python/branches/p3yk-noslice/Lib/idlelib/help.txt ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/help.txt (original) +++ python/branches/p3yk-noslice/Lib/idlelib/help.txt Fri Feb 23 18:29:35 2007 @@ -44,6 +44,10 @@ Find in Files... -- Open a search dialog box for searching files Replace... -- Open a search-and-replace dialog box Go to Line -- Ask for a line number and show that line + Show Calltip -- Open a small window with function param hints + Show Completions -- Open a scroll window allowing selection keywords + and attributes. (see '*TIPS*', below) + Show Parens -- Highlight the surrounding parenthesis Expand Word -- Expand the word you have typed to match another word in the same buffer; repeat to get a different expansion @@ -91,6 +95,7 @@ Code Context -- Open a pane at the top of the edit window which shows the block context of the section of code which is scrolling off the top or the window. + (Not present in Shell window.) Windows Menu: @@ -138,8 +143,11 @@ Control-left/right Arrow moves by words in a strange but useful way. Home/End go to begin/end of line. Control-Home/End go to begin/end of file. - Some useful Emacs bindings (Control-a, Control-e, Control-k, etc.) - are inherited from Tcl/Tk. + Some useful Emacs bindings are inherited from Tcl/Tk: + Control-a beginning of line + Control-e end of line + Control-k kill line (but doesn't put it in clipboard) + Control-l center window around the insertion point Standard Windows bindings may work on that platform. Keybindings are selected in the Settings Dialog, look there. @@ -155,6 +163,52 @@ See also the indent/dedent region commands in the edit menu. +Completions: + + Completions are supplied for functions, classes, and attributes of + classes, both built-in and user-defined. Completions are also provided + for filenames. + + The AutoCompleteWindow (ACW) will open after a predefined delay + (default is two seconds) after a '.' or (in a string) an os.sep is + typed. If after one of those characters (plus zero or more other + characters) you type a Tab the ACW will open immediately if a possible + continuation is found. + + If there is only one possible completion for the characters entered, a + Tab will supply that completion without opening the ACW. + + 'Show Completions' will force open a completions window. In an empty + string, this will contain the files in the current directory. On a + blank line, it will contain the built-in and user-defined functions and + classes in the current name spaces, plus any modules imported. If some + characters have been entered, the ACW will attempt to be more specific. + + If string of characters is typed, the ACW selection will jump to the + entry most closely matching those characters. Entering a Tab will cause + the longest non-ambiguous match to be entered in the Edit window or + Shell. Two Tabs in a row will supply the current ACW selection, as + will Return or a double click. Cursor keys, Page Up/Down, mouse + selection, and the scrollwheel all operate on the ACW. + + 'Hidden' attributes can be accessed by typing the beginning of hidden + name after a '.'. e.g. '_'. This allows access to modules with + '__all__' set, or to class-private attributes. + + Completions and the 'Expand Word' facility can save a lot of typing! + + Completions are currently limited to those in the namespaces. Names in + an Edit window which are not via __main__ or sys.modules will not be + found. Run the module once with your imports to correct this + situation. Note that IDLE itself places quite a few modules in + sys.modules, so much can be found by default, e.g. the re module. + + If you don't like the ACW popping up unbidden, simply make the delay + longer or disable the extension. OTOH, you could make the delay zero. + + You could also switch off the CallTips extension. (We will be adding + a delay to the call tip window.) + Python Shell window: Control-c interrupts executing command. @@ -165,7 +219,7 @@ Alt-p retrieves previous command matching what you have typed. Alt-n retrieves next. - (These are Control-p, Control-n on the Mac) + (These are Control-p, Control-n on the Mac) Return while cursor is on a previous command retrieves that command. Expand word is also useful to reduce typing. @@ -196,7 +250,7 @@ be changed using the Settings dialog. Command line usage: - + Enter idle -h at the command prompt to get a usage message. Running without a subprocess: @@ -211,3 +265,18 @@ re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. + +Extensions: + + IDLE contains an extension facility. See the beginning of + config-extensions.def in the idlelib directory for further information. + The default extensions are currently: + + FormatParagraph + AutoExpand + ZoomHeight + ScriptBinding + CallTips + ParenMatch + AutoComplete + CodeContext Modified: python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py Fri Feb 23 18:29:35 2007 @@ -263,6 +263,6 @@ def run(): keySeq='' dlg=GetKeysDialog(root,'Get Keys','find-again',[]) - print dlg.result + print(dlg.result) Button(root,text='Dialog',command=run).pack() root.mainloop() Modified: python/branches/p3yk-noslice/Lib/idlelib/rpc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/rpc.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/rpc.py Fri Feb 23 18:29:35 2007 @@ -104,14 +104,14 @@ raise except: erf = sys.__stderr__ - print>>erf, '\n' + '-'*40 - print>>erf, 'Unhandled server exception!' - print>>erf, 'Thread: %s' % threading.currentThread().getName() - print>>erf, 'Client Address: ', client_address - print>>erf, 'Request: ', repr(request) + print('\n' + '-'*40, file=erf) + print('Unhandled server exception!', file=erf) + print('Thread: %s' % threading.currentThread().getName(), file=erf) + print('Client Address: ', client_address, file=erf) + print('Request: ', repr(request), file=erf) traceback.print_exc(file=erf) - print>>erf, '\n*** Unrecoverable, server exiting!' - print>>erf, '-'*40 + print('\n*** Unrecoverable, server exiting!', file=erf) + print('-'*40, file=erf) os._exit(0) #----------------- end class RPCServer -------------------- @@ -152,7 +152,7 @@ s = self.location + " " + str(threading.currentThread().getName()) for a in args: s = s + " " + str(a) - print>>sys.__stderr__, s + print(s, file=sys.__stderr__) def register(self, oid, object): self.objtable[oid] = object @@ -201,7 +201,7 @@ except: msg = "*** Internal Error: rpc.py:SocketIO.localcall()\n\n"\ " Object: %s \n Method: %s \n Args: %s\n" - print>>sys.__stderr__, msg % (oid, method, args) + print(msg % (oid, method, args), file=sys.__stderr__) traceback.print_exc(file=sys.__stderr__) return ("EXCEPTION", None) @@ -323,7 +323,7 @@ try: s = pickle.dumps(message) except pickle.PicklingError: - print >>sys.__stderr__, "Cannot pickle:", repr(message) + print("Cannot pickle:", repr(message), file=sys.__stderr__) raise s = struct.pack(" 0: @@ -379,10 +379,10 @@ try: message = pickle.loads(packet) except pickle.UnpicklingError: - print >>sys.__stderr__, "-----------------------" - print >>sys.__stderr__, "cannot unpickle packet:", repr(packet) + print("-----------------------", file=sys.__stderr__) + print("cannot unpickle packet:", repr(packet), file=sys.__stderr__) traceback.print_stack(file=sys.__stderr__) - print >>sys.__stderr__, "-----------------------" + print("-----------------------", file=sys.__stderr__) raise return message @@ -526,11 +526,11 @@ def accept(self): working_sock, address = self.listening_sock.accept() if self.debugging: - print>>sys.__stderr__, "****** Connection request from ", address + print("****** Connection request from ", address, file=sys.__stderr__) if address[0] == LOCALHOST: SocketIO.__init__(self, working_sock) else: - print>>sys.__stderr__, "** Invalid host: ", address + print("** Invalid host: ", address, file=sys.__stderr__) raise socket.error def get_remote_proxy(self, oid): Modified: python/branches/p3yk-noslice/Lib/idlelib/run.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/run.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/run.py Fri Feb 23 18:29:35 2007 @@ -115,11 +115,11 @@ server = MyRPCServer(address, MyHandler) break except socket.error as err: - print>>sys.__stderr__,"IDLE Subprocess: socket error: "\ - + err[1] + ", retrying...." + print("IDLE Subprocess: socket error: "\ + + err[1] + ", retrying....", file=sys.__stderr__) else: - print>>sys.__stderr__, "IDLE Subprocess: Connection to "\ - "IDLE GUI failed, exiting." + print("IDLE Subprocess: Connection to "\ + "IDLE GUI failed, exiting.", file=sys.__stderr__) show_socket_error(err, address) global exit_now exit_now = True @@ -149,14 +149,14 @@ typ, val, tb = excinfo = sys.exc_info() sys.last_type, sys.last_value, sys.last_traceback = excinfo tbe = traceback.extract_tb(tb) - print>>efile, '\nTraceback (most recent call last):' + print('\nTraceback (most recent call last):', file=efile) exclude = ("run.py", "rpc.py", "threading.py", "Queue.py", "RemoteDebugger.py", "bdb.py") cleanup_traceback(tbe, exclude) traceback.print_list(tbe, file=efile) lines = traceback.format_exception_only(typ, val) for line in lines: - print>>efile, line, + print(line, end=' ', file=efile) def cleanup_traceback(tb, exclude): "Remove excluded traces from beginning/end of tb; get cached lines" @@ -178,7 +178,7 @@ if len(tb) == 0: # exception was in IDLE internals, don't prune! tb[:] = orig_tb[:] - print>>sys.stderr, "** IDLE Internal Exception: " + print("** IDLE Internal Exception: ", file=sys.stderr) rpchandler = rpc.objecttable['exec'].rpchandler for i in range(len(tb)): fn, ln, nm, line = tb[i] @@ -190,12 +190,7 @@ tb[i] = fn, ln, nm, line def flush_stdout(): - try: - if sys.stdout.softspace: - sys.stdout.softspace = 0 - sys.stdout.write("\n") - except (AttributeError, EOFError): - pass + """XXX How to do this now?""" def exit(): """Exit subprocess, possibly after first deleting sys.exitfunc @@ -227,14 +222,14 @@ thread.interrupt_main() except: erf = sys.__stderr__ - print>>erf, '\n' + '-'*40 - print>>erf, 'Unhandled server exception!' - print>>erf, 'Thread: %s' % threading.currentThread().getName() - print>>erf, 'Client Address: ', client_address - print>>erf, 'Request: ', repr(request) + print('\n' + '-'*40, file=erf) + print('Unhandled server exception!', file=erf) + print('Thread: %s' % threading.currentThread().getName(), file=erf) + print('Client Address: ', client_address, file=erf) + print('Request: ', repr(request), file=erf) traceback.print_exc(file=erf) - print>>erf, '\n*** Unrecoverable, server exiting!' - print>>erf, '-'*40 + print('\n*** Unrecoverable, server exiting!', file=erf) + print('-'*40, file=erf) quitting = True thread.interrupt_main() Modified: python/branches/p3yk-noslice/Lib/ihooks.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ihooks.py (original) +++ python/branches/p3yk-noslice/Lib/ihooks.py Fri Feb 23 18:29:35 2007 @@ -87,9 +87,9 @@ def message(self, format, *args): if args: - print format%args + print(format%args) else: - print format + print(format) class BasicModuleLoader(_Verbose): Modified: python/branches/p3yk-noslice/Lib/imaplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/imaplib.py (original) +++ python/branches/p3yk-noslice/Lib/imaplib.py Fri Feb 23 18:29:35 2007 @@ -1485,15 +1485,15 @@ run('uid', ('FETCH', '%s' % uid[-1], '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)')) - print '\nAll tests OK.' + print('\nAll tests OK.') except: - print '\nTests failed.' + print('\nTests failed.') if not Debug: - print ''' + print(''' If you would like to see debugging output, try: %s -d5 -''' % sys.argv[0] +''' % sys.argv[0]) raise Modified: python/branches/p3yk-noslice/Lib/imghdr.py ============================================================================== --- python/branches/p3yk-noslice/Lib/imghdr.py (original) +++ python/branches/p3yk-noslice/Lib/imghdr.py Fri Feb 23 18:29:35 2007 @@ -144,18 +144,18 @@ import os for filename in list: if os.path.isdir(filename): - print filename + '/:', + print(filename + '/:', end=' ') if recursive or toplevel: - print 'recursing down:' + print('recursing down:') import glob names = glob.glob(os.path.join(filename, '*')) testall(names, recursive, 0) else: - print '*** directory (use -r) ***' + print('*** directory (use -r) ***') else: - print filename + ':', + print(filename + ':', end=' ') sys.stdout.flush() try: - print what(filename) + print(what(filename)) except IOError: - print '*** not found ***' + print('*** not found ***') Modified: python/branches/p3yk-noslice/Lib/imputil.py ============================================================================== --- python/branches/p3yk-noslice/Lib/imputil.py (original) +++ python/branches/p3yk-noslice/Lib/imputil.py Fri Feb 23 18:29:35 2007 @@ -500,7 +500,7 @@ s = _os_stat(pathname) except OSError: return None - return long(s.st_mtime) + return int(s.st_mtime) ###################################################################### @@ -552,6 +552,10 @@ # This method is only used when we look for a module within a package. assert parent + for submodule_path in parent.__path__: + code = self._import_pathname(_os_path_join(submodule_path, modname), fqname) + if code is not None: + return code return self._import_pathname(_os_path_join(parent.__pkgdir__, modname), fqname) @@ -583,7 +587,7 @@ def py_suffix_importer(filename, finfo, fqname): file = filename[:-3] + _suffix - t_py = long(finfo[8]) + t_py = int(finfo[8]) t_pyc = _timestamp(file) code = None @@ -618,9 +622,9 @@ items.sort() for name, module in items: if module: - print name, module.__dict__.get('__importer__', '-- no importer') + print(name, module.__dict__.get('__importer__', '-- no importer')) else: - print name, '-- non-existent module' + print(name, '-- non-existent module') def _test_revamp(): ImportManager().install() Modified: python/branches/p3yk-noslice/Lib/lib-tk/Dialog.py ============================================================================== --- python/branches/p3yk-noslice/Lib/lib-tk/Dialog.py (original) +++ python/branches/p3yk-noslice/Lib/lib-tk/Dialog.py Fri Feb 23 18:29:35 2007 @@ -36,7 +36,7 @@ 'strings': ('Save File', 'Discard Changes', 'Return to Editor')}) - print d.num + print(d.num) if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/lib-tk/FileDialog.py ============================================================================== --- python/branches/p3yk-noslice/Lib/lib-tk/FileDialog.py (original) +++ python/branches/p3yk-noslice/Lib/lib-tk/FileDialog.py Fri Feb 23 18:29:35 2007 @@ -267,7 +267,7 @@ loadfile = fd.go(key="test") fd = SaveFileDialog(root) savefile = fd.go(key="test") - print loadfile, savefile + print(loadfile, savefile) if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/lib-tk/SimpleDialog.py ============================================================================== --- python/branches/p3yk-noslice/Lib/lib-tk/SimpleDialog.py (original) +++ python/branches/p3yk-noslice/Lib/lib-tk/SimpleDialog.py Fri Feb 23 18:29:35 2007 @@ -102,7 +102,7 @@ default=0, cancel=2, title="Test Dialog") - print d.go() + print(d.go()) t = Button(root, text='Test', command=doit) t.pack() q = Button(root, text='Quit', command=t.quit) Modified: python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py ============================================================================== --- python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py (original) +++ python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py Fri Feb 23 18:29:35 2007 @@ -86,7 +86,7 @@ try: cnf.update(c) except (AttributeError, TypeError) as msg: - print "_cnfmerge: fallback due to:", msg + print("_cnfmerge: fallback due to:", msg) for k, v in c.items(): cnf[k] = v return cnf Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkColorChooser.py ============================================================================== --- python/branches/p3yk-noslice/Lib/lib-tk/tkColorChooser.py (original) +++ python/branches/p3yk-noslice/Lib/lib-tk/tkColorChooser.py Fri Feb 23 18:29:35 2007 @@ -67,4 +67,4 @@ if __name__ == "__main__": - print "color", askcolor() + print("color", askcolor()) Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkFileDialog.py ============================================================================== --- python/branches/p3yk-noslice/Lib/lib-tk/tkFileDialog.py (original) +++ python/branches/p3yk-noslice/Lib/lib-tk/tkFileDialog.py Fri Feb 23 18:29:35 2007 @@ -204,12 +204,12 @@ fp=open(openfilename,"r") fp.close() except: - print "Could not open File: " - print sys.exc_info()[1] + print("Could not open File: ") + print(sys.exc_info()[1]) - print "open", openfilename.encode(enc) + print("open", openfilename.encode(enc)) # dialog for saving files saveasfilename=asksaveasfilename() - print "saveas", saveasfilename.encode(enc) + print("saveas", saveasfilename.encode(enc)) Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkFont.py ============================================================================== --- python/branches/p3yk-noslice/Lib/lib-tk/tkFont.py (original) +++ python/branches/p3yk-noslice/Lib/lib-tk/tkFont.py Fri Feb 23 18:29:35 2007 @@ -185,22 +185,22 @@ # create a font f = Font(family="times", size=30, weight=NORMAL) - print f.actual() - print f.actual("family") - print f.actual("weight") + print(f.actual()) + print(f.actual("family")) + print(f.actual("weight")) - print f.config() - print f.cget("family") - print f.cget("weight") + print(f.config()) + print(f.cget("family")) + print(f.cget("weight")) - print names() + print(names()) - print f.measure("hello"), f.metrics("linespace") + print(f.measure("hello"), f.metrics("linespace")) - print f.metrics() + print(f.metrics()) f = Font(font=("Courier", 20, "bold")) - print f.measure("hello"), f.metrics("linespace") + print(f.measure("hello"), f.metrics("linespace")) w = Tkinter.Label(root, text="Hello, world", font=f) w.pack() Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkMessageBox.py ============================================================================== --- python/branches/p3yk-noslice/Lib/lib-tk/tkMessageBox.py (original) +++ python/branches/p3yk-noslice/Lib/lib-tk/tkMessageBox.py Fri Feb 23 18:29:35 2007 @@ -122,11 +122,11 @@ if __name__ == "__main__": - print "info", showinfo("Spam", "Egg Information") - print "warning", showwarning("Spam", "Egg Warning") - print "error", showerror("Spam", "Egg Alert") - print "question", askquestion("Spam", "Question?") - print "proceed", askokcancel("Spam", "Proceed?") - print "yes/no", askyesno("Spam", "Got it?") - print "yes/no/cancel", askyesnocancel("Spam", "Want it?") - print "try again", askretrycancel("Spam", "Try again?") + print("info", showinfo("Spam", "Egg Information")) + print("warning", showwarning("Spam", "Egg Warning")) + print("error", showerror("Spam", "Egg Alert")) + print("question", askquestion("Spam", "Question?")) + print("proceed", askokcancel("Spam", "Proceed?")) + print("yes/no", askyesno("Spam", "Got it?")) + print("yes/no/cancel", askyesnocancel("Spam", "Want it?")) + print("try again", askretrycancel("Spam", "Try again?")) Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkSimpleDialog.py ============================================================================== --- python/branches/p3yk-noslice/Lib/lib-tk/tkSimpleDialog.py (original) +++ python/branches/p3yk-noslice/Lib/lib-tk/tkSimpleDialog.py Fri Feb 23 18:29:35 2007 @@ -50,9 +50,9 @@ # If the master is not viewable, don't # make the child transient, or else it # would be opened withdrawn - if parent.winfo_viewable(): + if parent.winfo_viewable(): self.transient(parent) - + if title: self.title(title) @@ -315,6 +315,6 @@ root = Tk() root.update() - print askinteger("Spam", "Egg count", initialvalue=12*12) - print askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100) - print askstring("Spam", "Egg label") + print(askinteger("Spam", "Egg count", initialvalue=12*12)) + print(askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100)) + print(askstring("Spam", "Egg label")) Modified: python/branches/p3yk-noslice/Lib/locale.py ============================================================================== --- python/branches/p3yk-noslice/Lib/locale.py (original) +++ python/branches/p3yk-noslice/Lib/locale.py Fri Feb 23 18:29:35 2007 @@ -262,10 +262,10 @@ setlocale(LC_ALL, "") #do grouping s1 = format("%d", 123456789,1) - print s1, "is", atoi(s1) + print(s1, "is", atoi(s1)) #standard formatting s1 = str(3.14) - print s1, "is", atof(s1) + print(s1, "is", atof(s1)) ### Locale name aliasing engine @@ -1499,49 +1499,49 @@ _init_categories() del categories['LC_ALL'] - print 'Locale defaults as determined by getdefaultlocale():' - print '-'*72 + print('Locale defaults as determined by getdefaultlocale():') + print('-'*72) lang, enc = getdefaultlocale() - print 'Language: ', lang or '(undefined)' - print 'Encoding: ', enc or '(undefined)' - print + print('Language: ', lang or '(undefined)') + print('Encoding: ', enc or '(undefined)') + print() - print 'Locale settings on startup:' - print '-'*72 + print('Locale settings on startup:') + print('-'*72) for name,category in categories.items(): - print name, '...' + print(name, '...') lang, enc = getlocale(category) - print ' Language: ', lang or '(undefined)' - print ' Encoding: ', enc or '(undefined)' - print - - print - print 'Locale settings after calling resetlocale():' - print '-'*72 + print(' Language: ', lang or '(undefined)') + print(' Encoding: ', enc or '(undefined)') + print() + + print() + print('Locale settings after calling resetlocale():') + print('-'*72) resetlocale() for name,category in categories.items(): - print name, '...' + print(name, '...') lang, enc = getlocale(category) - print ' Language: ', lang or '(undefined)' - print ' Encoding: ', enc or '(undefined)' - print + print(' Language: ', lang or '(undefined)') + print(' Encoding: ', enc or '(undefined)') + print() try: setlocale(LC_ALL, "") except: - print 'NOTE:' - print 'setlocale(LC_ALL, "") does not support the default locale' - print 'given in the OS environment variables.' + print('NOTE:') + print('setlocale(LC_ALL, "") does not support the default locale') + print('given in the OS environment variables.') else: - print - print 'Locale settings after calling setlocale(LC_ALL, ""):' - print '-'*72 + print() + print('Locale settings after calling setlocale(LC_ALL, ""):') + print('-'*72) for name,category in categories.items(): - print name, '...' + print(name, '...') lang, enc = getlocale(category) - print ' Language: ', lang or '(undefined)' - print ' Encoding: ', enc or '(undefined)' - print + print(' Language: ', lang or '(undefined)') + print(' Encoding: ', enc or '(undefined)') + print() ### @@ -1553,10 +1553,10 @@ __all__.append("LC_MESSAGES") if __name__=='__main__': - print 'Locale aliasing:' - print + print('Locale aliasing:') + print() _print_locale() - print - print 'Number formatting:' - print + print() + print('Number formatting:') + print() _test() Modified: python/branches/p3yk-noslice/Lib/logging/__init__.py ============================================================================== --- python/branches/p3yk-noslice/Lib/logging/__init__.py (original) +++ python/branches/p3yk-noslice/Lib/logging/__init__.py Fri Feb 23 18:29:35 2007 @@ -1,4 +1,4 @@ -# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, @@ -21,7 +21,7 @@ Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. -Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.5.0.0" -__date__ = "08 January 2007" +__version__ = "0.5.0.2" +__date__ = "16 February 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -68,7 +68,7 @@ except: return sys.exc_traceback.tb_frame.f_back -if hasattr(sys, '_getframe'): currentframe = sys._getframe +if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) # done filching # _srcfile is only used in conjunction with sys._getframe(). @@ -251,7 +251,7 @@ self.lineno = lineno self.funcName = func self.created = ct - self.msecs = (ct - long(ct)) * 1000 + self.msecs = (ct - int(ct)) * 1000 self.relativeCreated = (self.created - _startTime) * 1000 if logThreads and thread: self.thread = thread.get_ident() @@ -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-noslice/Lib/logging/config.py ============================================================================== --- python/branches/p3yk-noslice/Lib/logging/config.py (original) +++ python/branches/p3yk-noslice/Lib/logging/config.py Fri Feb 23 18:29:35 2007 @@ -202,7 +202,7 @@ #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. - existing = root.manager.loggerDict.keys() + existing = list(root.manager.loggerDict.keys()) #now set up the new ones... for log in llist: sectname = "logger_%s" % log Modified: python/branches/p3yk-noslice/Lib/logging/handlers.py ============================================================================== --- python/branches/p3yk-noslice/Lib/logging/handlers.py (original) +++ python/branches/p3yk-noslice/Lib/logging/handlers.py Fri Feb 23 18:29:35 2007 @@ -1,4 +1,4 @@ -# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, @@ -22,7 +22,7 @@ Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. -Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ @@ -32,6 +32,7 @@ import cPickle as pickle except ImportError: import pickle +from stat import ST_DEV, ST_INO try: import codecs @@ -134,10 +135,8 @@ os.remove(dfn) os.rename(self.baseFilename, dfn) #print "%s -> %s" % (self.baseFilename, dfn) - if self.encoding: - self.stream = codecs.open(self.baseFilename, 'w', self.encoding) - else: - self.stream = open(self.baseFilename, 'w') + self.mode = 'w' + self.stream = self._open() def shouldRollover(self, record): """ @@ -280,12 +279,58 @@ s.sort() os.remove(s[0]) #print "%s -> %s" % (self.baseFilename, dfn) - if self.encoding: - self.stream = codecs.open(self.baseFilename, 'w', self.encoding) - else: - self.stream = open(self.baseFilename, 'w') + self.mode = 'w' + self.stream = self._open() 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 @@ -737,7 +782,7 @@ try: import smtplib try: - from email.Utils import formatdate + from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport @@ -789,8 +834,8 @@ logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, } except ImportError: - print "The Python Win32 extensions for NT (service, event "\ - "logging) appear not to be available." + print("The Python Win32 extensions for NT (service, event "\ + "logging) appear not to be available.") self._welu = None def getMessageID(self, record): Modified: python/branches/p3yk-noslice/Lib/macurl2path.py ============================================================================== --- python/branches/p3yk-noslice/Lib/macurl2path.py (original) +++ python/branches/p3yk-noslice/Lib/macurl2path.py Fri Feb 23 18:29:35 2007 @@ -82,7 +82,7 @@ "/foo/bar/index.html", "/foo/bar/", "/"]: - print '%r -> %r' % (url, url2pathname(url)) + print('%r -> %r' % (url, url2pathname(url))) for path in ["drive:", "drive:dir:", "drive:dir:file", @@ -91,7 +91,7 @@ ":file", ":dir:", ":dir:file"]: - print '%r -> %r' % (path, pathname2url(path)) + print('%r -> %r' % (path, pathname2url(path))) if __name__ == '__main__': test() Modified: python/branches/p3yk-noslice/Lib/mailbox.py ============================================================================== --- python/branches/p3yk-noslice/Lib/mailbox.py (original) +++ python/branches/p3yk-noslice/Lib/mailbox.py Fri Feb 23 18:29:35 2007 @@ -16,8 +16,8 @@ import errno import copy import email -import email.Message -import email.Generator +import email.message +import email.generator import rfc822 import StringIO try: @@ -99,7 +99,7 @@ def itervalues(self): """Return an iterator over all messages.""" - for key in self.iterkeys(): + for key in self.keys(): try: value = self[key] except KeyError: @@ -107,7 +107,7 @@ yield value def __iter__(self): - return self.itervalues() + return self.values() def values(self): """Return a list of messages. Memory intensive.""" @@ -115,7 +115,7 @@ def iteritems(self): """Return an iterator over (key, message) tuples.""" - for key in self.iterkeys(): + for key in self.keys(): try: value = self[key] except KeyError: @@ -136,7 +136,7 @@ def clear(self): """Delete all messages.""" - for key in self.iterkeys(): + for key in self.keys(): self.discard(key) def pop(self, key, default=None): @@ -150,7 +150,7 @@ def popitem(self): """Delete an arbitrary (key, message) pair and return it.""" - for key in self.iterkeys(): + for key in self.keys(): return (key, self.pop(key)) # This is only run once. else: raise KeyError('No messages in mailbox') @@ -158,7 +158,7 @@ def update(self, arg=None): """Change the messages that correspond to certain keys.""" if hasattr(arg, 'iteritems'): - source = arg.iteritems() + source = arg.items() elif hasattr(arg, 'items'): source = arg.items() else: @@ -193,9 +193,9 @@ # To get native line endings on disk, the user-friendly \n line endings # used in strings and by email.Message are translated here. """Dump message contents to target file.""" - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): buffer = StringIO.StringIO() - gen = email.Generator.Generator(buffer, mangle_from_, 0) + gen = email.generator.Generator(buffer, mangle_from_, 0) gen.flatten(message) buffer.seek(0) target.write(buffer.read().replace('\n', os.linesep)) @@ -477,7 +477,7 @@ def next(self): """Return the next message in a one-time iteration.""" if not hasattr(self, '_onetime_keys'): - self._onetime_keys = self.iterkeys() + self._onetime_keys = iter(self.keys()) while True: try: return self[self._onetime_keys.next()] @@ -569,7 +569,7 @@ # 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) @@ -578,7 +578,7 @@ 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 = {} @@ -704,7 +704,7 @@ message = '' elif isinstance(message, _mboxMMDFMessage): from_line = 'From ' + message.get_from() - elif isinstance(message, email.Message.Message): + elif isinstance(message, email.message.Message): from_line = message.get_unixfrom() # May be None. if from_line is None: from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime()) @@ -950,7 +950,7 @@ def __len__(self): """Return a count of messages in the mailbox.""" - return len(list(self.iterkeys())) + return len(list(self.keys())) def lock(self): """Lock the mailbox.""" @@ -1038,7 +1038,7 @@ f = open(os.path.join(self._path, '.mh_sequences'), 'r+') try: os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC)) - for name, keys in sequences.iteritems(): + for name, keys in sequences.items(): if len(keys) == 0: continue f.write('%s:' % name) @@ -1067,7 +1067,7 @@ sequences = self.get_sequences() prev = 0 changes = [] - for key in self.iterkeys(): + for key in self.keys(): if key - 1 != prev: changes.append((key, prev + 1)) if hasattr(os, 'link'): @@ -1091,7 +1091,7 @@ """Inspect a new MHMessage and update sequences appropriately.""" pending_sequences = message.get_sequences() all_sequences = self.get_sequences() - for name, key_list in all_sequences.iteritems(): + for name, key_list in all_sequences.items(): if name in pending_sequences: key_list.append(key) elif key in key_list: @@ -1219,7 +1219,7 @@ 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' % @@ -1254,9 +1254,9 @@ self._file.write(os.linesep) else: self._file.write('1,,' + os.linesep) - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): orig_buffer = StringIO.StringIO() - orig_generator = email.Generator.Generator(orig_buffer, False, 0) + orig_generator = email.generator.Generator(orig_buffer, False, 0) orig_generator.flatten(message) orig_buffer.seek(0) while True: @@ -1267,7 +1267,7 @@ self._file.write('*** EOOH ***' + os.linesep) if isinstance(message, BabylMessage): vis_buffer = StringIO.StringIO() - vis_generator = email.Generator.Generator(vis_buffer, False, 0) + vis_generator = email.generator.Generator(vis_buffer, False, 0) vis_generator.flatten(message.get_visible()) while True: line = vis_buffer.readline() @@ -1323,12 +1323,12 @@ return (start, stop) -class Message(email.Message.Message): +class Message(email.message.Message): """Message with mailbox-format-specific properties.""" def __init__(self, message=None): """Initialize a Message instance.""" - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): self._become_message(copy.deepcopy(message)) if isinstance(message, Message): message._explain_to(self) @@ -1337,7 +1337,7 @@ elif hasattr(message, "read"): self._become_message(email.message_from_file(message)) elif message is None: - email.Message.Message.__init__(self) + email.message.Message.__init__(self) else: raise TypeError('Invalid message type: %s' % type(message)) @@ -1468,7 +1468,7 @@ def __init__(self, message=None): """Initialize an mboxMMDFMessage instance.""" self.set_from('MAILER-DAEMON', True) - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): unixfrom = message.get_unixfrom() if unixfrom is not None and unixfrom.startswith('From '): self.set_from(unixfrom[5:]) @@ -1990,10 +1990,12 @@ # that the two characters preceding "From " are \n\n or the beginning of # the file. Fixing this would require a more extensive rewrite than is # necessary. For convenience, we've added a PortableUnixMailbox class - # which uses the more lenient _fromlinepattern regular expression. + # which does no checking of the format of the 'From' line. - _fromlinepattern = r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" \ - r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*$" + _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" + r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*" + r"[^\s]*\s*" + "$") _regexp = None def _strict_isrealfromline(self, line): @@ -2043,7 +2045,7 @@ # list = map(long, filter(pat.match, os.listdir(self.dirname))) list = os.listdir(self.dirname) list = filter(pat.match, list) - list = map(long, list) + list = map(int, list) list.sort() # This only works in Python 1.6 or later; # before that str() added 'L': Modified: python/branches/p3yk-noslice/Lib/mailcap.py ============================================================================== --- python/branches/p3yk-noslice/Lib/mailcap.py (original) +++ python/branches/p3yk-noslice/Lib/mailcap.py Fri Feb 23 18:29:35 2007 @@ -24,7 +24,7 @@ continue morecaps = readmailcapfile(fp) fp.close() - for key, value in morecaps.iteritems(): + for key, value in morecaps.items(): if not key in caps: caps[key] = value else: @@ -219,37 +219,37 @@ for i in range(1, len(sys.argv), 2): args = sys.argv[i:i+2] if len(args) < 2: - print "usage: mailcap [MIMEtype file] ..." + print("usage: mailcap [MIMEtype file] ...") return MIMEtype = args[0] file = args[1] command, e = findmatch(caps, MIMEtype, 'view', file) if not command: - print "No viewer found for", type + print("No viewer found for", type) else: - print "Executing:", command + print("Executing:", command) sts = os.system(command) if sts: - print "Exit status:", sts + print("Exit status:", sts) def show(caps): - print "Mailcap files:" - for fn in listmailcapfiles(): print "\t" + fn - print + print("Mailcap files:") + for fn in listmailcapfiles(): print("\t" + fn) + print() if not caps: caps = getcaps() - print "Mailcap entries:" - print + print("Mailcap entries:") + print() ckeys = caps.keys() ckeys.sort() for type in ckeys: - print type + print(type) entries = caps[type] for e in entries: keys = e.keys() keys.sort() for k in keys: - print " %-15s" % k, e[k] - print + print(" %-15s" % k, e[k]) + print() if __name__ == '__main__': test() Modified: python/branches/p3yk-noslice/Lib/mhlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/mhlib.py (original) +++ python/branches/p3yk-noslice/Lib/mhlib.py Fri Feb 23 18:29:35 2007 @@ -314,7 +314,7 @@ """Write the set of sequences back to the folder.""" fullname = self.getsequencesfilename() f = None - for key, seq in sequences.iteritems(): + for key, seq in sequences.items(): s = IntSet('', ' ') s.fromlist(seq) if not f: f = open(fullname, 'w') @@ -959,7 +959,7 @@ global mh, f os.system('rm -rf $HOME/Mail/@test') mh = MH() - def do(s): print s; print eval(s) + def do(s): print(s); print(eval(s)) do('mh.listfolders()') do('mh.listallfolders()') testfolders = ['@test', '@test/test1', '@test/test2', @@ -974,7 +974,7 @@ do('f.getsequences()') seqs = f.getsequences() seqs['foo'] = IntSet('1-10 12-20', ' ').tolist() - print seqs + print(seqs) f.putsequences(seqs) do('f.getsequences()') for t in reversed(testfolders): do('mh.deletefolder(%r)' % (t,)) @@ -990,10 +990,10 @@ try: do('f.parsesequence(%r)' % (seq,)) except Error as msg: - print "Error:", msg + print("Error:", msg) stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read() list = map(int, stuff.split()) - print list, "<-- pick" + print(list, "<-- pick") do('f.listmessages()') Modified: python/branches/p3yk-noslice/Lib/mimetypes.py ============================================================================== --- python/branches/p3yk-noslice/Lib/mimetypes.py (original) +++ python/branches/p3yk-noslice/Lib/mimetypes.py Fri Feb 23 18:29:35 2007 @@ -503,8 +503,8 @@ """ def usage(code, msg=''): - print USAGE - if msg: print msg + print(USAGE) + if msg: print(msg) sys.exit(code) try: @@ -525,9 +525,9 @@ for gtype in args: if extension: guess = guess_extension(gtype, strict) - if not guess: print "I don't know anything about type", gtype - else: print guess + if not guess: print("I don't know anything about type", gtype) + else: print(guess) else: guess, encoding = guess_type(gtype, strict) - if not guess: print "I don't know anything about type", gtype - else: print 'type:', guess, 'encoding:', encoding + if not guess: print("I don't know anything about type", gtype) + else: print('type:', guess, 'encoding:', encoding) Modified: python/branches/p3yk-noslice/Lib/mimify.py ============================================================================== --- python/branches/p3yk-noslice/Lib/mimify.py (original) +++ python/branches/p3yk-noslice/Lib/mimify.py Fri Feb 23 18:29:35 2007 @@ -434,11 +434,11 @@ decode_base64 = 0 opts, args = getopt.getopt(sys.argv[1:], 'l:edb') if len(args) not in (0, 1, 2): - print usage + print(usage) sys.exit(1) if (('-e', '') in opts) == (('-d', '') in opts) or \ ((('-b', '') in opts) and (('-d', '') not in opts)): - print usage + print(usage) sys.exit(1) for o, a in opts: if o == '-e': @@ -449,7 +449,7 @@ try: MAXLEN = int(a) except (ValueError, OverflowError): - print usage + print(usage) sys.exit(1) elif o == '-b': decode_base64 = 1 Modified: python/branches/p3yk-noslice/Lib/modulefinder.py ============================================================================== --- python/branches/p3yk-noslice/Lib/modulefinder.py (original) +++ python/branches/p3yk-noslice/Lib/modulefinder.py Fri Feb 23 18:29:35 2007 @@ -89,11 +89,11 @@ def msg(self, level, str, *args): if level <= self.debug: for i in range(self.indent): - print " ", - print str, + print(" ", end=' ') + print(str, end=' ') for arg in args: - print repr(arg), - print + print(repr(arg), end=' ') + print() def msgin(self, *args): level = args[0] @@ -482,38 +482,38 @@ """Print a report to stdout, listing the found modules with their paths, as well as modules that are missing, or seem to be missing. """ - print - print " %-25s %s" % ("Name", "File") - print " %-25s %s" % ("----", "----") + print() + print(" %-25s %s" % ("Name", "File")) + print(" %-25s %s" % ("----", "----")) # Print modules found keys = self.modules.keys() keys.sort() for key in keys: m = self.modules[key] if m.__path__: - print "P", + print("P", end=' ') else: - print "m", - print "%-25s" % key, m.__file__ or "" + print("m", end=' ') + print("%-25s" % key, m.__file__ or "") # Print missing modules missing, maybe = self.any_missing_maybe() if missing: - print - print "Missing modules:" + print() + print("Missing modules:") for name in missing: mods = self.badmodules[name].keys() mods.sort() - print "?", name, "imported from", ', '.join(mods) + print("?", name, "imported from", ', '.join(mods)) # Print modules that may be missing, but then again, maybe not... if maybe: - print - print "Submodules thay appear to be missing, but could also be", - print "global names in the parent package:" + print() + print("Submodules thay appear to be missing, but could also be", end=' ') + print("global names in the parent package:") for name in maybe: mods = self.badmodules[name].keys() mods.sort() - print "?", name, "imported from", ', '.join(mods) + print("?", name, "imported from", ', '.join(mods)) def any_missing(self): """Return a list of modules that appear to be missing. Use @@ -603,7 +603,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") except getopt.error as msg: - print msg + print(msg) return # Process options @@ -634,9 +634,9 @@ path[0] = os.path.dirname(script) path = addpath + path if debug > 1: - print "path:" + print("path:") for item in path: - print " ", repr(item) + print(" ", repr(item)) # Create the module finder and turn its crank mf = ModuleFinder(path, debug, exclude) @@ -660,4 +660,4 @@ try: mf = test() except KeyboardInterrupt: - print "\n[interrupt]" + print("\n[interrupt]") Modified: python/branches/p3yk-noslice/Lib/msilib/__init__.py ============================================================================== --- python/branches/p3yk-noslice/Lib/msilib/__init__.py (original) +++ python/branches/p3yk-noslice/Lib/msilib/__init__.py Fri Feb 23 18:29:35 2007 @@ -40,7 +40,7 @@ index -= 1 unk = type & ~knownbits if unk: - print "%s.%s unknown bits %x" % (self.name, name, unk) + print("%s.%s unknown bits %x" % (self.name, name, unk)) size = type & datasizemask dtype = type & typemask if dtype == type_string: @@ -59,7 +59,7 @@ tname="OBJECT" else: tname="unknown" - print "%s.%sunknown integer type %d" % (self.name, name, size) + print("%s.%sunknown integer type %d" % (self.name, name, size)) if type & type_nullable: flags = "" else: @@ -99,7 +99,7 @@ assert len(value) == count, value for i in range(count): field = value[i] - if isinstance(field, (int, long)): + if isinstance(field, (int, int)): r.SetInteger(i+1,field) elif isinstance(field, basestring): r.SetString(i+1,field) Modified: python/branches/p3yk-noslice/Lib/netrc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/netrc.py (original) +++ python/branches/p3yk-noslice/Lib/netrc.py Fri Feb 23 18:29:35 2007 @@ -108,4 +108,4 @@ return rep if __name__ == '__main__': - print netrc() + print(netrc()) Modified: python/branches/p3yk-noslice/Lib/nntplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/nntplib.py (original) +++ python/branches/p3yk-noslice/Lib/nntplib.py Fri Feb 23 18:29:35 2007 @@ -5,7 +5,7 @@ >>> from nntplib import NNTP >>> s = NNTP('news') >>> resp, count, first, last, name = s.group('comp.lang.python') ->>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last +>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) Group comp.lang.python has 51 articles, range 5770 to 5821 >>> resp, subs = s.xhdr('subject', first + '-' + last) >>> resp = s.quit() @@ -175,7 +175,7 @@ If the response code is 200, posting is allowed; if it 201, posting is not allowed.""" - if self.debugging: print '*welcome*', repr(self.welcome) + if self.debugging: print('*welcome*', repr(self.welcome)) return self.welcome def set_debuglevel(self, level): @@ -190,12 +190,12 @@ def putline(self, line): """Internal: send one line to the server, appending CRLF.""" line = line + CRLF - if self.debugging > 1: print '*put*', repr(line) + if self.debugging > 1: print('*put*', repr(line)) self.sock.sendall(line) def putcmd(self, line): """Internal: send one command to the server (through putline()).""" - if self.debugging: print '*cmd*', repr(line) + if self.debugging: print('*cmd*', repr(line)) self.putline(line) def getline(self): @@ -203,7 +203,7 @@ Raise EOFError if the connection is closed.""" line = self.file.readline() if self.debugging > 1: - print '*get*', repr(line) + print('*get*', repr(line)) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] @@ -213,7 +213,7 @@ """Internal: get a response from the server. Raise various errors if the response indicates an error.""" resp = self.getline() - if self.debugging: print '*resp*', repr(resp) + if self.debugging: print('*resp*', repr(resp)) c = resp[:1] if c == '4': raise NNTPTemporaryError(resp) @@ -618,11 +618,11 @@ mode = None s = NNTP(newshost, readermode=mode) resp, count, first, last, name = s.group('comp.lang.python') - print resp - print 'Group', name, 'has', count, 'articles, range', first, 'to', last + print(resp) + print('Group', name, 'has', count, 'articles, range', first, 'to', last) resp, subs = s.xhdr('subject', first + '-' + last) - print resp + print(resp) for item in subs: - print "%7s %s" % item + print("%7s %s" % item) resp = s.quit() - print resp + print(resp) Modified: python/branches/p3yk-noslice/Lib/ntpath.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ntpath.py (original) +++ python/branches/p3yk-noslice/Lib/ntpath.py Fri Feb 23 18:29:35 2007 @@ -344,8 +344,10 @@ var = path[:index] if var in os.environ: res = res + os.environ[var] + else: + res = res + '${' + var + '}' except ValueError: - res = res + path + res = res + '${' + path index = pathlen - 1 else: var = '' @@ -357,8 +359,10 @@ c = path[index:index + 1] if var in os.environ: res = res + os.environ[var] + else: + res = res + '$' + var if c != '': - res = res + c + index = index - 1 else: res = res + c index = index + 1 Modified: python/branches/p3yk-noslice/Lib/opcode.py ============================================================================== --- python/branches/p3yk-noslice/Lib/opcode.py (original) +++ python/branches/p3yk-noslice/Lib/opcode.py Fri Feb 23 18:29:35 2007 @@ -86,10 +86,7 @@ def_op('GET_ITER', 68) def_op('PRINT_EXPR', 70) -def_op('PRINT_ITEM', 71) -def_op('PRINT_NEWLINE', 72) -def_op('PRINT_ITEM_TO', 73) -def_op('PRINT_NEWLINE_TO', 74) + def_op('INPLACE_LSHIFT', 75) def_op('INPLACE_RSHIFT', 76) def_op('INPLACE_AND', 77) Modified: python/branches/p3yk-noslice/Lib/optparse.py ============================================================================== --- python/branches/p3yk-noslice/Lib/optparse.py (original) +++ python/branches/p3yk-noslice/Lib/optparse.py Fri Feb 23 18:29:35 2007 @@ -407,7 +407,7 @@ return _parse_num(val, int) def _parse_long(val): - return _parse_num(val, long) + return _parse_num(val, int) _builtin_cvt = { "int" : (_parse_int, _("integer")), "long" : (_parse_long, _("long integer")), @@ -611,8 +611,7 @@ else: setattr(self, attr, None) if attrs: - attrs = attrs.keys() - attrs.sort() + attrs = sorted(attrs.keys()) raise OptionError( "invalid keyword arguments: %s" % ", ".join(attrs), self) @@ -1578,7 +1577,7 @@ or not defined. """ if self.usage: - print >>file, self.get_usage() + print(self.get_usage(), file=file) def get_version(self): if self.version: @@ -1595,7 +1594,7 @@ name. Does nothing if self.version is empty or undefined. """ if self.version: - print >>file, self.get_version() + print(self.get_version(), file=file) def format_option_help(self, formatter=None): if formatter is None: Modified: python/branches/p3yk-noslice/Lib/pdb.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pdb.py (original) +++ python/branches/p3yk-noslice/Lib/pdb.py Fri Feb 23 18:29:35 2007 @@ -135,7 +135,7 @@ if self._wait_for_mainpyfile: return if self.stop_here(frame): - print >>self.stdout, '--Call--' + print('--Call--', file=self.stdout) self.interaction(frame, None) def user_line(self, frame): @@ -171,7 +171,7 @@ def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" frame.f_locals['__return__'] = return_value - print >>self.stdout, '--Return--' + print('--Return--', file=self.stdout) self.interaction(frame, None) def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): @@ -181,7 +181,7 @@ if type(exc_type) == type(''): exc_type_name = exc_type else: exc_type_name = exc_type.__name__ - print >>self.stdout, exc_type_name + ':', _saferepr(exc_value) + print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout) self.interaction(frame, exc_traceback) # General interaction function @@ -204,7 +204,7 @@ if type(t) == type(''): exc_type_name = t else: exc_type_name = t.__name__ - print >>self.stdout, '***', exc_type_name + ':', v + print('***', exc_type_name + ':', v, file=self.stdout) def precmd(self, line): """Handle alias expansion and ';;' separator.""" @@ -283,7 +283,7 @@ try: bnum = int(arg) except: - print >>self.stdout, "Usage : commands [bnum]\n ...\n end" + print("Usage : commands [bnum]\n ...\n end", file=self.stdout) return self.commands_bnum = bnum self.commands[bnum] = [] @@ -300,7 +300,7 @@ # break [ ([filename:]lineno | function) [, "condition"] ] if not arg: if self.breaks: # There's at least one - print >>self.stdout, "Num Type Disp Enb Where" + print("Num Type Disp Enb Where", file=self.stdout) for bp in bdb.Breakpoint.bpbynumber: if bp: bp.bpprint(self.stdout) @@ -322,8 +322,8 @@ filename = arg[:colon].rstrip() f = self.lookupmodule(filename) if not f: - print >>self.stdout, '*** ', repr(filename), - print >>self.stdout, 'not found from sys.path' + print('*** ', repr(filename), end=' ', file=self.stdout) + print('not found from sys.path', file=self.stdout) return else: filename = f @@ -331,7 +331,7 @@ try: lineno = int(arg) except ValueError as msg: - print >>self.stdout, '*** Bad lineno:', arg + print('*** Bad lineno:', arg, file=self.stdout) return else: # no colon; can be lineno or function @@ -357,10 +357,10 @@ # last thing to try (ok, filename, ln) = self.lineinfo(arg) if not ok: - print >>self.stdout, '*** The specified object', - print >>self.stdout, repr(arg), - print >>self.stdout, 'is not a function' - print >>self.stdout, 'or was not found along sys.path.' + print('*** The specified object', end=' ', file=self.stdout) + print(repr(arg), end=' ', file=self.stdout) + print('is not a function', file=self.stdout) + print('or was not found along sys.path.', file=self.stdout) return funcname = ok # ok contains a function name lineno = int(ln) @@ -371,12 +371,12 @@ if line: # now set the break point err = self.set_break(filename, line, temporary, cond, funcname) - if err: print >>self.stdout, '***', err + if err: print('***', err, file=self.stdout) else: bp = self.get_breaks(filename, line)[-1] - print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number, + print("Breakpoint %d at %s:%d" % (bp.number, bp.file, - bp.line) + bp.line), file=self.stdout) # To be overridden in derived debuggers def defaultFile(self): @@ -432,13 +432,13 @@ """ line = linecache.getline(filename, lineno) if not line: - print >>self.stdout, 'End of file' + print('End of file', file=self.stdout) return 0 line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): - print >>self.stdout, '*** Blank or comment' + print('*** Blank or comment', file=self.stdout) return 0 return lineno @@ -448,11 +448,11 @@ try: i = int(i) except ValueError: - print >>self.stdout, 'Breakpoint index %r is not a number' % i + print('Breakpoint index %r is not a number' % i, file=self.stdout) continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): - print >>self.stdout, 'No breakpoint numbered', i + print('No breakpoint numbered', i, file=self.stdout) continue bp = bdb.Breakpoint.bpbynumber[i] @@ -465,11 +465,11 @@ try: i = int(i) except ValueError: - print >>self.stdout, 'Breakpoint index %r is not a number' % i + print('Breakpoint index %r is not a number' % i, file=self.stdout) continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): - print >>self.stdout, 'No breakpoint numbered', i + print('No breakpoint numbered', i, file=self.stdout) continue bp = bdb.Breakpoint.bpbynumber[i] @@ -479,7 +479,11 @@ def do_condition(self, arg): # arg is breakpoint number and condition args = arg.split(' ', 1) - bpnum = int(args[0].strip()) + try: + bpnum = int(args[0].strip()) + except ValueError: + # something went wrong + print('Breakpoint index %r is not a number' % args[0], file=self.stdout) try: cond = args[1] except: @@ -488,13 +492,17 @@ if bp: bp.cond = cond if not cond: - print >>self.stdout, 'Breakpoint', bpnum, - print >>self.stdout, 'is now unconditional.' + print('Breakpoint', bpnum, end=' ', file=self.stdout) + print('is now unconditional.', file=self.stdout) def do_ignore(self,arg): """arg is bp number followed by ignore count.""" args = arg.split() - bpnum = int(args[0].strip()) + try: + bpnum = int(args[0].strip()) + except ValueError: + # something went wrong + print('Breakpoint index %r is not a number' % args[0], file=self.stdout) try: count = int(args[1].strip()) except: @@ -508,10 +516,10 @@ reply = reply + '%d crossings' % count else: reply = reply + '1 crossing' - print >>self.stdout, reply + ' of breakpoint %d.' % bpnum + print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout) else: - print >>self.stdout, 'Will stop next time breakpoint', - print >>self.stdout, bpnum, 'is reached.' + print('Will stop next time breakpoint', end=' ', file=self.stdout) + print(bpnum, 'is reached.', file=self.stdout) def do_clear(self, arg): """Three possibilities, tried in this order: @@ -538,24 +546,24 @@ err = "Invalid line number (%s)" % arg else: err = self.clear_break(filename, lineno) - if err: print >>self.stdout, '***', err + if err: print('***', err, file=self.stdout) return numberlist = arg.split() for i in numberlist: try: i = int(i) except ValueError: - print >>self.stdout, 'Breakpoint index %r is not a number' % i + print('Breakpoint index %r is not a number' % i, file=self.stdout) continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): - print >>self.stdout, 'No breakpoint numbered', i + print('No breakpoint numbered', i, file=self.stdout) continue err = self.clear_bpbynumber(i) if err: - print >>self.stdout, '***', err + print('***', err, file=self.stdout) else: - print >>self.stdout, 'Deleted breakpoint', i + print('Deleted breakpoint', i, file=self.stdout) do_cl = do_clear # 'c' is already an abbreviation for 'continue' def do_where(self, arg): @@ -565,7 +573,7 @@ def do_up(self, arg): if self.curindex == 0: - print >>self.stdout, '*** Oldest frame' + print('*** Oldest frame', file=self.stdout) else: self.curindex = self.curindex - 1 self.curframe = self.stack[self.curindex][0] @@ -575,7 +583,7 @@ def do_down(self, arg): if self.curindex + 1 == len(self.stack): - print >>self.stdout, '*** Newest frame' + print('*** Newest frame', file=self.stdout) else: self.curindex = self.curindex + 1 self.curframe = self.stack[self.curindex][0] @@ -605,12 +613,12 @@ def do_jump(self, arg): if self.curindex + 1 != len(self.stack): - print >>self.stdout, "*** You can only jump within the bottom frame" + print("*** You can only jump within the bottom frame", file=self.stdout) return try: arg = int(arg) except ValueError: - print >>self.stdout, "*** The 'jump' command requires a line number." + print("*** The 'jump' command requires a line number.", file=self.stdout) else: try: # Do the jump, fix up our copy of the stack, and display the @@ -619,7 +627,7 @@ self.stack[self.curindex] = self.stack[self.curindex][0], arg self.print_stack_entry(self.stack[self.curindex]) except ValueError as e: - print >>self.stdout, '*** Jump failed:', e + print('*** Jump failed:', e, file=self.stdout) do_j = do_jump def do_debug(self, arg): @@ -628,9 +636,9 @@ locals = self.curframe.f_locals p = Pdb() p.prompt = "(%s) " % self.prompt.strip() - print >>self.stdout, "ENTERING RECURSIVE DEBUGGER" + print("ENTERING RECURSIVE DEBUGGER", file=self.stdout) sys.call_tracing(p.run, (arg, globals, locals)) - print >>self.stdout, "LEAVING RECURSIVE DEBUGGER" + print("LEAVING RECURSIVE DEBUGGER", file=self.stdout) sys.settrace(self.trace_dispatch) self.lastcmd = p.lastcmd @@ -643,7 +651,7 @@ do_exit = do_quit def do_EOF(self, arg): - print >>self.stdout + print(file=self.stdout) self._user_requested_quit = 1 self.set_quit() return 1 @@ -657,16 +665,16 @@ if co.co_flags & 8: n = n+1 for i in range(n): name = co.co_varnames[i] - print >>self.stdout, name, '=', - if name in dict: print >>self.stdout, dict[name] - else: print >>self.stdout, "*** undefined ***" + print(name, '=', end=' ', file=self.stdout) + if name in dict: print(dict[name], file=self.stdout) + else: print("*** undefined ***", file=self.stdout) do_a = do_args def do_retval(self, arg): if '__return__' in self.curframe.f_locals: - print >>self.stdout, self.curframe.f_locals['__return__'] + print(self.curframe.f_locals['__return__'], file=self.stdout) else: - print >>self.stdout, '*** Not yet returned!' + print('*** Not yet returned!', file=self.stdout) do_rv = do_retval def _getval(self, arg): @@ -678,12 +686,12 @@ if isinstance(t, str): exc_type_name = t else: exc_type_name = t.__name__ - print >>self.stdout, '***', exc_type_name + ':', repr(v) + print('***', exc_type_name + ':', repr(v), file=self.stdout) raise def do_p(self, arg): try: - print >>self.stdout, repr(self._getval(arg)) + print(repr(self._getval(arg)), file=self.stdout) except: pass @@ -709,7 +717,7 @@ else: first = max(1, int(x) - 5) except: - print >>self.stdout, '*** Error in argument:', repr(arg) + print('*** Error in argument:', repr(arg), file=self.stdout) return elif self.lineno is None: first = max(1, self.curframe.f_lineno - 5) @@ -723,7 +731,7 @@ for lineno in range(first, last+1): line = linecache.getline(filename, lineno) if not line: - print >>self.stdout, '[EOF]' + print('[EOF]', file=self.stdout) break else: s = repr(lineno).rjust(3) @@ -732,7 +740,7 @@ else: s = s + ' ' if lineno == self.curframe.f_lineno: s = s + '->' - print >>self.stdout, s + '\t' + line, + print(s + '\t' + line, end='', file=self.stdout) self.lineno = lineno except KeyboardInterrupt: pass @@ -747,23 +755,23 @@ if type(t) == type(''): exc_type_name = t else: exc_type_name = t.__name__ - print >>self.stdout, '***', exc_type_name + ':', repr(v) + print('***', exc_type_name + ':', repr(v), file=self.stdout) return code = None # Is it a function? try: code = value.func_code except: pass if code: - print >>self.stdout, 'Function', code.co_name + print('Function', code.co_name, file=self.stdout) return # Is it an instance method? try: code = value.im_func.func_code except: pass if code: - print >>self.stdout, 'Method', code.co_name + print('Method', code.co_name, file=self.stdout) return # None of the above... - print >>self.stdout, type(value) + print(type(value), file=self.stdout) def do_alias(self, arg): args = arg.split() @@ -771,10 +779,10 @@ keys = self.aliases.keys() keys.sort() for alias in keys: - print >>self.stdout, "%s = %s" % (alias, self.aliases[alias]) + print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout) return if args[0] in self.aliases and len(args) == 1: - print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]]) + print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout) else: self.aliases[args[0]] = ' '.join(args[1:]) @@ -806,11 +814,11 @@ def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix): frame, lineno = frame_lineno if frame is self.curframe: - print >>self.stdout, '>', + print('>', end=' ', file=self.stdout) else: - print >>self.stdout, ' ', - print >>self.stdout, self.format_stack_entry(frame_lineno, - prompt_prefix) + print(' ', end=' ', file=self.stdout) + print(self.format_stack_entry(frame_lineno, + prompt_prefix), file=self.stdout) # Help methods (derived from pdb.doc) @@ -819,20 +827,20 @@ self.help_h() def help_h(self): - print >>self.stdout, """h(elp) + print("""h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command "help pdb" pipes the full documentation file to the $PAGER -"help exec" gives help on the ! command""" +"help exec" gives help on the ! command""", file=self.stdout) def help_where(self): self.help_w() def help_w(self): - print >>self.stdout, """w(here) + print("""w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the "current frame", which determines the -context of most commands. 'bt' is an alias for this command.""" +context of most commands. 'bt' is an alias for this command.""", file=self.stdout) help_bt = help_w @@ -840,23 +848,23 @@ self.help_d() def help_d(self): - print >>self.stdout, """d(own) + print("""d(own) Move the current frame one level down in the stack trace -(to a newer frame).""" +(to a newer frame).""", file=self.stdout) def help_up(self): self.help_u() def help_u(self): - print >>self.stdout, """u(p) + print("""u(p) Move the current frame one level up in the stack trace -(to an older frame).""" +(to an older frame).""", file=self.stdout) def help_break(self): self.help_b() def help_b(self): - print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition] + print("""b(reak) ([file:]lineno | function) [, condition] With a line number argument, set a break there in the current file. With a function name, set a break at first executable line of that function. Without argument, list all breaks. If a second @@ -866,14 +874,14 @@ The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet). The file is searched for on sys.path; -the .py suffix may be omitted.""" +the .py suffix may be omitted.""", file=self.stdout) def help_clear(self): self.help_cl() def help_cl(self): - print >>self.stdout, "cl(ear) filename:lineno" - print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]] + print("cl(ear) filename:lineno", file=self.stdout) + print("""cl(ear) [bpnumber [bpnumber...]] With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, @@ -882,59 +890,59 @@ Note that the argument is different from previous versions of the debugger (in python distributions 1.5.1 and before) where a linenumber was used instead of either filename:lineno or -breakpoint numbers.""" +breakpoint numbers.""", file=self.stdout) def help_tbreak(self): - print >>self.stdout, """tbreak same arguments as break, but breakpoint is -removed when first hit.""" + print("""tbreak same arguments as break, but breakpoint is +removed when first hit.""", file=self.stdout) def help_enable(self): - print >>self.stdout, """enable bpnumber [bpnumber ...] + print("""enable bpnumber [bpnumber ...] Enables the breakpoints given as a space separated list of -bp numbers.""" +bp numbers.""", file=self.stdout) def help_disable(self): - print >>self.stdout, """disable bpnumber [bpnumber ...] + print("""disable bpnumber [bpnumber ...] Disables the breakpoints given as a space separated list of -bp numbers.""" +bp numbers.""", file=self.stdout) def help_ignore(self): - print >>self.stdout, """ignore bpnumber count + print("""ignore bpnumber count Sets the ignore count for the given breakpoint number. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates -to true.""" +to true.""", file=self.stdout) def help_condition(self): - print >>self.stdout, """condition bpnumber str_condition + print("""condition bpnumber str_condition str_condition is a string specifying an expression which must evaluate to true before the breakpoint is honored. If str_condition is absent, any existing condition is removed; -i.e., the breakpoint is made unconditional.""" +i.e., the breakpoint is made unconditional.""", file=self.stdout) def help_step(self): self.help_s() def help_s(self): - print >>self.stdout, """s(tep) + print("""s(tep) Execute the current line, stop at the first possible occasion -(either in a function that is called or in the current function).""" +(either in a function that is called or in the current function).""", file=self.stdout) def help_next(self): self.help_n() def help_n(self): - print >>self.stdout, """n(ext) + print("""n(ext) Continue execution until the next line in the current function -is reached or it returns.""" +is reached or it returns.""", file=self.stdout) def help_return(self): self.help_r() def help_r(self): - print >>self.stdout, """r(eturn) -Continue execution until the current function returns.""" + print("""r(eturn) +Continue execution until the current function returns.""", file=self.stdout) def help_continue(self): self.help_c() @@ -943,51 +951,51 @@ self.help_c() def help_c(self): - print >>self.stdout, """c(ont(inue)) -Continue execution, only stop when a breakpoint is encountered.""" + print("""c(ont(inue)) +Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout) def help_jump(self): self.help_j() def help_j(self): - print >>self.stdout, """j(ump) lineno -Set the next line that will be executed.""" + print("""j(ump) lineno +Set the next line that will be executed.""", file=self.stdout) def help_debug(self): - print >>self.stdout, """debug code + print("""debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed -in the current environment).""" +in the current environment).""", file=self.stdout) def help_list(self): self.help_l() def help_l(self): - print >>self.stdout, """l(ist) [first [,last]] + print("""l(ist) [first [,last]] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With one argument, list 11 lines starting at that line. With two arguments, list the given range; -if the second argument is less than the first, it is a count.""" +if the second argument is less than the first, it is a count.""", file=self.stdout) def help_args(self): self.help_a() def help_a(self): - print >>self.stdout, """a(rgs) -Print the arguments of the current function.""" + print("""a(rgs) +Print the arguments of the current function.""", file=self.stdout) def help_p(self): - print >>self.stdout, """p expression -Print the value of the expression.""" + print("""p expression +Print the value of the expression.""", file=self.stdout) def help_pp(self): - print >>self.stdout, """pp expression -Pretty-print the value of the expression.""" + print("""pp expression +Pretty-print the value of the expression.""", file=self.stdout) def help_exec(self): - print >>self.stdout, """(!) statement + print("""(!) statement Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word @@ -995,27 +1003,27 @@ To assign to a global variable you must always prefix the command with a 'global' command, e.g.: (Pdb) global list_options; list_options = ['-l'] -(Pdb)""" +(Pdb)""", file=self.stdout) def help_quit(self): self.help_q() def help_q(self): - print >>self.stdout, """q(uit) or exit - Quit from the debugger. -The program being executed is aborted.""" + print("""q(uit) or exit - Quit from the debugger. +The program being executed is aborted.""", file=self.stdout) help_exit = help_q def help_whatis(self): - print >>self.stdout, """whatis arg -Prints the type of the argument.""" + print("""whatis arg +Prints the type of the argument.""", file=self.stdout) def help_EOF(self): - print >>self.stdout, """EOF -Handles the receipt of EOF as a command.""" + print("""EOF +Handles the receipt of EOF as a command.""", file=self.stdout) def help_alias(self): - print >>self.stdout, """alias [name [command [parameter parameter ...] ]] + print("""alias [name [command [parameter parameter ...] ]] Creates an alias called 'name' the executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters are indicated by %1, %2, and so on, while %* is replaced by all the @@ -1036,14 +1044,14 @@ #Print instance variables in self alias ps pi self -""" +""", file=self.stdout) def help_unalias(self): - print >>self.stdout, """unalias name -Deletes the specified alias.""" + print("""unalias name +Deletes the specified alias.""", file=self.stdout) def help_commands(self): - print >>self.stdout, """commands [bpnumber] + print("""commands [bpnumber] (com) ... (com) end (Pdb) @@ -1075,7 +1083,7 @@ be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you see no sign that the breakpoint was reached. -""" +""", file=self.stdout) def help_pdb(self): help() @@ -1166,20 +1174,20 @@ fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) - if sts: print '*** Pager exit status:', sts + if sts: print('*** Pager exit status:', sts) break else: - print 'Sorry, can\'t find the help file "pdb.doc"', - print 'along the Python search path' + print('Sorry, can\'t find the help file "pdb.doc"', end=' ') + print('along the Python search path') def main(): if not sys.argv[1:]: - print "usage: pdb.py scriptfile [arg] ..." + print("usage: pdb.py scriptfile [arg] ...") sys.exit(2) mainpyfile = sys.argv[1] # Get script filename if not os.path.exists(mainpyfile): - print 'Error:', mainpyfile, 'does not exist' + print('Error:', mainpyfile, 'does not exist') sys.exit(1) del sys.argv[0] # Hide "pdb.py" from argument list @@ -1198,20 +1206,20 @@ pdb._runscript(mainpyfile) if pdb._user_requested_quit: break - print "The program finished and will be restarted" + print("The program finished and will be restarted") except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. - print "The program exited via sys.exit(). Exit status: ", - print sys.exc_info()[1] + print("The program exited via sys.exit(). Exit status: ", end=' ') + print(sys.exc_info()[1]) except: traceback.print_exc() - print "Uncaught exception. Entering post mortem debugging" - print "Running 'cont' or 'step' will restart the program" + print("Uncaught exception. Entering post mortem debugging") + print("Running 'cont' or 'step' will restart the program") t = sys.exc_info()[2] while t.tb_next is not None: t = t.tb_next pdb.interaction(t.tb_frame,t) - print "Post mortem debugger finished. The "+mainpyfile+" will be restarted" + print("Post mortem debugger finished. The "+mainpyfile+" will be restarted") # When invoked as main program, invoke the debugger on a script Modified: python/branches/p3yk-noslice/Lib/pickle.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pickle.py (original) +++ python/branches/p3yk-noslice/Lib/pickle.py Fri Feb 23 18:29:35 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) @@ -646,7 +666,7 @@ write(MARK + DICT) self.memoize(obj) - self._batch_setitems(obj.iteritems()) + self._batch_setitems(iter(obj.items())) dispatch[DictionaryType] = save_dict if not PyStringMap is None: @@ -878,7 +898,7 @@ try: val = int(data) except ValueError: - val = long(data) + val = int(data) self.append(val) dispatch[INT] = load_int @@ -895,7 +915,7 @@ dispatch[BININT2] = load_binint2 def load_long(self): - self.append(long(self.readline()[:-1], 0)) + self.append(int(self.readline()[:-1], 0)) dispatch[LONG] = load_long def load_long1(self): @@ -1219,22 +1239,22 @@ def encode_long(x): r"""Encode a long to a two's complement little-endian binary string. - Note that 0L is a special case, returning an empty string, to save a + Note that 0 is a special case, returning an empty string, to save a byte in the LONG1 pickling context. - >>> 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' >>> """ @@ -1264,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') @@ -1304,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-noslice/Lib/pickletools.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pickletools.py (original) +++ python/branches/p3yk-noslice/Lib/pickletools.py Fri Feb 23 18:29:35 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.") @@ -1757,18 +1757,18 @@ for name in pickle.__all__: if not re.match("[A-Z][A-Z0-9_]+$", name): if verbose: - print "skipping %r: it doesn't look like an opcode name" % name + print("skipping %r: it doesn't look like an opcode name" % name) continue picklecode = getattr(pickle, name) if not isinstance(picklecode, str) or len(picklecode) != 1: if verbose: - print ("skipping %r: value %r doesn't look like a pickle " - "code" % (name, picklecode)) + print(("skipping %r: value %r doesn't look like a pickle " + "code" % (name, picklecode))) continue if picklecode in copy: if verbose: - print "checking name %r w/ code %r for consistency" % ( - name, picklecode) + print("checking name %r w/ code %r for consistency" % ( + name, picklecode)) d = copy[picklecode] if d.name != name: raise ValueError("for pickle code %r, pickle.py uses name %r " @@ -1899,7 +1899,7 @@ errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: - print >> out, "%5d:" % pos, + print("%5d:" % pos, end=' ', file=out) line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), @@ -1964,7 +1964,7 @@ line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg - print >> out, line + print(line, file=out) if errormsg: # Note that we delayed complaining until the offending opcode @@ -1983,7 +1983,7 @@ stack.extend(after) - print >> out, "highest protocol among opcodes =", maxproto + print("highest protocol among opcodes =", maxproto, file=out) if stack: raise ValueError("stack not empty after STOP: %r" % stack) @@ -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 Modified: python/branches/p3yk-noslice/Lib/pipes.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pipes.py (original) +++ python/branches/p3yk-noslice/Lib/pipes.py Fri Feb 23 18:29:35 2007 @@ -188,7 +188,7 @@ def makepipeline(self, infile, outfile): cmd = makepipeline(infile, self.steps, outfile) if self.debugging: - print cmd + print(cmd) cmd = 'set -x; ' + cmd return cmd @@ -286,7 +286,7 @@ # Small test program and example def test(): - print 'Testing...' + print('Testing...') t = Template() t.append('togif $IN $OUT', 'ff') t.append('giftoppm', '--') @@ -295,4 +295,4 @@ t.debug(1) FILE = '/usr/local/images/rgb/rogues/guido.rgb' t.copy(FILE, '@temp') - print 'Done.' + print('Done.') Modified: python/branches/p3yk-noslice/Lib/plat-aix3/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-aix3/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-aix3/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-aix4/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-aix4/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-aix4/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-atheos/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-atheos/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-atheos/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-atheos/TYPES.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-atheos/TYPES.py (original) +++ python/branches/p3yk-noslice/Lib/plat-atheos/TYPES.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-beos5/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-beos5/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-beos5/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-freebsd2/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-freebsd2/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-freebsd2/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-freebsd3/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-freebsd3/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-freebsd3/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-irix5/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix5/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix5/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-irix5/cddb.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix5/cddb.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix5/cddb.py Fri Feb 23 18:29:35 2007 @@ -89,7 +89,7 @@ break match = reg.match(line) if not match: - print 'syntax error in ' + file + print('syntax error in ' + file) continue name1, name2, value = match.group(1, 2, 3) if name1 == 'album': @@ -101,17 +101,17 @@ if not self.toc: self.toc = value if self.toc != value: - print 'toc\'s don\'t match' + print('toc\'s don\'t match') elif name2 == 'notes': self.notes.append(value) elif name1[:5] == 'track': try: trackno = int(name1[5:]) except strings.atoi_error: - print 'syntax error in ' + file + print('syntax error in ' + file) continue if trackno > ntracks: - print 'track number %r in file %r out of range' % (trackno, file) + print('track number %r in file %r out of range' % (trackno, file)) continue if name2 == 'title': self.track[trackno] = value Modified: python/branches/p3yk-noslice/Lib/plat-irix5/cdplayer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix5/cdplayer.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix5/cdplayer.py Fri Feb 23 18:29:35 2007 @@ -51,7 +51,7 @@ line = line[l:] match = reg.match(line) if not match: - print 'syntax error in ~/' + cdplayerrc + print('syntax error in ~/' + cdplayerrc) continue name, value = match.group(1, 2) if name == 'title': Modified: python/branches/p3yk-noslice/Lib/plat-irix5/flp.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix5/flp.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix5/flp.py Fri Feb 23 18:29:35 2007 @@ -66,7 +66,7 @@ return None try: if fp.read(4) != MAGIC: - print 'flp: bad magic word in cache file', cachename + print('flp: bad magic word in cache file', cachename) return None cache_mtime = rdlong(fp) file_mtime = getmtime(filename) @@ -122,7 +122,7 @@ try: fp = open(cachename, 'w') except IOError: - print 'flp: can\'t create cache file', cachename + print('flp: can\'t create cache file', cachename) return # Never mind fp.write('\0\0\0\0') # Seek back and write MAGIC when done wrlong(fp, getmtime(filename)) @@ -145,8 +145,8 @@ def freeze(filename): forms = parse_forms(filename) altforms = _pack_cache(forms) - print 'import flp' - print 'flp._internal_cache[', repr(filename), '] =', altforms + print('import flp') + print('flp._internal_cache[', repr(filename), '] =', altforms) # # Internal: create the data structure to be placed in the cache @@ -426,7 +426,7 @@ if len(sys.argv) == 2: forms = parse_forms(sys.argv[1]) t1 = time.time() - print 'parse time:', 0.001*(t1-t0), 'sec.' + print('parse time:', 0.001*(t1-t0), 'sec.') keys = forms.keys() keys.sort() for i in keys: @@ -434,18 +434,18 @@ elif len(sys.argv) == 3: form = parse_form(sys.argv[1], sys.argv[2]) t1 = time.time() - print 'parse time:', round(t1-t0, 3), 'sec.' + print('parse time:', round(t1-t0, 3), 'sec.') _printform(form) else: - print 'Usage: test fdfile [form]' + print('Usage: test fdfile [form]') def _printform(form): f = form[0] objs = form[1] - print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects + print('Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects) for i in objs: - print ' Obj ', i.Name, ' type ', i.Class, i.Type - print ' Box ', i.Box, ' btype ', i.Boxtype - print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment - print ' cols ', i.Colors - print ' cback ', i.Callback, i.Argument + print(' Obj ', i.Name, ' type ', i.Class, i.Type) + print(' Box ', i.Box, ' btype ', i.Boxtype) + print(' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment) + print(' cols ', i.Colors) + print(' cback ', i.Callback, i.Argument) Modified: python/branches/p3yk-noslice/Lib/plat-irix5/panel.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix5/panel.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix5/panel.py Fri Feb 23 18:29:35 2007 @@ -62,18 +62,18 @@ def show_actuator(prefix, a): for item in a: if not is_list(item): - print prefix, item + print(prefix, item) elif item and item[0] == 'al': - print prefix, 'Subactuator list:' + print(prefix, 'Subactuator list:') for a in item[1:]: show_actuator(prefix + ' ', a) elif len(item) == 2: - print prefix, item[0], '=>', item[1] + print(prefix, item[0], '=>', item[1]) elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] + print(prefix, 'Prop', item[1], '=>', end=' ') + print(item[2]) else: - print prefix, '?', item + print(prefix, '?', item) # Neatly display a panel. @@ -81,18 +81,18 @@ def show_panel(prefix, p): for item in p: if not is_list(item): - print prefix, item + print(prefix, item) elif item and item[0] == 'al': - print prefix, 'Actuator list:' + print(prefix, 'Actuator list:') for a in item[1:]: show_actuator(prefix + ' ', a) elif len(item) == 2: - print prefix, item[0], '=>', item[1] + print(prefix, item[0], '=>', item[1]) elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] + print(prefix, 'Prop', item[1], '=>', end=' ') + print(item[2]) else: - print prefix, '?', item + print(prefix, '?', item) # Exception raised by build_actuator or build_panel. @@ -123,18 +123,18 @@ # Strange default set by Panel Editor... ok = 0 else: - print 'unknown value', value, 'for', name + print('unknown value', value, 'for', name) ok = 0 if ok: lhs = 'target.' + prefix + name stmt = lhs + '=' + repr(value) - if debug: print 'exec', stmt + if debug: print('exec', stmt) try: exec(stmt + '\n') except KeyboardInterrupt: # Don't catch this! raise KeyboardInterrupt except: - print 'assign failed:', stmt + print('assign failed:', stmt) # Build a real actuator from an actuator description. @@ -185,7 +185,7 @@ act.addsubact(super_act) if name: stmt = 'panel.' + name + ' = act' - if debug: print 'exec', stmt + if debug: print('exec', stmt) exec(stmt + '\n') if is_endgroup(a): panel.endgroup() Modified: python/branches/p3yk-noslice/Lib/plat-irix6/FILE.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix6/FILE.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix6/FILE.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-irix6/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix6/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix6/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-irix6/WAIT.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix6/WAIT.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix6/WAIT.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-irix6/cddb.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix6/cddb.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix6/cddb.py Fri Feb 23 18:29:35 2007 @@ -89,7 +89,7 @@ break match = reg.match(line) if not match: - print 'syntax error in ' + file + print('syntax error in ' + file) continue name1, name2, value = match.group(1, 2, 3) if name1 == 'album': @@ -101,17 +101,17 @@ if not self.toc: self.toc = value if self.toc != value: - print 'toc\'s don\'t match' + print('toc\'s don\'t match') elif name2 == 'notes': self.notes.append(value) elif name1[:5] == 'track': try: trackno = int(name1[5:]) except ValueError: - print 'syntax error in ' + file + print('syntax error in ' + file) continue if trackno > ntracks: - print 'track number %r in file %s out of range' % (trackno, file) + print('track number %r in file %s out of range' % (trackno, file)) continue if name2 == 'title': self.track[trackno] = value Modified: python/branches/p3yk-noslice/Lib/plat-irix6/cdplayer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix6/cdplayer.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix6/cdplayer.py Fri Feb 23 18:29:35 2007 @@ -51,7 +51,7 @@ line = line[l:] match = reg.match(line) if not match: - print 'syntax error in ~/' + cdplayerrc + print('syntax error in ~/' + cdplayerrc) continue name, value = match.group(1, 2) if name == 'title': Modified: python/branches/p3yk-noslice/Lib/plat-irix6/flp.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix6/flp.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix6/flp.py Fri Feb 23 18:29:35 2007 @@ -65,7 +65,7 @@ return None try: if fp.read(4) != MAGIC: - print 'flp: bad magic word in cache file', cachename + print('flp: bad magic word in cache file', cachename) return None cache_mtime = rdlong(fp) file_mtime = getmtime(filename) @@ -121,7 +121,7 @@ try: fp = open(cachename, 'w') except IOError: - print 'flp: can\'t create cache file', cachename + print('flp: can\'t create cache file', cachename) return # Never mind fp.write('\0\0\0\0') # Seek back and write MAGIC when done wrlong(fp, getmtime(filename)) @@ -144,8 +144,8 @@ def freeze(filename): forms = parse_forms(filename) altforms = _pack_cache(forms) - print 'import flp' - print 'flp._internal_cache[', repr(filename), '] =', altforms + print('import flp') + print('flp._internal_cache[', repr(filename), '] =', altforms) # # Internal: create the data structure to be placed in the cache @@ -425,7 +425,7 @@ if len(sys.argv) == 2: forms = parse_forms(sys.argv[1]) t1 = time.time() - print 'parse time:', 0.001*(t1-t0), 'sec.' + print('parse time:', 0.001*(t1-t0), 'sec.') keys = forms.keys() keys.sort() for i in keys: @@ -433,18 +433,18 @@ elif len(sys.argv) == 3: form = parse_form(sys.argv[1], sys.argv[2]) t1 = time.time() - print 'parse time:', round(t1-t0, 3), 'sec.' + print('parse time:', round(t1-t0, 3), 'sec.') _printform(form) else: - print 'Usage: test fdfile [form]' + print('Usage: test fdfile [form]') def _printform(form): f = form[0] objs = form[1] - print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects + print('Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects) for i in objs: - print ' Obj ', i.Name, ' type ', i.Class, i.Type - print ' Box ', i.Box, ' btype ', i.Boxtype - print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment - print ' cols ', i.Colors - print ' cback ', i.Callback, i.Argument + print(' Obj ', i.Name, ' type ', i.Class, i.Type) + print(' Box ', i.Box, ' btype ', i.Boxtype) + print(' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment) + print(' cols ', i.Colors) + print(' cback ', i.Callback, i.Argument) Modified: python/branches/p3yk-noslice/Lib/plat-irix6/panel.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix6/panel.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix6/panel.py Fri Feb 23 18:29:35 2007 @@ -62,18 +62,18 @@ def show_actuator(prefix, a): for item in a: if not is_list(item): - print prefix, item + print(prefix, item) elif item and item[0] == 'al': - print prefix, 'Subactuator list:' + print(prefix, 'Subactuator list:') for a in item[1:]: show_actuator(prefix + ' ', a) elif len(item) == 2: - print prefix, item[0], '=>', item[1] + print(prefix, item[0], '=>', item[1]) elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] + print(prefix, 'Prop', item[1], '=>', end=' ') + print(item[2]) else: - print prefix, '?', item + print(prefix, '?', item) # Neatly display a panel. @@ -81,18 +81,18 @@ def show_panel(prefix, p): for item in p: if not is_list(item): - print prefix, item + print(prefix, item) elif item and item[0] == 'al': - print prefix, 'Actuator list:' + print(prefix, 'Actuator list:') for a in item[1:]: show_actuator(prefix + ' ', a) elif len(item) == 2: - print prefix, item[0], '=>', item[1] + print(prefix, item[0], '=>', item[1]) elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] + print(prefix, 'Prop', item[1], '=>', end=' ') + print(item[2]) else: - print prefix, '?', item + print(prefix, '?', item) # Exception raised by build_actuator or build_panel. @@ -123,18 +123,18 @@ # Strange default set by Panel Editor... ok = 0 else: - print 'unknown value', value, 'for', name + print('unknown value', value, 'for', name) ok = 0 if ok: lhs = 'target.' + prefix + name stmt = lhs + '=' + repr(value) - if debug: print 'exec', stmt + if debug: print('exec', stmt) try: exec(stmt + '\n') except KeyboardInterrupt: # Don't catch this! raise KeyboardInterrupt except: - print 'assign failed:', stmt + print('assign failed:', stmt) # Build a real actuator from an actuator description. @@ -185,7 +185,7 @@ act.addsubact(super_act) if name: stmt = 'panel.' + name + ' = act' - if debug: print 'exec', stmt + if debug: print('exec', stmt) exec(stmt + '\n') if is_endgroup(a): panel.endgroup() Modified: python/branches/p3yk-noslice/Lib/plat-linux2/DLFCN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-linux2/DLFCN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-linux2/DLFCN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-linux2/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-linux2/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-linux2/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-linux2/TYPES.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-linux2/TYPES.py (original) +++ python/branches/p3yk-noslice/Lib/plat-linux2/TYPES.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Audio_mac.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Audio_mac.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Audio_mac.py Fri Feb 23 18:29:35 2007 @@ -104,7 +104,7 @@ fn = EasyDialogs.AskFileForOpen(message="Select an AIFF soundfile", typeList=("AIFF",)) if not fn: return af = aifc.open(fn, 'r') - print af.getparams() + print(af.getparams()) p = Play_Audio_mac() p.setoutrate(af.getframerate()) p.setsampwidth(af.getsampwidth()) @@ -114,7 +114,7 @@ data = af.readframes(BUFSIZ) if not data: break p.writeframes(data) - print 'wrote', len(data), 'space', p.getfillable() + print('wrote', len(data), 'space', p.getfillable()) p.wait() if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/CarbonEvents.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/CarbonEvents.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/CarbonEvents.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/Components.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Components.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Components.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/Controls.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Controls.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Controls.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/Dragconst.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Dragconst.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Dragconst.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/Folders.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Folders.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Folders.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/Fonts.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Fonts.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Fonts.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/Icons.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Icons.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Icons.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/MacTextEditor.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/MacTextEditor.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/MacTextEditor.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/OSAconst.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/OSAconst.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/OSAconst.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/QDOffscreen.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QDOffscreen.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QDOffscreen.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/QuickDraw.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickDraw.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickDraw.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/QuickTime.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickTime.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickTime.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/Sound.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Sound.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Sound.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/Carbon/Windows.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Windows.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Windows.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/EasyDialogs.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py Fri Feb 23 18:29:35 2007 @@ -75,7 +75,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return h = d.GetDialogItemAsControl(2) SetDialogItemText(h, lf2cr(msg)) @@ -108,7 +108,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return h = d.GetDialogItemAsControl(3) SetDialogItemText(h, lf2cr(prompt)) @@ -150,7 +150,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return h = d.GetDialogItemAsControl(3) SetDialogItemText(h, lf2cr(prompt)) @@ -194,7 +194,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return # Button assignments: # 1 = default (invisible) @@ -429,7 +429,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return # h = d.GetDialogItemAsControl(3) # SetDialogItemText(h, lf2cr(prompt)) @@ -791,7 +791,7 @@ argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0) Message("Command line: %s"%' '.join(argv)) for i in range(len(argv)): - print 'arg[%d] = %r' % (i, argv[i]) + print('arg[%d] = %r' % (i, argv[i])) ok = AskYesNoCancel("Do you want to proceed?") ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No") if ok > 0: Modified: python/branches/p3yk-noslice/Lib/plat-mac/FrameWork.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/FrameWork.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/FrameWork.py Fri Feb 23 18:29:35 2007 @@ -250,7 +250,7 @@ if window in self._windows: self._windows[window].do_itemhit(item, event) else: - print 'Dialog event for unknown dialog' + print('Dialog event for unknown dialog') return 1 return 0 @@ -323,14 +323,14 @@ def do_unknownpartcode(self, partcode, window, event): (what, message, when, where, modifiers) = event - if DEBUG: print "Mouse down at global:", where - if DEBUG: print "\tUnknown part code:", partcode - if DEBUG: print "\tEvent:", self.printevent(event) + if DEBUG: print("Mouse down at global:", where) + if DEBUG: print("\tUnknown part code:", partcode) + if DEBUG: print("\tEvent:", self.printevent(event)) if hasattr(MacOS, 'HandleEvent'): MacOS.HandleEvent(event) def do_unknownwindow(self, partcode, window, event): - if DEBUG: print 'Unknown window:', window + if DEBUG: print('Unknown window:', window) if hasattr(MacOS, 'HandleEvent'): MacOS.HandleEvent(event) @@ -373,7 +373,7 @@ # else it wasn't for us, sigh... def do_char(self, c, event): - if DEBUG: print "Character", repr(c) + if DEBUG: print("Character", repr(c)) def do_updateEvt(self, event): (what, message, when, where, modifiers) = event @@ -402,7 +402,7 @@ self.do_suspendresume(event) else: if DEBUG: - print 'unknown osEvt:', + print('unknown osEvt:', end=' ') self.printevent(event) def do_suspendresume(self, event): @@ -415,7 +415,7 @@ def do_kHighLevelEvent(self, event): (what, message, when, where, modifiers) = event if DEBUG: - print "High Level Event:", + print("High Level Event:", end=' ') self.printevent(event) try: AEProcessAppleEvent(event) @@ -426,7 +426,7 @@ def do_unknownevent(self, event): if DEBUG: - print "Unhandled event:", + print("Unhandled event:", end=' ') self.printevent(event) def printevent(self, event): @@ -434,13 +434,13 @@ nicewhat = repr(what) if what in eventname: nicewhat = eventname[what] - print nicewhat, + print(nicewhat, end=' ') if what == kHighLevelEvent: h, v = where - print repr(ostypecode(message)), hex(when), repr(ostypecode(h | (v<<16))), + print(repr(ostypecode(message)), hex(when), repr(ostypecode(h | (v<<16))), end=' ') else: - print hex(message), hex(when), where, - print hex(modifiers) + print(hex(message), hex(when), where, end=' ') + print(hex(modifiers)) class MenuBar: @@ -477,7 +477,7 @@ def addmenu(self, title, after = 0, id=None): if id == None: id = self.getnextid() - if DEBUG: print 'Newmenu', title, id # XXXX + if DEBUG: print('Newmenu', title, id) # XXXX m = NewMenu(id, title) m.InsertMenu(after) if after >= 0: @@ -488,7 +488,7 @@ return id, m def delmenu(self, id): - if DEBUG: print 'Delmenu', id # XXXX + if DEBUG: print('Delmenu', id) # XXXX DeleteMenu(id) def addpopup(self, title = ''): @@ -531,8 +531,8 @@ if id in self.menus: self.menus[id].dispatch(id, item, window, event) else: - if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ - (id, item, window, event) + if DEBUG: print("MenuBar.dispatch(%d, %d, %s, %s)" % \ + (id, item, window, event)) # XXX Need a way to get menus as resources and bind them to callbacks @@ -837,10 +837,10 @@ def do_contentclick(self, local, modifiers, event): if DEBUG: - print 'Click in contents at %s, modifiers %s'%(local, modifiers) + print('Click in contents at %s, modifiers %s'%(local, modifiers)) def do_rawupdate(self, window, event): - if DEBUG: print "raw update for", window + if DEBUG: print("raw update for", window) SetPort(window) window.BeginUpdate() self.do_update(window, event) @@ -857,12 +857,12 @@ EraseRgn(window.GetWindowPort().visRgn) def do_activate(self, activate, event): - if DEBUG: print 'Activate %d for %s'%(activate, self.wid) + if DEBUG: print('Activate %d for %s'%(activate, self.wid)) class ControlsWindow(Window): def do_rawupdate(self, window, event): - if DEBUG: print "raw update for", window + if DEBUG: print("raw update for", window) SetPort(window) window.BeginUpdate() self.do_update(window, event) @@ -872,7 +872,7 @@ window.EndUpdate() def do_controlhit(self, window, control, pcode, event): - if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode + if DEBUG: print("control hit in", window, "on", control, "; pcode =", pcode) def do_inContent(self, partcode, window, event): if MyFrontWindow() != window: @@ -885,8 +885,8 @@ if pcode and control: self.do_rawcontrolhit(window, control, pcode, local, event) else: - if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \ - (local, window, pcode, control) + if DEBUG: print("FindControl(%s, %s) -> (%s, %s)" % \ + (local, window, pcode, control)) self.do_contentclick(local, modifiers, event) def do_rawcontrolhit(self, window, control, pcode, local, event): @@ -975,11 +975,11 @@ pcode = control.TrackControl(local) if pcode == inThumb: value = control.GetControlValue() - print 'setbars', which, value #DBG + print('setbars', which, value) #DBG self.scrollbar_callback(which, 'set', value) self.updatescrollbars() else: - print 'funny part', pcode #DBG + print('funny part', pcode) #DBG return 1 def do_controltrack(self, control, pcode): @@ -1045,7 +1045,7 @@ return 0, 0 def scrollbar_callback(self, which, what, value): - print 'scroll', which, what, value + print('scroll', which, what, value) class DialogWindow(Window): """A modeless dialog window""" @@ -1063,7 +1063,7 @@ Window.do_postclose(self) def do_itemhit(self, item, event): - print 'Dialog %s, item %d hit'%(self.dlg, item) + print('Dialog %s, item %d hit'%(self.dlg, item)) def do_rawupdate(self, window, event): pass @@ -1096,7 +1096,7 @@ self.quititem = MenuItem(m, "Quit", "Q", self.quit) def save(self, *args): - print "Save" + print("Save") def quit(self, *args): raise self @@ -1106,7 +1106,7 @@ self.nohelpitem = MenuItem(hm, "There isn't any", None, self.nohelp) def nohelp(self, *args): - print "I told you there isn't any!" + print("I told you there isn't any!") def debug(self, *args): import pdb Modified: python/branches/p3yk-noslice/Lib/plat-mac/MiniAEFrame.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/MiniAEFrame.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/MiniAEFrame.py Fri Feb 23 18:29:35 2007 @@ -71,8 +71,8 @@ try: AE.AEProcessAppleEvent(event) except AE.Error as err: - print 'AE error: ', err - print 'in', msg + print('AE error: ', err) + print('in', msg) traceback.print_exc() return elif what == keyDown: @@ -107,7 +107,7 @@ if hasattr(MacOS, 'HandleEvent'): MacOS.HandleEvent(event) else: - print "Unhandled event:", event + print("Unhandled event:", event) def getabouttext(self): return self.__class__.__name__ @@ -191,7 +191,7 @@ pass def other(self, _object=None, _class=None, _type=None, **args): - print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args + print('AppleEvent', (_class, _type), 'for', _object, 'Other args:', args) if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/plat-mac/aepack.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/aepack.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/aepack.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/aetools.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/aetools.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/aetools.py Fri Feb 23 18:29:35 2007 @@ -349,15 +349,15 @@ target = AE.AECreateDesc('sign', 'quil') ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0) - print unpackevent(ae) + print(unpackevent(ae)) raw_input(":") ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0) obj = Character(2, Word(1, Document(1))) - print obj - print repr(obj) + print(obj) + print(repr(obj)) packevent(ae, {'----': obj}) params, attrs = unpackevent(ae) - print params['----'] + print(params['----']) raw_input(":") if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py Fri Feb 23 18:29:35 2007 @@ -51,9 +51,9 @@ except ValueError as arg: raise Error, "Unpack header error: %s" % (arg,) if verbose: - print 'Magic: 0x%8.8x' % (magic,) - print 'Version: 0x%8.8x' % (version,) - print 'Entries: %d' % (nentry,) + print('Magic: 0x%8.8x' % (magic,)) + print('Version: 0x%8.8x' % (version,)) + print('Entries: %d' % (nentry,)) if magic != AS_MAGIC: raise Error, "Unknown AppleSingle magic number 0x%8.8x" % (magic,) if version != AS_VERSION: @@ -68,7 +68,7 @@ except ValueError as arg: raise Error, "Unpack entry error: %s" % (arg,) if verbose: - print "Fork %d, offset %d, length %d" % (restype, offset, length) + print("Fork %d, offset %d, length %d" % (restype, offset, length)) fileobj.seek(offset) data = fileobj.read(length) if len(data) != length: @@ -124,7 +124,7 @@ def _test(): if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4: - print 'Usage: applesingle.py [-r] applesinglefile decodedfile' + print('Usage: applesingle.py [-r] applesinglefile decodedfile') sys.exit(1) if sys.argv[1] == '-r': resonly = True Modified: python/branches/p3yk-noslice/Lib/plat-mac/argvemulator.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/argvemulator.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/argvemulator.py Fri Feb 23 18:29:35 2007 @@ -37,7 +37,7 @@ self._dooneevent(mask, timeout) if not self.quitting: - print "argvemulator: timeout waiting for arguments" + print("argvemulator: timeout waiting for arguments") self.close() @@ -54,12 +54,12 @@ AE.AEProcessAppleEvent(event) except AE.Error as err: msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16))) - print 'AE error: ', err - print 'in', msg + print('AE error: ', err) + print('in', msg) traceback.print_exc() return else: - print "Unhandled event:", event + print("Unhandled event:", event) def _quit(self): @@ -78,7 +78,7 @@ pathname = fsref.as_pathname() sys.argv.append(pathname) except Exception as e: - print "argvemulator.py warning: can't unpack an open document event" + print("argvemulator.py warning: can't unpack an open document event") import traceback traceback.print_exc() @@ -86,4 +86,4 @@ if __name__ == '__main__': ArgvCollector().mainloop() - print "sys.argv=", sys.argv + print("sys.argv=", sys.argv) Modified: python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py Fri Feb 23 18:29:35 2007 @@ -831,8 +831,8 @@ def usage(msg=None): if msg: - print msg - print cmdline_doc + print(msg) + print(cmdline_doc) sys.exit(1) def main(builder=None): Modified: python/branches/p3yk-noslice/Lib/plat-mac/findertools.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/findertools.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/findertools.py Fri Feb 23 18:29:35 2007 @@ -695,76 +695,76 @@ def _test(): import EasyDialogs - print 'Original findertools functionality test...' - print 'Testing launch...' + print('Original findertools functionality test...') + print('Testing launch...') pathname = EasyDialogs.AskFileForOpen('File to launch:') if pathname: result = launch(pathname) if result: - print 'Result: ', result - print 'Press return-', + print('Result: ', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing print...' + print('Testing print...') pathname = EasyDialogs.AskFileForOpen('File to print:') if pathname: result = Print(pathname) if result: - print 'Result: ', result - print 'Press return-', + print('Result: ', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing copy...' + print('Testing copy...') pathname = EasyDialogs.AskFileForOpen('File to copy:') if pathname: destdir = EasyDialogs.AskFolder('Destination:') if destdir: result = copy(pathname, destdir) if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing move...' + print('Testing move...') pathname = EasyDialogs.AskFileForOpen('File to move:') if pathname: destdir = EasyDialogs.AskFolder('Destination:') if destdir: result = move(pathname, destdir) if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing sleep...' + print('Testing sleep...') if EasyDialogs.AskYesNoCancel('Sleep?') > 0: result = sleep() if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing shutdown...' + print('Testing shutdown...') if EasyDialogs.AskYesNoCancel('Shut down?') > 0: result = shutdown() if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing restart...' + print('Testing restart...') if EasyDialogs.AskYesNoCancel('Restart?') > 0: result = restart() if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() def _test2(): - print '\nmorefindertools version %s\nTests coming up...' %__version__ + print('\nmorefindertools version %s\nTests coming up...' %__version__) import os import random # miscellaneous - print '\tfilesharing on?', filesharing() # is file sharing on, off, starting up? - print '\tOS version', OSversion() # the version of the system software + print('\tfilesharing on?', filesharing()) # is file sharing on, off, starting up? + print('\tOS version', OSversion()) # the version of the system software # set the soundvolume in a simple way - print '\tSystem beep volume' + print('\tSystem beep volume') for i in range(0, 7): volumelevel(i) MacOS.SysBeep() @@ -781,10 +781,10 @@ windowview(base, 1) # set the view by list label(f, 2) # set the label of this file to something orange - print '\tlabel', label(f) # get the label of this file + print('\tlabel', label(f)) # get the label of this file # the file location only works in a window with icon view! - print 'Random locations for an icon' + print('Random locations for an icon') windowview(base, 0) # set the view by icon windowsize(base, (600, 600)) for i in range(50): @@ -794,36 +794,36 @@ windowview(base, 1) # set the view by icon orgpos = windowposition(base) - print 'Animated window location' + print('Animated window location') for i in range(10): pos = (100+i*10, 100+i*10) windowposition(base, pos) - print '\twindow position', pos + print('\twindow position', pos) windowposition(base, orgpos) # park it where it was before - print 'Put a comment in file', f, ':' - print '\t', comment(f) # print the Finder comment this file has + print('Put a comment in file', f, ':') + print('\t', comment(f)) # print the Finder comment this file has s = 'This is a comment no one reads!' comment(f, s) # set the Finder comment def _test3(): - print 'MacOS9 or better specific functions' + print('MacOS9 or better specific functions') # processes pr = processes() # return a list of tuples with (active_processname, creatorcode) - print 'Return a list of current active processes:' + print('Return a list of current active processes:') for p in pr: - print '\t', p + print('\t', p) # get attributes of the first process in the list - print 'Attributes of the first process in the list:' + print('Attributes of the first process in the list:') pinfo = processinfo(pr[0][0]) - print '\t', pr[0][0] - print '\t\tmemory partition', pinfo.partition # the memory allocated to this process - print '\t\tmemory used', pinfo.used # the memory actuall used by this process - print '\t\tis visible', pinfo.visible # is the process visible to the user - print '\t\tis frontmost', pinfo.frontmost # is the process the front most one? - print '\t\thas scripting', pinfo.hasscripting # is the process scriptable? - print '\t\taccepts high level events', pinfo.accepthighlevel # does the process accept high level appleevents? + print('\t', pr[0][0]) + print('\t\tmemory partition', pinfo.partition) # the memory allocated to this process + print('\t\tmemory used', pinfo.used) # the memory actuall used by this process + print('\t\tis visible', pinfo.visible) # is the process visible to the user + print('\t\tis frontmost', pinfo.frontmost) # is the process the front most one? + print('\t\thas scripting', pinfo.hasscripting) # is the process scriptable? + print('\t\taccepts high level events', pinfo.accepthighlevel) # does the process accept high level appleevents? if __name__ == '__main__': _test() Modified: python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py Fri Feb 23 18:29:35 2007 @@ -115,8 +115,8 @@ processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) except MacOS.Error as arg: - print "Error getting terminology:", arg - print "Retry, manually parsing resources" + print("Error getting terminology:", arg) + print("Retry, manually parsing resources") processfile_fromresource(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) @@ -145,10 +145,10 @@ edit_modnames=None, creatorsignature=None, dump=None, verbose=None): """Process all resources in a single file""" if not is_scriptable(fullname) and verbose: - print >>verbose, "Warning: app does not seem scriptable: %s" % fullname + print("Warning: app does not seem scriptable: %s" % fullname, file=verbose) cur = CurResFile() if verbose: - print >>verbose, "Processing", fullname + print("Processing", fullname, file=verbose) rf = macresource.open_pathname(fullname) try: UseResFile(rf) @@ -160,11 +160,11 @@ res = Get1IndResource('aeut', 1+i) resources.append(res) if verbose: - print >>verbose, "\nLISTING aete+aeut RESOURCES IN", repr(fullname) + print("\nLISTING aete+aeut RESOURCES IN", repr(fullname), file=verbose) aetelist = [] for res in resources: if verbose: - print >>verbose, "decoding", res.GetResInfo(), "..." + print("decoding", res.GetResInfo(), "...", file=verbose) data = res.data aete = decode(data, verbose) aetelist.append((aete, res.GetResInfo())) @@ -185,15 +185,15 @@ verbose=None): """Ask an application for its terminology and process that""" if not is_scriptable(fullname) and verbose: - print >>verbose, "Warning: app does not seem scriptable: %s" % fullname + print("Warning: app does not seem scriptable: %s" % fullname, file=verbose) if verbose: - print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname) + print("\nASKING FOR aete DICTIONARY IN", repr(fullname), file=verbose) try: aedescobj, launched = OSATerminology.GetAppTerminology(fullname) except MacOS.Error as arg: if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound if verbose: - print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually" + print("GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually", file=verbose) aedata, sig = getappterminology(fullname, verbose=verbose) if not creatorsignature: creatorsignature = sig @@ -202,15 +202,15 @@ else: if launched: if verbose: - print >>verbose, "Launched", fullname + print("Launched", fullname, file=verbose) raw = aetools.unpack(aedescobj) if not raw: if verbose: - print >>verbose, 'Unpack returned empty value:', raw + print('Unpack returned empty value:', raw, file=verbose) return if not raw[0].data: if verbose: - print >>verbose, 'Unpack returned value without data:', raw + print('Unpack returned value without data:', raw, file=verbose) return aedata = raw[0] aete = decode(aedata.data, verbose) @@ -246,7 +246,7 @@ talker._start() except (MacOS.Error, aetools.Error) as arg: if verbose: - print >>verbose, 'Warning: start() failed, continuing anyway:', arg + print('Warning: start() failed, continuing anyway:', arg, file=verbose) reply = talker.send("ascr", "gdte") #reply2 = talker.send("ascr", "gdut") # Now pick the bits out of the return that we need. @@ -344,9 +344,9 @@ return list def alt_generic(what, f, *args): - print "generic", repr(what), args + print("generic", repr(what), args) res = vageneric(what, f, args) - print '->', repr(res) + print('->', repr(res)) return res def generic(what, f, *args): @@ -940,14 +940,14 @@ for mapper in self.othernamemappers: if mapper.hasname(name) and mapper.modulename != self.modulename: if self.verbose: - print >>self.verbose, "Duplicate Python identifier:", name, self.modulename, mapper.modulename + print("Duplicate Python identifier:", name, self.modulename, mapper.modulename, file=self.verbose) return True return False def askdefinitionmodule(self, type, code): if not self.can_interact: if self.verbose: - print >>self.verbose, "** No definition for %s '%s' found" % (type, code) + print("** No definition for %s '%s' found" % (type, code), file=self.verbose) return None path = EasyDialogs.AskFileForSave(message='Where is %s %s declared?'%(type, code)) if not path: return @@ -1018,7 +1018,7 @@ if self.fp and (elements or len(properties) > 1 or (len(properties) == 1 and properties[0][1] != 'c@#!')): if self.verbose: - print >>self.verbose, '** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code) + print('** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code), file=self.verbose) raise RuntimeError, "About to skip non-empty class" return plist = [] Modified: python/branches/p3yk-noslice/Lib/plat-mac/ic.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/ic.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/ic.py Fri Feb 23 18:29:35 2007 @@ -94,7 +94,7 @@ chr(0) + _code_default(name) def _code_boolean(data, key): - print 'XXXX boolean:', repr(data) + print('XXXX boolean:', repr(data)) return chr(data) def _code_text(data, key): @@ -258,7 +258,7 @@ v = ic[k] except error: v = '????' - print k, '\t', v + print(k, '\t', v) sys.exit(1) if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/plat-mac/macfs.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/macfs.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/macfs.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-mac/macresource.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/macresource.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/macresource.py Fri Feb 23 18:29:35 2007 @@ -140,7 +140,7 @@ import tempfile fd, newpathname = tempfile.mkstemp(".rsrc") if verbose: - print 'Decoding', pathname, 'to', newpathname + print('Decoding', pathname, 'to', newpathname) import applesingle applesingle.decode(pathname, newpathname, resonly=1) return newpathname Modified: python/branches/p3yk-noslice/Lib/plat-mac/pimp.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/pimp.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/pimp.py Fri Feb 23 18:29:35 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 @@ -229,7 +229,7 @@ #print 'SKIP', member.name else: member.name = newprefix + member.name[len(oldprefix):] - print ' ', member.name + print(' ', member.name) break elif oldprefix2 and member.name[:len(oldprefix2)] == oldprefix2: if newprefix is None: @@ -1020,8 +1020,8 @@ elif mode =='list': if not args: args = db.listnames() - print "%-20.20s\t%s" % ("Package", "Description") - print + print("%-20.20s\t%s" % ("Package", "Description")) + print() for pkgname in args: pkg = db.find(pkgname) if pkg: @@ -1029,21 +1029,21 @@ pkgname = pkg.fullname() else: description = 'Error: no such package' - print "%-20.20s\t%s" % (pkgname, description) + print("%-20.20s\t%s" % (pkgname, description)) if verbose: - print "\tHome page:\t", pkg.homepage() + print("\tHome page:\t", pkg.homepage()) try: - print "\tDownload URL:\t", pkg.downloadURL() + print("\tDownload URL:\t", pkg.downloadURL()) except KeyError: pass description = pkg.description() description = '\n\t\t\t\t\t'.join(description.splitlines()) - print "\tDescription:\t%s" % description + print("\tDescription:\t%s" % description) elif mode =='status': if not args: args = db.listnames() - print "%-20.20s\t%s\t%s" % ("Package", "Installed", "Message") - print + print("%-20.20s\t%s\t%s" % ("Package", "Installed", "Message")) + print() for pkgname in args: pkg = db.find(pkgname) if pkg: @@ -1052,7 +1052,7 @@ else: status = 'error' msg = 'No such package' - print "%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg) + print("%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg)) if verbose and status == "no": prereq = pkg.prerequisites() for pkg, msg in prereq: @@ -1060,22 +1060,22 @@ pkg = '' else: pkg = pkg.fullname() - print "%-20.20s\tRequirement: %s %s" % ("", pkg, msg) + print("%-20.20s\tRequirement: %s %s" % ("", pkg, msg)) elif mode == 'install': if not args: - print 'Please specify packages to install' + print('Please specify packages to install') sys.exit(1) inst = PimpInstaller(db) for pkgname in args: pkg = db.find(pkgname) if not pkg: - print '%s: No such package' % pkgname + print('%s: No such package' % pkgname) continue list, messages = inst.prepareInstall(pkg, force) if messages and not force: - print "%s: Not installed:" % pkgname + print("%s: Not installed:" % pkgname) for m in messages: - print "\t", m + print("\t", m) else: if verbose: output = sys.stdout @@ -1083,26 +1083,26 @@ output = None messages = inst.install(list, output) if messages: - print "%s: Not installed:" % pkgname + print("%s: Not installed:" % pkgname) for m in messages: - print "\t", m + print("\t", m) def main(): """Minimal commandline tool to drive pimp.""" import getopt def _help(): - print "Usage: pimp [options] -s [package ...] List installed status" - print " pimp [options] -l [package ...] Show package information" - print " pimp [options] -i package ... Install packages" - print " pimp -d Dump database to stdout" - print " pimp -V Print version number" - print "Options:" - print " -v Verbose" - print " -f Force installation" - print " -D dir Set destination directory" - print " (default: %s)" % DEFAULT_INSTALLDIR - print " -u url URL for database" + print("Usage: pimp [options] -s [package ...] List installed status") + print(" pimp [options] -l [package ...] Show package information") + print(" pimp [options] -i package ... Install packages") + print(" pimp -d Dump database to stdout") + print(" pimp -V Print version number") + print("Options:") + print(" -v Verbose") + print(" -f Force installation") + print(" -D dir Set destination directory") + print(" (default: %s)" % DEFAULT_INSTALLDIR) + print(" -u url URL for database") sys.exit(1) class _Watcher: @@ -1152,7 +1152,7 @@ if not mode: _help() if mode == 'version': - print 'Pimp version %s; module name is %s' % (PIMP_VERSION, __name__) + print('Pimp version %s; module name is %s' % (PIMP_VERSION, __name__)) else: _run(mode, verbose, force, args, prefargs, watcher) Modified: python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py Fri Feb 23 18:29:35 2007 @@ -268,8 +268,7 @@ def writeDict(self, d): self.beginElement("dict") - items = d.items() - items.sort() + items = sorted(d.items()) for key, value in items: if not isinstance(key, (str, unicode)): raise TypeError("keys must be strings") Modified: python/branches/p3yk-noslice/Lib/plat-mac/videoreader.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/videoreader.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/videoreader.py Fri Feb 23 18:29:35 2007 @@ -272,8 +272,8 @@ fname = 'frame%04.4d.jpg'%num num = num+1 pname = os.path.join(dstdir, fname) - if not img: print 'Not', - print 'Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data)) + if not img: print('Not', end=' ') + print('Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data))) if img: wrt = img.writer(imgfmt, pname) wrt.width = imgw @@ -282,9 +282,9 @@ timestamp, data = rdr.ReadVideo() MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG') if num > 20: - print 'stopping at 20 frames so your disk does not fill up:-)' + print('stopping at 20 frames so your disk does not fill up:-)') break - print 'Total frames:', num + print('Total frames:', num) if __name__ == '__main__': _test() Modified: python/branches/p3yk-noslice/Lib/plat-os2emx/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-os2emx/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-os2emx/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-os2emx/_emx_link.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-os2emx/_emx_link.py (original) +++ python/branches/p3yk-noslice/Lib/plat-os2emx/_emx_link.py Fri Feb 23 18:29:35 2007 @@ -74,6 +74,6 @@ try: link(sys.argv[1], sys.argv[2]) except IndexError: - print 'Usage: emx_link ' + print('Usage: emx_link ') except OSError: - print 'emx_link: %s' % str(sys.exc_info()[1]) + print('emx_link: %s' % str(sys.exc_info()[1])) Modified: python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py (original) +++ python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py Fri Feb 23 18:29:35 2007 @@ -60,12 +60,12 @@ "/foo/bar/index.html", "/foo/bar/", "/"]: - print '%r -> %r' % (url, url2pathname(url)) - print "*******************************************************" + print('%r -> %r' % (url, url2pathname(url))) + print("*******************************************************") for path in ["SCSI::SCSI4.$.Anwendung", "PythonApp:Lib", "PythonApp:Lib.rourl2path/py"]: - print '%r -> %r' % (path, pathname2url(path)) + print('%r -> %r' % (path, pathname2url(path))) if __name__ == '__main__': test() Modified: python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-sunos5/STROPTS.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py (original) +++ python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-sunos5/TYPES.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-sunos5/TYPES.py (original) +++ python/branches/p3yk-noslice/Lib/plat-sunos5/TYPES.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-unixware7/IN.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py (original) +++ python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py Fri Feb 23 18:29:35 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-noslice/Lib/plat-unixware7/STROPTS.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py (original) +++ python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py Fri Feb 23 18:29:35 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-noslice/Lib/platform.py ============================================================================== --- python/branches/p3yk-noslice/Lib/platform.py (original) +++ python/branches/p3yk-noslice/Lib/platform.py Fri Feb 23 18:29:35 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(): -def dist(distname='',version='',id='', + 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)) - supported_dists=('SuSE', 'debian', 'fedora', 'redhat', 'mandrake')): +def linux_distribution(distname='', version='', id='', + + 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] == '.': @@ -593,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 @@ -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\.]+)') + +_sys_version_cache = {} -def _sys_version(): +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 + + # 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 - 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 + # 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, @@ -1250,5 +1480,5 @@ # Default is to print the aliased verbose platform string terse = ('terse' in sys.argv or '--terse' in sys.argv) aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv) - print platform(aliased,terse) + print(platform(aliased,terse)) sys.exit(0) Modified: python/branches/p3yk-noslice/Lib/popen2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/popen2.py (original) +++ python/branches/p3yk-noslice/Lib/popen2.py Fri Feb 23 18:29:35 2007 @@ -213,14 +213,14 @@ # sometimes adding an extra newline at the start or the # end. So we strip whitespace off both ends for comparison. expected = teststr.strip() - print "testing popen2..." + print("testing popen2...") r, w = popen2(cmd) w.write(teststr) w.close() got = r.read() if got.strip() != expected: raise ValueError("wrote %r read %r" % (teststr, got)) - print "testing popen3..." + print("testing popen3...") try: r, w, e = popen3([cmd]) except: @@ -238,7 +238,7 @@ _cleanup() if _active: raise ValueError("_active not empty") - print "All OK" + print("All OK") if __name__ == '__main__': _test() Modified: python/branches/p3yk-noslice/Lib/poplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/poplib.py (original) +++ python/branches/p3yk-noslice/Lib/poplib.py Fri Feb 23 18:29:35 2007 @@ -100,14 +100,14 @@ def _putline(self, line): - if self._debugging > 1: print '*put*', repr(line) + if self._debugging > 1: print('*put*', repr(line)) self.sock.sendall('%s%s' % (line, CRLF)) # Internal: send one command to the server (through _putline()) def _putcmd(self, line): - if self._debugging: print '*cmd*', repr(line) + if self._debugging: print('*cmd*', repr(line)) self._putline(line) @@ -117,7 +117,7 @@ def _getline(self): line = self.file.readline() - if self._debugging > 1: print '*get*', repr(line) + if self._debugging > 1: print('*get*', repr(line)) if not line: raise error_proto('-ERR EOF') octets = len(line) # server can send any combination of CR & LF @@ -135,7 +135,7 @@ def _getresp(self): resp, o = self._getline() - if self._debugging > 1: print '*resp*', repr(resp) + if self._debugging > 1: print('*resp*', repr(resp)) c = resp[:1] if c != '+': raise error_proto(resp) @@ -209,7 +209,7 @@ """ retval = self._shortcmd('STAT') rets = retval.split() - if self._debugging: print '*stat*', repr(rets) + if self._debugging: print('*stat*', repr(rets)) numMessages = int(rets[1]) sizeMessages = int(rets[2]) return (numMessages, sizeMessages) @@ -375,7 +375,7 @@ match = renewline.match(self.buffer) line = match.group(0) self.buffer = renewline.sub('' ,self.buffer, 1) - if self._debugging > 1: print '*get*', repr(line) + if self._debugging > 1: print('*get*', repr(line)) octets = len(line) if line[-2:] == CRLF: @@ -385,7 +385,7 @@ return line[:-1], octets def _putline(self, line): - if self._debugging > 1: print '*put*', repr(line) + if self._debugging > 1: print('*put*', repr(line)) line += CRLF bytes = len(line) while bytes > 0: @@ -409,15 +409,15 @@ if __name__ == "__main__": import sys a = POP3(sys.argv[1]) - print a.getwelcome() + print(a.getwelcome()) a.user(sys.argv[2]) a.pass_(sys.argv[3]) a.list() (numMsgs, totalSize) = a.stat() for i in range(1, numMsgs + 1): (header, msg, octets) = a.retr(i) - print "Message %d:" % i + print("Message %d:" % i) for line in msg: - print ' ' + line - print '-----------------------' + print(' ' + line) + print('-----------------------') a.quit() Modified: python/branches/p3yk-noslice/Lib/pprint.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pprint.py (original) +++ python/branches/p3yk-noslice/Lib/pprint.py Fri Feb 23 18:29:35 2007 @@ -141,8 +141,7 @@ if length: context[objid] = 1 indent = indent + self._indent_per_level - items = object.items() - items.sort() + items = sorted(object.items()) key, ent = items[0] rep = self._repr(key, context, level) write(rep) @@ -313,8 +312,8 @@ t2 = time.time() p.pformat(object) t3 = time.time() - print "_safe_repr:", t2 - t1 - print "pformat:", t3 - t2 + print("_safe_repr:", t2 - t1) + print("pformat:", t3 - t2) if __name__ == "__main__": _perfcheck() Modified: python/branches/p3yk-noslice/Lib/profile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/profile.py (original) +++ python/branches/p3yk-noslice/Lib/profile.py Fri Feb 23 18:29:35 2007 @@ -94,8 +94,8 @@ # Backwards compatibility. def help(): - print "Documentation for the profile module can be found " - print "in the Python Library Reference, section 'The Python Profiler'." + print("Documentation for the profile module can be found ") + print("in the Python Library Reference, section 'The Python Profiler'.") if os.name == "mac": import MacOS @@ -439,10 +439,10 @@ def snapshot_stats(self): self.stats = {} - for func, (cc, ns, tt, ct, callers) in self.timings.iteritems(): + for func, (cc, ns, tt, ct, callers) in self.timings.items(): callers = callers.copy() nc = 0 - for callcnt in callers.itervalues(): + for callcnt in callers.values(): nc += callcnt self.stats[func] = cc, nc, tt, ct, callers @@ -550,7 +550,7 @@ t1 = get_time() elapsed_noprofile = t1 - t0 if verbose: - print "elapsed time without profiling =", elapsed_noprofile + print("elapsed time without profiling =", elapsed_noprofile) # elapsed_profile <- time f(m) takes with profiling. The difference # is profiling overhead, only some of which the profiler subtracts @@ -561,7 +561,7 @@ t1 = get_time() elapsed_profile = t1 - t0 if verbose: - print "elapsed time with profiling =", elapsed_profile + print("elapsed time with profiling =", elapsed_profile) # reported_time <- "CPU seconds" the profiler charged to f and f1. total_calls = 0.0 @@ -573,8 +573,8 @@ reported_time += tt if verbose: - print "'CPU seconds' profiler reported =", reported_time - print "total # calls =", total_calls + print("'CPU seconds' profiler reported =", reported_time) + print("total # calls =", total_calls) if total_calls != m + 1: raise ValueError("internal error: total calls = %d" % total_calls) @@ -584,12 +584,12 @@ # overhead per event. mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls if verbose: - print "mean stopwatch overhead per profile event =", mean + print("mean stopwatch overhead per profile event =", mean) return mean #**************************************************************************** def Stats(*args): - print 'Report generating functions are in the "pstats" module\a' + print('Report generating functions are in the "pstats" module\a') def main(): usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..." Modified: python/branches/p3yk-noslice/Lib/pstats.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pstats.py (original) +++ python/branches/p3yk-noslice/Lib/pstats.py Fri Feb 23 18:29:35 2007 @@ -110,9 +110,9 @@ trouble = 0 finally: if trouble: - print >> self.stream, "Invalid timing data", - if self.files: print >> self.stream, self.files[-1], - print >> self.stream + print("Invalid timing data", end=' ', file=self.stream) + if self.files: print(self.files[-1], end=' ', file=self.stream) + print(file=self.stream) def load_stats(self, arg): if not arg: self.stats = {} @@ -163,7 +163,7 @@ self.fcn_list = None - for func, stat in other.stats.iteritems(): + for func, stat in other.stats.items(): if func in self.stats: old_func_stat = self.stats[func] else: @@ -199,7 +199,7 @@ if not self.sort_arg_dict: self.sort_arg_dict = dict = {} bad_list = {} - for word, tup in self.sort_arg_dict_default.iteritems(): + for word, tup in self.sort_arg_dict_default.items(): fragment = word while fragment: if not fragment: @@ -234,7 +234,7 @@ connector = ", " stats_list = [] - for func, (cc, nc, tt, ct, callers) in self.stats.iteritems(): + for func, (cc, nc, tt, ct, callers) in self.stats.items(): stats_list.append((cc, nc, tt, ct) + func + (func_std_string(func), func)) @@ -254,12 +254,12 @@ oldstats = self.stats self.stats = newstats = {} max_name_len = 0 - for func, (cc, nc, tt, ct, callers) in oldstats.iteritems(): + for func, (cc, nc, tt, ct, callers) in oldstats.items(): newfunc = func_strip_path(func) if len(func_std_string(newfunc)) > max_name_len: max_name_len = len(func_std_string(newfunc)) newcallers = {} - for func2, caller in callers.iteritems(): + for func2, caller in callers.items(): newcallers[func_strip_path(func2)] = caller if newfunc in newstats: @@ -282,10 +282,10 @@ def calc_callees(self): if self.all_callees: return self.all_callees = all_callees = {} - for func, (cc, nc, tt, ct, callers) in self.stats.iteritems(): + for func, (cc, nc, tt, ct, callers) in self.stats.items(): if not func in all_callees: all_callees[func] = {} - for func2, caller in callers.iteritems(): + for func2, caller in callers.items(): if not func2 in all_callees: all_callees[func2] = {} all_callees[func2][func] = caller @@ -334,7 +334,7 @@ if not list: return 0, list - print >> self.stream, msg + print(msg, file=self.stream) if count < len(self.stats): width = 0 for func in list: @@ -344,24 +344,24 @@ def print_stats(self, *amount): for filename in self.files: - print >> self.stream, filename - if self.files: print >> self.stream + print(filename, file=self.stream) + if self.files: print(file=self.stream) indent = ' ' * 8 for func in self.top_level: - print >> self.stream, indent, func_get_function_name(func) + print(indent, func_get_function_name(func), file=self.stream) - print >> self.stream, indent, self.total_calls, "function calls", + print(indent, self.total_calls, "function calls", end=' ', file=self.stream) if self.total_calls != self.prim_calls: - print >> self.stream, "(%d primitive calls)" % self.prim_calls, - print >> self.stream, "in %.3f CPU seconds" % self.total_tt - print >> self.stream + print("(%d primitive calls)" % self.prim_calls, end=' ', file=self.stream) + print("in %.3f CPU seconds" % self.total_tt, file=self.stream) + print(file=self.stream) width, list = self.get_print_list(amount) if list: self.print_title() for func in list: self.print_line(func) - print >> self.stream - print >> self.stream + print(file=self.stream) + print(file=self.stream) return self def print_callees(self, *amount): @@ -375,8 +375,8 @@ self.print_call_line(width, func, self.all_callees[func]) else: self.print_call_line(width, func, {}) - print >> self.stream - print >> self.stream + print(file=self.stream) + print(file=self.stream) return self def print_callers(self, *amount): @@ -386,29 +386,28 @@ for func in list: cc, nc, tt, ct, callers = self.stats[func] self.print_call_line(width, func, callers, "<-") - print >> self.stream - print >> self.stream + print(file=self.stream) + print(file=self.stream) return self def print_call_heading(self, name_size, column_title): - print >> self.stream, "Function ".ljust(name_size) + column_title + print("Function ".ljust(name_size) + column_title, file=self.stream) # print sub-header only if we have new-style callers subheader = False - for cc, nc, tt, ct, callers in self.stats.itervalues(): + for cc, nc, tt, ct, callers in self.stats.values(): if callers: - value = callers.itervalues().next() + value = iter(callers.values()).next() subheader = isinstance(value, tuple) break if subheader: - print >> self.stream, " "*name_size + " ncalls tottime cumtime" + print(" "*name_size + " ncalls tottime cumtime", file=self.stream) def print_call_line(self, name_size, source, call_dict, arrow="->"): - print >> self.stream, func_std_string(source).ljust(name_size) + arrow, + print(func_std_string(source).ljust(name_size) + arrow, end=' ', file=self.stream) if not call_dict: - print >> self.stream + print(file=self.stream) return - clist = call_dict.keys() - clist.sort() + clist = sorted(call_dict.keys()) indent = "" for func in clist: name = func_std_string(func) @@ -425,30 +424,30 @@ else: substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3])) left_width = name_size + 3 - print >> self.stream, indent*left_width + substats + print(indent*left_width + substats, file=self.stream) indent = " " def print_title(self): - print >> self.stream, ' ncalls tottime percall cumtime percall', - print >> self.stream, 'filename:lineno(function)' + print(' ncalls tottime percall cumtime percall', end=' ', file=self.stream) + print('filename:lineno(function)', file=self.stream) def print_line(self, func): # hack : should print percentages cc, nc, tt, ct, callers = self.stats[func] c = str(nc) if nc != cc: c = c + '/' + str(cc) - print >> self.stream, c.rjust(9), - print >> self.stream, f8(tt), + print(c.rjust(9), end=' ', file=self.stream) + print(f8(tt), end=' ', file=self.stream) if nc == 0: - print >> self.stream, ' '*8, + print(' '*8, end=' ', file=self.stream) else: - print >> self.stream, f8(tt/nc), - print >> self.stream, f8(ct), + print(f8(tt/nc), end=' ', file=self.stream) + print(f8(ct), end=' ', file=self.stream) if cc == 0: - print >> self.stream, ' '*8, + print(' '*8, end=' ', file=self.stream) else: - print >> self.stream, f8(ct/cc), - print >> self.stream, func_std_string(func) + print(f8(ct/cc), end=' ', file=self.stream) + print(func_std_string(func), file=self.stream) class TupleComp: """This class provides a generic function for comparing any two tuples. @@ -508,9 +507,9 @@ def add_callers(target, source): """Combine two caller lists in a single list.""" new_callers = {} - for func, caller in target.iteritems(): + for func, caller in target.items(): new_callers[func] = caller - for func, caller in source.iteritems(): + for func, caller in source.items(): if func in new_callers: new_callers[func] = caller + new_callers[func] else: @@ -520,7 +519,7 @@ def count_calls(callers): """Sum the caller statistics to get total number of calls received.""" nc = 0 - for calls in callers.itervalues(): + for calls in callers.values(): nc += calls return nc @@ -565,7 +564,7 @@ try: frac = float(term) if frac > 1 or frac < 0: - print >> self.stream, "Fraction argument must be in [0, 1]" + print("Fraction argument must be in [0, 1]", file=self.stream) continue processed.append(frac) continue @@ -575,93 +574,93 @@ if self.stats: getattr(self.stats, fn)(*processed) else: - print >> self.stream, "No statistics object is loaded." + print("No statistics object is loaded.", file=self.stream) return 0 def generic_help(self): - print >> self.stream, "Arguments may be:" - print >> self.stream, "* An integer maximum number of entries to print." - print >> self.stream, "* A decimal fractional number between 0 and 1, controlling" - print >> self.stream, " what fraction of selected entries to print." - print >> self.stream, "* A regular expression; only entries with function names" - print >> self.stream, " that match it are printed." + print("Arguments may be:", file=self.stream) + print("* An integer maximum number of entries to print.", file=self.stream) + print("* A decimal fractional number between 0 and 1, controlling", file=self.stream) + print(" what fraction of selected entries to print.", file=self.stream) + print("* A regular expression; only entries with function names", file=self.stream) + print(" that match it are printed.", file=self.stream) def do_add(self, line): self.stats.add(line) return 0 def help_add(self): - print >> self.stream, "Add profile info from given file to current statistics object." + print("Add profile info from given file to current statistics object.", file=self.stream) def do_callees(self, line): return self.generic('print_callees', line) def help_callees(self): - print >> self.stream, "Print callees statistics from the current stat object." + print("Print callees statistics from the current stat object.", file=self.stream) self.generic_help() def do_callers(self, line): return self.generic('print_callers', line) def help_callers(self): - print >> self.stream, "Print callers statistics from the current stat object." + print("Print callers statistics from the current stat object.", file=self.stream) self.generic_help() def do_EOF(self, line): - print >> self.stream, "" + print("", file=self.stream) return 1 def help_EOF(self): - print >> self.stream, "Leave the profile brower." + print("Leave the profile brower.", file=self.stream) def do_quit(self, line): return 1 def help_quit(self): - print >> self.stream, "Leave the profile brower." + print("Leave the profile brower.", file=self.stream) def do_read(self, line): if line: try: self.stats = Stats(line) except IOError as args: - print >> self.stream, args[1] + print(args[1], file=self.stream) return self.prompt = line + "% " elif len(self.prompt) > 2: line = self.prompt[-2:] else: - print >> self.stream, "No statistics object is current -- cannot reload." + print("No statistics object is current -- cannot reload.", file=self.stream) return 0 def help_read(self): - print >> self.stream, "Read in profile data from a specified file." + print("Read in profile data from a specified file.", file=self.stream) def do_reverse(self, line): self.stats.reverse_order() return 0 def help_reverse(self): - print >> self.stream, "Reverse the sort order of the profiling report." + print("Reverse the sort order of the profiling report.", file=self.stream) def do_sort(self, line): abbrevs = self.stats.get_sort_arg_defs() if line and not filter(lambda x,a=abbrevs: x not in a,line.split()): self.stats.sort_stats(*line.split()) else: - print >> self.stream, "Valid sort keys (unique prefixes are accepted):" - for (key, value) in Stats.sort_arg_dict_default.iteritems(): - print >> self.stream, "%s -- %s" % (key, value[1]) + print("Valid sort keys (unique prefixes are accepted):", file=self.stream) + for (key, value) in Stats.sort_arg_dict_default.items(): + print("%s -- %s" % (key, value[1]), file=self.stream) return 0 def help_sort(self): - print >> self.stream, "Sort profile data according to specified keys." - print >> self.stream, "(Typing `sort' without arguments lists valid keys.)" + print("Sort profile data according to specified keys.", file=self.stream) + print("(Typing `sort' without arguments lists valid keys.)", file=self.stream) def complete_sort(self, text, *args): return [a for a in Stats.sort_arg_dict_default if a.startswith(text)] def do_stats(self, line): return self.generic('print_stats', line) def help_stats(self): - print >> self.stream, "Print statistics from the current stat object." + print("Print statistics from the current stat object.", file=self.stream) self.generic_help() def do_strip(self, line): self.stats.strip_dirs() return 0 def help_strip(self): - print >> self.stream, "Strip leading path information from filenames in the report." + print("Strip leading path information from filenames in the report.", file=self.stream) def postcmd(self, stop, line): if stop: @@ -675,9 +674,9 @@ initprofile = None try: browser = ProfileBrowser(initprofile) - print >> browser.stream, "Welcome to the profile statistics browser." + print("Welcome to the profile statistics browser.", file=browser.stream) browser.cmdloop() - print >> browser.stream, "Goodbye." + print("Goodbye.", file=browser.stream) except KeyboardInterrupt: pass Modified: python/branches/p3yk-noslice/Lib/pty.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pty.py (original) +++ python/branches/p3yk-noslice/Lib/pty.py Fri Feb 23 18:29:35 2007 @@ -123,7 +123,7 @@ os.close(tmp_fd) else: os.close(slave_fd) - + # Parent and child process. return pid, master_fd Modified: python/branches/p3yk-noslice/Lib/py_compile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/py_compile.py (original) +++ python/branches/p3yk-noslice/Lib/py_compile.py Fri Feb 23 18:29:35 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-noslice/Lib/pyclbr.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pyclbr.py (original) +++ python/branches/p3yk-noslice/Lib/pyclbr.py Fri Feb 23 18:29:35 2007 @@ -328,13 +328,13 @@ getattr(b, 'lineno', 0))) for obj in objs: if isinstance(obj, Class): - print "class", obj.name, obj.super, obj.lineno - methods = sorted(obj.methods.iteritems(), key=itemgetter(1)) + print("class", obj.name, obj.super, obj.lineno) + methods = sorted(obj.methods.items(), key=itemgetter(1)) for name, lineno in methods: if name != "__path__": - print " def", name, lineno + print(" def", name, lineno) elif isinstance(obj, Function): - print "def", obj.name, obj.lineno + print("def", obj.name, obj.lineno) if __name__ == "__main__": _main() Modified: python/branches/p3yk-noslice/Lib/pydoc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pydoc.py (original) +++ python/branches/p3yk-noslice/Lib/pydoc.py Fri Feb 23 18:29:35 2007 @@ -1468,19 +1468,19 @@ 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)): + 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) desc += ' object' pager(title % desc + '\n\n' + text.document(object, name)) except (ImportError, ErrorDuringImport) as value: - print value + print(value) def writedoc(thing, forceload=0): """Write HTML documentation to a file in the current directory.""" @@ -1490,9 +1490,9 @@ file = open(name + '.html', 'w') file.write(page) file.close() - print 'wrote', name + '.html' + print('wrote', name + '.html') except (ImportError, ErrorDuringImport) as value: - print value + print(value) def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" @@ -1883,7 +1883,7 @@ def callback(path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' - print modname, desc and '- ' + desc + print(modname, desc and '- ' + desc) try: import warnings except ImportError: pass else: warnings.filterwarnings('ignore') # ignore problems during import @@ -2200,9 +2200,9 @@ except ValueError: raise BadUsage def ready(server): - print 'pydoc server ready at %s' % server.url + print('pydoc server ready at %s' % server.url) def stopped(): - print 'pydoc server stopped' + print('pydoc server stopped') serve(port, ready, stopped) return if opt == '-w': @@ -2211,7 +2211,7 @@ if not args: raise BadUsage for arg in args: if ispath(arg) and not os.path.exists(arg): - print 'file %r does not exist' % arg + print('file %r does not exist' % arg) break try: if ispath(arg) and os.path.isfile(arg): @@ -2224,11 +2224,11 @@ else: help.help(arg) except ErrorDuringImport as value: - print value + print(value) except (getopt.error, BadUsage): cmd = os.path.basename(sys.argv[0]) - print """pydoc - the Python documentation tool + print("""pydoc - the Python documentation tool %s ... Show text documentation on something. may be the name of a @@ -2251,6 +2251,6 @@ Write out the HTML documentation for a module to a file in the current directory. If contains a '%s', it is treated as a filename; if it names a directory, documentation is written for all the contents. -""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep) +""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)) if __name__ == '__main__': cli() Modified: python/branches/p3yk-noslice/Lib/quopri.py ============================================================================== --- python/branches/p3yk-noslice/Lib/quopri.py (original) +++ python/branches/p3yk-noslice/Lib/quopri.py Fri Feb 23 18:29:35 2007 @@ -196,10 +196,10 @@ opts, args = getopt.getopt(sys.argv[1:], 'td') except getopt.error as msg: sys.stdout = sys.stderr - print msg - print "usage: quopri [-t | -d] [file] ..." - print "-t: quote tabs" - print "-d: decode; default encode" + print(msg) + print("usage: quopri [-t | -d] [file] ...") + print("-t: quote tabs") + print("-d: decode; default encode") sys.exit(2) deco = 0 tabs = 0 @@ -208,7 +208,7 @@ if o == '-d': deco = 1 if tabs and deco: sys.stdout = sys.stderr - print "-t and -d are mutually exclusive" + print("-t and -d are mutually exclusive") sys.exit(2) if not args: args = ['-'] sts = 0 Modified: python/branches/p3yk-noslice/Lib/random.py ============================================================================== --- python/branches/p3yk-noslice/Lib/random.py (original) +++ python/branches/p3yk-noslice/Lib/random.py Fri Feb 23 18:29:35 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< -1 and beta} > -1. + Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. """ @@ -626,12 +626,12 @@ 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 - if not isinstance(a, (int, long)): + if not isinstance(a, (int, int)): a = hash(a) a, x = divmod(a, 30268) @@ -721,7 +721,7 @@ if 0 == x == y == z: # Initialize from current time import time - t = long(time.time() * 256) + t = int(time.time() * 256) t = int((t&0xffffff) ^ (t>>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): @@ -792,7 +792,7 @@ def _test_generator(n, func, args): import time - print n, 'times', func.__name__ + print(n, 'times', func.__name__) total = 0.0 sqsum = 0.0 smallest = 1e10 @@ -805,11 +805,11 @@ smallest = min(x, smallest) largest = max(x, largest) t1 = time.time() - print round(t1-t0, 3), 'sec,', + print(round(t1-t0, 3), 'sec,', end=' ') avg = total/n stddev = _sqrt(sqsum/n - avg*avg) - print 'avg %g, stddev %g, min %g, max %g' % \ - (avg, stddev, smallest, largest) + print('avg %g, stddev %g, min %g, max %g' % \ + (avg, stddev, smallest, largest)) def _test(N=2000): Modified: python/branches/p3yk-noslice/Lib/repr.py ============================================================================== --- python/branches/p3yk-noslice/Lib/repr.py (original) +++ python/branches/p3yk-noslice/Lib/repr.py Fri Feb 23 18:29:35 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) Modified: python/branches/p3yk-noslice/Lib/rexec.py ============================================================================== --- python/branches/p3yk-noslice/Lib/rexec.py (original) +++ python/branches/p3yk-noslice/Lib/rexec.py Fri Feb 23 18:29:35 2007 @@ -552,7 +552,7 @@ try: fp = open(args[0]) except IOError as msg: - print "%s: can't open file %r" % (sys.argv[0], args[0]) + print("%s: can't open file %r" % (sys.argv[0], args[0])) return 1 if fp.isatty(): try: Modified: python/branches/p3yk-noslice/Lib/rfc822.py ============================================================================== --- python/branches/p3yk-noslice/Lib/rfc822.py (original) +++ python/branches/p3yk-noslice/Lib/rfc822.py Fri Feb 23 18:29:35 2007 @@ -437,18 +437,18 @@ def keys(self): """Get all of a message's header field names.""" - return self.dict.keys() + return list(self.dict.keys()) def values(self): """Get all of a message's header field values.""" - return self.dict.values() + return list(self.dict.values()) def items(self): """Get all of a message's headers. Returns a list of name, value tuples. """ - return self.dict.items() + return list(self.dict.items()) def __str__(self): return ''.join(self.headers) @@ -850,6 +850,11 @@ if data[0][-1] in (',', '.') or data[0].lower() in _daynames: # There's a dayname here. Skip it del data[0] + else: + # no space after the "weekday,"? + i = data[0].rfind(',') + if i >= 0: + data[0] = data[0][i+1:] if len(data) == 3: # RFC 850 date, deprecated stuff = data[0].split('-') if len(stuff) == 3: @@ -967,32 +972,32 @@ if sys.argv[1:]: file = sys.argv[1] f = open(file, 'r') m = Message(f) - print 'From:', m.getaddr('from') - print 'To:', m.getaddrlist('to') - print 'Subject:', m.getheader('subject') - print 'Date:', m.getheader('date') + print('From:', m.getaddr('from')) + print('To:', m.getaddrlist('to')) + print('Subject:', m.getheader('subject')) + print('Date:', m.getheader('date')) date = m.getdate_tz('date') tz = date[-1] date = time.localtime(mktime_tz(date)) if date: - print 'ParsedDate:', time.asctime(date), + print('ParsedDate:', time.asctime(date), end=' ') hhmmss = tz hhmm, ss = divmod(hhmmss, 60) hh, mm = divmod(hhmm, 60) - print "%+03d%02d" % (hh, mm), - if ss: print ".%02d" % ss, - print + print("%+03d%02d" % (hh, mm), end=' ') + if ss: print(".%02d" % ss, end=' ') + print() else: - print 'ParsedDate:', None + print('ParsedDate:', None) m.rewindbody() n = 0 while f.readline(): n += 1 - print 'Lines:', n - print '-'*70 - print 'len =', len(m) - if 'Date' in m: print 'Date =', m['Date'] + print('Lines:', n) + print('-'*70) + print('len =', len(m)) + if 'Date' in m: print('Date =', m['Date']) if 'X-Nonsense' in m: pass - print 'keys =', m.keys() - print 'values =', m.values() - print 'items =', m.items() + print('keys =', m.keys()) + print('values =', m.values()) + print('items =', m.items()) Modified: python/branches/p3yk-noslice/Lib/robotparser.py ============================================================================== --- python/branches/p3yk-noslice/Lib/robotparser.py (original) +++ python/branches/p3yk-noslice/Lib/robotparser.py Fri Feb 23 18:29:35 2007 @@ -16,7 +16,7 @@ debug = 0 def _debug(msg): - if debug: print msg + if debug: print(msg) class RobotFileParser: @@ -244,10 +244,10 @@ else: ac = "access allowed" if a!=b: - print "failed" + print("failed") else: - print "ok (%s)" % ac - print + print("ok (%s)" % ac) + print() def _test(): global debug Modified: python/branches/p3yk-noslice/Lib/runpy.py ============================================================================== --- python/branches/p3yk-noslice/Lib/runpy.py (original) +++ python/branches/p3yk-noslice/Lib/runpy.py Fri Feb 23 18:29:35 2007 @@ -98,7 +98,7 @@ if __name__ == "__main__": # Run the module specified as the next command line argument if len(sys.argv) < 2: - print >> sys.stderr, "No module specified for execution" + print("No module specified for execution", file=sys.stderr) else: del sys.argv[0] # Make the requested module sys.argv[0] run_module(sys.argv[0], run_name="__main__", alter_sys=True) Modified: python/branches/p3yk-noslice/Lib/sgmllib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sgmllib.py (original) +++ python/branches/p3yk-noslice/Lib/sgmllib.py Fri Feb 23 18:29:35 2007 @@ -382,8 +382,8 @@ # Example -- report an unbalanced tag. def report_unbalanced(self, tag): if self.verbose: - print '*** Unbalanced ' - print '*** Stack:', self.stack + print('*** Unbalanced ') + print('*** Stack:', self.stack) def convert_charref(self, name): """Convert character reference, may be overridden.""" @@ -468,40 +468,40 @@ data = self.testdata if data: self.testdata = "" - print 'data:', repr(data) + print('data:', repr(data)) def handle_comment(self, data): self.flush() r = repr(data) if len(r) > 68: r = r[:32] + '...' + r[-32:] - print 'comment:', r + print('comment:', r) def unknown_starttag(self, tag, attrs): self.flush() if not attrs: - print 'start tag: <' + tag + '>' + print('start tag: <' + tag + '>') else: - print 'start tag: <' + tag, + print('start tag: <' + tag, end=' ') for name, value in attrs: - print name + '=' + '"' + value + '"', - print '>' + print(name + '=' + '"' + value + '"', end=' ') + print('>') def unknown_endtag(self, tag): self.flush() - print 'end tag: ' + print('end tag: ') def unknown_entityref(self, ref): self.flush() - print '*** unknown entity ref: &' + ref + ';' + print('*** unknown entity ref: &' + ref + ';') def unknown_charref(self, ref): self.flush() - print '*** unknown char ref: &#' + ref + ';' + print('*** unknown char ref: &#' + ref + ';') def unknown_decl(self, data): self.flush() - print '*** unknown decl: [' + data + ']' + print('*** unknown decl: [' + data + ']') def close(self): SGMLParser.close(self) @@ -531,7 +531,7 @@ try: f = open(file, 'r') except IOError as msg: - print file, ":", msg + print(file, ":", msg) sys.exit(1) data = f.read() Modified: python/branches/p3yk-noslice/Lib/shelve.py ============================================================================== --- python/branches/p3yk-noslice/Lib/shelve.py (original) +++ python/branches/p3yk-noslice/Lib/shelve.py Fri Feb 23 18:29:35 2007 @@ -144,7 +144,7 @@ def sync(self): if self.writeback and self.cache: self.writeback = False - for key, entry in self.cache.iteritems(): + for key, entry in self.cache.items(): self[key] = entry self.writeback = True self.cache = {} Modified: python/branches/p3yk-noslice/Lib/shlex.py ============================================================================== --- python/branches/p3yk-noslice/Lib/shlex.py (original) +++ python/branches/p3yk-noslice/Lib/shlex.py Fri Feb 23 18:29:35 2007 @@ -53,13 +53,13 @@ self.filestack = deque() self.source = None if self.debug: - print 'shlex: reading from %s, line %d' \ - % (self.instream, self.lineno) + print('shlex: reading from %s, line %d' \ + % (self.instream, self.lineno)) def push_token(self, tok): "Push a token onto the stack popped by the get_token method" if self.debug >= 1: - print "shlex: pushing token " + repr(tok) + print("shlex: pushing token " + repr(tok)) self.pushback.appendleft(tok) def push_source(self, newstream, newfile=None): @@ -72,17 +72,17 @@ self.lineno = 1 if self.debug: if newfile is not None: - print 'shlex: pushing to file %s' % (self.infile,) + print('shlex: pushing to file %s' % (self.infile,)) else: - print 'shlex: pushing to stream %s' % (self.instream,) + print('shlex: pushing to stream %s' % (self.instream,)) def pop_source(self): "Pop the input source stack." self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() if self.debug: - print 'shlex: popping to %s, line %d' \ - % (self.instream, self.lineno) + print('shlex: popping to %s, line %d' \ + % (self.instream, self.lineno)) self.state = ' ' def get_token(self): @@ -90,7 +90,7 @@ if self.pushback: tok = self.pushback.popleft() if self.debug >= 1: - print "shlex: popping token " + repr(tok) + print("shlex: popping token " + repr(tok)) return tok # No pushback. Get a token. raw = self.read_token() @@ -112,9 +112,9 @@ # Neither inclusion nor EOF if self.debug >= 1: if raw != self.eof: - print "shlex: token=" + repr(raw) + print("shlex: token=" + repr(raw)) else: - print "shlex: token=EOF" + print("shlex: token=EOF") return raw def read_token(self): @@ -125,8 +125,8 @@ if nextchar == '\n': self.lineno = self.lineno + 1 if self.debug >= 3: - print "shlex: in state", repr(self.state), \ - "I see character:", repr(nextchar) + print("shlex: in state", repr(self.state), \ + "I see character:", repr(nextchar)) if self.state is None: self.token = '' # past end of file break @@ -136,7 +136,7 @@ break elif nextchar in self.whitespace: if self.debug >= 2: - print "shlex: I see whitespace in whitespace state" + print("shlex: I see whitespace in whitespace state") if self.token or (self.posix and quoted): break # emit current token else: @@ -167,7 +167,7 @@ quoted = True if not nextchar: # end of file if self.debug >= 2: - print "shlex: I see EOF in quotes state" + print("shlex: I see EOF in quotes state") # XXX what error should be raised here? raise ValueError, "No closing quotation" if nextchar == self.state: @@ -186,7 +186,7 @@ elif self.state in self.escape: if not nextchar: # end of file if self.debug >= 2: - print "shlex: I see EOF in escape state" + print("shlex: I see EOF in escape state") # XXX what error should be raised here? raise ValueError, "No escaped character" # In posix shells, only the quote itself or the escape @@ -202,7 +202,7 @@ break elif nextchar in self.whitespace: if self.debug >= 2: - print "shlex: I see whitespace in word state" + print("shlex: I see whitespace in word state") self.state = ' ' if self.token or (self.posix and quoted): break # emit current token @@ -228,7 +228,7 @@ else: self.pushback.appendleft(nextchar) if self.debug >= 2: - print "shlex: I see punctuation in word state" + print("shlex: I see punctuation in word state") self.state = ' ' if self.token: break # emit current token @@ -240,9 +240,9 @@ result = None if self.debug > 1: if result: - print "shlex: raw token=" + repr(result) + print("shlex: raw token=" + repr(result)) else: - print "shlex: raw token=EOF" + print("shlex: raw token=EOF") return result def sourcehook(self, newfile): @@ -287,6 +287,6 @@ while 1: tt = lexer.get_token() if tt: - print "Token: " + repr(tt) + print("Token: " + repr(tt)) else: break Modified: python/branches/p3yk-noslice/Lib/shutil.py ============================================================================== --- python/branches/p3yk-noslice/Lib/shutil.py (original) +++ python/branches/p3yk-noslice/Lib/shutil.py Fri Feb 23 18:29:35 2007 @@ -60,13 +60,15 @@ os.chmod(dst, mode) def copystat(src, dst): - """Copy all stat info (mode bits, atime and mtime) from src to dst""" + """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) + if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): + os.chflags(dst, st.st_flags) def copy(src, dst): Modified: python/branches/p3yk-noslice/Lib/site.py ============================================================================== --- python/branches/p3yk-noslice/Lib/site.py (original) +++ python/branches/p3yk-noslice/Lib/site.py Fri Feb 23 18:29:35 2007 @@ -301,7 +301,7 @@ while 1: try: for i in range(lineno, lineno + self.MAXLINES): - print self.__lines[i] + print(self.__lines[i]) except IndexError: break else: @@ -424,10 +424,10 @@ main() def _test(): - print "sys.path = [" + print("sys.path = [") for dir in sys.path: - print " %r," % (dir,) - print "]" + print(" %r," % (dir,)) + print("]") if __name__ == '__main__': _test() Modified: python/branches/p3yk-noslice/Lib/smtpd.py ============================================================================== --- python/branches/p3yk-noslice/Lib/smtpd.py (original) +++ python/branches/p3yk-noslice/Lib/smtpd.py Fri Feb 23 18:29:35 2007 @@ -98,9 +98,9 @@ def usage(code, msg=''): - print >> sys.stderr, __doc__ % globals() + print(__doc__ % globals(), file=sys.stderr) if msg: - print >> sys.stderr, msg + print(msg, file=sys.stderr) sys.exit(code) @@ -122,7 +122,7 @@ self.__data = '' self.__fqdn = socket.getfqdn() self.__peer = conn.getpeername() - print >> DEBUGSTREAM, 'Peer:', repr(self.__peer) + print('Peer:', repr(self.__peer), file=DEBUGSTREAM) self.push('220 %s %s' % (self.__fqdn, __version__)) self.set_terminator('\r\n') @@ -137,7 +137,7 @@ # Implementation of base class abstract method def found_terminator(self): line = EMPTYSTRING.join(self.__line) - print >> DEBUGSTREAM, 'Data:', repr(line) + print('Data:', repr(line), file=DEBUGSTREAM) self.__line = [] if self.__state == self.COMMAND: if not line: @@ -220,7 +220,7 @@ return address def smtp_MAIL(self, arg): - print >> DEBUGSTREAM, '===> MAIL', arg + print('===> MAIL', arg, file=DEBUGSTREAM) address = self.__getaddr('FROM:', arg) if not address: self.push('501 Syntax: MAIL FROM:
') @@ -229,11 +229,11 @@ self.push('503 Error: nested MAIL command') return self.__mailfrom = address - print >> DEBUGSTREAM, 'sender:', self.__mailfrom + print('sender:', self.__mailfrom, file=DEBUGSTREAM) self.push('250 Ok') def smtp_RCPT(self, arg): - print >> DEBUGSTREAM, '===> RCPT', arg + print('===> RCPT', arg, file=DEBUGSTREAM) if not self.__mailfrom: self.push('503 Error: need MAIL command') return @@ -242,7 +242,7 @@ self.push('501 Syntax: RCPT TO:
') return self.__rcpttos.append(address) - print >> DEBUGSTREAM, 'recips:', self.__rcpttos + print('recips:', self.__rcpttos, file=DEBUGSTREAM) self.push('250 Ok') def smtp_RSET(self, arg): @@ -279,14 +279,13 @@ self.set_reuse_addr() self.bind(localaddr) self.listen(5) - print >> DEBUGSTREAM, \ - '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( + print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( self.__class__.__name__, time.ctime(time.time()), - localaddr, remoteaddr) + localaddr, remoteaddr), file=DEBUGSTREAM) def handle_accept(self): conn, addr = self.accept() - print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr) + print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM) channel = SMTPChannel(self, conn, addr) # API for "doing something useful with the message" @@ -321,14 +320,14 @@ def process_message(self, peer, mailfrom, rcpttos, data): inheaders = 1 lines = data.split('\n') - print '---------- MESSAGE FOLLOWS ----------' + print('---------- MESSAGE FOLLOWS ----------') for line in lines: # headers first if inheaders and not line: - print 'X-Peer:', peer[0] + print('X-Peer:', peer[0]) inheaders = 0 - print line - print '------------ END MESSAGE ------------' + print(line) + print('------------ END MESSAGE ------------') @@ -345,7 +344,7 @@ data = NEWLINE.join(lines) refused = self._deliver(mailfrom, rcpttos, data) # TBD: what to do with refused addresses? - print >> DEBUGSTREAM, 'we got some refusals:', refused + print('we got some refusals:', refused, file=DEBUGSTREAM) def _deliver(self, mailfrom, rcpttos, data): import smtplib @@ -358,10 +357,10 @@ finally: s.quit() except smtplib.SMTPRecipientsRefused as e: - print >> DEBUGSTREAM, 'got SMTPRecipientsRefused' + print('got SMTPRecipientsRefused', file=DEBUGSTREAM) refused = e.recipients except (socket.error, smtplib.SMTPException) as e: - print >> DEBUGSTREAM, 'got', e.__class__ + print('got', e.__class__, file=DEBUGSTREAM) # All recipients were refused. If the exception had an associated # error code, use it. Otherwise,fake it with a non-triggering # exception code. @@ -410,11 +409,11 @@ for rcpt, listname, command in listnames: rcpttos.remove(rcpt) # If there's any non-list destined recipients left, - print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos) + print('forwarding recips:', ' '.join(rcpttos), file=DEBUGSTREAM) if rcpttos: refused = self._deliver(mailfrom, rcpttos, data) # TBD: what to do with refused addresses? - print >> DEBUGSTREAM, 'we got refusals:', refused + print('we got refusals:', refused, file=DEBUGSTREAM) # Now deliver directly to the list commands mlists = {} s = StringIO(data) @@ -427,7 +426,7 @@ if not msg.getheader('date'): msg['Date'] = time.ctime(time.time()) for rcpt, listname, command in listnames: - print >> DEBUGSTREAM, 'sending message to', rcpt + print('sending message to', rcpt, file=DEBUGSTREAM) mlist = mlists.get(listname) if not mlist: mlist = MailList.MailList(listname, lock=0) @@ -472,7 +471,7 @@ if opt in ('-h', '--help'): usage(0) elif opt in ('-V', '--version'): - print >> sys.stderr, __version__ + print(__version__, file=sys.stderr) sys.exit(0) elif opt in ('-n', '--nosetuid'): options.setuid = 0 @@ -522,16 +521,14 @@ try: import pwd except ImportError: - print >> sys.stderr, \ - 'Cannot import module "pwd"; try running with -n option.' + print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr) sys.exit(1) nobody = pwd.getpwnam('nobody')[2] try: os.setuid(nobody) except OSError as e: if e.errno != errno.EPERM: raise - print >> sys.stderr, \ - 'Cannot setuid "nobody"; try running with -n option.' + print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr) sys.exit(1) classname = options.classname if "." in classname: Modified: python/branches/p3yk-noslice/Lib/smtplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/smtplib.py (original) +++ python/branches/p3yk-noslice/Lib/smtplib.py Fri Feb 23 18:29:35 2007 @@ -15,7 +15,7 @@ >>> import smtplib >>> s=smtplib.SMTP("localhost") - >>> print s.help() + >>> print(s.help()) This is Sendmail version 8.8.4 Topics: HELO EHLO MAIL RCPT DATA @@ -43,10 +43,10 @@ import socket import re -import email.Utils +import email.utils import base64 import hmac -from email.base64MIME import encode as encode_base64 +from email.base64mime import encode as encode_base64 from sys import stderr __all__ = ["SMTPException","SMTPServerDisconnected","SMTPResponseException", @@ -172,7 +172,7 @@ """ m = (None, None) try: - m = email.Utils.parseaddr(addr)[1] + m = email.utils.parseaddr(addr)[1] except AttributeError: pass if m == (None, None): # Indicates parse failure or AttributeError @@ -277,7 +277,7 @@ # This makes it simpler for SMTP_SSL to use the SMTP connect code # and just alter the socket connection bit. self.sock = socket.socket(af, socktype, proto) - if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) + if self.debuglevel > 0: print('connect:', (host, port), file=stderr) self.sock.connect(sa) def connect(self, host='localhost', port = 0): @@ -299,7 +299,7 @@ except ValueError: raise socket.error, "nonnumeric port" if not port: port = self.default_port - if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) + if self.debuglevel > 0: print('connect:', (host, port), file=stderr) msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): @@ -307,7 +307,7 @@ try: self._get_socket(af,socktype,proto,sa) except socket.error as msg: - if self.debuglevel > 0: print>>stderr, 'connect fail:', msg + if self.debuglevel > 0: print('connect fail:', msg, file=stderr) if self.sock: self.sock.close() self.sock = None @@ -316,12 +316,12 @@ if not self.sock: raise socket.error, msg (code, msg) = self.getreply() - if self.debuglevel > 0: print>>stderr, "connect:", msg + if self.debuglevel > 0: print("connect:", msg, file=stderr) return (code, msg) def send(self, str): """Send `str' to the server.""" - if self.debuglevel > 0: print>>stderr, 'send:', repr(str) + if self.debuglevel > 0: print('send:', repr(str), file=stderr) if self.sock: try: self.sock.sendall(str) @@ -360,7 +360,7 @@ if line == '': self.close() raise SMTPServerDisconnected("Connection unexpectedly closed") - if self.debuglevel > 0: print>>stderr, 'reply:', repr(line) + if self.debuglevel > 0: print('reply:', repr(line), file=stderr) resp.append(line[4:].strip()) code=line[:3] # Check that the error code is syntactically correct. @@ -376,7 +376,7 @@ errmsg = "\n".join(resp) if self.debuglevel > 0: - print>>stderr, 'reply: retcode (%s); Msg: %s' % (errcode,errmsg) + print('reply: retcode (%s); Msg: %s' % (errcode,errmsg), file=stderr) return errcode, errmsg def docmd(self, cmd, args=""): @@ -489,7 +489,7 @@ """ self.putcmd("data") (code,repl)=self.getreply() - if self.debuglevel >0 : print>>stderr, "data:", (code,repl) + if self.debuglevel >0 : print("data:", (code,repl), file=stderr) if code != 354: raise SMTPDataError(code,repl) else: @@ -499,7 +499,7 @@ q = q + "." + CRLF self.send(q) (code,msg)=self.getreply() - if self.debuglevel >0 : print>>stderr, "data:", (code,msg) + if self.debuglevel >0 : print("data:", (code,msg), file=stderr) return (code,msg) def verify(self, address): @@ -740,7 +740,7 @@ def _get_socket(self,af, socktype, proto,sa): self.sock = socket.socket(af, socktype, proto) - if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) + if self.debuglevel > 0: print('connect:', (host, port), file=stderr) self.sock.connect(sa) sslobj = socket.ssl(self.sock, self.keyfile, self.certfile) self.sock = SSLFakeSocket(self.sock, sslobj) @@ -757,14 +757,14 @@ fromaddr = prompt("From") toaddrs = prompt("To").split(',') - print "Enter message, end with ^D:" + print("Enter message, end with ^D:") msg = '' while 1: line = sys.stdin.readline() if not line: break msg = msg + line - print "Message length is %d" % len(msg) + print("Message length is %d" % len(msg)) server = SMTP('localhost') server.set_debuglevel(1) Modified: python/branches/p3yk-noslice/Lib/sndhdr.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sndhdr.py (original) +++ python/branches/p3yk-noslice/Lib/sndhdr.py Fri Feb 23 18:29:35 2007 @@ -208,21 +208,21 @@ import os for filename in list: if os.path.isdir(filename): - print filename + '/:', + print(filename + '/:', end=' ') if recursive or toplevel: - print 'recursing down:' + print('recursing down:') import glob names = glob.glob(os.path.join(filename, '*')) testall(names, recursive, 0) else: - print '*** directory (use -r) ***' + print('*** directory (use -r) ***') else: - print filename + ':', + print(filename + ':', end=' ') sys.stdout.flush() try: - print what(filename) + print(what(filename)) except IOError: - print '*** not found ***' + print('*** not found ***') if __name__ == '__main__': test() Modified: python/branches/p3yk-noslice/Lib/socket.py ============================================================================== --- python/branches/p3yk-noslice/Lib/socket.py (original) +++ python/branches/p3yk-noslice/Lib/socket.py Fri Feb 23 18:29:35 2007 @@ -202,17 +202,17 @@ default_bufsize = 8192 name = "" - __slots__ = ["mode", "bufsize", "softspace", + __slots__ = ["mode", "bufsize", # "closed" is a property, see below - "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"] + "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", + "_close"] - def __init__(self, sock, mode='rb', bufsize=-1): + def __init__(self, sock, mode='rb', bufsize=-1, close=False): self._sock = sock self.mode = mode # Not actually used in this version if bufsize < 0: bufsize = self.default_bufsize self.bufsize = bufsize - self.softspace = False if bufsize == 0: self._rbufsize = 1 elif bufsize == 1: @@ -222,6 +222,7 @@ self._wbufsize = bufsize self._rbuf = "" # A string self._wbuf = [] # A list of strings + self._close = close def _getclosed(self): return self._sock is None @@ -232,6 +233,8 @@ if self._sock: self.flush() finally: + if self._close: + self._sock.close() self._sock = None def __del__(self): Modified: python/branches/p3yk-noslice/Lib/sqlite3/dbapi2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sqlite3/dbapi2.py (original) +++ python/branches/p3yk-noslice/Lib/sqlite3/dbapi2.py Fri Feb 23 18:29:35 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-noslice/Lib/sqlite3/test/dbapi.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py (original) +++ python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py Fri Feb 23 18:29:35 2007 @@ -327,7 +327,7 @@ except TypeError: return except Exception as e: - print "raised", e.__class__ + print("raised", e.__class__) self.fail("raised wrong exception.") def CheckFetchIter(self): Modified: python/branches/p3yk-noslice/Lib/sqlite3/test/factory.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sqlite3/test/factory.py (original) +++ python/branches/p3yk-noslice/Lib/sqlite3/test/factory.py Fri Feb 23 18:29:35 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-noslice/Lib/sqlite3/test/regression.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py (original) +++ python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py Fri Feb 23 18:29:35 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-noslice/Lib/sqlite3/test/types.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sqlite3/test/types.py (original) +++ python/branches/p3yk-noslice/Lib/sqlite3/test/types.py Fri Feb 23 18:29:35 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-noslice/Lib/sre_compile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sre_compile.py (original) +++ python/branches/p3yk-noslice/Lib/sre_compile.py Fri Feb 23 18:29:35 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-noslice/Lib/sre_constants.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sre_constants.py (original) +++ python/branches/p3yk-noslice/Lib/sre_constants.py Fri Feb 23 18:29:35 2007 @@ -258,4 +258,4 @@ f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET) f.close() - print "done" + print("done") Modified: python/branches/p3yk-noslice/Lib/sre_parse.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sre_parse.py (original) +++ python/branches/p3yk-noslice/Lib/sre_parse.py Fri Feb 23 18:29:35 2007 @@ -103,30 +103,30 @@ nl = 1 seqtypes = type(()), type([]) for op, av in self.data: - print level*" " + op,; nl = 0 + print(level*" " + op, end=' '); nl = 0 if op == "in": # member sublanguage - print; nl = 1 + print(); nl = 1 for op, a in av: - print (level+1)*" " + op, a + print((level+1)*" " + op, a) elif op == "branch": - print; nl = 1 + print(); nl = 1 i = 0 for a in av[1]: if i > 0: - print level*" " + "or" + print(level*" " + "or") a.dump(level+1); nl = 1 i = i + 1 elif type(av) in seqtypes: for a in av: if isinstance(a, SubPattern): - if not nl: print + if not nl: print() a.dump(level+1); nl = 1 else: - print a, ; nl = 0 + print(a, end=' ') ; nl = 0 else: - print av, ; nl = 0 - if not nl: print + print(av, end=' ') ; nl = 0 + if not nl: print() def __repr__(self): return repr(self.data) def __len__(self): @@ -147,7 +147,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: @@ -170,8 +170,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-noslice/Lib/stat.py ============================================================================== --- python/branches/p3yk-noslice/Lib/stat.py (original) +++ python/branches/p3yk-noslice/Lib/stat.py Fri Feb 23 18:29:35 2007 @@ -84,3 +84,16 @@ S_IROTH = 00004 S_IWOTH = 00002 S_IXOTH = 00001 + +# Names for file flags + +UF_NODUMP = 0x00000001 +UF_IMMUTABLE = 0x00000002 +UF_APPEND = 0x00000004 +UF_OPAQUE = 0x00000008 +UF_NOUNLINK = 0x00000010 +SF_ARCHIVED = 0x00010000 +SF_IMMUTABLE = 0x00020000 +SF_APPEND = 0x00040000 +SF_NOUNLINK = 0x00100000 +SF_SNAPSHOT = 0x00200000 Modified: python/branches/p3yk-noslice/Lib/string.py ============================================================================== --- python/branches/p3yk-noslice/Lib/string.py (original) +++ python/branches/p3yk-noslice/Lib/string.py Fri Feb 23 18:29:35 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-noslice/Lib/stringold.py ============================================================================== --- python/branches/p3yk-noslice/Lib/stringold.py (original) +++ python/branches/p3yk-noslice/Lib/stringold.py Fri Feb 23 18:29:35 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-noslice/Lib/subprocess.py ============================================================================== --- python/branches/p3yk-noslice/Lib/subprocess.py (original) +++ python/branches/p3yk-noslice/Lib/subprocess.py Fri Feb 23 18:29:35 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('"') @@ -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: @@ -593,14 +593,30 @@ c2pread, c2pwrite, errread, errwrite) - if p2cwrite: + # On Windows, you cannot just redirect one or two handles: You + # either have to redirect all three or none. If the subprocess + # user has only redirected one or two handles, we are + # automatically creating PIPEs for the rest. We should close + # these after the process is started. See bug #1124861. + if mswindows: + if stdin is None and p2cwrite is not None: + os.close(p2cwrite) + p2cwrite = None + if stdout is None and c2pread is not None: + os.close(c2pread) + c2pread = None + if stderr is None and errread is not None: + os.close(errread) + errread = None + + if p2cwrite is not None: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) - if c2pread: + if c2pread is not None: if universal_newlines: self.stdout = os.fdopen(c2pread, 'rU', bufsize) else: self.stdout = os.fdopen(c2pread, 'rb', bufsize) - if errread: + if errread is not None: if universal_newlines: self.stderr = os.fdopen(errread, 'rU', bufsize) else: @@ -669,7 +685,9 @@ if stdin is None: p2cread = GetStdHandle(STD_INPUT_HANDLE) - elif stdin == PIPE: + if p2cread is not None: + pass + elif stdin is None or stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) # Detach and turn into fd p2cwrite = p2cwrite.Detach() @@ -683,7 +701,9 @@ if stdout is None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) - elif stdout == PIPE: + if c2pwrite is not None: + pass + elif stdout is None or stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) # Detach and turn into fd c2pread = c2pread.Detach() @@ -697,7 +717,9 @@ if stderr is None: errwrite = GetStdHandle(STD_ERROR_HANDLE) - elif stderr == PIPE: + if errwrite is not None: + pass + elif stderr is None or stderr == PIPE: errread, errwrite = CreatePipe(None, 0) # Detach and turn into fd errread = errread.Detach() @@ -764,7 +786,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 @@ -987,29 +1009,29 @@ # Child try: # Close parent's pipe ends - if p2cwrite: + if p2cwrite is not None: os.close(p2cwrite) - if c2pread: + if c2pread is not None: os.close(c2pread) - if errread: + if errread is not None: os.close(errread) os.close(errpipe_read) # Dup fds for child - if p2cread: + if p2cread is not None: os.dup2(p2cread, 0) - if c2pwrite: + if c2pwrite is not None: os.dup2(c2pwrite, 1) - if errwrite: + if errwrite is not None: os.dup2(errwrite, 2) # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - if p2cread and p2cread not in (0,): + if p2cread is not None and p2cread not in (0,): os.close(p2cread) - if c2pwrite and c2pwrite not in (p2cread, 1): + if c2pwrite is not None and c2pwrite not in (p2cread, 1): os.close(c2pwrite) - if errwrite and errwrite not in (p2cread, c2pwrite, 2): + if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2): os.close(errwrite) # Close all other fds, if asked for @@ -1042,11 +1064,11 @@ # Parent os.close(errpipe_write) - if p2cread and p2cwrite: + if p2cread is not None and p2cwrite is not None: os.close(p2cread) - if c2pwrite and c2pread: + if c2pwrite is not None and c2pread is not None: os.close(c2pwrite) - if errwrite and errread: + if errwrite is not None and errread is not None: os.close(errwrite) # Wait for exec to fail or succeed; possibly raising exception @@ -1121,7 +1143,7 @@ # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) - input_offset += bytes_written + input_offset += bytes_written if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) @@ -1165,8 +1187,8 @@ # Example 1: Simple redirection: Get process list # plist = Popen(["ps"], stdout=PIPE).communicate()[0] - print "Process list:" - print plist + print("Process list:") + print(plist) # # Example 2: Change uid before executing child @@ -1178,42 +1200,42 @@ # # Example 3: Connecting several subprocesses # - print "Looking for 'hda'..." + print("Looking for 'hda'...") p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) - print repr(p2.communicate()[0]) + print(repr(p2.communicate()[0])) # # Example 4: Catch execution error # - print - print "Trying a weird file..." + print() + print("Trying a weird file...") try: - print Popen(["/this/path/does/not/exist"]).communicate() + print(Popen(["/this/path/does/not/exist"]).communicate()) except OSError as e: if e.errno == errno.ENOENT: - print "The file didn't exist. I thought so..." - print "Child traceback:" - print e.child_traceback + print("The file didn't exist. I thought so...") + print("Child traceback:") + print(e.child_traceback) else: - print "Error", e.errno + print("Error", e.errno) else: - print >>sys.stderr, "Gosh. No error." + print("Gosh. No error.", file=sys.stderr) def _demo_windows(): # # Example 1: Connecting several subprocesses # - print "Looking for 'PROMPT' in set output..." + print("Looking for 'PROMPT' in set output...") p1 = Popen("set", stdout=PIPE, shell=True) p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) - print repr(p2.communicate()[0]) + print(repr(p2.communicate()[0])) # # Example 2: Simple execution of program # - print "Executing calc..." + print("Executing calc...") p = Popen("calc") p.wait() Modified: python/branches/p3yk-noslice/Lib/sunau.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sunau.py (original) +++ python/branches/p3yk-noslice/Lib/sunau.py Fri Feb 23 18:29:35 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-noslice/Lib/sunaudio.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sunaudio.py (original) +++ python/branches/p3yk-noslice/Lib/sunaudio.py Fri Feb 23 18:29:35 2007 @@ -36,9 +36,9 @@ data_size, encoding, sample_rate, channels, info = hdr while info[-1:] == '\0': info = info[:-1] - print 'File name: ', file - print 'Data size: ', data_size - print 'Encoding: ', encoding - print 'Sample rate:', sample_rate - print 'Channels: ', channels - print 'Info: ', repr(info) + print('File name: ', file) + print('Data size: ', data_size) + print('Encoding: ', encoding) + print('Sample rate:', sample_rate) + print('Channels: ', channels) + print('Info: ', repr(info)) Modified: python/branches/p3yk-noslice/Lib/symbol.py ============================================================================== --- python/branches/p3yk-noslice/Lib/symbol.py (original) +++ python/branches/p3yk-noslice/Lib/symbol.py Fri Feb 23 18:29:35 2007 @@ -30,78 +30,77 @@ small_stmt = 273 expr_stmt = 274 augassign = 275 -print_stmt = 276 -del_stmt = 277 -pass_stmt = 278 -flow_stmt = 279 -break_stmt = 280 -continue_stmt = 281 -return_stmt = 282 -yield_stmt = 283 -raise_stmt = 284 -import_stmt = 285 -import_name = 286 -import_from = 287 -import_as_name = 288 -dotted_as_name = 289 -import_as_names = 290 -dotted_as_names = 291 -dotted_name = 292 -global_stmt = 293 -assert_stmt = 294 -compound_stmt = 295 -if_stmt = 296 -while_stmt = 297 -for_stmt = 298 -try_stmt = 299 -with_stmt = 300 -with_var = 301 -except_clause = 302 -suite = 303 -testlist_safe = 304 -old_test = 305 -old_lambdef = 306 -test = 307 -or_test = 308 -and_test = 309 -not_test = 310 -comparison = 311 -comp_op = 312 -expr = 313 -xor_expr = 314 -and_expr = 315 -shift_expr = 316 -arith_expr = 317 -term = 318 -factor = 319 -power = 320 -atom = 321 -listmaker = 322 -testlist_gexp = 323 -lambdef = 324 -trailer = 325 -subscriptlist = 326 -subscript = 327 -sliceop = 328 -exprlist = 329 -testlist = 330 -dictsetmaker = 331 -classdef = 332 -arglist = 333 -argument = 334 -list_iter = 335 -list_for = 336 -list_if = 337 -gen_iter = 338 -gen_for = 339 -gen_if = 340 -testlist1 = 341 -encoding_decl = 342 -yield_expr = 343 +del_stmt = 276 +pass_stmt = 277 +flow_stmt = 278 +break_stmt = 279 +continue_stmt = 280 +return_stmt = 281 +yield_stmt = 282 +raise_stmt = 283 +import_stmt = 284 +import_name = 285 +import_from = 286 +import_as_name = 287 +dotted_as_name = 288 +import_as_names = 289 +dotted_as_names = 290 +dotted_name = 291 +global_stmt = 292 +assert_stmt = 293 +compound_stmt = 294 +if_stmt = 295 +while_stmt = 296 +for_stmt = 297 +try_stmt = 298 +with_stmt = 299 +with_var = 300 +except_clause = 301 +suite = 302 +testlist_safe = 303 +old_test = 304 +old_lambdef = 305 +test = 306 +or_test = 307 +and_test = 308 +not_test = 309 +comparison = 310 +comp_op = 311 +expr = 312 +xor_expr = 313 +and_expr = 314 +shift_expr = 315 +arith_expr = 316 +term = 317 +factor = 318 +power = 319 +atom = 320 +listmaker = 321 +testlist_gexp = 322 +lambdef = 323 +trailer = 324 +subscriptlist = 325 +subscript = 326 +sliceop = 327 +exprlist = 328 +testlist = 329 +dictsetmaker = 330 +classdef = 331 +arglist = 332 +argument = 333 +list_iter = 334 +list_for = 335 +list_if = 336 +gen_iter = 337 +gen_for = 338 +gen_if = 339 +testlist1 = 340 +encoding_decl = 341 +yield_expr = 342 #--end constants-- sym_name = {} -for _name, _value in globals().items(): +for _name, _value in list(globals().items()): if type(_value) is type(0): sym_name[_value] = _name Modified: python/branches/p3yk-noslice/Lib/symtable.py ============================================================================== --- python/branches/p3yk-noslice/Lib/symtable.py (original) +++ python/branches/p3yk-noslice/Lib/symtable.py Fri Feb 23 18:29:35 2007 @@ -13,7 +13,7 @@ def symtable(code, filename, compile_type): raw = _symtable.symtable(code, filename, compile_type) - for top in raw.itervalues(): + for top in raw.values(): if top.name == 'top': break return newSymbolTable(top, filename) @@ -249,4 +249,4 @@ mod = symtable(src, os.path.split(sys.argv[0])[1], "exec") for ident in mod.get_identifiers(): info = mod.lookup(ident) - print info, info.is_local(), info.is_namespace() + print(info, info.is_local(), info.is_namespace()) Modified: python/branches/p3yk-noslice/Lib/tabnanny.py ============================================================================== --- python/branches/p3yk-noslice/Lib/tabnanny.py (original) +++ python/branches/p3yk-noslice/Lib/tabnanny.py Fri Feb 23 18:29:35 2007 @@ -83,7 +83,7 @@ if os.path.isdir(file) and not os.path.islink(file): if verbose: - print "%r: listing directory" % (file,) + print("%r: listing directory" % (file,)) names = os.listdir(file) for name in names: fullname = os.path.join(file, name) @@ -100,7 +100,7 @@ return if verbose > 1: - print "checking %r ..." % file + print("checking %r ..." % file) try: process_tokens(tokenize.generate_tokens(f.readline)) @@ -117,17 +117,17 @@ badline = nag.get_lineno() line = nag.get_line() if verbose: - print "%r: *** Line %d: trouble in tab city! ***" % (file, badline) - print "offending line: %r" % (line,) - print nag.get_msg() + print("%r: *** Line %d: trouble in tab city! ***" % (file, badline)) + print("offending line: %r" % (line,)) + print(nag.get_msg()) else: if ' ' in file: file = '"' + file + '"' - if filename_only: print file - else: print file, badline, repr(line) + if filename_only: print(file) + else: print(file, badline, repr(line)) return if verbose: - print "%r: Clean bill of health." % (file,) + print("%r: Clean bill of health." % (file,)) class Whitespace: # the characters used for space and tab Modified: python/branches/p3yk-noslice/Lib/tarfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/tarfile.py (original) +++ python/branches/p3yk-noslice/Lib/tarfile.py Fri Feb 23 18:29:35 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(" 0: + self.fileobj.seek(- BLOCKSIZE, 1) break if self._mode in "aw": @@ -1122,7 +1127,7 @@ 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression - 'a' or 'a:' open for appending + 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression @@ -1378,7 +1383,7 @@ if stat.S_ISREG(stmd): tarinfo.size = statres.st_size else: - tarinfo.size = 0L + tarinfo.size = 0 tarinfo.mtime = statres.st_mtime tarinfo.type = type tarinfo.linkname = linkname @@ -1408,25 +1413,25 @@ for tarinfo in self: if verbose: - print filemode(tarinfo.mode), - print "%s/%s" % (tarinfo.uname or tarinfo.uid, - tarinfo.gname or tarinfo.gid), + print(filemode(tarinfo.mode), end=' ') + print("%s/%s" % (tarinfo.uname or tarinfo.uid, + tarinfo.gname or tarinfo.gid), end=' ') if tarinfo.ischr() or tarinfo.isblk(): - print "%10s" % ("%d,%d" \ - % (tarinfo.devmajor, tarinfo.devminor)), + print("%10s" % ("%d,%d" \ + % (tarinfo.devmajor, tarinfo.devminor)), end=' ') else: - print "%10d" % tarinfo.size, - print "%d-%02d-%02d %02d:%02d:%02d" \ - % time.localtime(tarinfo.mtime)[:6], + print("%10d" % tarinfo.size, end=' ') + print("%d-%02d-%02d %02d:%02d:%02d" \ + % time.localtime(tarinfo.mtime)[:6], end=' ') - print tarinfo.name, + print(tarinfo.name, end=' ') if verbose: if tarinfo.issym(): - print "->", tarinfo.linkname, + print("->", tarinfo.linkname, end=' ') if tarinfo.islnk(): - print "link to", tarinfo.linkname, - print + print("link to", tarinfo.linkname, end=' ') + print() def add(self, name, arcname=None, recursive=True): """Add the file `name' to the archive. `name' may be any type of file @@ -1632,19 +1637,7 @@ # Create all upper directories. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): - ti = TarInfo() - ti.name = upperdirs - ti.type = DIRTYPE - ti.mode = 0777 - ti.mtime = tarinfo.mtime - ti.uid = tarinfo.uid - ti.gid = tarinfo.gid - ti.uname = tarinfo.uname - ti.gname = tarinfo.gname - try: - self._extract_member(ti, ti.name) - except: - pass + os.makedirs(upperdirs) if tarinfo.islnk() or tarinfo.issym(): self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) @@ -1924,8 +1917,8 @@ buf = tarinfo.buf sp = _ringbuffer() pos = 386 - lastpos = 0L - realpos = 0L + lastpos = 0 + realpos = 0 # There are 4 possible sparse structs in the # first header. for i in xrange(4): @@ -2034,7 +2027,7 @@ """Write debugging output to sys.stderr. """ if level <= self.debug: - print >> sys.stderr, msg + print(msg, file=sys.stderr) # class TarFile class TarIter: Modified: python/branches/p3yk-noslice/Lib/telnetlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/telnetlib.py (original) +++ python/branches/p3yk-noslice/Lib/telnetlib.py Fri Feb 23 18:29:35 2007 @@ -8,7 +8,7 @@ >>> from telnetlib import Telnet >>> tn = Telnet('www.python.org', 79) # connect to finger port >>> tn.write('guido\r\n') ->>> print tn.read_all() +>>> print(tn.read_all()) Login Name TTY Idle When Where guido Guido van Rossum pts/2 snag.cnri.reston.. @@ -248,11 +248,11 @@ """ if self.debuglevel > 0: - print 'Telnet(%s,%d):' % (self.host, self.port), + print('Telnet(%s,%d):' % (self.host, self.port), end=' ') if args: - print msg % args + print(msg % args) else: - print msg + print(msg) def set_debuglevel(self, debuglevel): """Set the debug level. @@ -545,7 +545,7 @@ try: text = self.read_eager() except EOFError: - print '*** Connection closed by remote host ***' + print('*** Connection closed by remote host ***') break if text: sys.stdout.write(text) @@ -572,7 +572,7 @@ try: data = self.read_eager() except EOFError: - print '*** Connection closed by remote host ***' + print('*** Connection closed by remote host ***') return if data: sys.stdout.write(data) Modified: python/branches/p3yk-noslice/Lib/test/badsyntax_future8.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/badsyntax_future8.py (original) +++ python/branches/p3yk-noslice/Lib/test/badsyntax_future8.py Fri Feb 23 18:29:35 2007 @@ -7,4 +7,4 @@ return x + y return g -print f(2)(4) +print(f(2)(4)) Modified: python/branches/p3yk-noslice/Lib/test/badsyntax_future9.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/badsyntax_future9.py (original) +++ python/branches/p3yk-noslice/Lib/test/badsyntax_future9.py Fri Feb 23 18:29:35 2007 @@ -7,4 +7,4 @@ return x + y return g -print f(2)(4) +print(f(2)(4)) Modified: python/branches/p3yk-noslice/Lib/test/crashers/bogus_sre_bytecode.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/crashers/bogus_sre_bytecode.py (original) +++ python/branches/p3yk-noslice/Lib/test/crashers/bogus_sre_bytecode.py Fri Feb 23 18:29:35 2007 @@ -38,7 +38,7 @@ while 1: code = [pick() for i in range(random.randrange(5, 25))] - print code + print(code) pat = _sre.compile(None, 0, code) for s in ss: try: Modified: python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_1.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_1.py (original) +++ python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_1.py Fri Feb 23 18:29:35 2007 @@ -8,7 +8,7 @@ class B(object): def __del__(self): - print 'hi' + print('hi') del D.__missing__ class D(dict): Modified: python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_2.py (original) +++ python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_2.py Fri Feb 23 18:29:35 2007 @@ -10,7 +10,7 @@ class B(object): def __del__(self): - print "hi" + print("hi") del C.d class D(object): Modified: python/branches/p3yk-noslice/Lib/test/crashers/gc_inspection.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/crashers/gc_inspection.py (original) +++ python/branches/p3yk-noslice/Lib/test/crashers/gc_inspection.py Fri Feb 23 18:29:35 2007 @@ -25,8 +25,8 @@ yield marker # now the marker is in the tuple being constructed [tup] = [x for x in gc.get_referrers(marker) if type(x) is tuple] - print tup - print tup[1] + print(tup) + print(tup[1]) tuple(g()) Modified: python/branches/p3yk-noslice/Lib/test/crashers/loosing_mro_ref.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/crashers/loosing_mro_ref.py (original) +++ python/branches/p3yk-noslice/Lib/test/crashers/loosing_mro_ref.py Fri Feb 23 18:29:35 2007 @@ -32,5 +32,5 @@ # there from the beginning :-) locals()[MyKey()] = 5 -print X.mykey +print(X.mykey) # I get a segfault, or a slightly wrong assertion error in a debug build. Modified: python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py (original) +++ python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py Fri Feb 23 18:29:35 2007 @@ -16,4 +16,4 @@ if __name__ == '__main__': del MyClass.__dict__ # if we set tp_dict to NULL, - print MyClass # doing anything with MyClass segfaults + print(MyClass) # doing anything with MyClass segfaults Modified: python/branches/p3yk-noslice/Lib/test/crashers/nasty_eq_vs_dict.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/crashers/nasty_eq_vs_dict.py (original) +++ python/branches/p3yk-noslice/Lib/test/crashers/nasty_eq_vs_dict.py Fri Feb 23 18:29:35 2007 @@ -44,4 +44,4 @@ z = Yuck() y.make_dangerous() -print dict[z] +print(dict[z]) Modified: python/branches/p3yk-noslice/Lib/test/crashers/weakref_in_del.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/crashers/weakref_in_del.py (original) +++ python/branches/p3yk-noslice/Lib/test/crashers/weakref_in_del.py Fri Feb 23 18:29:35 2007 @@ -1,11 +1,12 @@ import weakref # http://python.org/sf/1377858 +# Fixed for new-style classes in 2.5c1. ref = None def test_weakref_in_del(): - class Target(object): + class Target(): def __del__(self): global ref ref = weakref.ref(self) Modified: python/branches/p3yk-noslice/Lib/test/doctest_aliases.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/doctest_aliases.py (original) +++ python/branches/p3yk-noslice/Lib/test/doctest_aliases.py Fri Feb 23 18:29:35 2007 @@ -5,7 +5,7 @@ def f(self): ''' - >>> print TwoNames().f() + >>> print(TwoNames().f()) f ''' return 'f' Modified: python/branches/p3yk-noslice/Lib/test/fork_wait.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/fork_wait.py (original) +++ python/branches/p3yk-noslice/Lib/test/fork_wait.py Fri Feb 23 18:29:35 2007 @@ -51,8 +51,7 @@ time.sleep(LONGSLEEP) - a = self.alive.keys() - a.sort() + a = sorted(self.alive.keys()) self.assertEquals(a, range(NUM_THREADS)) prefork_lives = self.alive.copy() Modified: python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py (original) +++ python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py Fri Feb 23 18:29:35 2007 @@ -7,7 +7,7 @@ # line 7 def replace(func): def insteadfunc(): - print 'hello' + print('hello') return insteadfunc # line 13 Modified: python/branches/p3yk-noslice/Lib/test/list_tests.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/list_tests.py (original) +++ python/branches/p3yk-noslice/Lib/test/list_tests.py Fri Feb 23 18:29:35 2007 @@ -54,7 +54,7 @@ d.append(400) try: fo = open(test_support.TESTFN, "wb") - print >> fo, d, + fo.write(str(d)) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(d)) @@ -99,16 +99,16 @@ self.assertRaises(TypeError, a.__setitem__) a = self.type2test([0,1,2,3,4]) - a[0L] = 1 - a[1L] = 2 - a[2L] = 3 + a[0] = 1 + a[1] = 2 + a[2] = 3 self.assertEqual(a, self.type2test([1,2,3,3,4])) a[0] = 5 a[1] = 6 a[2] = 7 self.assertEqual(a, self.type2test([5,6,7,3,4])) - a[-2L] = 88 - a[-1L] = 99 + a[-2] = 88 + a[-1] = 99 self.assertEqual(a, self.type2test([5,6,7,88,99])) a[-2] = 8 a[-1] = 9 @@ -189,8 +189,8 @@ self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) - del a[1L:2L] - del a[0L:1L] + del a[1:2] + del a[0:1] self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) @@ -198,7 +198,7 @@ self.assertEqual(a, self.type2test([1])) a = self.type2test([0, 1]) - del a[-2L:-1L] + del a[-2:-1] self.assertEqual(a, self.type2test([1])) a = self.type2test([0, 1]) @@ -207,8 +207,8 @@ self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) - del a[1L:] - del a[:1L] + del a[1:] + del a[:1] self.assertEqual(a, self.type2test([])) a = self.type2test([0, 1]) @@ -216,7 +216,7 @@ self.assertEqual(a, self.type2test([0])) a = self.type2test([0, 1]) - del a[-1L:] + del a[-1:] self.assertEqual(a, self.type2test([0])) a = self.type2test([0, 1]) Modified: python/branches/p3yk-noslice/Lib/test/mapping_tests.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/mapping_tests.py (original) +++ python/branches/p3yk-noslice/Lib/test/mapping_tests.py Fri Feb 23 18:29:35 2007 @@ -49,7 +49,7 @@ #Indexing for key, value in self.reference.items(): self.assertEqual(d[key], value) - knownkey = self.other.keys()[0] + knownkey = list(self.other.keys())[0] self.failUnlessRaises(KeyError, lambda:d[knownkey]) #len self.assertEqual(len(p), 0) @@ -73,13 +73,16 @@ self.assert_(hasattr(iter, '__iter__')) x = list(iter) self.assert_(set(x)==set(lst)==set(ref)) - check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys()) - check_iterandlist(iter(d), d.keys(), self.reference.keys()) - check_iterandlist(d.itervalues(), d.values(), self.reference.values()) - check_iterandlist(d.iteritems(), d.items(), self.reference.items()) + check_iterandlist(iter(d.keys()), list(d.keys()), + self.reference.keys()) + check_iterandlist(iter(d), list(d.keys()), self.reference.keys()) + check_iterandlist(iter(d.values()), list(d.values()), + self.reference.values()) + check_iterandlist(iter(d.items()), list(d.items()), + self.reference.items()) #get - key, value = d.iteritems().next() - knownkey, knownvalue = self.other.iteritems().next() + key, value = iter(d.items()).next() + knownkey, knownvalue = iter(self.other.items()).next() self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.failIf(knownkey in d) @@ -98,14 +101,14 @@ #update p.update(self.reference) self.assertEqual(dict(p), self.reference) - items = p.items() + items = list(p.items()) p = self._empty_mapping() p.update(items) self.assertEqual(dict(p), self.reference) d = self._full_mapping(self.reference) #setdefault - key, value = d.iteritems().next() - knownkey, knownvalue = self.other.iteritems().next() + key, value = iter(d.items()).next() + knownkey, knownvalue = iter(self.other.items()).next() self.assertEqual(d.setdefault(key, knownvalue), value) self.assertEqual(d[key], value) self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue) @@ -137,21 +140,21 @@ def test_keys(self): d = self._empty_mapping() - self.assertEqual(d.keys(), []) + self.assertEqual(list(d.keys()), []) d = self.reference - self.assert_(self.inmapping.keys()[0] in d.keys()) - self.assert_(self.other.keys()[0] not in d.keys()) + self.assert_(list(self.inmapping.keys())[0] in d.keys()) + self.assert_(list(self.other.keys())[0] not in d.keys()) self.assertRaises(TypeError, d.keys, None) def test_values(self): d = self._empty_mapping() - self.assertEqual(d.values(), []) + self.assertEqual(list(d.values()), []) self.assertRaises(TypeError, d.values, None) def test_items(self): d = self._empty_mapping() - self.assertEqual(d.items(), []) + self.assertEqual(list(d.items()), []) self.assertRaises(TypeError, d.items, None) @@ -161,7 +164,8 @@ def test_getitem(self): d = self.reference - self.assertEqual(d[self.inmapping.keys()[0]], self.inmapping.values()[0]) + self.assertEqual(d[list(self.inmapping.keys())[0]], + list(self.inmapping.values())[0]) self.assertRaises(TypeError, d.__getitem__) @@ -169,7 +173,7 @@ # mapping argument d = self._empty_mapping() d.update(self.other) - self.assertEqual(d.items(), self.other.items()) + self.assertEqual(list(d.items()), list(self.other.items())) # No argument d = self._empty_mapping() @@ -179,12 +183,12 @@ # item sequence d = self._empty_mapping() d.update(self.other.items()) - self.assertEqual(d.items(), self.other.items()) + self.assertEqual(list(d.items()), list(self.other.items())) # Iterator d = self._empty_mapping() - d.update(self.other.iteritems()) - self.assertEqual(d.items(), self.other.items()) + d.update(self.other.items()) + self.assertEqual(list(d.items()), list(self.other.items())) # FIXME: Doesn't work with UserDict # self.assertRaises((TypeError, AttributeError), d.update, None) @@ -200,10 +204,8 @@ return self.d[i] d.clear() d.update(SimpleUserDict()) - i1 = d.items() - i2 = self.reference.items() - i1.sort() - i2.sort() + i1 = sorted(d.items()) + i2 = sorted(self.reference.items()) self.assertEqual(i1, i2) class Exc(Exception): pass @@ -266,13 +268,15 @@ def test_get(self): d = self._empty_mapping() - self.assert_(d.get(self.other.keys()[0]) is None) - self.assertEqual(d.get(self.other.keys()[0], 3), 3) + self.assert_(d.get(list(self.other.keys())[0]) is None) + self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) d = self.reference - self.assert_(d.get(self.other.keys()[0]) is None) - self.assertEqual(d.get(self.other.keys()[0], 3), 3) - self.assertEqual(d.get(self.inmapping.keys()[0]), self.inmapping.values()[0]) - self.assertEqual(d.get(self.inmapping.keys()[0], 3), self.inmapping.values()[0]) + self.assert_(d.get(list(self.other.keys())[0]) is None) + self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) + self.assertEqual(d.get(list(self.inmapping.keys())[0]), + list(self.inmapping.values())[0]) + self.assertEqual(d.get(list(self.inmapping.keys())[0], 3), + list(self.inmapping.values())[0]) self.assertRaises(TypeError, d.get) self.assertRaises(TypeError, d.get, None, None, None) @@ -287,9 +291,9 @@ def test_pop(self): d = self._empty_mapping() - k, v = self.inmapping.items()[0] + k, v = list(self.inmapping.items())[0] d[k] = v - self.assertRaises(KeyError, d.pop, self.other.keys()[0]) + self.assertRaises(KeyError, d.pop, list(self.other.keys())[0]) self.assertEqual(d.pop(k), v) self.assertEqual(len(d), 0) @@ -313,7 +317,7 @@ def test_keys(self): BasicTestMappingProtocol.test_keys(self) d = self._empty_mapping() - self.assertEqual(d.keys(), []) + self.assertEqual(list(d.keys()), []) d = self._full_mapping({'a': 1, 'b': 2}) k = d.keys() self.assert_('a' in k) @@ -323,13 +327,13 @@ def test_values(self): BasicTestMappingProtocol.test_values(self) d = self._full_mapping({1:2}) - self.assertEqual(d.values(), [2]) + self.assertEqual(list(d.values()), [2]) def test_items(self): BasicTestMappingProtocol.test_items(self) d = self._full_mapping({1:2}) - self.assertEqual(d.items(), [(1, 2)]) + self.assertEqual(list(d.items()), [(1, 2)]) def test_contains(self): d = self._empty_mapping() @@ -400,7 +404,7 @@ # iterator d = self._full_mapping({1:3, 2:4}) - d.update(self._full_mapping({1:2, 3:4, 5:6}).iteritems()) + d.update(self._full_mapping({1:2, 3:4, 5:6}).items()) self.assertEqual(d, {1:2, 2:4, 3:4, 5:6}) class SimpleUserDict: @@ -526,7 +530,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 = self._full_mapping({x: 'anything', y: 'something else'}) self.assertEqual(h[x], h[y]) @@ -626,7 +630,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-noslice/Lib/test/output/test_cProfile ============================================================================== --- python/branches/p3yk-noslice/Lib/test/output/test_cProfile (original) +++ python/branches/p3yk-noslice/Lib/test/output/test_cProfile Fri Feb 23 18:29:35 2007 @@ -29,12 +29,12 @@ :1() -> 1 0.270 1.000 test_cProfile.py:30(testfunc) test_cProfile.py:103(subhelper) -> 16 0.016 0.016 test_cProfile.py:115(__getattr__) 8 0.000 0.000 {range} -test_cProfile.py:115(__getattr__) -> +test_cProfile.py:115(__getattr__) -> test_cProfile.py:30(testfunc) -> 1 0.014 0.130 test_cProfile.py:40(factorial) 2 0.040 0.600 test_cProfile.py:60(helper) test_cProfile.py:40(factorial) -> 20/3 0.130 0.147 test_cProfile.py:40(factorial) 20 0.020 0.020 test_cProfile.py:53(mul) -test_cProfile.py:53(mul) -> +test_cProfile.py:53(mul) -> test_cProfile.py:60(helper) -> 4 0.116 0.120 test_cProfile.py:78(helper1) 2 0.000 0.140 test_cProfile.py:89(helper2_indirect) 6 0.234 0.300 test_cProfile.py:93(helper2) @@ -47,10 +47,10 @@ 8 0.000 0.008 {hasattr} {exec} -> 1 0.000 1.000 :1() {hasattr} -> 12 0.012 0.012 test_cProfile.py:115(__getattr__) -{method 'append' of 'list' objects} -> -{method 'disable' of '_lsprof.Profiler' objects} -> -{range} -> -{sys.exc_info} -> +{method 'append' of 'list' objects} -> +{method 'disable' of '_lsprof.Profiler' objects} -> +{range} -> +{sys.exc_info} -> Ordered by: standard name @@ -71,11 +71,11 @@ test_cProfile.py:89(helper2_indirect) <- 2 0.000 0.140 test_cProfile.py:60(helper) test_cProfile.py:93(helper2) <- 6 0.234 0.300 test_cProfile.py:60(helper) 2 0.078 0.100 test_cProfile.py:89(helper2_indirect) -{exec} <- +{exec} <- {hasattr} <- 4 0.000 0.004 test_cProfile.py:78(helper1) 8 0.000 0.008 test_cProfile.py:93(helper2) {method 'append' of 'list' objects} <- 4 0.000 0.000 test_cProfile.py:78(helper1) -{method 'disable' of '_lsprof.Profiler' objects} <- +{method 'disable' of '_lsprof.Profiler' objects} <- {range} <- 8 0.000 0.000 test_cProfile.py:103(subhelper) {sys.exc_info} <- 4 0.000 0.000 test_cProfile.py:78(helper1) Modified: python/branches/p3yk-noslice/Lib/test/output/test_class ============================================================================== --- python/branches/p3yk-noslice/Lib/test/output/test_class (original) +++ python/branches/p3yk-noslice/Lib/test/output/test_class Fri Feb 23 18:29:35 2007 @@ -44,7 +44,7 @@ __pos__: () __abs__: () __int__: () -__long__: () +__int__: () __float__: () __oct__: () __hex__: () Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_new ============================================================================== --- /python/branches/p3yk-noslice/Lib/test/output/test_new Fri Feb 23 18:29:35 2007 +++ (empty file) @@ -1,6 +0,0 @@ -test_new -new.module() -new.classobj() -new.instancemethod() -new.function() -new.code() Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_popen ============================================================================== --- /python/branches/p3yk-noslice/Lib/test/output/test_popen Fri Feb 23 18:29:35 2007 +++ (empty file) @@ -1,3 +0,0 @@ -test_popen -Test popen: -popen seemed to process the command-line correctly Modified: python/branches/p3yk-noslice/Lib/test/output/test_profile ============================================================================== --- python/branches/p3yk-noslice/Lib/test/output/test_profile (original) +++ python/branches/p3yk-noslice/Lib/test/output/test_profile Fri Feb 23 18:29:35 2007 @@ -27,24 +27,24 @@ Ordered by: standard name Function called... -:0(append) -> -:0(exc_info) -> +:0(append) -> +:0(exc_info) -> :0(exec) -> :1()(1) 1.000 :0(hasattr) -> test_profile.py:115(__getattr__)(12) 0.028 -:0(range) -> -:0(setprofile) -> +:0(range) -> +:0(setprofile) -> :1() -> test_profile.py:30(testfunc)(1) 1.000 profile:0(profiler) -> profile:0(testfunc())(1) 1.000 profile:0(testfunc()) -> :0(exec)(1) 1.000 :0(setprofile)(1) 0.000 test_profile.py:103(subhelper) -> :0(range)(8) 0.000 test_profile.py:115(__getattr__)(16) 0.028 -test_profile.py:115(__getattr__) -> +test_profile.py:115(__getattr__) -> test_profile.py:30(testfunc) -> test_profile.py:40(factorial)(1) 0.170 test_profile.py:60(helper)(2) 0.600 test_profile.py:40(factorial) -> test_profile.py:40(factorial)(20) 0.170 test_profile.py:53(mul)(20) 0.020 -test_profile.py:53(mul) -> +test_profile.py:53(mul) -> test_profile.py:60(helper) -> test_profile.py:78(helper1)(4) 0.120 test_profile.py:89(helper2_indirect)(2) 0.140 test_profile.py:93(helper2)(6) 0.400 @@ -68,7 +68,7 @@ :0(range) <- test_profile.py:103(subhelper)(8) 0.080 :0(setprofile) <- profile:0(testfunc())(1) 1.000 :1() <- :0(exec)(1) 1.000 -profile:0(profiler) <- +profile:0(profiler) <- profile:0(testfunc()) <- profile:0(profiler)(1) 0.000 test_profile.py:103(subhelper) <- test_profile.py:93(helper2)(8) 0.400 test_profile.py:115(__getattr__) <- :0(hasattr)(12) 0.012 Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_resource ============================================================================== --- /python/branches/p3yk-noslice/Lib/test/output/test_resource Fri Feb 23 18:29:35 2007 +++ (empty file) @@ -1,2 +0,0 @@ -test_resource -True Modified: python/branches/p3yk-noslice/Lib/test/pickletester.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/pickletester.py (original) +++ python/branches/p3yk-noslice/Lib/test/pickletester.py Fri Feb 23 18:29:35 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 @@ -438,7 +438,7 @@ for proto in protocols: s = self.dumps(d, proto) x = self.loads(s) - self.assertEqual(x.keys(), [1]) + self.assertEqual(list(x.keys()), [1]) self.assert_(x[1] is x) def test_recursive_inst(self): @@ -461,7 +461,7 @@ x = self.loads(s) self.assertEqual(len(x), 1) self.assertEqual(dir(x[0]), dir(i)) - self.assertEqual(x[0].attr.keys(), [1]) + self.assertEqual(list(x[0].attr.keys()), [1]) self.assert_(x[0].attr[1] is x) def test_garyp(self): @@ -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-noslice/Lib/test/pydocfodder.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/pydocfodder.py (original) +++ python/branches/p3yk-noslice/Lib/test/pydocfodder.py Fri Feb 23 18:29:35 2007 @@ -192,19 +192,19 @@ def __init__(self, attr): self.attr = attr def __call__(self, inst): - print 'Get called', self, inst + print('Get called', self, inst) return inst.desc[self.attr] class set_desc: def __init__(self, attr): self.attr = attr def __call__(self, inst, val): - print 'Set called', self, inst, val + print('Set called', self, inst, val) inst.desc[self.attr] = val class del_desc: def __init__(self, attr): self.attr = attr def __call__(self, inst): - print 'Del called', self, inst + print('Del called', self, inst) del inst.desc[self.attr] x = property(get_desc('x'), set_desc('x'), del_desc('x'), 'prop x') Modified: python/branches/p3yk-noslice/Lib/test/pystone.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/pystone.py (original) +++ python/branches/p3yk-noslice/Lib/test/pystone.py Fri Feb 23 18:29:35 2007 @@ -59,9 +59,9 @@ def main(loops=LOOPS): benchtime, stones = pystones(loops) - print "Pystone(%s) time for %d passes = %g" % \ - (__version__, loops, benchtime) - print "This machine benchmarks at %g pystones/second" % stones + print("Pystone(%s) time for %d passes = %g" % \ + (__version__, loops, benchtime)) + print("This machine benchmarks at %g pystones/second" % stones) def pystones(loops=LOOPS): @@ -251,8 +251,8 @@ if __name__ == '__main__': import sys def error(msg): - print >>sys.stderr, msg, - print >>sys.stderr, "usage: %s [number_of_loops]" % sys.argv[0] + print(msg, end=' ', file=sys.stderr) + print("usage: %s [number_of_loops]" % sys.argv[0], file=sys.stderr) sys.exit(100) nargs = len(sys.argv) - 1 if nargs > 1: Modified: python/branches/p3yk-noslice/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/regrtest.py (original) +++ python/branches/p3yk-noslice/Lib/test/regrtest.py Fri Feb 23 18:29:35 2007 @@ -171,8 +171,8 @@ def usage(code, msg=''): - print __doc__ - if msg: print msg + print(__doc__) + if msg: print(msg) sys.exit(code) @@ -253,7 +253,7 @@ elif o in ('-R', '--huntrleaks'): huntrleaks = a.split(':') if len(huntrleaks) != 3: - print a, huntrleaks + print(a, huntrleaks) usage(2, '-R takes three colon-separated arguments') if len(huntrleaks[0]) == 0: huntrleaks[0] = 5 @@ -298,7 +298,7 @@ try: import gc except ImportError: - print 'No GC available, disabling findleaks.' + print('No GC available, disabling findleaks.') findleaks = False else: # Uncomment the line below to report garbage that is not @@ -355,7 +355,7 @@ save_modules = sys.modules.keys() for test in tests: if not quiet: - print test + print(test) sys.stdout.flush() if trace: # If we're tracing code coverage, then we don't exit with status @@ -368,7 +368,7 @@ huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C - print + print() break except: raise @@ -383,8 +383,8 @@ if findleaks: gc.collect() if gc.garbage: - print "Warning: test created", len(gc.garbage), - print "uncollectable object(s)." + print("Warning: test created", len(gc.garbage), end=' ') + print("uncollectable object(s).") # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) @@ -401,16 +401,16 @@ if good and not quiet: if not bad and not skipped and len(good) > 1: - print "All", - print count(len(good), "test"), "OK." + print("All", end=' ') + print(count(len(good), "test"), "OK.") if verbose: - print "CAUTION: stdout isn't compared in verbose mode:" - print "a test that passes in verbose mode may fail without it." + print("CAUTION: stdout isn't compared in verbose mode:") + print("a test that passes in verbose mode may fail without it.") if bad: - print count(len(bad), "test"), "failed:" + print(count(len(bad), "test"), "failed:") printlist(bad) if skipped and not quiet: - print count(len(skipped), "test"), "skipped:" + print(count(len(skipped), "test"), "skipped:") printlist(skipped) e = _ExpectedSkips() @@ -418,19 +418,19 @@ if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: - print count(len(surprise), "skip"), \ - "unexpected on", plat + ":" + print(count(len(surprise), "skip"), \ + "unexpected on", plat + ":") printlist(surprise) else: - print "Those skips are all expected on", plat + "." + print("Those skips are all expected on", plat + ".") else: - print "Ask someone to teach regrtest.py about which tests are" - print "expected to get skipped on", plat + "." + print("Ask someone to teach regrtest.py about which tests are") + print("expected to get skipped on", plat + ".") if verbose2 and bad: - print "Re-running failed tests in verbose mode" + print("Re-running failed tests in verbose mode") for test in bad: - print "Re-running test %r in verbose mode" % test + print("Re-running test %r in verbose mode" % test) sys.stdout.flush() try: test_support.verbose = 1 @@ -438,7 +438,7 @@ huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C - print + print() break except: raise @@ -537,7 +537,7 @@ try: if cfp: sys.stdout = cfp - print test # Output file starts with test name + print(test) # Output file starts with test name if test.startswith('test.'): abstest = test else: @@ -558,23 +558,23 @@ sys.stdout = save_stdout except test_support.ResourceDenied as msg: if not quiet: - print test, "skipped --", msg + print(test, "skipped --", msg) sys.stdout.flush() return -2 except (ImportError, test_support.TestSkipped) as msg: if not quiet: - print test, "skipped --", msg + print(test, "skipped --", msg) sys.stdout.flush() return -1 except KeyboardInterrupt: raise except test_support.TestFailed as msg: - print "test", test, "failed --", msg + print("test", test, "failed --", msg) sys.stdout.flush() return 0 except: type, value = sys.exc_info()[:2] - print "test", test, "crashed --", str(type) + ":", value + print("test", test, "crashed --", str(type) + ":", value) sys.stdout.flush() if verbose: traceback.print_exc(file=sys.stdout) @@ -590,8 +590,8 @@ # Write it since it already exists (and the contents # may have changed), but let the user know it isn't # needed: - print "output file", outputfile, \ - "is no longer needed; consider removing it" + print("output file", outputfile, \ + "is no longer needed; consider removing it") else: # We don't need it, so don't create it. return 1 @@ -607,7 +607,7 @@ expected = test + "\n" if output == expected or huntrleaks: return 1 - print "test", test, "produced unexpected output:" + print("test", test, "produced unexpected output:") sys.stdout.flush() reportdiff(expected, output) sys.stdout.flush() @@ -637,12 +637,12 @@ "directory nor file" % name) if verbose: - print "%r left behind %s %r" % (testname, kind, name) + print("%r left behind %s %r" % (testname, kind, name)) try: nuker(name) except Exception as msg: - print >> sys.stderr, ("%r left behind %s %r and it couldn't be " - "removed: %s" % (testname, kind, name, msg)) + print(("%r left behind %s %r and it couldn't be " + "removed: %s" % (testname, kind, name, msg)), file=sys.stderr) def dash_R(the_module, test, indirect_test, huntrleaks): # This code is hackish and inelegant, but it seems to do the job. @@ -667,8 +667,8 @@ deltas = [] nwarmup, ntracked, fname = huntrleaks repcount = nwarmup + ntracked - print >> sys.stderr, "beginning", repcount, "repetitions" - print >> sys.stderr, ("1234567890"*(repcount//10 + 1))[:repcount] + print("beginning", repcount, "repetitions", file=sys.stderr) + print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr) dash_R_cleanup(fs, ps, pic) for i in range(repcount): rc = sys.gettotalrefcount() @@ -677,11 +677,11 @@ dash_R_cleanup(fs, ps, pic) if i >= nwarmup: deltas.append(sys.gettotalrefcount() - rc - 2) - print >> sys.stderr + print(file=sys.stderr) if any(deltas): - print >> sys.stderr, test, 'leaked', deltas, 'references' + print(test, 'leaked', deltas, 'references', file=sys.stderr) refrep = open(fname, "a") - print >> refrep, test, 'leaked', deltas, 'references' + print(test, 'leaked', deltas, 'references', file=refrep) refrep.close() def dash_R_cleanup(fs, ps, pic): @@ -717,7 +717,7 @@ def reportdiff(expected, output): import difflib - print "*" * 70 + print("*" * 70) a = expected.splitlines(1) b = output.splitlines(1) sm = difflib.SequenceMatcher(a=a, b=b) @@ -736,26 +736,26 @@ pass elif op == 'delete': - print "***", pair(a0, a1), "of expected output missing:" + print("***", pair(a0, a1), "of expected output missing:") for line in a[a0:a1]: - print "-", line, + print("-", line, end='') elif op == 'replace': - print "*** mismatch between", pair(a0, a1), "of expected", \ - "output and", pair(b0, b1), "of actual output:" + print("*** mismatch between", pair(a0, a1), "of expected", \ + "output and", pair(b0, b1), "of actual output:") for line in difflib.ndiff(a[a0:a1], b[b0:b1]): - print line, + print(line, end='') elif op == 'insert': - print "***", pair(b0, b1), "of actual output doesn't appear", \ - "in expected output after line", str(a1)+":" + print("***", pair(b0, b1), "of actual output doesn't appear", \ + "in expected output after line", str(a1)+":") for line in b[b0:b1]: - print "+", line, + print("+", line, end='') else: - print "get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1) + print("get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1)) - print "*" * 70 + print("*" * 70) def findtestdir(): if __name__ == '__main__': @@ -786,8 +786,8 @@ from textwrap import fill blanks = ' ' * indent - print fill(' '.join(map(str, x)), width, - initial_indent=blanks, subsequent_indent=blanks) + print(fill(' '.join(map(str, x)), width, + initial_indent=blanks, subsequent_indent=blanks)) # Map sys.platform to a string containing the basenames of tests # expected to be skipped on that platform. @@ -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') @@ -1369,5 +1369,5 @@ if os.path.abspath(os.path.normpath(sys.path[i])) == mydir: del sys.path[i] if len(sys.path) == pathlen: - print 'Could not find %r in sys.path to remove it' % mydir + print('Could not find %r in sys.path to remove it' % mydir) main() Modified: python/branches/p3yk-noslice/Lib/test/reperf.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/reperf.py (original) +++ python/branches/p3yk-noslice/Lib/test/reperf.py Fri Feb 23 18:29:35 2007 @@ -17,7 +17,7 @@ finally: t1 = time.clock() if n > 1: - print n, "times", - print func.__name__, "%.3f" % (t1-t0), "CPU seconds" + print(n, "times", end=' ') + print(func.__name__, "%.3f" % (t1-t0), "CPU seconds") main() Modified: python/branches/p3yk-noslice/Lib/test/sample_doctest.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/sample_doctest.py (original) +++ python/branches/p3yk-noslice/Lib/test/sample_doctest.py Fri Feb 23 18:29:35 2007 @@ -40,9 +40,9 @@ def w_blank(): """ >>> if 1: - ... print 'a' - ... print - ... print 'b' + ... print('a') + ... print() + ... print('b') a b Modified: python/branches/p3yk-noslice/Lib/test/seq_tests.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/seq_tests.py (original) +++ python/branches/p3yk-noslice/Lib/test/seq_tests.py Fri Feb 23 18:29:35 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])) def test_contains(self): u = self.type2test([0, 1, 2]) @@ -252,16 +252,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) @@ -306,10 +306,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-noslice/Lib/test/sortperf.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/sortperf.py (original) +++ python/branches/p3yk-noslice/Lib/test/sortperf.py Fri Feb 23 18:29:35 2007 @@ -38,7 +38,7 @@ except os.error: pass except IOError as msg: - print "can't write", fn, ":", msg + print("can't write", fn, ":", msg) else: result = marshal.load(fp) fp.close() @@ -60,7 +60,7 @@ t0 = time.clock() L.sort() t1 = time.clock() - print "%6.2f" % (t1-t0), + print("%6.2f" % (t1-t0), end=' ') flush() def tabulate(r): @@ -84,11 +84,11 @@ """ cases = tuple([ch + "sort" for ch in r"*\/3+%~=!"]) fmt = ("%2s %7s" + " %6s"*len(cases)) - print fmt % (("i", "2**i") + cases) + print(fmt % (("i", "2**i") + cases)) for i in r: n = 1 << i L = randfloats(n) - print "%2d %7d" % (i, n), + print("%2d %7d" % (i, n), end=' ') flush() doit(L) # *sort L.reverse() @@ -137,7 +137,7 @@ # significantly faster if we leave tham as ints. L = map(float, L) doit(L) # !sort - print + print() def main(): """Main program when invoked as a script. Modified: python/branches/p3yk-noslice/Lib/test/string_tests.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/string_tests.py (original) +++ python/branches/p3yk-noslice/Lib/test/string_tests.py Fri Feb 23 18:29:35 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'] @@ -40,7 +40,7 @@ elif isinstance(obj, dict): return dict([ (self.fixtype(key), self.fixtype(value)) - for (key, value) in obj.iteritems() + for (key, value) in obj.items() ]) else: return obj @@ -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)) @@ -962,7 +962,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-noslice/Lib/test/test___all__.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test___all__.py (original) +++ python/branches/p3yk-noslice/Lib/test/test___all__.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_al.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_al.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_al.py Fri Feb 23 18:29:35 2007 @@ -14,10 +14,10 @@ def main(): # touch all the attributes of al without doing anything if verbose: - print 'Touching al module attributes...' + print('Touching al module attributes...') for attr in alattrs: if verbose: - print 'touching: ', attr + print('touching: ', attr) getattr(al, attr) main() Modified: python/branches/p3yk-noslice/Lib/test/test_anydbm.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_anydbm.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_anydbm.py Fri Feb 23 18:29:35 2007 @@ -72,10 +72,8 @@ f.close() def keys_helper(self, f): - keys = f.keys() - keys.sort() - dkeys = self._dict.keys() - dkeys.sort() + keys = sorted(f.keys()) + dkeys = sorted(self._dict.keys()) self.assertEqual(keys, dkeys) return keys Modified: python/branches/p3yk-noslice/Lib/test/test_array.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_array.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_array.py Fri Feb 23 18:29:35 2007 @@ -12,6 +12,10 @@ class ArraySubclass(array.array): pass +class ArraySubclassWithKwargs(array.array): + def __init__(self, typecode, newarg=None): + array.array.__init__(typecode) + tests = [] # list to accumulate all tests typecodes = "cubBhHiIlLfd" @@ -61,7 +65,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 +327,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 +342,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 +350,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) @@ -715,6 +719,9 @@ b = array.array('B', range(64)) self.assertEqual(rc, sys.getrefcount(10)) + def test_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError + ArraySubclassWithKwargs('b', newarg=1) class StringTest(BaseTest): @@ -754,7 +761,7 @@ self.assertEqual(s.color, "blue") s.color = "red" self.assertEqual(s.color, "red") - self.assertEqual(s.__dict__.keys(), ["color"]) + self.assertEqual(list(s.__dict__.keys()), ["color"]) def test_nounicode(self): a = array.array(self.typecode, self.example) @@ -809,7 +816,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, [])) @@ -895,8 +902,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): @@ -908,7 +915,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) @@ -1000,7 +1007,7 @@ test_support.run_unittest(*tests) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_ast.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_ast.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_ast.py Fri Feb 23 18:29:35 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] @@ -30,8 +30,6 @@ "v = 1", # AugAssign "v += 1", - # Print - "print >>f, 1, ", # For "for v in v:pass", # While @@ -93,7 +91,7 @@ # Call "f(1,2,c=3,*d,**e)", # Num - "10L", + "10", # Str "'string'", # Attribute @@ -117,11 +115,11 @@ if __name__=='__main__' and sys.argv[1:] == ['-g']: for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), (eval_tests, "eval")): - print kind+"_results = [" + print(kind+"_results = [") for s in statements: - print repr(to_tuple(compile(s, "?", kind, 0x400)))+"," - print "]" - print "run_tests()" + print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",") + print("]") + print("run_tests()") raise SystemExit def test_order(ast_node, parent_pos): @@ -157,7 +155,6 @@ ('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]), ('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]), ('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]), -('Module', [('Print', (1, 0), ('Name', (1, 8), 'f', ('Load',)), [('Num', (1, 11), 1)], False)]), ('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]), ('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]), ('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]), Modified: python/branches/p3yk-noslice/Lib/test/test_asynchat.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_asynchat.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_asynchat.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_atexit.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_atexit.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_atexit.py Fri Feb 23 18:29:35 2007 @@ -75,16 +75,16 @@ ### helpers def h1(self): - print "h1" + print("h1") def h2(self): - print "h2" + print("h2") def h3(self): - print "h3" + print("h3") def h4(self, *args, **kwargs): - print "h4", args, kwargs + print("h4", args, kwargs) def raise1(self): raise TypeError Modified: python/branches/p3yk-noslice/Lib/test/test_audioop.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_audioop.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_audioop.py Fri Feb 23 18:29:35 2007 @@ -7,7 +7,7 @@ def gendata2(): if verbose: - print 'getsample' + print('getsample') if audioop.getsample('\0\1', 2, 0) == 1: return '\0\0\0\1\0\2' else: @@ -15,7 +15,7 @@ def gendata4(): if verbose: - print 'getsample' + print('getsample') if audioop.getsample('\0\0\0\1', 4, 0) == 1: return '\0\0\0\0\0\0\0\1\0\0\0\2' else: @@ -23,7 +23,7 @@ def testmax(data): if verbose: - print 'max' + print('max') if audioop.max(data[0], 1) != 2 or \ audioop.max(data[1], 2) != 2 or \ audioop.max(data[2], 4) != 2: @@ -32,7 +32,7 @@ def testminmax(data): if verbose: - print 'minmax' + print('minmax') if audioop.minmax(data[0], 1) != (0, 2) or \ audioop.minmax(data[1], 2) != (0, 2) or \ audioop.minmax(data[2], 4) != (0, 2): @@ -41,7 +41,7 @@ def testmaxpp(data): if verbose: - print 'maxpp' + print('maxpp') if audioop.maxpp(data[0], 1) != 0 or \ audioop.maxpp(data[1], 2) != 0 or \ audioop.maxpp(data[2], 4) != 0: @@ -50,7 +50,7 @@ def testavg(data): if verbose: - print 'avg' + print('avg') if audioop.avg(data[0], 1) != 1 or \ audioop.avg(data[1], 2) != 1 or \ audioop.avg(data[2], 4) != 1: @@ -59,7 +59,7 @@ def testavgpp(data): if verbose: - print 'avgpp' + print('avgpp') if audioop.avgpp(data[0], 1) != 0 or \ audioop.avgpp(data[1], 2) != 0 or \ audioop.avgpp(data[2], 4) != 0: @@ -75,7 +75,7 @@ def testcross(data): if verbose: - print 'cross' + print('cross') if audioop.cross(data[0], 1) != 0 or \ audioop.cross(data[1], 2) != 0 or \ audioop.cross(data[2], 4) != 0: @@ -84,7 +84,7 @@ def testadd(data): if verbose: - print 'add' + print('add') data2 = [] for d in data: str = '' @@ -99,7 +99,7 @@ def testbias(data): if verbose: - print 'bias' + print('bias') # Note: this test assumes that avg() works d1 = audioop.bias(data[0], 1, 100) d2 = audioop.bias(data[1], 2, 100) @@ -112,7 +112,7 @@ def testlin2lin(data): if verbose: - print 'lin2lin' + print('lin2lin') # too simple: we test only the size for d1 in data: for d2 in data: @@ -130,7 +130,7 @@ def testlin2adpcm(data): if verbose: - print 'lin2adpcm' + print('lin2adpcm') # Very cursory test if audioop.lin2adpcm('\0\0\0\0', 1, None) != ('\0\0', (0,0)): return 0 @@ -138,7 +138,7 @@ def testlin2alaw(data): if verbose: - print 'lin2alaw' + print('lin2alaw') if audioop.lin2alaw(data[0], 1) != '\xd5\xc5\xf5' or \ audioop.lin2alaw(data[1], 2) != '\xd5\xd5\xd5' or \ audioop.lin2alaw(data[2], 4) != '\xd5\xd5\xd5': @@ -147,7 +147,7 @@ def testalaw2lin(data): if verbose: - print 'alaw2lin' + print('alaw2lin') # Cursory d = audioop.lin2alaw(data[0], 1) if audioop.alaw2lin(d, 1) != data[0]: @@ -156,7 +156,7 @@ def testlin2ulaw(data): if verbose: - print 'lin2ulaw' + print('lin2ulaw') if audioop.lin2ulaw(data[0], 1) != '\xff\xe7\xdb' or \ audioop.lin2ulaw(data[1], 2) != '\xff\xff\xff' or \ audioop.lin2ulaw(data[2], 4) != '\xff\xff\xff': @@ -165,7 +165,7 @@ def testulaw2lin(data): if verbose: - print 'ulaw2lin' + print('ulaw2lin') # Cursory d = audioop.lin2ulaw(data[0], 1) if audioop.ulaw2lin(d, 1) != data[0]: @@ -174,7 +174,7 @@ def testmul(data): if verbose: - print 'mul' + print('mul') data2 = [] for d in data: str = '' @@ -189,7 +189,7 @@ def testratecv(data): if verbose: - print 'ratecv' + print('ratecv') state = None d1, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state) d2, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state) @@ -199,14 +199,14 @@ def testreverse(data): if verbose: - print 'reverse' + print('reverse') if audioop.reverse(data[0], 1) != '\2\1\0': return 0 return 1 def testtomono(data): if verbose: - print 'tomono' + print('tomono') data2 = '' for d in data[0]: data2 = data2 + d + d @@ -216,7 +216,7 @@ def testtostereo(data): if verbose: - print 'tostereo' + print('tostereo') data2 = '' for d in data[0]: data2 = data2 + d + d @@ -226,28 +226,28 @@ def testfindfactor(data): if verbose: - print 'findfactor' + print('findfactor') if audioop.findfactor(data[1], data[1]) != 1.0: return 0 return 1 def testfindfit(data): if verbose: - print 'findfit' + print('findfit') if audioop.findfit(data[1], data[1]) != (0, 1.0): return 0 return 1 def testfindmax(data): if verbose: - print 'findmax' + print('findmax') if audioop.findmax(data[1], 1) != 2: return 0 return 1 def testgetsample(data): if verbose: - print 'getsample' + print('getsample') for i in range(3): if audioop.getsample(data[0], 1, i) != i or \ audioop.getsample(data[1], 2, i) != i or \ @@ -259,15 +259,15 @@ try: func = eval('test'+name) except NameError: - print 'No test found for audioop.'+name+'()' + print('No test found for audioop.'+name+'()') return try: rv = func(data) except 'xx': - print 'Test FAILED for audioop.'+name+'() (with an exception)' + print('Test FAILED for audioop.'+name+'() (with an exception)') return if not rv: - print 'Test FAILED for audioop.'+name+'()' + print('Test FAILED for audioop.'+name+'()') def testall(): data = [gendata1(), gendata2(), gendata4()] Modified: python/branches/p3yk-noslice/Lib/test/test_bigmem.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_bigmem.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_bigmem.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_binop.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_binop.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_binop.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_bisect.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_bisect.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_bisect.py Fri Feb 23 18:29:35 2007 @@ -252,7 +252,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_bool.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_bool.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_bool.py Fri Feb 23 18:29:35 2007 @@ -27,7 +27,7 @@ def test_print(self): try: fo = open(test_support.TESTFN, "wb") - print >> fo, False, True + print(False, True, file=fo) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), 'False True\n') Modified: python/branches/p3yk-noslice/Lib/test/test_bsddb.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_bsddb.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_bsddb.py Fri Feb 23 18:29:35 2007 @@ -15,7 +15,7 @@ def setUp(self): self.f = self.openmethod[0](self.fname, self.openflag, cachesize=32768) self.d = dict(q='Guido', w='van', e='Rossum', r='invented', t='Python', y='') - for k, v in self.d.iteritems(): + for k, v in self.d.items(): self.f[k] = v def tearDown(self): @@ -29,7 +29,7 @@ pass def test_getitem(self): - for k, v in self.d.iteritems(): + for k, v in self.d.items(): self.assertEqual(self.f[k], v) def test_len(self): @@ -48,7 +48,7 @@ return self.f.close() self.f = self.openmethod[0](self.fname, 'w') - for k, v in self.d.iteritems(): + for k, v in self.d.items(): self.assertEqual(self.f[k], v) def assertSetEquals(self, seqn1, seqn2): @@ -61,9 +61,9 @@ self.assertSetEquals(d.keys(), f.keys()) self.assertSetEquals(d.values(), f.values()) self.assertSetEquals(d.items(), f.items()) - self.assertSetEquals(d.iterkeys(), f.iterkeys()) - self.assertSetEquals(d.itervalues(), f.itervalues()) - self.assertSetEquals(d.iteritems(), f.iteritems()) + self.assertSetEquals(d.keys(), f.keys()) + self.assertSetEquals(d.values(), f.values()) + self.assertSetEquals(d.items(), f.items()) def test_iter_while_modifying_values(self): if not hasattr(self.f, '__iter__'): @@ -94,7 +94,7 @@ if not hasattr(self.f, 'iteritems'): return - di = self.d.iteritems() + di = iter(self.d.items()) while 1: try: k, v = di.next() @@ -105,7 +105,7 @@ # it should behave the same as a dict. modifying values # of existing keys should not break iteration. (adding # or removing keys should) - fi = self.f.iteritems() + fi = iter(self.f.items()) while 1: try: k, v = fi.next() @@ -147,42 +147,42 @@ # in pybsddb's _DBWithCursor this causes an internal DBCursor # object is created. Other test_ methods in this class could # inadvertently cause the deadlock but an explicit test is needed. - if debug: print "A" + if debug: print("A") k,v = self.f.first() - if debug: print "B", k + if debug: print("B", k) self.f[k] = "deadlock. do not pass go. do not collect $200." - if debug: print "C" + if debug: print("C") # if the bsddb implementation leaves the DBCursor open during # the database write and locking+threading support is enabled # the cursor's read lock will deadlock the write lock request.. # test the iterator interface (if present) if hasattr(self.f, 'iteritems'): - if debug: print "D" - i = self.f.iteritems() + if debug: print("D") + i = iter(self.f.items()) k,v = i.next() - if debug: print "E" + if debug: print("E") self.f[k] = "please don't deadlock" - if debug: print "F" + if debug: print("F") while 1: try: k,v = i.next() except StopIteration: break - if debug: print "F2" + if debug: print("F2") i = iter(self.f) - if debug: print "G" + if debug: print("G") while i: try: - if debug: print "H" + if debug: print("H") k = i.next() - if debug: print "I" + if debug: print("I") self.f[k] = "deadlocks-r-us" - if debug: print "J" + if debug: print("J") except StopIteration: i = None - if debug: print "K" + if debug: print("K") # test the legacy cursor interface mixed with writes self.assert_(self.f.first()[0] in self.d) @@ -198,9 +198,9 @@ # do the bsddb._DBWithCursor _iter_mixin internals leak cursors? nc1 = len(self.f._cursor_refs) # create iterator - i = self.f.iteritems() + i = iter(self.f.iteritems()) nc2 = len(self.f._cursor_refs) - # use the iterator (should run to the first yeild, creating the cursor) + # use the iterator (should run to the first yield, creating the cursor) k, v = i.next() nc3 = len(self.f._cursor_refs) # destroy the iterator; this should cause the weakref callback @@ -210,7 +210,7 @@ self.assertEqual(nc1, nc2) self.assertEqual(nc1, nc4) - self.assert_(nc3 == nc1+1) + self.assertEqual(nc3, nc1+1) def test_popitem(self): k, v = self.f.popitem() @@ -240,14 +240,13 @@ new = dict(y='life', u='of', i='brian') self.f.update(new) self.d.update(new) - for k, v in self.d.iteritems(): + for k, v in self.d.items(): self.assertEqual(self.f[k], v) def test_keyordering(self): if self.openmethod[0] is not bsddb.btopen: return - keys = self.d.keys() - keys.sort() + keys = sorted(self.d.keys()) self.assertEqual(self.f.first()[0], keys[0]) self.assertEqual(self.f.next()[0], keys[1]) self.assertEqual(self.f.last()[0], keys[-1]) Modified: python/branches/p3yk-noslice/Lib/test/test_bsddb3.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_bsddb3.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_bsddb3.py Fri Feb 23 18:29:35 2007 @@ -65,12 +65,12 @@ # For invocation as a script if __name__ == '__main__': from bsddb import db - print '-=' * 38 - print db.DB_VERSION_STRING - print 'bsddb.db.version(): %s' % (db.version(),) - print 'bsddb.db.__version__: %s' % db.__version__ - print 'bsddb.db.cvsid: %s' % db.cvsid - print 'python version: %s' % sys.version - print '-=' * 38 + print('-=' * 38) + print(db.DB_VERSION_STRING) + print('bsddb.db.version(): %s' % (db.version(),)) + print('bsddb.db.__version__: %s' % db.__version__) + print('bsddb.db.cvsid: %s' % db.cvsid) + print('python version: %s' % sys.version) + print('-=' * 38) unittest.main(defaultTest='suite') Modified: python/branches/p3yk-noslice/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_builtin.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_builtin.py Fri Feb 23 18:29:35 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') @@ -204,15 +204,15 @@ self.assertRaises(TypeError, cmp) def test_compile(self): - compile('print 1\n', '', 'exec') + compile('print(1)\n', '', 'exec') bom = '\xef\xbb\xbf' - compile(bom + 'print 1\n', '', 'exec') + compile(bom + 'print(1)\n', '', 'exec') self.assertRaises(TypeError, compile) - self.assertRaises(ValueError, compile, 'print 42\n', '', 'badmode') - self.assertRaises(ValueError, compile, 'print 42\n', '', 'single', 0xff) + self.assertRaises(ValueError, compile, 'print(42)\n', '', 'badmode') + self.assertRaises(ValueError, compile, 'print(42)\n', '', 'single', 0xff) self.assertRaises(TypeError, compile, chr(0), 'f', 'exec') if have_unicode: - compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec') + compile(unicode('print(u"\xc3\xa5")\n', 'utf8'), '', 'exec') self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec') self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad') @@ -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)) @@ -347,7 +347,7 @@ def __getitem__(self, item): raise KeyError(item) def keys(self): - return 'a' + return 1 # used to be 'a' but that's no longer an error self.assertRaises(TypeError, eval, 'dir()', globals(), C()) # Done outside of the method test_z to get the correct scope @@ -525,8 +525,8 @@ unicode("123"): unicode("112233") } - for (cls, inps) in inputs.iteritems(): - for (inp, exp) in inps.iteritems(): + for (cls, inps) in inputs.items(): + for (inp, exp) in inps.items(): # make sure the output goes through __getitem__ # even if func is None self.assertEqual( @@ -541,7 +541,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 ") @@ -627,7 +627,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: @@ -645,22 +645,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)) @@ -670,7 +670,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) @@ -678,9 +678,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 "", "+", "-": @@ -703,9 +703,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. @@ -723,11 +723,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) @@ -738,79 +738,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__() @@ -832,7 +832,7 @@ class Foo4(int): def __int__(self): - return 42L + return 42 class Foo5(int): def __int__(self): @@ -842,7 +842,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): @@ -938,32 +938,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 "", "+", "-": @@ -973,121 +973,123 @@ 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(long(Foo2()), 42L) - self.assertEqual(long(Foo3()), 0) - self.assertEqual(long(Foo4()), 42) - self.assertRaises(TypeError, long, Foo5()) + self.assertEqual(int(Foo0()), 42) + self.assertEqual(int(Foo1()), 42) + # XXX invokes __int__ now + # self.assertEqual(long(Foo2()), 42L) + self.assertEqual(int(Foo3()), 0) + # XXX likewise + # self.assertEqual(long(Foo4()), 42) + # self.assertRaises(TypeError, long, Foo5()) def test_map(self): self.assertEqual( @@ -1175,9 +1177,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 @@ -1209,9 +1211,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) @@ -1251,9 +1253,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): @@ -1310,20 +1312,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.) @@ -1340,9 +1342,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): @@ -1352,8 +1354,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) @@ -1372,12 +1374,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) @@ -1398,7 +1400,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): @@ -1429,7 +1431,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({}), '{}') @@ -1485,7 +1487,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({}), '{}') @@ -1660,7 +1662,7 @@ run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": Modified: python/branches/p3yk-noslice/Lib/test/test_bytes.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_bytes.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_bytes.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_capi.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_capi.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_capi.py Fri Feb 23 18:29:35 2007 @@ -11,7 +11,7 @@ if name.startswith('test_'): test = getattr(_testcapi, name) if test_support.verbose: - print "internal", name + print("internal", name) try: test() except _testcapi.error: @@ -23,7 +23,7 @@ import time if test_support.verbose: - print "auto-thread-state" + print("auto-thread-state") idents = [] Modified: python/branches/p3yk-noslice/Lib/test/test_cd.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_cd.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_cd.py Fri Feb 23 18:29:35 2007 @@ -17,10 +17,10 @@ def main(): # touch all the attributes of cd without doing anything if verbose: - print 'Touching cd module attributes...' + print('Touching cd module attributes...') for attr in cdattrs: if verbose: - print 'touching: ', attr + print('touching: ', attr) getattr(cd, attr) main() Modified: python/branches/p3yk-noslice/Lib/test/test_cfgparser.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_cfgparser.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_cfgparser.py Fri Feb 23 18:29:35 2007 @@ -7,18 +7,13 @@ class SortedDict(UserDict.UserDict): def items(self): - result = self.data.items() - result.sort() - return result + return sorted(self.data.items()) def keys(self): - result = self.data.keys() - result.sort() - return result - + return sorted(self.data.keys()) + def values(self): - result = self.items() - return [i[1] for i in values] + return [i[1] for i in self.items()] def iteritems(self): return iter(self.items()) def iterkeys(self): return iter(self.keys()) @@ -446,12 +441,12 @@ "o2=3\n" "o1=4\n" "[a]\n" - "k=v\n") + "k=v\n") output = StringIO.StringIO() self.cf.write(output) self.assertEquals(output.getvalue(), "[a]\n" - "k = v\n\n" + "k = v\n\n" "[b]\n" "o1 = 4\n" "o2 = 3\n" Modified: python/branches/p3yk-noslice/Lib/test/test_cgi.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_cgi.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_cgi.py Fri Feb 23 18:29:35 2007 @@ -118,9 +118,7 @@ ] def norm(seq): - if isinstance(seq, list): - seq.sort(key=repr) - return seq + return sorted(seq, key=repr) def first_elts(list): return map(lambda x:x[0], list) Modified: python/branches/p3yk-noslice/Lib/test/test_cl.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_cl.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_cl.py Fri Feb 23 18:29:35 2007 @@ -69,10 +69,10 @@ def main(): # touch all the attributes of al without doing anything if verbose: - print 'Touching cl module attributes...' + print('Touching cl module attributes...') for attr in clattrs: if verbose: - print 'touching: ', attr + print('touching: ', attr) getattr(cl, attr) main() Modified: python/branches/p3yk-noslice/Lib/test/test_class.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_class.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_class.py Fri Feb 23 18:29:35 2007 @@ -65,73 +65,69 @@ class AllTests: def __hash__(self, *args): - print "__hash__:", args + print("__hash__:", args) return hash(id(self)) def __str__(self, *args): - print "__str__:", args + print("__str__:", args) return "AllTests" def __repr__(self, *args): - print "__repr__:", args + print("__repr__:", args) return "AllTests" def __int__(self, *args): - print "__int__:", args + print("__int__:", args) return 1 def __float__(self, *args): - print "__float__:", args + print("__float__:", args) return 1.0 - def __long__(self, *args): - print "__long__:", args - return 1L - def __oct__(self, *args): - print "__oct__:", args + print("__oct__:", args) return '01' def __hex__(self, *args): - print "__hex__:", args + print("__hex__:", args) return '0x1' def __cmp__(self, *args): - print "__cmp__:", args + print("__cmp__:", args) return 0 def __eq__(self, *args): - print "__eq__:", args + print("__eq__:", args) return True def __ne__(self, *args): - print "__ne__:", args + print("__ne__:", args) return False def __lt__(self, *args): - print "__lt__:", args + print("__lt__:", args) return False def __le__(self, *args): - print "__le__:", args + print("__le__:", args) return True def __gt__(self, *args): - print "__gt__:", args + print("__gt__:", args) return False def __ge__(self, *args): - print "__ge__:", args + print("__ge__:", args) return True def __del__(self, *args): - print "__del__:", args + print("__del__:", args) # Synthesize AllTests methods from the names in testmeths. method_template = """\ def __%(method)s__(self, *args): - print "__%(method)s__:", args + print("__%(method)s__:", args) """ d = {} @@ -190,7 +186,7 @@ try: 1 in Empty() - print 'failed, should have raised TypeError' + print('failed, should have raised TypeError') except TypeError: pass @@ -228,9 +224,9 @@ else: # This works under Jython, but the actual slice values are # different. - print "__getitem__: (slice(0, 42, None),)" - print "__setitem__: (slice(0, 42, None), 'The Answer')" - print "__delitem__: (slice(0, 42, None),)" + print("__getitem__: (slice(0, 42, None),)") + print("__setitem__: (slice(0, 42, None), 'The Answer')") + print("__delitem__: (slice(0, 42, None),)") # Unary operations @@ -238,7 +234,7 @@ +testme abs(testme) int(testme) -long(testme) +int(testme) float(testme) oct(testme) hex(testme) @@ -269,14 +265,14 @@ class ExtraTests: def __getattr__(self, *args): - print "__getattr__:", args + print("__getattr__:", args) return "SomeVal" def __setattr__(self, *args): - print "__setattr__:", args + print("__setattr__:", args) def __delattr__(self, *args): - print "__delattr__:", args + print("__delattr__:", args) testme = ExtraTests() testme.spam @@ -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: @@ -374,7 +349,7 @@ A().a # Raised AttributeError: A instance has no attribute 'a' except AttributeError as x: if str(x) != "booh": - print "attribute error for A().a got masked:", str(x) + print("attribute error for A().a got masked:", str(x)) class E: __eq__ = property(booh) @@ -387,7 +362,7 @@ except AttributeError as x: pass else: - print "attribute error for I.__init__ got masked" + print("attribute error for I.__init__ got masked") # Test comparison and hash of methods Modified: python/branches/p3yk-noslice/Lib/test/test_cmath.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_cmath.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_cmath.py Fri Feb 23 18:29:35 2007 @@ -43,10 +43,10 @@ f = getattr(cmath, func) r = f(testdict[func]) if verbose: - print 'Calling %s(%f) = %f' % (func, testdict[func], abs(r)) + print('Calling %s(%f) = %f' % (func, testdict[func], abs(r))) p = cmath.pi e = cmath.e if verbose: - print 'PI = ', abs(p) - print 'E = ', abs(e) + print('PI = ', abs(p)) + print('E = ', abs(e)) Modified: python/branches/p3yk-noslice/Lib/test/test_code.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_code.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_code.py Fri Feb 23 18:29:35 2007 @@ -50,15 +50,15 @@ consts: ('None',) >>> def attrs(obj): -... print obj.attr1 -... print obj.attr2 -... print obj.attr3 +... print(obj.attr1) +... print(obj.attr2) +... print(obj.attr3) >>> dump(attrs.func_code) name: attrs argcount: 1 kwonlyargcount: 0 -names: ('attr1', 'attr2', 'attr3') +names: ('print', 'attr1', 'attr2', 'attr3') varnames: ('obj',) cellvars: () freevars: () @@ -70,7 +70,7 @@ ... 'doc string' ... 'not a docstring' ... 53 -... 53L +... 0x53 >>> dump(optimize_away.func_code) name: optimize_away @@ -115,8 +115,8 @@ """Print out a text representation of a code object.""" for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames", "cellvars", "freevars", "nlocals", "flags"]: - print "%s: %s" % (attr, getattr(co, "co_" + attr)) - print "consts:", tuple(consts(co.co_consts)) + print("%s: %s" % (attr, getattr(co, "co_" + attr))) + print("consts:", tuple(consts(co.co_consts))) def test_main(verbose=None): from test.test_support import run_doctest Modified: python/branches/p3yk-noslice/Lib/test/test_codecs.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_codecs.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_codecs.py Fri Feb 23 18:29:35 2007 @@ -548,7 +548,7 @@ for i in punycode_testcases: if len(i)!=2: - print repr(i) + print(repr(i)) class PunycodeTest(unittest.TestCase): def test_encode(self): Modified: python/branches/p3yk-noslice/Lib/test/test_compare.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_compare.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_compare.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_compile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_compile.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_compile.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_compiler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_compiler.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_compiler.py Fri Feb 23 18:29:35 2007 @@ -7,6 +7,12 @@ # How much time in seconds can pass before we print a 'Still working' message. _PRINT_WORKING_MSG_INTERVAL = 5 * 60 +class TrivialContext(object): + def __enter__(self): + return self + def __exit__(self, *exc_info): + pass + class CompilerTest(unittest.TestCase): def testCompileLibrary(self): @@ -24,8 +30,7 @@ # Print still working message since this test can be really slow if next_time <= time.time(): next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - print >>sys.__stdout__, \ - ' testCompileLibrary still working, be patient...' + print(' testCompileLibrary still working, be patient...', file=sys.__stdout__) sys.__stdout__.flush() if not basename.endswith(".py"): @@ -34,7 +39,7 @@ continue path = os.path.join(dir, basename) if test.test_support.verbose: - print "compiling", path + print("compiling", path) f = open(path, "U") buf = f.read() f.close() @@ -88,7 +93,7 @@ try: self._check_lineno(node) except AssertionError: - print node.__class__, node.lineno + print(node.__class__, node.lineno) raise def _check_lineno(self, node): @@ -157,6 +162,31 @@ exec(c, dct) self.assertEquals(dct['f'].func_annotations, expected) + def testWith(self): + # SF bug 1638243 + c = compiler.compile('from __future__ import with_statement\n' + 'def f():\n' + ' with TrivialContext():\n' + ' return 1\n' + 'result = f()', + '', + 'exec' ) + dct = {'TrivialContext': TrivialContext} + exec(c, dct) + self.assertEquals(dct.get('result'), 1) + + def testWithAss(self): + c = compiler.compile('from __future__ import with_statement\n' + 'def f():\n' + ' with TrivialContext() as tc:\n' + ' return 1\n' + 'result = f()', + '', + 'exec' ) + dct = {'TrivialContext': TrivialContext} + exec(c, dct) + self.assertEquals(dct.get('result'), 1) + NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard, compiler.ast.Const) @@ -187,7 +217,7 @@ a, b = b, a try: - print yo + print(yo) except: yo = 3 else: Modified: python/branches/p3yk-noslice/Lib/test/test_complex.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_complex.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_complex.py Fri Feb 23 18:29:35 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) @@ -315,7 +315,7 @@ fo = None try: fo = open(test_support.TESTFN, "wb") - print >>fo, a, b + print(a, b, file=fo) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), "%s %s\n" % (a, b)) Modified: python/branches/p3yk-noslice/Lib/test/test_cookie.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_cookie.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_cookie.py Fri Feb 23 18:29:35 2007 @@ -38,7 +38,7 @@ C.load(case['data']) self.assertEqual(repr(C), case['repr']) self.assertEqual(C.output(sep='\n'), case['output']) - for k, v in sorted(case['dict'].iteritems()): + for k, v in sorted(case['dict'].items()): self.assertEqual(C[k].value, v) def test_load(self): Modified: python/branches/p3yk-noslice/Lib/test/test_cookielib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_cookielib.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_cookielib.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_copy.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_copy.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_copy.py Fri Feb 23 18:29:35 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: @@ -491,7 +491,7 @@ def test_reduce_5tuple(self): class C(dict): def __reduce__(self): - return (C, (), self.__dict__, None, self.iteritems()) + return (C, (), self.__dict__, None, self.items()) def __eq__(self, other): return (dict(self) == dict(other) and self.__dict__ == other.__dict__) Modified: python/branches/p3yk-noslice/Lib/test/test_copy_reg.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_copy_reg.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_copy_reg.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_crypt.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_crypt.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_crypt.py Fri Feb 23 18:29:35 2007 @@ -8,4 +8,4 @@ c = crypt.crypt('mypassword', 'ab') if verbose: - print 'Test encryption: ', c + print('Test encryption: ', c) Modified: python/branches/p3yk-noslice/Lib/test/test_csv.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_csv.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_csv.py Fri Feb 23 18:29:35 2007 @@ -894,7 +894,7 @@ self.assertEqual(dialect.quotechar, "'") if not hasattr(sys, "gettotalrefcount"): - if test_support.verbose: print "*** skipping leakage tests ***" + if test_support.verbose: print("*** skipping leakage tests ***") else: class NUL: def write(s, *args): Modified: python/branches/p3yk-noslice/Lib/test/test_curses.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_curses.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_curses.py Fri Feb 23 18:29:35 2007 @@ -228,7 +228,7 @@ ('\x8a', '!^J'), ('\xc1', '!A'), ]: if ascii.unctrl(ch) != expected: - print 'curses.unctrl fails on character', repr(ch) + print('curses.unctrl fails on character', repr(ch)) def test_userptr_without_set(stdscr): Modified: python/branches/p3yk-noslice/Lib/test/test_datetime.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_datetime.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_datetime.py Fri Feb 23 18:29:35 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) @@ -1767,6 +1767,11 @@ self.assertEqual(t.isoformat(), "00:00:00.100000") self.assertEqual(t.isoformat(), str(t)) + def test_1653736(self): + # verify it doesn't accept extra keyword arguments + t = self.theclass(second=1) + self.assertRaises(TypeError, t.isoformat, foo=3) + def test_strftime(self): t = self.theclass(1, 2, 3, 4) self.assertEqual(t.strftime('%H %M %S'), "01 02 03") @@ -3287,11 +3292,11 @@ gc.garbage) if hasattr(sys, 'gettotalrefcount'): thisrc = sys.gettotalrefcount() - print >> sys.stderr, '*' * 10, 'total refs:', thisrc, + print('*' * 10, 'total refs:', thisrc, end=' ', file=sys.stderr) if lastrc: - print >> sys.stderr, 'delta:', thisrc - lastrc + print('delta:', thisrc - lastrc, file=sys.stderr) else: - print >> sys.stderr + print(file=sys.stderr) lastrc = thisrc if __name__ == "__main__": Modified: python/branches/p3yk-noslice/Lib/test/test_dbm.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_dbm.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_dbm.py Fri Feb 23 18:29:35 2007 @@ -31,7 +31,7 @@ d.keys() if 'a' in d: if verbose: - print 'Test dbm keys: ', d.keys() + print('Test dbm keys: ', d.keys()) d.close() Modified: python/branches/p3yk-noslice/Lib/test/test_decimal.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_decimal.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_decimal.py Fri Feb 23 18:29:35 2007 @@ -143,8 +143,8 @@ try: t = self.eval_line(line) except InvalidOperation: - print 'Error in test cases:' - print line + print('Error in test cases:') + print(line) continue except DecimalException as exception: #Exception raised where there shoudn't have been one. @@ -271,7 +271,7 @@ 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 + print("ERROR:", s) raise myexceptions = self.getexceptions() @@ -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-noslice/Lib/test/test_defaultdict.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_defaultdict.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_defaultdict.py Fri Feb 23 18:29:35 2007 @@ -47,6 +47,7 @@ self.assertEqual(err.args, (15,)) else: self.fail("d2[15] didn't raise KeyError") + self.assertRaises(TypeError, defaultdict, 1) def test_missing(self): d1 = defaultdict() @@ -60,10 +61,10 @@ self.assertEqual(repr(d1), "defaultdict(None, {})") d1[11] = 41 self.assertEqual(repr(d1), "defaultdict(None, {11: 41})") - d2 = defaultdict(0) - self.assertEqual(d2.default_factory, 0) + d2 = defaultdict(int) + self.assertEqual(d2.default_factory, int) d2[12] = 42 - self.assertEqual(repr(d2), "defaultdict(0, {12: 42})") + self.assertEqual(repr(d2), "defaultdict(, {12: 42})") def foo(): return 43 d3 = defaultdict(foo) self.assert_(d3.default_factory is foo) @@ -81,8 +82,8 @@ try: f = open(tfn, "w+") try: - print >>f, d1 - print >>f, d2 + print(d1, file=f) + print(d2, file=f) f.seek(0) self.assertEqual(f.readline(), repr(d1) + "\n") self.assertEqual(f.readline(), repr(d2) + "\n") Modified: python/branches/p3yk-noslice/Lib/test/test_deque.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_deque.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_deque.py Fri Feb 23 18:29:35 2007 @@ -245,7 +245,7 @@ d.append(d) try: fo = open(test_support.TESTFN, "wb") - print >> fo, d, + fo.write(str(d)) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(d)) @@ -486,6 +486,16 @@ d1 == d2 # not clear if this is supposed to be True or False, # but it used to give a SystemError + +class SubclassWithKwargs(deque): + def __init__(self, newarg=1): + deque.__init__(self) + +class TestSubclassWithKwargs(unittest.TestCase): + def test_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError + SubclassWithKwargs(newarg=1) + #============================================================================== libreftest = """ @@ -494,7 +504,7 @@ >>> from collections import deque >>> d = deque('ghi') # make a new deque with three items >>> for elem in d: # iterate over the deque's elements -... print elem.upper() +... print(elem.upper()) G H I @@ -564,8 +574,8 @@ ... >>> for value in roundrobin('abc', 'd', 'efgh'): -... print value -... +... print(value) +... a d e @@ -583,7 +593,7 @@ ... d.append(pair) ... return list(d) ... ->>> print maketree('abcdefgh') +>>> print(maketree('abcdefgh')) [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]] """ @@ -599,6 +609,7 @@ TestBasic, TestVariousIteratorArgs, TestSubclass, + TestSubclassWithKwargs, ) test_support.run_unittest(*test_classes) @@ -611,7 +622,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) # doctests from test import test_deque Modified: python/branches/p3yk-noslice/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_descr.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_descr.py Fri Feb 23 18:29:35 2007 @@ -13,7 +13,7 @@ raise TestFailed, "%r is %r" % (a, b) def testunop(a, res, expr="len(a)", meth="__len__"): - if verbose: print "checking", expr + if verbose: print("checking", expr) dict = {'a': a} vereq(eval(expr, dict), res) t = type(a) @@ -26,7 +26,7 @@ vereq(bm(), res) def testbinop(a, b, res, expr="a+b", meth="__add__"): - if verbose: print "checking", expr + if verbose: print("checking", expr) dict = {'a': a, 'b': b} vereq(eval(expr, dict), res) @@ -40,7 +40,7 @@ vereq(bm(b), res) def testternop(a, b, c, res, expr="a[b:c]", meth="__getitem__"): - if verbose: print "checking", expr + if verbose: print("checking", expr) dict = {'a': a, 'b': b, 'c': c} vereq(eval(expr, dict), res) t = type(a) @@ -53,7 +53,7 @@ vereq(bm(slice(b, c, None)), res) def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"): - if verbose: print "checking", stmt + if verbose: print("checking", stmt) dict = {'a': deepcopy(a), 'b': b} exec(stmt, dict) vereq(dict['a'], res) @@ -71,7 +71,7 @@ vereq(dict['a'], res) def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"): - if verbose: print "checking", stmt + if verbose: print("checking", stmt) dict = {'a': deepcopy(a), 'b': b, 'c': c} exec(stmt, dict) vereq(dict['a'], res) @@ -89,7 +89,7 @@ vereq(dict['a'], res) def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"): - if verbose: print "checking", stmt + if verbose: print("checking", stmt) dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d} exec(stmt, dict) vereq(dict['a'], res) @@ -135,7 +135,7 @@ verify(NewDynamic2.__doc__ is None) def lists(): - if verbose: print "Testing list operations..." + if verbose: print("Testing list operations...") testbinop([1], [2], [1,2], "a+b", "__add__") testbinop([1,2,3], 2, 1, "b in a", "__contains__") testbinop([1,2,3], 4, 0, "b in a", "__contains__") @@ -150,7 +150,7 @@ testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setitem__") def dicts(): - if verbose: print "Testing dict operations..." + if verbose: print("Testing dict operations...") ##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__") testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__") @@ -175,7 +175,7 @@ def dict_constructor(): if verbose: - print "Testing dict constructor ..." + print("Testing dict constructor ...") d = dict() vereq(d, {}) d = dict({}) @@ -183,7 +183,7 @@ d = dict({1: 2, 'a': 'b'}) vereq(d, {1: 2, 'a': 'b'}) vereq(d, dict(d.items())) - vereq(d, dict(d.iteritems())) + vereq(d, dict(d.items())) d = dict({'one':1, 'two':2}) vereq(d, dict(one=1, two=2)) vereq(d, dict(**d)) @@ -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: @@ -258,13 +258,13 @@ def test_dir(): if verbose: - print "Testing dir() ..." + print("Testing dir() ...") junk = 12 vereq(dir(), ['junk']) 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', @@ -414,7 +413,7 @@ testunop(a, res, expr, name) def ints(): - if verbose: print "Testing int operations..." + if verbose: print("Testing int operations...") numops(100, 3) # The following crashes in Python 2.2 vereq((1).__bool__(), True) @@ -423,31 +422,24 @@ class C(int): def __add__(self, other): return NotImplemented - vereq(C(5L), 5) + vereq(C(5), 5) try: C() + "" except TypeError: 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..." - numops(100L, 3L) + if verbose: print("Testing long operations...") + numops(100, 3) def floats(): - if verbose: print "Testing float operations..." + if verbose: print("Testing float operations...") numops(100.0, 3.0) def complexes(): - if verbose: print "Testing complex operations..." + if verbose: print("Testing complex operations...") numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float']) class Number(complex): __slots__ = ['prec'] @@ -477,7 +469,7 @@ vereq(a.prec, 12) def spamlists(): - if verbose: print "Testing spamlist operations..." + if verbose: print("Testing spamlist operations...") import copy, xxsubtype as spam def spamlist(l, memo=None): import xxsubtype as spam @@ -513,7 +505,7 @@ vereq(a.getstate(), 42) def spamdicts(): - if verbose: print "Testing spamdict operations..." + if verbose: print("Testing spamdict operations...") import copy, xxsubtype as spam def spamdict(d, memo=None): import xxsubtype as spam @@ -549,16 +541,16 @@ class C(spam.spamdict): def foo(self): return 1 a = C() - vereq(a.items(), []) + vereq(list(a.items()), []) vereq(a.foo(), 1) a['foo'] = 'bar' - vereq(a.items(), [('foo', 'bar')]) + vereq(list(a.items()), [('foo', 'bar')]) vereq(a.getstate(), 0) a.setstate(100) vereq(a.getstate(), 100) def pydicts(): - if verbose: print "Testing Python subclass of dict..." + if verbose: print("Testing Python subclass of dict...") verify(issubclass(dict, dict)) verify(isinstance({}, dict)) d = dict() @@ -599,7 +591,7 @@ vereq(a[42], 0) a[42] = 24 vereq(a[42], 24) - if verbose: print "pydict stress test ..." + if verbose: print("pydict stress test ...") N = 50 for i in range(N): a[i] = C() @@ -610,7 +602,7 @@ vereq(a[i][j], i*j) def pylists(): - if verbose: print "Testing Python subclass of list..." + if verbose: print("Testing Python subclass of list...") class C(list): def __getitem__(self, i): if isinstance(i, slice): @@ -624,7 +616,7 @@ vereq(a[100:200], (100,200)) def metaclass(): - if verbose: print "Testing __metaclass__..." + if verbose: print("Testing __metaclass__...") class C: __metaclass__ = type def __init__(self): @@ -722,7 +714,7 @@ # named _get_x and/or _set_x are found def __new__(metaclass, name, bases, dict): hits = {} - for key, val in dict.iteritems(): + for key, val in dict.items(): if key.startswith("_get_"): key = key[5:] get, set = hits.get(key, (None, None)) @@ -733,7 +725,7 @@ get, set = hits.get(key, (None, None)) set = val hits[key] = get, set - for key, (get, set) in hits.iteritems(): + for key, (get, set) in hits.items(): dict[key] = property(get, set) return super(autoproperty, metaclass).__new__(metaclass, name, bases, dict) @@ -786,7 +778,7 @@ else: raise TestFailed, "calling object w/o call method should raise TypeError" def pymods(): - if verbose: print "Testing Python subclass of module..." + if verbose: print("Testing Python subclass of module...") log = [] import sys MT = type(sys) @@ -811,7 +803,7 @@ ("delattr", "foo")]) def multi(): - if verbose: print "Testing multiple inheritance..." + if verbose: print("Testing multiple inheritance...") class C(object): def __init__(self): self.__state = 0 @@ -828,9 +820,9 @@ type({}).__init__(self) C.__init__(self) d = D() - vereq(d.keys(), []) + vereq(list(d.keys()), []) d["hello"] = "world" - vereq(d.items(), [("hello", "world")]) + vereq(list(d.items()), [("hello", "world")]) vereq(d["hello"], "world") vereq(d.getstate(), 0) d.setstate(10) @@ -852,7 +844,7 @@ vereq(int(Frag()), 42) def diamond(): - if verbose: print "Testing multiple inheritance special cases..." + if verbose: print("Testing multiple inheritance special cases...") class A(object): def spam(self): return "A" vereq(A().spam(), "A") @@ -890,7 +882,7 @@ # see thread python-dev/2002-October/029035.html def ex5(): - if verbose: print "Testing ex5 from C3 switch discussion..." + if verbose: print("Testing ex5 from C3 switch discussion...") class A(object): pass class B(object): pass class C(object): pass @@ -902,7 +894,7 @@ # see "A Monotonic Superclass Linearization for Dylan", # by Kim Barrett et al. (OOPSLA 1996) def monotonicity(): - if verbose: print "Testing MRO monotonicity..." + if verbose: print("Testing MRO monotonicity...") class Boat(object): pass class DayBoat(Boat): pass class WheelBoat(Boat): pass @@ -925,7 +917,7 @@ # see "A Monotonic Superclass Linearization for Dylan", # by Kim Barrett et al. (OOPSLA 1996) def consistency_with_epg(): - if verbose: print "Testing consistentcy with EPG..." + if verbose: print("Testing consistentcy with EPG...") class Pane(object): pass class ScrollingMixin(object): pass class EditingMixin(object): pass @@ -941,7 +933,7 @@ order (MRO) for bases """ def mro_disagreement(): - if verbose: print "Testing error messages for MRO disagreement..." + if verbose: print("Testing error messages for MRO disagreement...") def raises(exc, expected, callable, *args): try: callable(*args) @@ -971,7 +963,7 @@ type, "ConfusedGrid", (HVGrid, VHGrid), {}) def objects(): - if verbose: print "Testing object class..." + if verbose: print("Testing object class...") a = object() vereq(a.__class__, object) vereq(type(a), object) @@ -995,7 +987,7 @@ vereq(x.__dict__, {'foo': 1}) def slots(): - if verbose: print "Testing __slots__..." + if verbose: print("Testing __slots__...") class C0(object): __slots__ = [] x = C0() @@ -1160,7 +1152,7 @@ sys.stderr = save_stderr def slotspecials(): - if verbose: print "Testing __dict__ and __weakref__ in __slots__..." + if verbose: print("Testing __dict__ and __weakref__ in __slots__...") class D(object): __slots__ = ["__dict__"] @@ -1207,7 +1199,7 @@ # __slots__ = [] def dynamics(): - if verbose: print "Testing class attribute propagation..." + if verbose: print("Testing class attribute propagation...") class D(object): pass class E(D): @@ -1270,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) @@ -1286,7 +1278,7 @@ verify(someclass != object) def errors(): - if verbose: print "Testing errors..." + if verbose: print("Testing errors...") try: class C(list, dict): @@ -1331,7 +1323,7 @@ verify(0, "__slots__ = [1] should be illegal") def classmethods(): - if verbose: print "Testing class methods..." + if verbose: print("Testing class methods...") class C(object): def foo(*a): return a goo = classmethod(foo) @@ -1377,7 +1369,7 @@ raise TestFailed, "classmethod shouldn't accept keyword args" def classmethods_in_c(): - if verbose: print "Testing C-based class methods..." + if verbose: print("Testing C-based class methods...") import xxsubtype as spam a = (1, 2, 3) d = {'abc': 123} @@ -1391,7 +1383,7 @@ vereq(d, d1) def staticmethods(): - if verbose: print "Testing static methods..." + if verbose: print("Testing static methods...") class C(object): def foo(*a): return a goo = staticmethod(foo) @@ -1408,7 +1400,7 @@ vereq(D.foo(d, 1), (d, 1)) def staticmethods_in_c(): - if verbose: print "Testing C-based static methods..." + if verbose: print("Testing C-based static methods...") import xxsubtype as spam a = (1, 2, 3) d = {"abc": 123} @@ -1422,7 +1414,7 @@ vereq(d, d1) def classic(): - if verbose: print "Testing classic classes..." + if verbose: print("Testing classic classes...") class C: def foo(*a): return a goo = classmethod(foo) @@ -1443,7 +1435,7 @@ verify(repr(C.foo.__get__(C())).startswith("> 12).__class__ is int) - class octlong(long): + class octlong(int): __slots__ = [] def __str__(self): s = oct(self) @@ -2056,45 +2048,45 @@ # 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'] def __init__(self, value=0.0, prec=12): self.prec = int(prec) - float.__init__(value) + float.__init__(self, value) def __repr__(self): return "%.*g" % (self.prec, self) vereq(repr(precfloat(1.1)), "1.1") @@ -2363,10 +2355,10 @@ def keywords(): if verbose: - print "Testing keyword args to basic type constructors ..." + 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 +2366,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) @@ -2389,7 +2381,7 @@ return import rexec if verbose: - print "Testing interaction with restricted execution ..." + print("Testing interaction with restricted execution ...") sandbox = rexec.RExec() @@ -2429,7 +2421,7 @@ def str_subclass_as_dict_key(): if verbose: - print "Testing a str subclass used as dict key .." + print("Testing a str subclass used as dict key ..") class cistr(str): """Sublcass of str that computes __eq__ case-insensitively. @@ -2461,48 +2453,48 @@ vereq(d.get(cistr('thrEE')), 3) def classic_comparisons(): - if verbose: print "Testing classic comparisons..." + if verbose: print("Testing classic comparisons...") class classic: pass for base in (classic, int, object): - if verbose: print " (base = %s)" % base + if verbose: print(" (base = %s)" % base) class C(base): def __init__(self, value): self.value = int(value) 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 @@ -2522,7 +2514,7 @@ def rich_comparisons(): if verbose: - print "Testing rich comparisons..." + print("Testing rich comparisons...") class Z(complex): pass z = Z(1) @@ -2541,7 +2533,7 @@ class classic: pass for base in (classic, int, object, list): - if verbose: print " (base = %s)" % base + if verbose: print(" (base = %s)" % base) class C(base): def __init__(self, value): self.value = int(value) @@ -2550,37 +2542,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) @@ -2599,14 +2591,14 @@ "x=%d, y=%d" % (x, y)) def descrdoc(): - if verbose: print "Testing descriptor doc strings..." + if verbose: print("Testing descriptor doc strings...") def check(descr, what): vereq(descr.__doc__, what) check(file.closed, "True if the file is closed") # getset descriptor check(file.name, "file name") # member descriptor def setclass(): - if verbose: print "Testing __class__ assignment..." + if verbose: print("Testing __class__ assignment...") class C(object): pass class D(object): pass class E(object): pass @@ -2648,7 +2640,7 @@ del o def setdict(): - if verbose: print "Testing __dict__ assignment..." + if verbose: print("Testing __dict__ assignment...") class C(object): pass a = C() a.__dict__ = {'b': 1} @@ -2669,7 +2661,7 @@ def pickles(): if verbose: - print "Testing pickling and copying new-style classes and objects..." + print("Testing pickling and copying new-style classes and objects...") import pickle try: import cPickle @@ -2677,9 +2669,7 @@ cPickle = None def sorteditems(d): - L = d.items() - L.sort() - return L + return sorted(d.items()) global C class C(object): @@ -2734,7 +2724,7 @@ continue # cPickle not found -- skip it for bin in 0, 1: if verbose: - print p.__name__, ["text", "binary"][bin] + print(p.__name__, ["text", "binary"][bin]) for cls in C, C1, C2: s = p.dumps(cls, bin) @@ -2752,8 +2742,8 @@ vereq(repr(x), repr(a)) vereq(repr(y), repr(b)) if verbose: - print "a = x =", a - print "b = y =", b + print("a = x =", a) + print("b = y =", b) # Test for __getstate__ and __setstate__ on new style class u = C3(42) s = p.dumps(u, bin) @@ -2770,7 +2760,7 @@ # Testing copy.deepcopy() if verbose: - print "deepcopy" + print("deepcopy") import copy for cls in C, C1, C2: cls2 = copy.deepcopy(cls) @@ -2786,11 +2776,11 @@ vereq(repr(x), repr(a)) vereq(repr(y), repr(b)) if verbose: - print "a = x =", a - print "b = y =", b + print("a = x =", a) + print("b = y =", b) def pickleslots(): - if verbose: print "Testing pickling of classes with __slots__ ..." + if verbose: print("Testing pickling of classes with __slots__ ...") import pickle, pickle as cPickle # Pickling of classes with __slots__ but without __getstate__ should fail global B, C, D, E @@ -2877,7 +2867,7 @@ vereq(y.b, x.b) def copies(): - if verbose: print "Testing copy.copy() and copy.deepcopy()..." + if verbose: print("Testing copy.copy() and copy.deepcopy()...") import copy class C(object): pass @@ -2898,7 +2888,7 @@ vereq(d.bar, [1,2,3]) def binopoverride(): - if verbose: print "Testing overrides of binary operations..." + if verbose: print("Testing overrides of binary operations...") class I(int): def __repr__(self): return "I(%r)" % int(self) @@ -2928,7 +2918,7 @@ return self.lower() == other.lower() def subclasspropagation(): - if verbose: print "Testing propagation of slot functions to subclasses..." + if verbose: print("Testing propagation of slot functions to subclasses...") class A(object): pass class B(A): @@ -3001,7 +2991,7 @@ import binascii # SF bug [#470040] ParseTuple t# vs subclasses. if verbose: - print "Testing that buffer interface is inherited ..." + print("Testing that buffer interface is inherited ...") class MyStr(str): pass @@ -3033,7 +3023,7 @@ import cStringIO if verbose: - print "Testing __str__ defined in subclass of str ..." + print("Testing __str__ defined in subclass of str ...") class octetstring(str): def __str__(self): @@ -3053,13 +3043,13 @@ capture = cStringIO.StringIO() # Calling str() or not exercises different internal paths. - print >> capture, o - print >> capture, str(o) + print(o, file=capture) + print(str(o), file=capture) vereq(capture.getvalue(), '41\n41\n') capture.close() def kwdargs(): - if verbose: print "Testing keyword arguments to __init__, __call__..." + if verbose: print("Testing keyword arguments to __init__, __call__...") def f(a): return a vereq(f.__call__(a=42), 42) a = [] @@ -3067,8 +3057,8 @@ vereq(a, [0, 1, 2]) def recursive__call__(): - if verbose: print ("Testing recursive __call__() by setting to instance of " - "class ...") + if verbose: print(("Testing recursive __call__() by setting to instance of " + "class ...")) class A(object): pass @@ -3082,7 +3072,7 @@ "__call__()") def delhook(): - if verbose: print "Testing __del__ hook..." + if verbose: print("Testing __del__ hook...") log = [] class C(object): def __del__(self): @@ -3099,7 +3089,7 @@ else: raise TestFailed, "invalid del() didn't raise TypeError" def hashinherit(): - if verbose: print "Testing hash of mutable subclasses..." + if verbose: print("Testing hash of mutable subclasses...") class mydict(dict): pass @@ -3168,7 +3158,7 @@ vereq('%c' % '5', '5') def deepcopyrecursive(): - if verbose: print "Testing deepcopy of recursive objects..." + if verbose: print("Testing deepcopy of recursive objects...") class Node: pass a = Node() @@ -3178,7 +3168,7 @@ z = deepcopy(a) # This blew up before def modules(): - if verbose: print "Testing uninitialized module objects..." + if verbose: print("Testing uninitialized module objects...") from types import ModuleType as M m = M.__new__(M) str(m) @@ -3193,8 +3183,8 @@ class C(object): def meth(self): pass - if verbose: print "Testing dict-proxy iterkeys..." - keys = [ key for key in C.__dict__.iterkeys() ] + if verbose: print("Testing dict-proxy iterkeys...") + keys = [ key for key in C.__dict__.keys() ] keys.sort() vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) @@ -3202,21 +3192,21 @@ class C(object): def meth(self): pass - if verbose: print "Testing dict-proxy itervalues..." - values = [ values for values in C.__dict__.itervalues() ] + if verbose: print("Testing dict-proxy itervalues...") + values = [ values for values in C.__dict__.values() ] vereq(len(values), 5) def dictproxyiteritems(): class C(object): def meth(self): pass - if verbose: print "Testing dict-proxy iteritems..." - keys = [ key for (key, value) in C.__dict__.iteritems() ] + if verbose: print("Testing dict-proxy iteritems...") + keys = [ key for (key, value) in C.__dict__.items() ] keys.sort() vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) def funnynew(): - if verbose: print "Testing __new__ returning something unexpected..." + if verbose: print("Testing __new__ returning something unexpected...") class C(object): def __new__(cls, arg): if isinstance(arg, str): return [1, 2, 3] @@ -3238,7 +3228,7 @@ def imulbug(): # SF bug 544647 - if verbose: print "Testing for __imul__ problems..." + if verbose: print("Testing for __imul__ problems...") class C(object): def __imul__(self, other): return (self, other) @@ -3250,11 +3240,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)) @@ -3264,7 +3254,7 @@ def docdescriptor(): # SF bug 542984 - if verbose: print "Testing __doc__ descriptor..." + if verbose: print("Testing __doc__ descriptor...") class DocDescr(object): def __get__(self, object, otype): if object: @@ -3283,7 +3273,7 @@ def copy_setstate(): if verbose: - print "Testing that copy.*copy() correctly uses __setstate__..." + print("Testing that copy.*copy() correctly uses __setstate__...") import copy class C(object): def __init__(self, foo=None): @@ -3311,7 +3301,7 @@ def slices(): if verbose: - print "Testing cases with slices and overridden __getitem__ ..." + print("Testing cases with slices and overridden __getitem__ ...") # Strings vereq("hello"[:4], "hell") vereq("hello"[slice(4)], "hell") @@ -3355,7 +3345,7 @@ def subtype_resurrection(): if verbose: - print "Testing resurrection of new-style instance..." + print("Testing resurrection of new-style instance...") class C(object): container = [] @@ -3385,7 +3375,7 @@ def slottrash(): # Deallocating deeply nested slotted trash caused stack overflows if verbose: - print "Testing slot trash..." + print("Testing slot trash...") class trash(object): __slots__ = ['x'] def __init__(self, x): @@ -3411,7 +3401,7 @@ def testrmul(): # SF patch 592646 if verbose: - print "Testing correct invocation of __rmul__..." + print("Testing correct invocation of __rmul__...") class C(object): def __mul__(self, other): return "mul" @@ -3426,7 +3416,7 @@ def testipow(): # [SF bug 620179] if verbose: - print "Testing correct invocation of __ipow__..." + print("Testing correct invocation of __ipow__...") class C(object): def __ipow__(self, other): pass @@ -3435,7 +3425,7 @@ def do_this_first(): if verbose: - print "Testing SF bug 551412 ..." + print("Testing SF bug 551412 ...") # This dumps core when SF bug 551412 isn't fixed -- # but only when test_descr.py is run separately. # (That can't be helped -- as soon as PyType_Ready() @@ -3444,19 +3434,19 @@ def __pow__(self, *args): pass try: - pow(0L, UserLong(), 0L) + pow(0, UserLong(), 0) except: pass if verbose: - print "Testing SF bug 570483..." + print("Testing SF bug 570483...") # Another segfault only when run early # (before PyType_Ready(tuple) is called) type.mro(tuple) def test_mutable_bases(): if verbose: - print "Testing mutable bases..." + print("Testing mutable bases...") # stuff that should work: class C(object): pass @@ -3546,7 +3536,7 @@ def test_mutable_bases_with_failing_mro(): if verbose: - print "Testing mutable bases with failing mro..." + print("Testing mutable bases with failing mro...") class WorkOnce(type): def __new__(self, name, bases, ns): self.flag = 0 @@ -3601,7 +3591,7 @@ def test_mutable_bases_catch_mro_conflict(): if verbose: - print "Testing mutable bases catch mro conflict..." + print("Testing mutable bases catch mro conflict...") class A(object): pass @@ -3626,7 +3616,7 @@ def mutable_names(): if verbose: - print "Testing mutable names..." + print("Testing mutable names...") class C(object): pass @@ -3641,7 +3631,7 @@ def subclass_right_op(): if verbose: - print "Testing correct dispatch of subclass overloading __r__..." + print("Testing correct dispatch of subclass overloading __r__...") # This code tests various cases where right-dispatch of a subclass # should be preferred over left-dispatch of a base class. @@ -3693,7 +3683,7 @@ def dict_type_with_metaclass(): if verbose: - print "Testing type of __dict__ when __metaclass__ set..." + print("Testing type of __dict__ when __metaclass__ set...") class B(object): pass @@ -3707,7 +3697,7 @@ def meth_class_get(): # Full coverage of descrobject.c::classmethod_get() if verbose: - print "Testing __get__ method of METH_CLASS C methods..." + print("Testing __get__ method of METH_CLASS C methods...") # Baseline arg = [1, 2, 3] res = {1: None, 2: None, 3: None} @@ -3746,7 +3736,7 @@ def isinst_isclass(): if verbose: - print "Testing proxy isinstance() and isclass()..." + print("Testing proxy isinstance() and isclass()...") class Proxy(object): def __init__(self, obj): self.__obj = obj @@ -3786,7 +3776,7 @@ def proxysuper(): if verbose: - print "Testing super() for a proxy object..." + print("Testing super() for a proxy object...") class Proxy(object): def __init__(self, obj): self.__obj = obj @@ -3810,7 +3800,7 @@ def carloverre(): if verbose: - print "Testing prohibition of Carlo Verre's hack..." + print("Testing prohibition of Carlo Verre's hack...") try: object.__setattr__(str, "foo", 42) except TypeError: @@ -3827,7 +3817,7 @@ def weakref_segfault(): # SF 742911 if verbose: - print "Testing weakref segfault..." + print("Testing weakref segfault...") import weakref @@ -3855,7 +3845,7 @@ # Fix SF #762455, segfault when sys.stdout is changed in getattr def filefault(): if verbose: - print "Testing sys.stdout is changed in getattr..." + print("Testing sys.stdout is changed in getattr...") import sys class StdoutGuard: def __getattr__(self, attr): @@ -3863,7 +3853,7 @@ raise RuntimeError("Premature access to sys.stdout.%s" % attr) sys.stdout = StdoutGuard() try: - print "Oops!" + print("Oops!") except RuntimeError: pass @@ -3872,7 +3862,7 @@ # python-dev 2003-04-17, turned into an example & fixed by Michael # Hudson just less than four months later... if verbose: - print "Testing vicious_descriptor_nonsense..." + print("Testing vicious_descriptor_nonsense...") class Evil(object): def __hash__(self): @@ -3911,7 +3901,7 @@ def methodwrapper(): # did not support any reflection before 2.5 if verbose: - print "Testing method-wrapper objects..." + print("Testing method-wrapper objects...") return # XXX should methods really support __eq__? @@ -3939,7 +3929,7 @@ def notimplemented(): # all binary methods should be able to return a NotImplemented if verbose: - print "Testing NotImplemented..." + print("Testing NotImplemented...") import sys import types @@ -3956,7 +3946,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]: @@ -4099,7 +4089,7 @@ methodwrapper() notimplemented() - if verbose: print "All OK" + if verbose: print("All OK") if __name__ == "__main__": test_main() Modified: python/branches/p3yk-noslice/Lib/test/test_descrtut.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_descrtut.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_descrtut.py Fri Feb 23 18:29:35 2007 @@ -36,28 +36,28 @@ Here's the new type at work: - >>> print defaultdict # show our type + >>> print(defaultdict) # show our type - >>> print type(defaultdict) # its metatype + >>> print(type(defaultdict)) # its metatype >>> a = defaultdict(default=0.0) # create an instance - >>> print a # show the instance + >>> print(a) # show the instance {} - >>> print type(a) # show its type + >>> print(type(a)) # show its type - >>> print a.__class__ # show its class + >>> print(a.__class__) # show its class - >>> print type(a) is a.__class__ # its type is its class + >>> print(type(a) is a.__class__) # its type is its class True >>> a[1] = 3.25 # modify the instance - >>> print a # show the new value + >>> print(a) # show the new value {1: 3.25} - >>> print a[1] # show the new item + >>> print(a[1]) # show the new item 3.25 - >>> print a[0] # a non-existant item + >>> print(a[0]) # a non-existant item 0.0 >>> a.merge({1:100, 2:200}) # use a dict method - >>> print sortdict(a) # show the result + >>> print(sortdict(a)) # show the result {1: 3.25, 2: 200} >>> @@ -65,13 +65,14 @@ dictionaries, such as the locals/globals dictionaries for the exec statement or the built-in function eval(): - >>> print sorted(a.keys()) + >>> print(sorted(a.keys())) [1, 2] - >>> exec("x = 3; print x", a) + >>> a['print'] = print # need the print function here + >>> exec("x = 3; print(x)", a) 3 - >>> print sorted(a.keys(), key=lambda x: (str(type(x)), x)) - [1, 2, '__builtins__', 'x'] - >>> print a['x'] + >>> print(sorted(a.keys(), key=lambda x: (str(type(x)), x))) + [1, 2, '__builtins__', 'print', 'x'] + >>> print(a['x']) 3 >>> @@ -79,21 +80,21 @@ just like classic classes: >>> a.default = -1 - >>> print a["noway"] + >>> print(a["noway"]) -1 >>> a.default = -1000 - >>> print a["noway"] + >>> print(a["noway"]) -1000 >>> 'default' in dir(a) True >>> a.x1 = 100 >>> a.x2 = 200 - >>> print a.x1 + >>> print(a.x1) 100 >>> d = dir(a) >>> 'default' in d and 'x1' in d and 'x2' in d True - >>> print sortdict(a.__dict__) + >>> print(sortdict(a.__dict__)) {'default': -1000, 'x1': 100, 'x2': 200} >>> """ @@ -239,10 +240,10 @@ static methods in C++ or Java. Here's an example: >>> class C: - ... + ... ... @staticmethod ... def foo(x, y): - ... print "staticmethod", x, y + ... print("staticmethod", x, y) >>> C.foo(1, 2) staticmethod 1 2 @@ -256,7 +257,7 @@ >>> class C: ... @classmethod ... def foo(cls, y): - ... print "classmethod", cls, y + ... print("classmethod", cls, y) >>> C.foo(1) classmethod 1 @@ -282,7 +283,7 @@ >>> class E(C): ... @classmethod ... def foo(cls, y): # override C.foo - ... print "E.foo() called" + ... print("E.foo() called") ... C.foo(y) >>> E.foo(1) @@ -340,10 +341,10 @@ >>> a = C() >>> a.x = 10 - >>> print a.x + >>> print(a.x) 10 >>> a.x = -10 - >>> print a.x + >>> print(a.x) 0 >>> @@ -366,10 +367,10 @@ >>> a = C() >>> a.x = 10 - >>> print a.x + >>> print(a.x) 10 >>> a.x = -10 - >>> print a.x + >>> print(a.x) 0 >>> """ @@ -382,12 +383,12 @@ >>> class A: # implicit new-style class ... def save(self): -... print "called A.save()" +... print("called A.save()") >>> class B(A): ... pass >>> class C(A): ... def save(self): -... print "called C.save()" +... print("called C.save()") >>> class D(B, C): ... pass @@ -396,12 +397,12 @@ >>> class A(object): # explicit new-style class ... def save(self): -... print "called A.save()" +... print("called A.save()") >>> class B(A): ... pass >>> class C(A): ... def save(self): -... print "called C.save()" +... print("called C.save()") >>> class D(B, C): ... pass @@ -430,7 +431,7 @@ Cooperative methods and "super" ->>> print D().m() # "DCBA" +>>> print(D().m()) # "DCBA" DCBA """ @@ -440,7 +441,7 @@ >>> class A: ... def foo(self): -... print "called A.foo()" +... print("called A.foo()") >>> class B(A): ... pass Modified: python/branches/p3yk-noslice/Lib/test/test_dict.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_dict.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_dict.py Fri Feb 23 18:29:35 2007 @@ -19,7 +19,7 @@ def test_keys(self): d = {} - self.assertEqual(d.keys(), []) + self.assertEqual(set(d.keys()), set()) d = {'a': 1, 'b': 2} k = d.keys() self.assert_('a' in d) @@ -29,18 +29,18 @@ def test_values(self): d = {} - self.assertEqual(d.values(), []) + self.assertEqual(set(d.values()), set()) d = {1:2} - self.assertEqual(d.values(), [2]) + self.assertEqual(set(d.values()), {2}) self.assertRaises(TypeError, d.values, None) def test_items(self): d = {} - self.assertEqual(d.items(), []) + self.assertEqual(set(d.items()), set()) d = {1:2} - self.assertEqual(d.items(), [(1, 2)]) + self.assertEqual(set(d.items()), {(1, 2)}) self.assertRaises(TypeError, d.items, None) @@ -182,6 +182,14 @@ self.assertRaises(ValueError, {}.update, [(1, 2, 3)]) + # SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses + class KeyUpperDict(dict): + def __getitem__(self, key): + return key.upper() + d.clear() + d.update(KeyUpperDict.fromkeys('abc')) + self.assertEqual(d, {'a':'A', 'b':'B', 'c':'C'}) + def test_fromkeys(self): self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = {} @@ -314,7 +322,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 +379,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-noslice/Lib/test/test_dis.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_dis.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_dis.py Fri Feb 23 18:29:35 2007 @@ -8,16 +8,17 @@ import unittest def _f(a): - print a + print(a) return 1 dis_f = """\ - %-4d 0 LOAD_FAST 0 (a) - 3 PRINT_ITEM - 4 PRINT_NEWLINE + %-4d 0 LOAD_GLOBAL 0 (print) + 3 LOAD_FAST 0 (a) + 6 CALL_FUNCTION 1 + 9 POP_TOP - %-4d 5 LOAD_CONST 1 (1) - 8 RETURN_VALUE + %-4d 10 LOAD_CONST 1 (1) + 13 RETURN_VALUE """%(_f.func_code.co_firstlineno + 1, _f.func_code.co_firstlineno + 2) Modified: python/branches/p3yk-noslice/Lib/test/test_dl.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_dl.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_dl.py Fri Feb 23 18:29:35 2007 @@ -16,19 +16,19 @@ for s, func in sharedlibs: try: if verbose: - print 'trying to open:', s, + print('trying to open:', s, end=' ') l = dl.open(s) except dl.error as err: if verbose: - print 'failed', repr(str(err)) + print('failed', repr(str(err))) pass else: if verbose: - print 'succeeded...', + print('succeeded...', end=' ') l.call(func) l.close() if verbose: - print 'worked!' + print('worked!') break else: raise TestSkipped, 'Could not open any shared libraries' Modified: python/branches/p3yk-noslice/Lib/test/test_doctest.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_doctest.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_doctest.py Fri Feb 23 18:29:35 2007 @@ -14,7 +14,7 @@ """ Blah blah - >>> print sample_func(22) + >>> print(sample_func(22)) 44 Yee ha! @@ -23,7 +23,7 @@ class SampleClass: """ - >>> print 1 + >>> print(1) 1 >>> # comments get ignored. so are empty PS1 and PS2 prompts: @@ -34,33 +34,33 @@ >>> sc = SampleClass(3) >>> for i in range(10): ... sc = sc.double() - ... print sc.get(), - 6 12 24 48 96 192 384 768 1536 3072 + ... print(sc.get(), end=' ') + 6 12 24 48 96 192 384 768 1536 3072 """ def __init__(self, val): """ - >>> print SampleClass(12).get() + >>> print(SampleClass(12).get()) 12 """ self.val = val def double(self): """ - >>> print SampleClass(12).double().get() + >>> print(SampleClass(12).double().get()) 24 """ return SampleClass(self.val + self.val) def get(self): """ - >>> print SampleClass(-5).get() + >>> print(SampleClass(-5).get()) -5 """ return self.val def a_staticmethod(v): """ - >>> print SampleClass.a_staticmethod(10) + >>> print(SampleClass.a_staticmethod(10)) 11 """ return v+1 @@ -68,16 +68,16 @@ def a_classmethod(cls, v): """ - >>> print SampleClass.a_classmethod(10) + >>> print(SampleClass.a_classmethod(10)) 12 - >>> print SampleClass(0).a_classmethod(10) + >>> print(SampleClass(0).a_classmethod(10)) 12 """ return v+2 a_classmethod = classmethod(a_classmethod) a_property = property(get, doc=""" - >>> print SampleClass(22).a_property + >>> print(SampleClass(22).a_property) 22 """) @@ -85,12 +85,12 @@ """ >>> x = SampleClass.NestedClass(5) >>> y = x.square() - >>> print y.get() + >>> print(y.get()) 25 """ def __init__(self, val=0): """ - >>> print SampleClass.NestedClass().get() + >>> print(SampleClass.NestedClass().get()) 0 """ self.val = val @@ -101,28 +101,28 @@ class SampleNewStyleClass(object): r""" - >>> print '1\n2\n3' + >>> print('1\n2\n3') 1 2 3 """ def __init__(self, val): """ - >>> print SampleNewStyleClass(12).get() + >>> print(SampleNewStyleClass(12).get()) 12 """ self.val = val def double(self): """ - >>> print SampleNewStyleClass(12).double().get() + >>> print(SampleNewStyleClass(12).double().get()) 24 """ return SampleNewStyleClass(self.val + self.val) def get(self): """ - >>> print SampleNewStyleClass(-5).get() + >>> print(SampleNewStyleClass(-5).get()) -5 """ return self.val @@ -143,7 +143,7 @@ def readline(self): line = self.lines.pop(0) - print line + print(line) return line+'\n' ###################################################################### @@ -166,10 +166,10 @@ These attributes are set by the constructor. `source` and `want` are required; the other attributes all have default values: - >>> example = doctest.Example('print 1', '1\n') + >>> example = doctest.Example('print(1)', '1\n') >>> (example.source, example.want, example.exc_msg, ... example.lineno, example.indent, example.options) - ('print 1\n', '1\n', None, 0, 0, {}) + ('print(1)\n', '1\n', None, 0, 0, {}) The first three attributes (`source`, `want`, and `exc_msg`) may be specified positionally; the remaining arguments should be specified as @@ -186,22 +186,22 @@ The constructor normalizes the `source` string to end in a newline: Source spans a single line: no terminating newline. - >>> e = doctest.Example('print 1', '1\n') + >>> e = doctest.Example('print(1)', '1\n') >>> e.source, e.want - ('print 1\n', '1\n') + ('print(1)\n', '1\n') - >>> e = doctest.Example('print 1\n', '1\n') + >>> e = doctest.Example('print(1)\n', '1\n') >>> e.source, e.want - ('print 1\n', '1\n') + ('print(1)\n', '1\n') Source spans multiple lines: require terminating newline. - >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n') + >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n') >>> e.source, e.want - ('print 1;\nprint 2\n', '1\n2\n') + ('print(1);\nprint(2)\n', '1\n2\n') - >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n') + >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n') >>> e.source, e.want - ('print 1;\nprint 2\n', '1\n2\n') + ('print(1);\nprint(2)\n', '1\n2\n') Empty source string (which should never appear in real examples) >>> e = doctest.Example('', '') @@ -211,13 +211,13 @@ The constructor normalizes the `want` string to end in a newline, unless it's the empty string: - >>> e = doctest.Example('print 1', '1\n') + >>> e = doctest.Example('print(1)', '1\n') >>> e.source, e.want - ('print 1\n', '1\n') + ('print(1)\n', '1\n') - >>> e = doctest.Example('print 1', '1') + >>> e = doctest.Example('print(1)', '1') >>> e.source, e.want - ('print 1\n', '1\n') + ('print(1)\n', '1\n') >>> e = doctest.Example('print', '') >>> e.source, e.want @@ -265,12 +265,12 @@ constructor: >>> docstring = ''' - ... >>> print 12 + ... >>> print(12) ... 12 ... ... Non-example text. ... - ... >>> print 'another\example' + ... >>> print('another\example') ... another ... example ... ''' @@ -278,15 +278,15 @@ >>> parser = doctest.DocTestParser() >>> test = parser.get_doctest(docstring, globs, 'some_test', ... 'some_file', 20) - >>> print test + >>> print(test) >>> len(test.examples) 2 >>> e1, e2 = test.examples >>> (e1.source, e1.want, e1.lineno) - ('print 12\n', '12\n', 1) + ('print(12)\n', '12\n', 1) >>> (e2.source, e2.want, e2.lineno) - ("print 'another\\example'\n", 'another\nexample\n', 6) + ("print('another\\example')\n", 'another\nexample\n', 6) Source information (name, filename, and line number) is available as attributes on the doctest object: @@ -307,7 +307,7 @@ expected output of an example, then `DocTest` will raise a ValueError: >>> docstring = r''' - ... >>> print 'bad\nindentation' + ... >>> print('bad\nindentation') ... bad ... indentation ... ''' @@ -319,29 +319,29 @@ continuation lines, then `DocTest` will raise a ValueError: >>> docstring = r''' - ... >>> print ('bad indentation', - ... ... 2) + ... >>> print(('bad indentation', + ... ... 2)) ... ('bad', 'indentation') ... ''' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): - ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)' + ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))' If there's no blank space after a PS1 prompt ('>>>'), then `DocTest` will raise a ValueError: - >>> docstring = '>>>print 1\n1' + >>> docstring = '>>>print(1)\n1' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): - ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1' + ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)' If there's no blank space after a PS2 prompt ('...'), then `DocTest` will raise a ValueError: - >>> docstring = '>>> if 1:\n...print 1\n1' + >>> docstring = '>>> if 1:\n...print(1)\n1' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): - ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1' + ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)' """ @@ -368,7 +368,7 @@ >>> tests = finder.find(sample_func) - >>> print tests # doctest: +ELLIPSIS + >>> print(tests) # doctest: +ELLIPSIS [] The exact name depends on how test_doctest was invoked, so allow for @@ -382,7 +382,7 @@ >>> e = tests[0].examples[0] >>> (e.source, e.want, e.lineno) - ('print sample_func(22)\n', '44\n', 3) + ('print(sample_func(22))\n', '44\n', 3) By default, tests are created for objects with no docstring: @@ -420,7 +420,7 @@ >>> finder = doctest.DocTestFinder() >>> tests = finder.find(SampleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ @@ -435,7 +435,7 @@ >>> tests = finder.find(SampleNewStyleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 1 SampleNewStyleClass 1 SampleNewStyleClass.__init__ 1 SampleNewStyleClass.double @@ -452,7 +452,7 @@ >>> m = new.module('some_module') >>> def triple(val): ... ''' - ... >>> print triple(11) + ... >>> print(triple(11)) ... 33 ... ''' ... return val*3 @@ -461,11 +461,11 @@ ... 'SampleClass': SampleClass, ... '__doc__': ''' ... Module docstring. - ... >>> print 'module' + ... >>> print('module') ... module ... ''', ... '__test__': { - ... 'd': '>>> print 6\n6\n>>> print 7\n7\n', + ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n', ... 'c': triple}}) >>> finder = doctest.DocTestFinder() @@ -474,7 +474,7 @@ >>> import test.test_doctest >>> tests = finder.find(m, module=test.test_doctest) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 1 some_module 3 some_module.SampleClass 3 some_module.SampleClass.NestedClass @@ -496,9 +496,9 @@ >>> from test import doctest_aliases >>> tests = excl_empty_finder.find(doctest_aliases) - >>> print len(tests) + >>> print(len(tests)) 2 - >>> print tests[0].name + >>> print(tests[0].name) test.doctest_aliases.TwoNames TwoNames.f and TwoNames.g are bound to the same object. @@ -514,7 +514,7 @@ >>> tests = doctest.DocTestFinder().find(SampleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ @@ -532,7 +532,7 @@ >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ @@ -552,7 +552,7 @@ >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass Line numbers @@ -570,8 +570,8 @@ ... ... ... ... >>> for x in range(10): - ... ... print x, - ... 0 1 2 3 4 5 6 7 8 9 + ... ... print(x, end=' ') + ... 0 1 2 3 4 5 6 7 8 9 ... >>> x//2 ... 6 ... ''' @@ -591,8 +591,8 @@ >>> s = ''' ... >>> x, y = 2, 3 # no output expected ... >>> if 1: - ... ... print x - ... ... print y + ... ... print(x) + ... ... print(y) ... 2 ... 3 ... @@ -603,13 +603,13 @@ >>> parser = doctest.DocTestParser() >>> for piece in parser.parse(s): ... if isinstance(piece, doctest.Example): - ... print 'Example:', (piece.source, piece.want, piece.lineno) + ... print('Example:', (piece.source, piece.want, piece.lineno)) ... else: - ... print ' Text:', repr(piece) + ... print(' Text:', repr(piece)) Text: '\n' Example: ('x, y = 2, 3 # no output expected\n', '', 1) Text: '' - Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2) + Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) Text: '\nSome text.\n' Example: ('x+y\n', '5\n', 9) Text: '' @@ -617,9 +617,9 @@ The `get_examples` method returns just the examples: >>> for piece in parser.get_examples(s): - ... print (piece.source, piece.want, piece.lineno) + ... print((piece.source, piece.want, piece.lineno)) ('x, y = 2, 3 # no output expected\n', '', 1) - ('if 1:\n print x\n print y\n', '2\n3\n', 2) + ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) ('x+y\n', '5\n', 9) The `get_doctest` method creates a Test from the examples, along with the @@ -629,9 +629,9 @@ >>> (test.name, test.filename, test.lineno) ('name', 'filename', 5) >>> for piece in test.examples: - ... print (piece.source, piece.want, piece.lineno) + ... print((piece.source, piece.want, piece.lineno)) ('x, y = 2, 3 # no output expected\n', '', 1) - ('if 1:\n print x\n print y\n', '2\n3\n', 2) + ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) ('x+y\n', '5\n', 9) """ @@ -645,7 +645,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print x + ... >>> print(x) ... 12 ... >>> x//2 ... 6 @@ -666,7 +666,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print x + ... >>> print(x) ... 14 ... >>> x//2 ... 6 @@ -679,13 +679,13 @@ Expecting nothing ok Trying: - print x + print(x) Expecting: 14 ********************************************************************** File ..., line 4, in f Failed example: - print x + print(x) Expected: 14 Got: @@ -704,7 +704,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print x + ... >>> print(x) ... 12 ... >>> x//2 ... 6 @@ -717,7 +717,7 @@ Expecting nothing ok Trying: - print x + print(x) Expecting: 12 ok @@ -747,7 +747,7 @@ Expecting nothing ok Trying: - print x + print(x) Expecting: 12 ok @@ -774,7 +774,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print x//0 + ... >>> print(x//0) ... Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero ... ''' @@ -790,7 +790,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print 'pre-exception output', x//0 + ... >>> print('pre-exception output', x//0) ... pre-exception output ... Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero @@ -801,7 +801,7 @@ ********************************************************************** File ..., line 4, in f Failed example: - print 'pre-exception output', x//0 + print('pre-exception output', x//0) Exception raised: ... ZeroDivisionError: integer division or modulo by zero @@ -942,7 +942,7 @@ and the '' marker: >>> def f(x): - ... '>>> print "a\\n\\nb"\na\n\nb\n' + ... '>>> print("a\\n\\nb")\na\n\nb\n' >>> # Without the flag: >>> test = doctest.DocTestFinder().find(f)[0] @@ -957,7 +957,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print "a\n\nb" + print("a\n\nb") Expected: a @@ -972,7 +972,7 @@ treated as equal: >>> def f(x): - ... '>>> print 1, 2, 3\n 1 2\n 3' + ... '>>> print(1, 2, 3)\n 1 2\n 3' >>> # Without the flag: >>> test = doctest.DocTestFinder().find(f)[0] @@ -981,7 +981,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print 1, 2, 3 + print(1, 2, 3) Expected: 1 2 3 @@ -996,7 +996,7 @@ (0, 1) An example from the docs: - >>> print range(20) #doctest: +NORMALIZE_WHITESPACE + >>> print(range(20)) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] @@ -1004,7 +1004,7 @@ output to match any substring in the actual output: >>> def f(x): - ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n' + ... '>>> print(range(15))\n[0, 1, 2, ..., 14]\n' >>> # Without the flag: >>> test = doctest.DocTestFinder().find(f)[0] @@ -1013,7 +1013,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(15) + print(range(15)) Expected: [0, 1, 2, ..., 14] Got: @@ -1028,22 +1028,26 @@ ... also matches nothing: - >>> for i in range(100): - ... print i**2, #doctest: +ELLIPSIS - 0 1...4...9 16 ... 36 49 64 ... 9801 + >>> if 1: + ... for i in range(100): + ... print(i**2, end=' ') #doctest: +ELLIPSIS + ... print('!') + 0 1...4...9 16 ... 36 49 64 ... 9801 ! ... can be surprising; e.g., this test passes: - >>> for i in range(21): #doctest: +ELLIPSIS - ... print i, + >>> if 1: #doctest: +ELLIPSIS + ... for i in range(20): + ... print(i, end=' ') + ... print(20) 0 1 2 ...1...2...0 Examples from the docs: - >>> print range(20) # doctest:+ELLIPSIS + >>> print(range(20)) # doctest:+ELLIPSIS [0, 1, ..., 18, 19] - >>> print range(20) # doctest: +ELLIPSIS + >>> print(range(20)) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE [0, 1, ..., 18, 19] @@ -1063,7 +1067,7 @@ UncheckedBlowUpError: Nobody checks me. >>> import random - >>> print random.random() # doctest: +SKIP + >>> print(random.random()) # doctest: +SKIP 0.721216923889 The REPORT_UDIFF flag causes failures that involve multi-line expected @@ -1071,7 +1075,7 @@ >>> def f(x): ... r''' - ... >>> print '\n'.join('abcdefg') + ... >>> print('\n'.join('abcdefg')) ... a ... B ... c @@ -1088,7 +1092,7 @@ ********************************************************************** File ..., line 3, in f Failed example: - print '\n'.join('abcdefg') + print('\n'.join('abcdefg')) Expected: a B @@ -1115,7 +1119,7 @@ ********************************************************************** File ..., line 3, in f Failed example: - print '\n'.join('abcdefg') + print('\n'.join('abcdefg')) Differences (unified diff with -expected +actual): @@ -1,7 +1,7 @@ a @@ -1140,7 +1144,7 @@ ********************************************************************** File ..., line 3, in f Failed example: - print '\n'.join('abcdefg') + print('\n'.join('abcdefg')) Differences (context diff with expected followed by actual): *************** *** 1,7 **** @@ -1168,7 +1172,7 @@ >>> def f(x): ... r''' - ... >>> print "a b c d e f g h i j k l m" + ... >>> print("a b c d e f g h i j k l m") ... a b c d e f g h i j k 1 m ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1178,7 +1182,7 @@ ********************************************************************** File ..., line 3, in f Failed example: - print "a b c d e f g h i j k l m" + print("a b c d e f g h i j k l m") Differences (ndiff with -expected +actual): - a b c d e f g h i j k 1 m ? ^ @@ -1191,15 +1195,15 @@ >>> def f(x): ... r''' - ... >>> print 1 # first success + ... >>> print(1) # first success ... 1 - ... >>> print 2 # first failure + ... >>> print(2) # first failure ... 200 - ... >>> print 3 # second failure + ... >>> print(3) # second failure ... 300 - ... >>> print 4 # second success + ... >>> print(4) # second success ... 4 - ... >>> print 5 # third failure + ... >>> print(5) # third failure ... 500 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1209,7 +1213,7 @@ ********************************************************************** File ..., line 5, in f Failed example: - print 2 # first failure + print(2) # first failure Expected: 200 Got: @@ -1221,18 +1225,18 @@ >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test) ... # doctest: +ELLIPSIS Trying: - print 1 # first success + print(1) # first success Expecting: 1 ok Trying: - print 2 # first failure + print(2) # first failure Expecting: 200 ********************************************************************** File ..., line 5, in f Failed example: - print 2 # first failure + print(2) # first failure Expected: 200 Got: @@ -1244,15 +1248,15 @@ >>> def f(x): ... r''' - ... >>> print 1 # first success + ... >>> print(1) # first success ... 1 ... >>> raise ValueError(2) # first failure ... 200 - ... >>> print 3 # second failure + ... >>> print(3) # second failure ... 300 - ... >>> print 4 # second success + ... >>> print(4) # second success ... 4 - ... >>> print 5 # third failure + ... >>> print(5) # third failure ... 500 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1298,10 +1302,10 @@ example with a comment of the form ``# doctest: +OPTION``: >>> def f(x): r''' - ... >>> print range(10) # should fail: no ellipsis + ... >>> print(range(10)) # should fail: no ellipsis ... [0, 1, ..., 9] ... - ... >>> print range(10) # doctest: +ELLIPSIS + ... >>> print(range(10)) # doctest: +ELLIPSIS ... [0, 1, ..., 9] ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1310,7 +1314,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # should fail: no ellipsis + print(range(10)) # should fail: no ellipsis Expected: [0, 1, ..., 9] Got: @@ -1321,11 +1325,11 @@ comment of the form ``# doctest: -OPTION``: >>> def f(x): r''' - ... >>> print range(10) + ... >>> print(range(10)) ... [0, 1, ..., 9] ... ... >>> # should fail: no ellipsis - ... >>> print range(10) # doctest: -ELLIPSIS + ... >>> print(range(10)) # doctest: -ELLIPSIS ... [0, 1, ..., 9] ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1335,7 +1339,7 @@ ********************************************************************** File ..., line 6, in f Failed example: - print range(10) # doctest: -ELLIPSIS + print(range(10)) # doctest: -ELLIPSIS Expected: [0, 1, ..., 9] Got: @@ -1346,13 +1350,13 @@ do not change the options for surrounding examples: >>> def f(x): r''' - ... >>> print range(10) # Should fail: no ellipsis + ... >>> print(range(10)) # Should fail: no ellipsis ... [0, 1, ..., 9] ... - ... >>> print range(10) # doctest: +ELLIPSIS + ... >>> print(range(10)) # doctest: +ELLIPSIS ... [0, 1, ..., 9] ... - ... >>> print range(10) # Should fail: no ellipsis + ... >>> print(range(10)) # Should fail: no ellipsis ... [0, 1, ..., 9] ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1361,7 +1365,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # Should fail: no ellipsis + print(range(10)) # Should fail: no ellipsis Expected: [0, 1, ..., 9] Got: @@ -1369,7 +1373,7 @@ ********************************************************************** File ..., line 8, in f Failed example: - print range(10) # Should fail: no ellipsis + print(range(10)) # Should fail: no ellipsis Expected: [0, 1, ..., 9] Got: @@ -1380,9 +1384,9 @@ may be separated by whitespace, commas, or both: >>> def f(x): r''' - ... >>> print range(10) # Should fail + ... >>> print(range(10)) # Should fail ... [0, 1, ..., 9] - ... >>> print range(10) # Should succeed + ... >>> print(range(10)) # Should succeed ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ... [0, 1, ..., 9] ... ''' @@ -1392,7 +1396,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # Should fail + print(range(10)) # Should fail Expected: [0, 1, ..., 9] Got: @@ -1400,9 +1404,9 @@ (1, 2) >>> def f(x): r''' - ... >>> print range(10) # Should fail + ... >>> print(range(10)) # Should fail ... [0, 1, ..., 9] - ... >>> print range(10) # Should succeed + ... >>> print(range(10)) # Should succeed ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE ... [0, 1, ..., 9] ... ''' @@ -1412,7 +1416,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # Should fail + print(range(10)) # Should fail Expected: [0, 1, ..., 9] Got: @@ -1420,9 +1424,9 @@ (1, 2) >>> def f(x): r''' - ... >>> print range(10) # Should fail + ... >>> print(range(10)) # Should fail ... [0, 1, ..., 9] - ... >>> print range(10) # Should succeed + ... >>> print(range(10)) # Should succeed ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... [0, 1, ..., 9] ... ''' @@ -1432,7 +1436,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # Should fail + print(range(10)) # Should fail Expected: [0, 1, ..., 9] Got: @@ -1443,7 +1447,7 @@ long as a continuation prompt is used: >>> def f(x): r''' - ... >>> print range(10) + ... >>> print(range(10)) ... ... # doctest: +ELLIPSIS ... [0, 1, ..., 9] ... ''' @@ -1456,12 +1460,12 @@ >>> def f(x): r''' ... >>> for x in range(10): # doctest: +ELLIPSIS - ... ... print x, - ... 0 1 2 ... 9 + ... ... print(x, end=' ') + ... 0 1 2 ... 9 ... ... >>> for x in range(10): - ... ... print x, # doctest: +ELLIPSIS - ... 0 1 2 ... 9 + ... ... print(x, end=' ') # doctest: +ELLIPSIS + ... 0 1 2 ... 9 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) @@ -1473,8 +1477,8 @@ >>> def f(x): r''' ... Should fail (option directive not on the last line): ... >>> for x in range(10): # doctest: +ELLIPSIS - ... ... print x, # doctest: +NORMALIZE_WHITESPACE - ... 0 1 2...9 + ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE + ... 0 1 2...9 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) @@ -1486,13 +1490,13 @@ `register_option`: >>> # Error: Option not registered - >>> s = '>>> print 12 #doctest: +BADOPTION' + >>> s = '>>> print(12) #doctest: +BADOPTION' >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0) Traceback (most recent call last): ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION' >>> # Error: No + or - prefix - >>> s = '>>> print 12 #doctest: ELLIPSIS' + >>> s = '>>> print(12) #doctest: ELLIPSIS' >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0) Traceback (most recent call last): ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS' @@ -1516,10 +1520,10 @@ >>> import test.test_doctest >>> name = 'test.test_doctest.sample_func' - >>> print doctest.testsource(test.test_doctest, name) + >>> print(doctest.testsource(test.test_doctest, name)) # Blah blah # - print sample_func(22) + print(sample_func(22)) # Expected: ## 44 # @@ -1527,8 +1531,8 @@ >>> name = 'test.test_doctest.SampleNewStyleClass' - >>> print doctest.testsource(test.test_doctest, name) - print '1\n2\n3' + >>> print(doctest.testsource(test.test_doctest, name)) + print('1\n2\n3') # Expected: ## 1 ## 2 @@ -1536,11 +1540,11 @@ >>> name = 'test.test_doctest.SampleClass.a_classmethod' - >>> print doctest.testsource(test.test_doctest, name) - print SampleClass.a_classmethod(10) + >>> print(doctest.testsource(test.test_doctest, name)) + print(SampleClass.a_classmethod(10)) # Expected: ## 12 - print SampleClass(0).a_classmethod(10) + print(SampleClass(0).a_classmethod(10)) # Expected: ## 12 @@ -1552,7 +1556,7 @@ >>> s = ''' ... >>> x = 12 - ... >>> print x + ... >>> print(x) ... 12 ... ''' @@ -1560,7 +1564,7 @@ >>> import tempfile >>> real_stdin = sys.stdin - >>> sys.stdin = _FakeInput(['next', 'print x', 'continue']) + >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue']) Run the debugger on the docstring, and then restore sys.stdin. @@ -1571,7 +1575,7 @@ 12 --Return-- > (1)()->None - (Pdb) print x + (Pdb) print(x) 12 (Pdb) continue @@ -1601,7 +1605,7 @@ >>> import tempfile >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ - ... 'print x', # print data defined by the example + ... 'print(x)', # print data defined by the example ... 'continue', # stop debugging ... '']) @@ -1610,7 +1614,7 @@ --Return-- > (1)()->None -> import pdb; pdb.set_trace() - (Pdb) print x + (Pdb) print(x) 42 (Pdb) continue (0, 2) @@ -1628,9 +1632,9 @@ >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ - ... 'print y', # print data defined in the function + ... 'print(y)', # print data defined in the function ... 'up', # out of function - ... 'print x', # print data defined by the example + ... 'print(x)', # print data defined by the example ... 'continue', # stop debugging ... '']) @@ -1641,12 +1645,12 @@ --Return-- > (3)calls_set_trace()->None -> import pdb; pdb.set_trace() - (Pdb) print y + (Pdb) print(y) 2 (Pdb) up > (1)() -> calls_set_trace() - (Pdb) print x + (Pdb) print(x) 1 (Pdb) continue (0, 2) @@ -1658,7 +1662,7 @@ ... >>> def f(x): ... ... g(x*2) ... >>> def g(x): - ... ... print x+3 + ... ... print(x+3) ... ... import pdb; pdb.set_trace() ... >>> f(3) ... ''' @@ -1680,7 +1684,7 @@ -> import pdb; pdb.set_trace() (Pdb) list 1 def g(x): - 2 print x+3 + 2 print(x+3) 3 -> import pdb; pdb.set_trace() [EOF] (Pdb) next @@ -1737,11 +1741,11 @@ >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ - ... 'print y', # print data defined in the function - ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z', - ... 'up', 'print x', - ... 'up', 'print y', - ... 'up', 'print foo', + ... 'print(y)', # print data defined in the function + ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)', + ... 'up', 'print(x)', + ... 'up', 'print(y)', + ... 'up', 'print(foo)', ... 'continue', # stop debugging ... '']) @@ -1751,7 +1755,7 @@ ... sys.stdin = real_stdin > (5)calls_set_trace() -> self.f1() - (Pdb) print y + (Pdb) print(y) 1 (Pdb) step --Call-- @@ -1773,22 +1777,22 @@ (Pdb) step > (13)f2() -> z = 2 - (Pdb) print z + (Pdb) print(z) 1 (Pdb) up > (9)f1() -> self.f2() - (Pdb) print x + (Pdb) print(x) 1 (Pdb) up > (5)calls_set_trace() -> self.f1() - (Pdb) print y + (Pdb) print(y) 1 (Pdb) up > (1)() -> calls_set_trace() - (Pdb) print foo + (Pdb) print(foo) *** NameError: name 'foo' is not defined (Pdb) continue (0, 2) @@ -2037,7 +2041,7 @@ Trailing spaces in expected output are significant: >>> x, y = 'foo', '' - >>> print x, y + >>> print(x, y) foo \n """ @@ -2054,7 +2058,7 @@ ... optionflags=doctest.DONT_ACCEPT_BLANKLINE) >>> import unittest >>> result = suite.run(unittest.TestResult()) - >>> print result.failures[0][1] # doctest: +ELLIPSIS + >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color @@ -2071,7 +2075,7 @@ Now, when we run the test: >>> result = suite.run(unittest.TestResult()) - >>> print result.failures[0][1] # doctest: +ELLIPSIS + >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color @@ -2092,16 +2096,16 @@ Then the default eporting options are ignored: >>> result = suite.run(unittest.TestResult()) - >>> print result.failures[0][1] # doctest: +ELLIPSIS + >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color ... Failed example: if 1: - print 'a' - print - print 'b' + print('a') + print() + print('b') Differences (ndiff with -expected +actual): a - @@ -2185,9 +2189,9 @@ ok Trying: if 1: - print 'a' - print - print 'b' + print('a') + print() + print('b') Expecting: a @@ -2279,19 +2283,19 @@ >>> t = Tester(globs={'x': 42}, verbose=0) >>> t.runstring(r''' ... >>> x = x * 2 -... >>> print x +... >>> print(x) ... 42 ... ''', 'XYZ') ********************************************************************** Line 3, in XYZ Failed example: - print x + print(x) Expected: 42 Got: 84 (1, 2) ->>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2') +>>> t.runstring(">>> x = x * 2\n>>> print(x)\n84\n", 'example2') (0, 2) >>> t.summarize() ********************************************************************** @@ -2407,7 +2411,7 @@ trace=0, count=1) tracer.run('reload(doctest); test_main()') r = tracer.results() - print 'Writing coverage results...' + print('Writing coverage results...') r.write_results(show_missing=True, summary=True, coverdir=coverdir) Modified: python/branches/p3yk-noslice/Lib/test/test_doctest.txt ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_doctest.txt (original) +++ python/branches/p3yk-noslice/Lib/test/test_doctest.txt Fri Feb 23 18:29:35 2007 @@ -9,9 +9,9 @@ We can make this fail by disabling the blank-line feature. >>> if 1: - ... print 'a' - ... print - ... print 'b' + ... print('a') + ... print() + ... print('b') a b Modified: python/branches/p3yk-noslice/Lib/test/test_doctest2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_doctest2.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_doctest2.py Fri Feb 23 18:29:35 2007 @@ -2,7 +2,7 @@ u"""A module to test whether doctest recognizes some 2.2 features, like static and class methods. ->>> print 'yup' # 1 +>>> print('yup') # 1 yup We include some (random) encoded (utf-8) text in the text surrounding @@ -17,7 +17,7 @@ class C(object): u"""Class C. - >>> print C() # 2 + >>> print(C()) # 2 42 @@ -31,13 +31,13 @@ def __init__(self): """C.__init__. - >>> print C() # 3 + >>> print(C()) # 3 42 """ def __str__(self): """ - >>> print C() # 4 + >>> print(C()) # 4 42 """ return "42" @@ -45,13 +45,13 @@ class D(object): """A nested D class. - >>> print "In D!" # 5 + >>> print("In D!") # 5 In D! """ def nested(self): """ - >>> print 3 # 6 + >>> print(3) # 6 3 """ @@ -59,7 +59,7 @@ """ >>> c = C() # 7 >>> c.x = 12 # 8 - >>> print c.x # 9 + >>> print(c.x) # 9 -12 """ return -self._x @@ -68,7 +68,7 @@ """ >>> c = C() # 10 >>> c.x = 12 # 11 - >>> print c.x # 12 + >>> print(c.x) # 12 -12 """ self._x = value @@ -76,7 +76,7 @@ x = property(getx, setx, doc="""\ >>> c = C() # 13 >>> c.x = 12 # 14 - >>> print c.x # 15 + >>> print(c.x) # 15 -12 """) @@ -85,9 +85,9 @@ """ A static method. - >>> print C.statm() # 16 + >>> print(C.statm()) # 16 666 - >>> print C().statm() # 17 + >>> print(C().statm()) # 17 666 """ return 666 @@ -97,9 +97,9 @@ """ A class method. - >>> print C.clsm(22) # 18 + >>> print(C.clsm(22)) # 18 22 - >>> print C().clsm(23) # 19 + >>> print(C().clsm(23)) # 19 23 """ return val Modified: python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py Fri Feb 23 18:29:35 2007 @@ -32,7 +32,7 @@ def test_dumbdbm_creation(self): f = dumbdbm.open(_fname, 'c') - self.assertEqual(f.keys(), []) + self.assertEqual(list(f.keys()), []) for key in self._dict: f[key] = self._dict[key] self.read_helper(f) @@ -49,13 +49,19 @@ f.close() finally: os.umask(old_umask) - + + expected_mode = 0635 + if os.name != 'posix': + # Windows only supports setting the read-only attribute. + # This shouldn't fail, but doesn't work like Unix either. + expected_mode = 0666 + import stat st = os.stat(_fname + '.dat') - self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) st = os.stat(_fname + '.dir') - self.assertEqual(stat.S_IMODE(st.st_mode), 0635) - + self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) + def test_close_twice(self): f = dumbdbm.open(_fname) f['a'] = 'b' @@ -122,10 +128,8 @@ f.close() def keys_helper(self, f): - keys = f.keys() - keys.sort() - dkeys = self._dict.keys() - dkeys.sort() + keys = sorted(f.keys()) + dkeys = sorted(self._dict.keys()) self.assertEqual(keys, dkeys) return keys @@ -150,10 +154,8 @@ f.close() f = dumbdbm.open(_fname) - expected = d.items() - expected.sort() - got = f.items() - got.sort() + expected = sorted(d.items()) + got = sorted(f.items()) self.assertEqual(expected, got) f.close() Modified: python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py Fri Feb 23 18:29:35 2007 @@ -72,13 +72,13 @@ start_time = int(time.time()) _thread.start_new_thread(delay_unlock,(self.lock, DELAY)) if test_support.verbose: - print - print "*** Waiting for thread to release the lock "\ - "(approx. %s sec.) ***" % DELAY + print() + print("*** Waiting for thread to release the lock "\ + "(approx. %s sec.) ***" % DELAY) self.lock.acquire() end_time = int(time.time()) if test_support.verbose: - print "done" + print("done") self.failUnless((end_time - start_time) >= DELAY, "Blocking by unconditional acquiring failed.") @@ -150,9 +150,9 @@ thread_count = 5 testing_queue = Queue.Queue(thread_count) if test_support.verbose: - print - print "*** Testing multiple thread creation "\ - "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count) + print() + print("*** Testing multiple thread creation "\ + "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)) for count in xrange(thread_count): if DELAY: local_delay = round(random.random(), 1) @@ -162,7 +162,7 @@ (testing_queue, local_delay)) time.sleep(DELAY) if test_support.verbose: - print 'done' + print('done') self.failUnless(testing_queue.qsize() == thread_count, "Not all %s threads executed properly after %s sec." % (thread_count, DELAY)) @@ -173,8 +173,8 @@ _thread = imported_module DELAY = 2 if test_support.verbose: - print - print "*** Using %s as _thread module ***" % _thread + print() + print("*** Using %s as _thread module ***" % _thread) test_support.run_unittest(LockTests, MiscTests, ThreadTests) if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/test/test_dummy_threading.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_dummy_threading.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_dummy_threading.py Fri Feb 23 18:29:35 2007 @@ -17,20 +17,20 @@ #delay = random.random() * 2 delay = 0 if verbose: - print 'task', self.getName(), 'will run for', delay, 'sec' + print('task', self.getName(), 'will run for', delay, 'sec') sema.acquire() mutex.acquire() running = running + 1 if verbose: - print running, 'tasks are running' + print(running, 'tasks are running') mutex.release() time.sleep(delay) if verbose: - print 'task', self.getName(), 'done' + print('task', self.getName(), 'done') mutex.acquire() running = running - 1 if verbose: - print self.getName(), 'is finished.', running, 'tasks are running' + print(self.getName(), 'is finished.', running, 'tasks are running') mutex.release() sema.release() @@ -61,11 +61,11 @@ starttasks() if verbose: - print 'waiting for all tasks to complete' + print('waiting for all tasks to complete') for t in threads: t.join() if verbose: - print 'all tasks done' + print('all tasks done') Modified: python/branches/p3yk-noslice/Lib/test/test_enumerate.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_enumerate.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_enumerate.py Fri Feb 23 18:29:35 2007 @@ -208,7 +208,7 @@ for i in xrange(len(counts)): test_support.run_unittest(*testclasses) counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_errno.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_errno.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_errno.py Fri Feb 23 18:29:35 2007 @@ -43,7 +43,7 @@ a = getattr(errno, error) except AttributeError: if verbose: - print '%s: not found' % error + print('%s: not found' % error) else: if verbose: - print '%s: %d' % (error, a) + print('%s: %d' % (error, a)) Modified: python/branches/p3yk-noslice/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_exceptions.py Fri Feb 23 18:29:35 2007 @@ -311,6 +311,13 @@ 'pickled "%r", attribute "%s' % (e, checkArgName)) + def testSlicing(self): + # Test that you can slice an exception directly instead of requiring + # going through the 'args' attribute. + args = (1, 2, 3) + exc = BaseException(*args) + self.failUnlessEqual(exc[:], args) + def testKeywordArgs(self): # test that builtin exception don't take keyword args, # but user-defined subclasses can if they want Modified: python/branches/p3yk-noslice/Lib/test/test_extcall.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_extcall.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_extcall.py Fri Feb 23 18:29:35 2007 @@ -2,16 +2,16 @@ from UserList import UserList def e(a, b): - print a, b + print(a, b) def f(*a, **k): - print a, sortdict(k) + print(a, sortdict(k)) def g(x, *y, **z): - print x, y, sortdict(z) + print(x, y, sortdict(z)) def h(j=1, a=2, h=3): - print j, a, h + print(j, a, h) f() f(1) @@ -31,28 +31,28 @@ except TypeError: pass else: - print "should raise TypeError: e() got an unexpected keyword argument 'c'" + print("should raise TypeError: e() got an unexpected keyword argument 'c'") try: g() except TypeError as err: - print "TypeError:", err + print("TypeError:", err) else: - print "should raise TypeError: not enough arguments; expected 1, got 0" + print("should raise TypeError: not enough arguments; expected 1, got 0") try: g(*()) except TypeError as err: - print "TypeError:", err + print("TypeError:", err) else: - print "should raise TypeError: not enough arguments; expected 1, got 0" + print("should raise TypeError: not enough arguments; expected 1, got 0") try: g(*(), **{}) except TypeError as err: - print "TypeError:", err + print("TypeError:", err) else: - print "should raise TypeError: not enough arguments; expected 1, got 0" + print("should raise TypeError: not enough arguments; expected 1, got 0") g(1) g(1, 2) @@ -64,7 +64,7 @@ except TypeError as attr: pass else: - print "should raise TypeError" + print("should raise TypeError") class Nothing: def __len__(self): @@ -74,7 +74,7 @@ except TypeError as attr: pass else: - print "should raise TypeError" + print("should raise TypeError") class Nothing: def __len__(self): @@ -96,7 +96,7 @@ except TypeError as attr: pass else: - print "should raise TypeError" + print("should raise TypeError") class Nothing: def __init__(self): @@ -116,8 +116,8 @@ d2 = d.copy() verify(d == d2) g(1, d=4, **d) -print sortdict(d) -print sortdict(d2) +print(sortdict(d)) +print(sortdict(d2)) verify(d == d2, "function call modified dictionary") # what about willful misconduct? @@ -133,79 +133,79 @@ try: g(1, 2, 3, **{'x':4, 'y':5}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: keyword parameter redefined" + print("should raise TypeError: keyword parameter redefined") try: g(1, 2, 3, a=4, b=5, *(6, 7), **{'a':8, 'b':9}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: keyword parameter redefined" + print("should raise TypeError: keyword parameter redefined") try: f(**{1:2}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: keywords must be strings" + print("should raise TypeError: keywords must be strings") try: h(**{'e': 2}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: unexpected keyword argument: e" + print("should raise TypeError: unexpected keyword argument: e") try: h(*h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: * argument must be a tuple" + print("should raise TypeError: * argument must be a tuple") try: dir(*h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: * argument must be a tuple" + print("should raise TypeError: * argument must be a tuple") try: None(*h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: * argument must be a tuple" + print("should raise TypeError: * argument must be a tuple") try: h(**h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: ** argument must be a dictionary" + print("should raise TypeError: ** argument must be a dictionary") try: dir(**h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: ** argument must be a dictionary" + print("should raise TypeError: ** argument must be a dictionary") try: None(**h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: ** argument must be a dictionary" + print("should raise TypeError: ** argument must be a dictionary") try: dir(b=1,**{'b':1}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: dir() got multiple values for keyword argument 'b'" + print("should raise TypeError: dir() got multiple values for keyword argument 'b'") def f2(*a, **b): return a, b @@ -215,27 +215,27 @@ key = 'k%d' % i d[key] = i a, b = f2(1, *(2, 3), **d) -print len(a), len(b), b == d +print(len(a), len(b), b == d) class Foo: def method(self, arg1, arg2): return arg1 + arg2 x = Foo() -print Foo.method(*(x, 1, 2)) -print Foo.method(x, *(1, 2)) +print(Foo.method(*(x, 1, 2))) +print(Foo.method(x, *(1, 2))) try: - print Foo.method(*(1, 2, 3)) + print(Foo.method(*(1, 2, 3))) except TypeError as err: pass else: - print 'expected a TypeError for unbound method call' + print('expected a TypeError for unbound method call') try: - print Foo.method(1, *(2, 3)) + print(Foo.method(1, *(2, 3))) except TypeError as err: pass else: - print 'expected a TypeError for unbound method call' + print('expected a TypeError for unbound method call') # A PyCFunction that takes only positional parameters should allow an # empty keyword dictionary to pass without a complaint, but raise a @@ -260,8 +260,8 @@ lambda x: '%s="%s"' % (x, x), defargs) if vararg: arglist.append('*' + vararg) if kwarg: arglist.append('**' + kwarg) - decl = (('def %s(%s): print "ok %s", a, b, d, e, v, ' + - 'type(k) is type ("") and k or sortdict(k)') + decl = (('def %s(%s): print("ok %s", a, b, d, e, v, ' + + 'type(k) is type ("") and k or sortdict(k))') % (name, ', '.join(arglist), name)) exec(decl) func = eval(name) @@ -274,6 +274,6 @@ for kwargs in ['', 'a', 'd', 'ad', 'abde']: kwdict = {} for k in kwargs: kwdict[k] = k + k - print func.func_name, args, sortdict(kwdict), '->', + print(func.func_name, args, sortdict(kwdict), '->', end=' ') try: func(*args, **kwdict) - except TypeError as err: print err + except TypeError as err: print(err) Modified: python/branches/p3yk-noslice/Lib/test/test_fcntl.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_fcntl.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_fcntl.py Fri Feb 23 18:29:35 2007 @@ -41,18 +41,18 @@ lockdata = struct.pack('hh'+start_len+'hh', fcntl.F_WRLCK, 0, 0, 0, 0, 0) if lockdata: if verbose: - print 'struct.pack: ', repr(lockdata) + print('struct.pack: ', repr(lockdata)) # the example from the library docs f = open(filename, 'w') rv = fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) if verbose: - print 'Status from fcntl with O_NONBLOCK: ', rv + print('Status from fcntl with O_NONBLOCK: ', rv) if sys.platform not in ['os2emx']: rv = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, lockdata) if verbose: - print 'String from fcntl with F_SETLKW: ', repr(rv) + print('String from fcntl with F_SETLKW: ', repr(rv)) f.close() os.unlink(filename) Modified: python/branches/p3yk-noslice/Lib/test/test_file.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_file.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_file.py Fri Feb 23 18:29:35 2007 @@ -30,14 +30,10 @@ def testAttributes(self): # verify expected attributes exist f = self.f - softspace = f.softspace f.name # merely shouldn't blow up f.mode # ditto f.closed # ditto - # verify softspace is writable - f.softspace = softspace # merely shouldn't blow up - # verify the others aren't for attr in 'name', 'mode', 'closed': self.assertRaises((AttributeError, TypeError), setattr, f, attr, 'oops') @@ -142,9 +138,9 @@ if sys.platform != 'osf1V5': self.assertRaises(IOError, sys.stdin.seek, -1) else: - print >>sys.__stdout__, ( + print(( ' Skipping sys.stdin.seek(-1), it may crash the interpreter.' - ' Test manually.') + ' Test manually.'), file=sys.__stdout__) self.assertRaises(IOError, sys.stdin.truncate) def testUnicodeOpen(self): Modified: python/branches/p3yk-noslice/Lib/test/test_fileinput.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_fileinput.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_fileinput.py Fri Feb 23 18:29:35 2007 @@ -34,7 +34,7 @@ def runTests(t1, t2, t3, t4, bs=0, round=0): start = 1 + round*6 if verbose: - print '%s. Simple iteration (bs=%s)' % (start+0, bs) + print('%s. Simple iteration (bs=%s)' % (start+0, bs)) fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) lines = list(fi) fi.close() @@ -45,7 +45,7 @@ verify(fi.filename() == t4) if verbose: - print '%s. Status variables (bs=%s)' % (start+1, bs) + print('%s. Status variables (bs=%s)' % (start+1, bs)) fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) s = "x" while s and s != 'Line 6 of file 2\n': @@ -57,14 +57,14 @@ verify(not fi.isstdin()) if verbose: - print '%s. Nextfile (bs=%s)' % (start+2, bs) + print('%s. Nextfile (bs=%s)' % (start+2, bs)) fi.nextfile() verify(fi.readline() == 'Line 1 of file 3\n') verify(fi.lineno() == 22) fi.close() if verbose: - print '%s. Stdin (bs=%s)' % (start+3, bs) + print('%s. Stdin (bs=%s)' % (start+3, bs)) fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs) savestdin = sys.stdin try: @@ -78,7 +78,7 @@ sys.stdin = savestdin if verbose: - print '%s. Boundary conditions (bs=%s)' % (start+4, bs) + print('%s. Boundary conditions (bs=%s)' % (start+4, bs)) fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) verify(fi.lineno() == 0) verify(fi.filename() == None) @@ -87,13 +87,13 @@ verify(fi.filename() == None) if verbose: - print '%s. Inplace (bs=%s)' % (start+5, bs) + print('%s. Inplace (bs=%s)' % (start+5, bs)) savestdout = sys.stdout try: fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs) for line in fi: line = line[:-1].upper() - print line + print(line) fi.close() finally: sys.stdout = savestdout @@ -124,7 +124,7 @@ # Next, check for proper behavior with 0-byte files. if verbose: - print "13. 0-byte files" + print("13. 0-byte files") try: t1 = writeTmp(1, [""]) t2 = writeTmp(2, [""]) @@ -146,7 +146,7 @@ remove_tempfiles(t1, t2, t3, t4) if verbose: - print "14. Files that don't end with newline" + print("14. Files that don't end with newline") try: t1 = writeTmp(1, ["A\nB\nC"]) t2 = writeTmp(2, ["D\nE\nF"]) @@ -159,7 +159,7 @@ remove_tempfiles(t1, t2) if verbose: - print "15. Unicode filenames" + print("15. Unicode filenames") try: t1 = writeTmp(1, ["A\nB"]) encoding = sys.getfilesystemencoding() @@ -172,7 +172,7 @@ remove_tempfiles(t1) if verbose: - print "16. fileno()" + print("16. fileno()") try: t1 = writeTmp(1, ["A\nB"]) t2 = writeTmp(2, ["C\nD"]) @@ -188,7 +188,7 @@ remove_tempfiles(t1, t2) if verbose: - print "17. Specify opening mode" + print("17. Specify opening mode") try: # invalid mode, should raise ValueError fi = FileInput(mode="w") @@ -205,7 +205,7 @@ remove_tempfiles(t1) if verbose: - print "18. Test file opening hook" + print("18. Test file opening hook") try: # cannot use openhook and inplace mode fi = FileInput(inplace=1, openhook=lambda f,m: None) Modified: python/branches/p3yk-noslice/Lib/test/test_format.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_format.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_format.py Fri Feb 23 18:29:35 2007 @@ -11,26 +11,26 @@ def testformat(formatstr, args, output=None): if verbose: if output: - print "%s %% %s =? %s ..." %\ - (repr(formatstr), repr(args), repr(output)), + print("%s %% %s =? %s ..." %\ + (repr(formatstr), repr(args), repr(output)), end=' ') else: - print "%s %% %s works? ..." % (repr(formatstr), repr(args)), + print("%s %% %s works? ..." % (repr(formatstr), repr(args)), end=' ') try: result = formatstr % args except OverflowError: if not overflowok: raise if verbose: - print 'overflow (this is fine)' + print('overflow (this is fine)') else: if output and result != output: if verbose: - print 'no' - print "%s %% %s == %s != %s" %\ - (repr(formatstr), repr(args), repr(result), repr(output)) + print('no') + print("%s %% %s == %s != %s" %\ + (repr(formatstr), repr(args), repr(result), repr(output))) else: if verbose: - print 'yes' + print('yes') def testboth(formatstr, *args): testformat(formatstr, *args) @@ -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,38 +163,38 @@ # 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: - print 'Testing exceptions' + print('Testing exceptions') def test_exc(formatstr, args, exception, excmsg): try: @@ -202,13 +202,13 @@ except exception as exc: if str(exc) == excmsg: if verbose: - print "yes" + print("yes") else: - if verbose: print 'no' - print 'Unexpected ', exception, ':', repr(str(exc)) + if verbose: print('no') + print('Unexpected ', exception, ':', repr(str(exc))) except: - if verbose: print 'no' - print 'Unexpected exception' + if verbose: print('no') + print('Unexpected exception') raise else: raise TestFailed, 'did not get expected exception: %s' % excmsg @@ -230,13 +230,13 @@ 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 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: Modified: python/branches/p3yk-noslice/Lib/test/test_funcattrs.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_funcattrs.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_funcattrs.py Fri Feb 23 18:29:35 2007 @@ -204,7 +204,7 @@ pass def temp(): - print 1 + print(1) if foo==bar: raise TestFailed @@ -235,7 +235,7 @@ def test_func_closure(): a = 12 - def f(): print a + def f(): print(a) c = f.func_closure verify(isinstance(c, tuple)) verify(len(c) == 1) @@ -284,10 +284,10 @@ def test_func_code(): a = b = 24 def f(): pass - def g(): print 12 - def f1(): print a - def g1(): print b - def f2(): print a, b + def g(): print(12) + def f1(): print(a) + def g1(): print(b) + def f2(): print(a, b) verify(type(f.func_code) is types.CodeType) f.func_code = g.func_code cantset(f, "func_code", None) Modified: python/branches/p3yk-noslice/Lib/test/test_functools.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_functools.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_functools.py Fri Feb 23 18:29:35 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) @@ -356,7 +356,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == '__main__': test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_gc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_gc.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_gc.py Fri Feb 23 18:29:35 2007 @@ -14,10 +14,10 @@ def run_test(name, thunk): if verbose: - print "testing %s..." % name, + print("testing %s..." % name, end=' ') thunk() if verbose: - print "ok" + print("ok") def test_list(): l = [] @@ -612,7 +612,7 @@ def test(): if verbose: - print "disabling automatic collection" + print("disabling automatic collection") enabled = gc.isenabled() gc.disable() verify(not gc.isenabled()) @@ -625,7 +625,7 @@ gc.set_debug(debug) # test gc.enable() even if GC is disabled by default if verbose: - print "restoring automatic collection" + print("restoring automatic collection") # make sure to always test gc.enable() gc.enable() verify(gc.isenabled()) Modified: python/branches/p3yk-noslice/Lib/test/test_gdbm.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_gdbm.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_gdbm.py Fri Feb 23 18:29:35 2007 @@ -15,7 +15,7 @@ g['12345678910'] = '019237410982340912840198242' a = g.keys() if verbose: - print 'Test gdbm file keys: ', a + print('Test gdbm file keys: ', a) 'a' in g g.close() Modified: python/branches/p3yk-noslice/Lib/test/test_generators.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_generators.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_generators.py Fri Feb 23 18:29:35 2007 @@ -6,7 +6,7 @@ ... yield 2 >>> for i in f(): - ... print i + ... print(i) 1 2 >>> g = f() @@ -78,7 +78,7 @@ ... raise StopIteration ... except: ... yield 42 - >>> print list(g2()) + >>> print(list(g2())) [42] This may be surprising at first: @@ -105,13 +105,13 @@ >>> def creator(): ... r = yrange(5) - ... print "creator", r.next() + ... print("creator", r.next()) ... return r ... >>> def caller(): ... r = creator() ... for i in r: - ... print "caller", i + ... print("caller", i) ... >>> caller() creator 0 @@ -161,7 +161,7 @@ ... return ... except: ... yield 1 - >>> print list(f1()) + >>> print(list(f1())) [] because, as in any function, return simply exits, but @@ -171,7 +171,7 @@ ... raise StopIteration ... except: ... yield 42 - >>> print list(f2()) + >>> print(list(f2())) [42] because StopIteration is captured by a bare "except", as is any @@ -221,7 +221,7 @@ ... finally: ... yield 10 ... yield 11 - >>> print list(f()) + >>> print(list(f())) [1, 2, 4, 5, 8, 9, 10, 11] >>> @@ -270,8 +270,8 @@ >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> # Print the nodes of the tree in in-order. >>> for x in t: - ... print x, - A B C D E F G H I J K L M N O P Q R S T U V W X Y Z + ... print(' '+x, end='') + A B C D E F G H I J K L M N O P Q R S T U V W X Y Z >>> # A non-recursive generator. >>> def inorder(node): @@ -291,8 +291,8 @@ >>> # Exercise the non-recursive generator. >>> for x in t: - ... print x, - A B C D E F G H I J K L M N O P Q R S T U V W X Y Z + ... print(' '+x, end='') + A B C D E F G H I J K L M N O P Q R S T U V W X Y Z """ @@ -345,9 +345,9 @@ >>> seq = range(1, 5) >>> for k in range(len(seq) + 2): -... print "%d-combs of %s:" % (k, seq) +... print("%d-combs of %s:" % (k, seq)) ... for c in gcomb(seq, k): -... print " ", c +... print(" ", c) 0-combs of [1, 2, 3, 4]: [] 1-combs of [1, 2, 3, 4]: @@ -383,7 +383,7 @@ >>> [s for s in dir(i) if not s.startswith('_')] ['close', 'gi_frame', 'gi_running', 'next', 'send', 'throw'] ->>> print i.next.__doc__ +>>> print(i.next.__doc__) x.next() -> the next value, or raise StopIteration >>> iter(i) is i True @@ -447,41 +447,41 @@ >>> gen = random.WichmannHill(42) >>> while 1: ... for s in sets: -... print "%s->%s" % (s, s.find()), -... print +... print(" %s->%s" % (s, s.find()), end='') +... print() ... if len(roots) > 1: ... s1 = gen.choice(roots) ... roots.remove(s1) ... s2 = gen.choice(roots) ... s1.union(s2) -... print "merged", s1, "into", s2 +... print("merged", s1, "into", s2) ... else: ... break -A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M + A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M merged D into G -A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M + A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M merged C into F -A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M + A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M merged L into A -A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M + A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M merged H into E -A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M + A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M merged B into E -A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M + A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M merged J into G -A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M + A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M merged E into G -A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M + A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M merged M into G -A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G + A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G merged I into K -A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G + A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G merged K into A -A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G + A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G merged F into A -A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G + A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G merged A into G -A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G + A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G """ # Emacs turd ' @@ -576,7 +576,7 @@ >>> result = m235() >>> for i in range(3): -... print firstn(result, 15) +... print(firstn(result, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] @@ -613,7 +613,7 @@ >>> m235 = LazyList(m235()) >>> for i in range(5): -... print [m235[j] for j in range(15*i, 15*(i+1))] +... print([m235[j] for j in range(15*i, 15*(i+1))]) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] @@ -684,7 +684,7 @@ >>> it = m235() >>> for i in range(5): -... print firstn(it, 15) +... print(firstn(it, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] @@ -890,13 +890,13 @@ ... yield i ... >>> g = f() ->>> print g.next() +>>> print(g.next()) 0 ->>> print g.next() +>>> print(g.next()) 1 ->>> print g.next() +>>> print(g.next()) 2 ->>> print g.next() +>>> print(g.next()) Traceback (most recent call last): StopIteration """ @@ -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): @@ -1082,12 +1082,12 @@ n = self.n assert n == len(row2col) sep = "+" + "-+" * n - print sep + print(sep) for i in range(n): squares = [" " for j in range(n)] squares[row2col[i]] = "Q" - print "|" + "|".join(squares) + "|" - print sep + print("|" + "|".join(squares) + "|") + print(sep) # A conjoin-based Knight's Tour solver. This is pretty sophisticated # (e.g., when used with flat_conjoin above, and passing hard=1 to the @@ -1279,11 +1279,11 @@ k += 1 sep = "+" + ("-" * w + "+") * n - print sep + print(sep) for i in range(m): row = squares[i] - print "|" + "|".join(row) + "|" - print sep + print("|" + "|".join(row) + "|") + print(sep) conjoin_tests = """ @@ -1291,7 +1291,7 @@ possible use of conjoin, just to generate the full cross-product. >>> for c in conjoin([lambda: iter((0, 1))] * 3): -... print c +... print(c) [0, 0, 0] [0, 0, 1] [0, 1, 0] @@ -1311,7 +1311,7 @@ >>> for n in range(10): ... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n))) -... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n +... print(n, len(all), all[0] == [0] * n, all[-1] == [1] * n) 0 1 True True 1 2 True True 2 4 True True @@ -1331,7 +1331,7 @@ >>> for row2col in q.solve(): ... count += 1 ... if count <= LIMIT: -... print "Solution", count +... print("Solution", count) ... q.printsolution(row2col) Solution 1 +-+-+-+-+-+-+-+-+ @@ -1370,7 +1370,7 @@ | | | | |Q| | | | +-+-+-+-+-+-+-+-+ ->>> print count, "solutions in all." +>>> print(count, "solutions in all.") 92 solutions in all. And run a Knight's Tour on a 10x10 board. Note that there are about @@ -1382,7 +1382,7 @@ >>> for x in k.solve(): ... count += 1 ... if count <= LIMIT: -... print "Solution", count +... print("Solution", count) ... k.printsolution(x) ... else: ... break @@ -1460,7 +1460,7 @@ Sending a value into a started generator: >>> def f(): -... print (yield 1) +... print((yield 1)) ... yield 2 >>> g = f() >>> g.next() @@ -1507,16 +1507,16 @@ >>> seq = [] >>> c = coroutine(seq) >>> c.next() ->>> print seq +>>> print(seq) [] >>> c.send(10) ->>> print seq +>>> print(seq) [10] >>> c.send(10) ->>> print seq +>>> print(seq) [10, 20] >>> c.send(10) ->>> print seq +>>> print(seq) [10, 20, 30] @@ -1553,9 +1553,9 @@ >>> def f(): ... while True: ... try: -... print (yield) +... print((yield)) ... except ValueError as v: -... print "caught ValueError (%s)" % (v), +... print("caught ValueError (%s)" % (v)) >>> import sys >>> g = f() >>> g.next() @@ -1616,7 +1616,7 @@ ... TypeError ->>> print g.gi_frame +>>> print(g.gi_frame) None >>> g.send(2) @@ -1639,7 +1639,7 @@ >>> def f(): ... try: yield ... except GeneratorExit: -... print "exiting" +... print("exiting") >>> g = f() >>> g.next() @@ -1660,7 +1660,7 @@ >>> def f(): ... try: yield ... finally: -... print "exiting" +... print("exiting") >>> g = f() >>> g.next() Modified: python/branches/p3yk-noslice/Lib/test/test_genexps.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_genexps.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_genexps.py Fri Feb 23 18:29:35 2007 @@ -157,12 +157,12 @@ >>> def creator(): ... r = yrange(5) - ... print "creator", r.next() + ... print("creator", r.next()) ... return r >>> def caller(): ... r = creator() ... for i in r: - ... print "caller", i + ... print("caller", i) >>> caller() creator 0 caller 1 @@ -221,7 +221,7 @@ >>> set(attr for attr in dir(g) if not attr.startswith('__')) >= expected True - >>> print g.next.__doc__ + >>> print(g.next.__doc__) x.next() -> the next value, or raise StopIteration >>> import types >>> isinstance(g, types.GeneratorType) @@ -274,7 +274,7 @@ test_support.run_doctest(test_genexps, verbose) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_getargs2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_getargs2.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_getargs2.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_getopt.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_getopt.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_getopt.py Fri Feb 23 18:29:35 2007 @@ -21,14 +21,14 @@ del os.environ["POSIXLY_CORRECT"] if verbose: - print 'Running tests on getopt.short_has_arg' + print('Running tests on getopt.short_has_arg') verify(getopt.short_has_arg('a', 'a:')) verify(not getopt.short_has_arg('a', 'a')) expectException("tmp = getopt.short_has_arg('a', 'b')", GetoptError) expectException("tmp = getopt.short_has_arg('a', '')", GetoptError) if verbose: - print 'Running tests on getopt.long_has_args' + print('Running tests on getopt.long_has_args') has_arg, option = getopt.long_has_args('abc', ['abc=']) verify(has_arg) verify(option == 'abc') @@ -47,7 +47,7 @@ GetoptError) if verbose: - print 'Running tests on getopt.do_shorts' + print('Running tests on getopt.do_shorts') opts, args = getopt.do_shorts([], 'a', 'a', []) verify(opts == [('-a', '')]) verify(args == []) @@ -69,7 +69,7 @@ GetoptError) if verbose: - print 'Running tests on getopt.do_longs' + print('Running tests on getopt.do_longs') opts, args = getopt.do_longs([], 'abc', ['abc'], []) verify(opts == [('--abc', '')]) verify(args == []) @@ -99,7 +99,7 @@ '--beta', 'arg1', 'arg2'] if verbose: - print 'Running tests on getopt.getopt' + print('Running tests on getopt.getopt') opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta']) verify(opts == [('-a', '1'), ('-b', ''), ('--alpha', '2'), ('--beta', ''), ('-a', '3'), ('-a', ''), ('--beta', '')] ) @@ -113,7 +113,7 @@ # Test handling of GNU style scanning mode. if verbose: - print 'Running tests on getopt.gnu_getopt' + print('Running tests on getopt.gnu_getopt') cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2'] # GNU style opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta=']) @@ -177,4 +177,4 @@ #------------------------------------------------------------------------------ if verbose: - print "Module getopt: tests completed successfully." + print("Module getopt: tests completed successfully.") Modified: python/branches/p3yk-noslice/Lib/test/test_gl.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_gl.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_gl.py Fri Feb 23 18:29:35 2007 @@ -91,60 +91,60 @@ # touch all the attributes of gl without doing anything if verbose: - print 'Touching gl module attributes...' + print('Touching gl module attributes...') for attr in glattrs: if verbose: - print 'touching: ', attr + print('touching: ', attr) getattr(gl, attr) # create a small 'Crisscross' window if verbose: - print 'Creating a small "CrissCross" window...' - print 'foreground' + print('Creating a small "CrissCross" window...') + print('foreground') gl.foreground() if verbose: - print 'prefposition' + print('prefposition') gl.prefposition(500, 900, 500, 900) if verbose: - print 'winopen "CrissCross"' + print('winopen "CrissCross"') w = gl.winopen('CrissCross') if verbose: - print 'clear' + print('clear') gl.clear() if verbose: - print 'ortho2' + print('ortho2') gl.ortho2(0.0, 400.0, 0.0, 400.0) if verbose: - print 'color WHITE' + print('color WHITE') gl.color(GL.WHITE) if verbose: - print 'color RED' + print('color RED') gl.color(GL.RED) if verbose: - print 'bgnline' + print('bgnline') gl.bgnline() if verbose: - print 'v2f' + print('v2f') gl.v2f(0.0, 0.0) gl.v2f(400.0, 400.0) if verbose: - print 'endline' + print('endline') gl.endline() if verbose: - print 'bgnline' + print('bgnline') gl.bgnline() if verbose: - print 'v2i' + print('v2i') gl.v2i(400, 0) gl.v2i(0, 400) if verbose: - print 'endline' + print('endline') gl.endline() if verbose: - print 'Displaying window for 2 seconds...' + print('Displaying window for 2 seconds...') time.sleep(2) if verbose: - print 'winclose' + print('winclose') gl.winclose(w) main() Modified: python/branches/p3yk-noslice/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_grammar.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_grammar.py Fri Feb 23 18:29:35 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) @@ -351,7 +351,7 @@ x = 1; pass; del x; foo() - ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt + ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt # Tested below def testExprStmt(self): @@ -367,76 +367,6 @@ check_syntax_error(self, "x + 1 = 1") check_syntax_error(self, "a + 1 = b + 2") - def testPrintStmt(self): - # 'print' (test ',')* [test] - import StringIO - - # Can't test printing to real stdout without comparing output - # which is not available in unittest. - save_stdout = sys.stdout - sys.stdout = StringIO.StringIO() - - print 1, 2, 3 - print 1, 2, 3, - print - print 0 or 1, 0 or 1, - print 0 or 1 - - # 'print' '>>' test ',' - print >> sys.stdout, 1, 2, 3 - print >> sys.stdout, 1, 2, 3, - print >> sys.stdout - print >> sys.stdout, 0 or 1, 0 or 1, - print >> sys.stdout, 0 or 1 - - # test printing to an instance - class Gulp: - def write(self, msg): pass - - gulp = Gulp() - print >> gulp, 1, 2, 3 - print >> gulp, 1, 2, 3, - print >> gulp - print >> gulp, 0 or 1, 0 or 1, - print >> gulp, 0 or 1 - - # test print >> None - def driver(): - oldstdout = sys.stdout - sys.stdout = Gulp() - try: - tellme(Gulp()) - tellme() - finally: - sys.stdout = oldstdout - - # we should see this once - def tellme(file=sys.stdout): - print >> file, 'hello world' - - driver() - - # we should not see this at all - def tellme(file=None): - print >> file, 'goodbye universe' - - driver() - - self.assertEqual(sys.stdout.getvalue(), '''\ -1 2 3 -1 2 3 -1 1 1 -1 2 3 -1 2 3 -1 1 1 -hello world -''') - sys.stdout = save_stdout - - # syntax errors - check_syntax_error(self, 'print ,') - check_syntax_error(self, 'print >> x,') - def testDelStmt(self): # 'del' exprlist abc = [1,2,3] @@ -902,7 +832,7 @@ # Test ifelse expressions in various cases def _checkeval(msg, ret): "helper to check that evaluation of expressions is done correctly" - print x + print(x) return ret self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) Modified: python/branches/p3yk-noslice/Lib/test/test_grp.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_grp.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_grp.py Fri Feb 23 18:29:35 2007 @@ -50,7 +50,7 @@ bynames[n] = g bygids[g] = n - allnames = bynames.keys() + allnames = list(bynames.keys()) namei = 0 fakename = allnames[namei] while fakename in bynames: Modified: python/branches/p3yk-noslice/Lib/test/test_gzip.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_gzip.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_gzip.py Fri Feb 23 18:29:35 2007 @@ -138,7 +138,7 @@ y = f.read(10) f.close() self.assertEquals(y, data1[20:30]) - + def test_seek_write(self): # Try seek, write test f = gzip.GzipFile(self.filename, 'w') @@ -153,6 +153,13 @@ self.assertEqual(f.myfileobj.mode, 'rb') f.close() + def test_1647484(self): + for mode in ('wb', 'rb'): + f = gzip.GzipFile(self.filename, mode) + self.assert_(hasattr(f, "name")) + self.assertEqual(f.name, self.filename) + f.close() + def test_main(verbose=None): test_support.run_unittest(TestGzip) Modified: python/branches/p3yk-noslice/Lib/test/test_hash.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_hash.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_hash.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_heapq.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_heapq.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_heapq.py Fri Feb 23 18:29:35 2007 @@ -1,6 +1,6 @@ """Unittests for heapq.""" -from heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest +from heapq import heappush, heappop, heapify, heapreplace, merge, nlargest, nsmallest import random import unittest from test import test_support @@ -103,6 +103,29 @@ heap_sorted = [heappop(heap) for i in range(size)] self.assertEqual(heap_sorted, sorted(data)) + def test_merge(self): + inputs = [] + for i in xrange(random.randrange(5)): + row = sorted(random.randrange(1000) for j in range(random.randrange(10))) + inputs.append(row) + self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs))) + self.assertEqual(list(merge()), []) + + def test_merge_stability(self): + class Int(int): + pass + inputs = [[], [], [], []] + for i in range(20000): + stream = random.randrange(4) + x = random.randrange(500) + obj = Int(x) + obj.pair = (x, stream) + inputs[stream].append(obj) + for stream in inputs: + stream.sort() + result = [i.pair for i in merge(*inputs)] + self.assertEqual(result, sorted(result)) + def test_nsmallest(self): data = [(random.randrange(2000), i) for i in range(1000)] for f in (None, lambda x: x[0] * 547 % 2000): @@ -281,7 +304,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_hexoct.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_hexoct.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_hexoct.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_imageop.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_imageop.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_imageop.py Fri Feb 23 18:29:35 2007 @@ -28,7 +28,7 @@ # Return the selected part of image, which should by width by height # in size and consist of pixels of psize bytes. if verbose: - print 'crop' + print('crop') newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1) # Return image scaled to size newwidth by newheight. No interpolation @@ -36,7 +36,7 @@ # Therefore, computer-generated images or dithered images will # not look nice after scaling. if verbose: - print 'scale' + print('scale') scaleimage = imageop.scale(image, 4, width, height, 1, 1) # Run a vertical low-pass filter over an image. It does so by computing @@ -44,34 +44,34 @@ # pixels. The main use of this routine is to forestall excessive flicker # if the image two vertically-aligned source pixels, hence the name. if verbose: - print 'tovideo' + print('tovideo') videoimage = imageop.tovideo (image, 4, width, height) # Convert an rgb image to an 8 bit rgb if verbose: - print 'rgb2rgb8' + print('rgb2rgb8') greyimage = imageop.rgb2rgb8(image, width, height) # Convert an 8 bit rgb image to a 24 bit rgb image if verbose: - print 'rgb82rgb' + print('rgb82rgb') image = imageop.rgb82rgb(greyimage, width, height) # Convert an rgb image to an 8 bit greyscale image if verbose: - print 'rgb2grey' + print('rgb2grey') greyimage = imageop.rgb2grey(image, width, height) # Convert an 8 bit greyscale image to a 24 bit rgb image if verbose: - print 'grey2rgb' + print('grey2rgb') image = imageop.grey2rgb(greyimage, width, height) # Convert a 8-bit deep greyscale image to a 1-bit deep image by # thresholding all the pixels. The resulting image is tightly packed # and is probably only useful as an argument to mono2grey. if verbose: - print 'grey2mono' + print('grey2mono') monoimage = imageop.grey2mono (greyimage, width, height, 0) # monoimage, width, height = getimage('monotest.rgb') @@ -81,42 +81,42 @@ # monochrome black-and-white image to greyscale pass the values 0 and # 255 respectively. if verbose: - print 'mono2grey' + print('mono2grey') greyimage = imageop.mono2grey (monoimage, width, height, 0, 255) # Convert an 8-bit greyscale image to a 1-bit monochrome image using a # (simple-minded) dithering algorithm. if verbose: - print 'dither2mono' + print('dither2mono') monoimage = imageop.dither2mono (greyimage, width, height) # Convert an 8-bit greyscale image to a 4-bit greyscale image without # dithering. if verbose: - print 'grey2grey4' + print('grey2grey4') grey4image = imageop.grey2grey4 (greyimage, width, height) # Convert an 8-bit greyscale image to a 2-bit greyscale image without # dithering. if verbose: - print 'grey2grey2' + print('grey2grey2') grey2image = imageop.grey2grey2 (greyimage, width, height) # Convert an 8-bit greyscale image to a 2-bit greyscale image with # dithering. As for dither2mono, the dithering algorithm is currently # very simple. if verbose: - print 'dither2grey2' + print('dither2grey2') grey2image = imageop.dither2grey2 (greyimage, width, height) # Convert a 4-bit greyscale image to an 8-bit greyscale image. if verbose: - print 'grey42grey' + print('grey42grey') greyimage = imageop.grey42grey (grey4image, width, height) # Convert a 2-bit greyscale image to an 8-bit greyscale image. if verbose: - print 'grey22grey' + print('grey22grey') image = imageop.grey22grey (grey2image, width, height) # Cleanup @@ -134,7 +134,7 @@ name = get_qualified_path(name) sizes = rgbimg.sizeofimage(name) if verbose: - print 'rgbimg opening test image: %s, sizes: %s' % (name, str(sizes)) + print('rgbimg opening test image: %s, sizes: %s' % (name, str(sizes))) image = rgbimg.longimagedata(name) return (image, sizes[0], sizes[1]) @@ -152,7 +152,7 @@ name = get_qualified_path(name) sizes = imgfile.getsizes(name) if verbose: - print 'imgfile opening test image: %s, sizes: %s' % (name, str(sizes)) + print('imgfile opening test image: %s, sizes: %s' % (name, str(sizes))) image = imgfile.read(name) return (image, sizes[0], sizes[1]) Modified: python/branches/p3yk-noslice/Lib/test/test_imgfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_imgfile.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_imgfile.py Fri Feb 23 18:29:35 2007 @@ -51,7 +51,7 @@ name = os.sep.join(parts) sizes = imgfile.getsizes(name) if verbose: - print 'Opening test image: %s, sizes: %s' % (name, str(sizes)) + print('Opening test image: %s, sizes: %s' % (name, str(sizes))) # This function reads and decodes the image on the specified file, # and returns it as a python string. The string has either 1 byte # greyscale pixels or 4 byte RGBA pixels. The bottom left pixel @@ -65,12 +65,12 @@ # are stored as 4 byte values of which only the lower three # bytes are used). These are the formats returned by gl.lrectread. if verbose: - print 'Writing output file' + print('Writing output file') imgfile.write (outputfile, image, sizes[0], sizes[1], sizes[2]) if verbose: - print 'Opening scaled test image: %s, sizes: %s' % (name, str(sizes)) + print('Opening scaled test image: %s, sizes: %s' % (name, str(sizes))) # This function is identical to read but it returns an image that # is scaled to the given x and y sizes. If the filter and blur # parameters are omitted scaling is done by simply dropping @@ -84,7 +84,7 @@ # makes no attempt to keep the aspect ratio correct, so that # is the users' responsibility. if verbose: - print 'Filtering with "impulse"' + print('Filtering with "impulse"') simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'impulse', 2.0) # This function sets a global flag which defines whether the @@ -92,23 +92,23 @@ # top (flag is zero, compatible with SGI GL) or from top to # bottom(flag is one, compatible with X). The default is zero. if verbose: - print 'Switching to X compatibility' + print('Switching to X compatibility') imgfile.ttob (1) if verbose: - print 'Filtering with "triangle"' + print('Filtering with "triangle"') simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'triangle', 3.0) if verbose: - print 'Switching back to SGI compatibility' + print('Switching back to SGI compatibility') imgfile.ttob (0) - if verbose: print 'Filtering with "quadratic"' + if verbose: print('Filtering with "quadratic"') simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'quadratic') - if verbose: print 'Filtering with "gaussian"' + if verbose: print('Filtering with "gaussian"') simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'gaussian', 1.0) if verbose: - print 'Writing output file' + print('Writing output file') imgfile.write (outputfile, simage, sizes[0]/2, sizes[1]/2, sizes[2]) os.unlink(outputfile) Modified: python/branches/p3yk-noslice/Lib/test/test_import.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_import.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_import.py Fri Feb 23 18:29:35 2007 @@ -45,11 +45,11 @@ pyc = TESTFN + os.extsep + "pyc" f = open(source, "w") - print >> f, "# This tests Python's ability to import a", ext, "file." + print("# This tests Python's ability to import a", ext, "file.", file=f) a = random.randrange(1000) b = random.randrange(1000) - print >> f, "a =", a - print >> f, "b =", b + print("a =", a, file=f) + print("b =", b, file=f) f.close() try: @@ -130,7 +130,7 @@ def test_failing_import_sticks(self): source = TESTFN + os.extsep + "py" f = open(source, "w") - print >> f, "a = 1/0" + print("a = 1/0", file=f) f.close() # New in 2.4, we shouldn't be able to import that no matter how often @@ -153,8 +153,8 @@ # A failing reload should leave the module object in sys.modules. source = TESTFN + os.extsep + "py" f = open(source, "w") - print >> f, "a = 1" - print >> f, "b = 2" + print("a = 1", file=f) + print("b = 2", file=f) f.close() sys.path.insert(0, os.curdir) @@ -172,8 +172,8 @@ # Now damage the module. f = open(source, "w") - print >> f, "a = 10" - print >> f, "b = 20//0" + print("a = 10", file=f) + print("b = 20//0", file=f) f.close() self.assertRaises(ZeroDivisionError, reload, mod) Modified: python/branches/p3yk-noslice/Lib/test/test_importhooks.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_importhooks.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_importhooks.py Fri Feb 23 18:29:35 2007 @@ -254,7 +254,7 @@ mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc") for mname in mnames: parent = mname.split(".")[0] - for n in sys.modules.keys(): + for n in list(sys.modules.keys()): if n.startswith(parent): del sys.modules[n] for mname in mnames: Modified: python/branches/p3yk-noslice/Lib/test/test_index.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_index.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_index.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_inspect.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_inspect.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_inspect.py Fri Feb 23 18:29:35 2007 @@ -61,7 +61,6 @@ self.istest(inspect.ismodule, 'mod') self.istest(inspect.istraceback, 'tb') self.istest(inspect.isdatadescriptor, '__builtin__.file.closed') - self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace') if hasattr(types, 'GetSetDescriptorType'): self.istest(inspect.isgetsetdescriptor, 'type(tb.tb_frame).f_locals') Modified: python/branches/p3yk-noslice/Lib/test/test_isinstance.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_isinstance.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_isinstance.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_iter.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_iter.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_iter.py Fri Feb 23 18:29:35 2007 @@ -225,7 +225,7 @@ dict = {} for i in range(10): dict[i] = None - self.check_for_loop(dict, dict.keys()) + self.check_for_loop(dict, list(dict.keys())) # Test a file def test_iter_file(self): @@ -254,7 +254,7 @@ self.assertEqual(list(range(10, -1, -1)), range(10, -1, -1)) d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(list(d), d.keys()) + self.assertEqual(list(d), list(d.keys())) self.assertRaises(TypeError, list, list) self.assertRaises(TypeError, list, 42) @@ -319,7 +319,7 @@ self.assertEqual(filter(None, "abc"), "abc") d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(filter(None, d), d.keys()) + self.assertEqual(filter(None, d), list(d.keys())) self.assertRaises(TypeError, filter, None, list) self.assertRaises(TypeError, filter, None, 42) @@ -365,8 +365,8 @@ d = {"one": 1, "two": 2, "three": 3} self.assertEqual(max(d), "two") self.assertEqual(min(d), "one") - self.assertEqual(max(d.itervalues()), 3) - self.assertEqual(min(iter(d.itervalues())), 1) + self.assertEqual(max(d.values()), 3) + self.assertEqual(min(iter(d.values())), 1) f = open(TESTFN, "w") try: @@ -393,16 +393,16 @@ self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6)) d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(map(None, d), d.keys()) - self.assertEqual(map(lambda k, d=d: (k, d[k]), d), d.items()) - dkeys = d.keys() + self.assertEqual(map(None, d), list(d.keys())) + self.assertEqual(map(lambda k, d=d: (k, d[k]), d), list(d.items())) + dkeys = list(d.keys()) expected = [(i < len(d) and dkeys[i] or None, i, i < len(d) and dkeys[i] or None) for i in range(5)] self.assertEqual(map(None, d, SequenceClass(5), - iter(d.iterkeys())), + iter(d.keys())), expected) f = open(TESTFN, "w") @@ -437,7 +437,7 @@ [(0,), (1,), (2,)]) d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(d.items(), list(zip(d, d.itervalues()))) + self.assertEqual(list(d.items()), list(zip(d, d.values()))) # Generate all ints starting at constructor arg. class IntsFrom: @@ -559,13 +559,13 @@ d = {"one": 1, "two": 2, "three": 3, 1j: 2j} for k in d: self.assert_(k in d) - self.assert_(k not in d.itervalues()) + self.assert_(k not in d.values()) for v in d.values(): - self.assert_(v in d.itervalues()) + self.assert_(v in d.values()) self.assert_(v not in d) - for k, v in d.iteritems(): - self.assert_((k, v) in d.iteritems()) - self.assert_((v, k) not in d.iteritems()) + for k, v in d.items(): + self.assert_((k, v) in d.items()) + self.assert_((v, k) not in d.items()) f = open(TESTFN, "w") try: @@ -600,9 +600,9 @@ d = {"one": 3, "two": 3, "three": 3, 1j: 2j} for k in d: self.assertEqual(countOf(d, k), 1) - self.assertEqual(countOf(d.itervalues(), 3), 3) - self.assertEqual(countOf(d.itervalues(), 2j), 1) - self.assertEqual(countOf(d.itervalues(), 1j), 0) + self.assertEqual(countOf(d.values(), 3), 3) + self.assertEqual(countOf(d.values(), 2j), 1) + self.assertEqual(countOf(d.values(), 1j), 0) f = open(TESTFN, "w") try: @@ -744,7 +744,7 @@ else: self.fail("should have raised TypeError") - a, b, c = {1: 42, 2: 42, 3: 42}.itervalues() + a, b, c = {1: 42, 2: 42, 3: 42}.values() self.assertEqual((a, b, c), (42, 42, 42)) f = open(TESTFN, "w") @@ -841,7 +841,7 @@ # XXX For a more thorough test, see towards the end of: # http://mail.python.org/pipermail/python-dev/2002-July/026512.html a = {1:1, 2:2, 0:0, 4:4, 3:3} - for b in iter(a), a.iterkeys(), a.iteritems(), a.itervalues(): + for b in iter(a), a.keys(), a.items(), a.values(): b = iter(a) self.assertEqual(len(list(b)), 5) self.assertEqual(list(b), []) Modified: python/branches/p3yk-noslice/Lib/test/test_iterlen.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_iterlen.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_iterlen.py Fri Feb 23 18:29:35 2007 @@ -139,14 +139,14 @@ def setUp(self): d = dict.fromkeys(xrange(n)) - self.it = d.iteritems() + self.it = iter(d.items()) self.mutate = d.popitem class TestDictValues(TestTemporarilyImmutable): def setUp(self): d = dict.fromkeys(xrange(n)) - self.it = d.itervalues() + self.it = iter(d.values()) self.mutate = d.popitem class TestSet(TestTemporarilyImmutable): Modified: python/branches/p3yk-noslice/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_itertools.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_itertools.py Fri Feb 23 18:29:35 2007 @@ -55,8 +55,7 @@ self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)]) self.assertRaises(TypeError, count, 2, 3) self.assertRaises(TypeError, count, 'a') - c = count(sys.maxint-2) # verify that rollover doesn't crash - c.next(); c.next(); c.next(); c.next(); c.next() + self.assertRaises(OverflowError, list, islice(count(sys.maxint-5), 10)) c = count(3) self.assertEqual(repr(c), 'count(3)') c.next() @@ -203,6 +202,51 @@ ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + def test_iziplongest(self): + for args in [ + ['abc', range(6)], + [range(6), 'abc'], + [range(1000), range(2000,2100), range(3000,3050)], + [range(1000), range(0), range(3000,3050), range(1200), range(1500)], + [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)], + ]: + target = map(None, *args) + self.assertEqual(list(izip_longest(*args)), target) + self.assertEqual(list(izip_longest(*args, **{})), target) + target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X' + self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target) + + self.assertEqual(take(3,izip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input + + self.assertEqual(list(izip_longest()), list(zip())) + self.assertEqual(list(izip_longest([])), list(zip([]))) + self.assertEqual(list(izip_longest('abcdef')), list(zip('abcdef'))) + + self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict + self.assertRaises(TypeError, izip_longest, 3) + self.assertRaises(TypeError, izip_longest, range(3), 3) + + for stmt in [ + "izip_longest('abc', fv=1)", + "izip_longest('abc', fillvalue=1, bogus_keyword=None)", + ]: + try: + eval(stmt, globals(), locals()) + except TypeError: + pass + else: + self.fail('Did not raise Type in: ' + stmt) + + # Check tuple re-use (implementation detail) + self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')], + list(zip('abc', 'def'))) + self.assertEqual([pair for pair in izip_longest('abc', 'def')], + list(zip('abc', 'def'))) + ids = map(id, izip_longest('abc', 'def')) + self.assertEqual(min(ids), max(ids)) + ids = map(id, list(izip_longest('abc', 'def'))) + self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + def test_repeat(self): self.assertEqual(lzip(xrange(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) @@ -616,6 +660,15 @@ self.assertRaises(TypeError, izip, N(s)) self.assertRaises(ZeroDivisionError, list, izip(E(s))) + def test_iziplongest(self): + for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): + for g in (G, I, Ig, S, L, R): + self.assertEqual(list(izip_longest(g(s))), list(zip(g(s)))) + self.assertEqual(list(izip_longest(g(s), g(s))), list(zip(g(s), g(s)))) + self.assertRaises(TypeError, izip_longest, X(s)) + self.assertRaises(TypeError, izip_longest, N(s)) + self.assertRaises(ZeroDivisionError, list, izip_longest(E(s))) + def test_imap(self): for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)): for g in (G, I, Ig, S, L, R): @@ -744,29 +797,44 @@ self.assertRaises(AssertionError, list, cycle(gen1())) self.assertEqual(hist, [0,1]) +class SubclassWithKwargsTest(unittest.TestCase): + def test_keywords_in_subclass(self): + # count is not subclassable... + for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap, + starmap, islice, takewhile, dropwhile, cycle): + class Subclass(cls): + def __init__(self, newarg=None, *args): + cls.__init__(self, *args) + try: + Subclass(newarg=1) + except TypeError as err: + # we expect type errors because of wrong argument count + self.failIf("does not take keyword arguments" in err.args[0]) + + libreftest = """ Doctest for examples in the library reference: libitertools.tex >>> amounts = [120.15, 764.05, 823.14] >>> for checknum, amount in izip(count(1200), amounts): -... print 'Check %d is for $%.2f' % (checknum, amount) -... +... print('Check %d is for $%.2f' % (checknum, amount)) +... Check 1200 is for $120.15 Check 1201 is for $764.05 Check 1202 is for $823.14 >>> import operator >>> for cube in imap(operator.pow, xrange(1,4), repeat(3)): -... print cube -... +... print(cube) +... 1 8 27 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele'] >>> for name in islice(reportlines, 3, None, 2): -... print name.title() -... +... print(name.title()) +... Alex Laura Martin @@ -775,10 +843,10 @@ >>> from operator import itemgetter >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) ->>> di = sorted(sorted(d.iteritems()), key=itemgetter(1)) +>>> di = sorted(sorted(d.items()), key=itemgetter(1)) >>> for k, g in groupby(di, itemgetter(1)): -... print k, map(itemgetter(0), g) -... +... print(k, map(itemgetter(0), g)) +... 1 ['a', 'c', 'e'] 2 ['b', 'd', 'f'] 3 ['g'] @@ -788,8 +856,8 @@ # same group. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): -... print map(operator.itemgetter(1), g) -... +... print(map(operator.itemgetter(1), g)) +... [1] [4, 5, 6] [10] @@ -808,7 +876,7 @@ ... return imap(function, count()) >>> def iteritems(mapping): -... return izip(mapping.iterkeys(), mapping.itervalues()) +... return izip(mapping.keys(), mapping.values()) >>> def nth(iterable, n): ... "Returns the nth item" @@ -938,7 +1006,8 @@ def test_main(verbose=None): test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC, - RegressionTests, LengthTransparency) + RegressionTests, LengthTransparency, + SubclassWithKwargsTest) test_support.run_unittest(*test_classes) # verify reference counting @@ -949,7 +1018,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) # doctest the examples in the library reference test_support.run_doctest(sys.modules[__name__], verbose) Modified: python/branches/p3yk-noslice/Lib/test/test_largefile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_largefile.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_largefile.py Fri Feb 23 18:29:35 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() @@ -52,22 +52,22 @@ def expect(got_this, expect_this): if test_support.verbose: - print '%r =?= %r ...' % (got_this, expect_this), + print('%r =?= %r ...' % (got_this, expect_this), end=' ') if got_this != expect_this: if test_support.verbose: - print 'no' + print('no') raise test_support.TestFailed, 'got %r, but expected %r' %\ (got_this, expect_this) else: if test_support.verbose: - print 'yes' + print('yes') # test that each file function works as expected for a large (i.e. >2GB, do # we have to check >4GB) files if test_support.verbose: - print 'create large file via seek (may be sparse file) ...' + print('create large file via seek (may be sparse file) ...') f = open(name, 'wb') try: f.write('z') @@ -76,16 +76,16 @@ f.write('a') f.flush() if test_support.verbose: - print 'check file size with os.fstat' + print('check file size with os.fstat') expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1) finally: f.close() if test_support.verbose: - print 'check file size with os.stat' + print('check file size with os.stat') expect(os.stat(name)[stat.ST_SIZE], size+1) if test_support.verbose: - print 'play around with seek() and read() with the built largefile' + print('play around with seek() and read() with the built largefile') f = open(name, 'rb') try: expect(f.tell(), 0) @@ -119,7 +119,7 @@ f.close() if test_support.verbose: - print 'play around with os.lseek() with the built largefile' + print('play around with os.lseek() with the built largefile') f = open(name, 'rb') try: expect(os.lseek(f.fileno(), 0, 0), 0) @@ -136,7 +136,7 @@ if hasattr(f, 'truncate'): if test_support.verbose: - print 'try truncate' + print('try truncate') f = open(name, 'r+b') try: f.seek(0, 2) Modified: python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py Fri Feb 23 18:29:35 2007 @@ -22,7 +22,7 @@ fp.close() if enc != SND_FORMAT_MULAW_8: - print "Expect .au file with 8-bit mu-law samples" + print("Expect .au file with 8-bit mu-law samples") return try: @@ -63,27 +63,27 @@ try: a.setparameters(-1, size, nchannels, fmt) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, -2, nchannels, fmt) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, size, 3, fmt) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, size, nchannels, 177) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, 16, nchannels, fmt) except ValueError as msg: - print msg + print(msg) def test(): play_sound_file(findfile('audiotest.au')) Modified: python/branches/p3yk-noslice/Lib/test/test_list.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_list.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_list.py Fri Feb 23 18:29:35 2007 @@ -30,7 +30,7 @@ test_support.run_unittest(ListTest) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": Modified: python/branches/p3yk-noslice/Lib/test/test_locale.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_locale.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_locale.py Fri Feb 23 18:29:35 2007 @@ -23,19 +23,19 @@ def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: - print "%s %% %s =? %s ..." %\ - (repr(formatstr), repr(value), repr(output)), + print("%s %% %s =? %s ..." %\ + (repr(formatstr), repr(value), repr(output)), end=' ') else: - print "%s %% %s works? ..." % (repr(formatstr), repr(value)), + print("%s %% %s works? ..." % (repr(formatstr), repr(value)), end=' ') result = func(formatstr, value, grouping = grouping) if output and result != output: if verbose: - print 'no' - print "%s %% %s == %s != %s" %\ - (repr(formatstr), repr(value), repr(result), repr(output)) + print('no') + print("%s %% %s == %s != %s" %\ + (repr(formatstr), repr(value), repr(result), repr(output))) else: if verbose: - print "yes" + print("yes") try: # On Solaris 10, the thousands_sep is the empty string @@ -80,15 +80,15 @@ # Test BSD Rune locale's bug for isctype functions. def teststrop(s, method, output): if verbose: - print "%s.%s() =? %s ..." % (repr(s), method, repr(output)), + print("%s.%s() =? %s ..." % (repr(s), method, repr(output)), end=' ') result = getattr(s, method)() if result != output: if verbose: - print "no" - print "%s.%s() == %s != %s" % (repr(s), method, repr(result), - repr(output)) + print("no") + print("%s.%s() == %s != %s" % (repr(s), method, repr(result), + repr(output))) elif verbose: - print "yes" + print("yes") try: if sys.platform == 'sunos5': Modified: python/branches/p3yk-noslice/Lib/test/test_long.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_long.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_long.py Fri Feb 23 18:29:35 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,17 +278,16 @@ 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") - # ----------------------------------- tests of auto int->long conversion def test_auto_overflow(self): @@ -305,14 +304,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 @@ -347,20 +346,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)", @@ -400,7 +399,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) @@ -416,7 +415,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): @@ -465,12 +464,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-noslice/Lib/test/test_long_future.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_long_future.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_long_future.py Fri Feb 23 18:29:35 2007 @@ -7,17 +7,17 @@ def test_true_division(): if verbose: - print "long true division" - huge = 1L << 40000 + print("long true division") + 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-noslice/Lib/test/test_mailbox.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_mailbox.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_mailbox.py Fri Feb 23 18:29:35 2007 @@ -4,7 +4,7 @@ import stat import socket import email -import email.Message +import email.message import rfc822 import re import StringIO @@ -22,15 +22,15 @@ def _check_sample(self, msg): # Inspect a mailbox.Message representation of the sample message - self.assert_(isinstance(msg, email.Message.Message)) + self.assert_(isinstance(msg, email.message.Message)) self.assert_(isinstance(msg, mailbox.Message)) - for key, value in _sample_headers.iteritems(): + for key, value in _sample_headers.items(): self.assert_(value in msg.get_all(key)) self.assert_(msg.is_multipart()) self.assert_(len(msg.get_payload()) == len(_sample_payloads)) for i, payload in enumerate(_sample_payloads): part = msg.get_payload(i) - self.assert_(isinstance(part, email.Message.Message)) + self.assert_(isinstance(part, email.message.Message)) self.assert_(not isinstance(part, mailbox.Message)) self.assert_(part.get_payload() == payload) @@ -174,7 +174,7 @@ def test_iterkeys(self): # Get keys using iterkeys() - self._check_iteration(self._box.iterkeys, do_keys=True, do_values=False) + self._check_iteration(self._box.keys, do_keys=True, do_values=False) def test_keys(self): # Get keys using keys() @@ -182,7 +182,7 @@ def test_itervalues(self): # Get values using itervalues() - self._check_iteration(self._box.itervalues, do_keys=False, + self._check_iteration(self._box.values, do_keys=False, do_values=True) def test_iter(self): @@ -196,7 +196,7 @@ def test_iteritems(self): # Get keys and values using iteritems() - self._check_iteration(self._box.iteritems, do_keys=True, + self._check_iteration(self._box.items, do_keys=True, do_values=True) def test_items(self): @@ -424,12 +424,12 @@ self.assertRaises(NotImplementedError, lambda: box.__delitem__('')) self.assertRaises(NotImplementedError, lambda: box.discard('')) self.assertRaises(NotImplementedError, lambda: box.__setitem__('', '')) - self.assertRaises(NotImplementedError, lambda: box.iterkeys()) self.assertRaises(NotImplementedError, lambda: box.keys()) - self.assertRaises(NotImplementedError, lambda: box.itervalues().next()) + self.assertRaises(NotImplementedError, lambda: box.keys()) + self.assertRaises(NotImplementedError, lambda: box.values().next()) self.assertRaises(NotImplementedError, lambda: box.__iter__().next()) self.assertRaises(NotImplementedError, lambda: box.values()) - self.assertRaises(NotImplementedError, lambda: box.iteritems().next()) + self.assertRaises(NotImplementedError, lambda: box.items().next()) self.assertRaises(NotImplementedError, lambda: box.items()) self.assertRaises(NotImplementedError, lambda: box.get('')) self.assertRaises(NotImplementedError, lambda: box.__getitem__('')) @@ -674,11 +674,11 @@ box = self._factory(self._path, factory=dummy_factory) folder = box.add_folder('folder1') self.assert_(folder._factory is dummy_factory) - + folder1_alias = box.get_folder('folder1') self.assert_(folder1_alias._factory is dummy_factory) - + class _TestMboxMMDF(TestMailbox): @@ -709,7 +709,7 @@ mtime = os.path.getmtime(self._path) self._box = self._factory(self._path) self.assert_(len(self._box) == 3) - for key in self._box.iterkeys(): + for key in self._box.keys(): self.assert_(self._box.get_string(key) in values) self._box.close() self.assert_(mtime == os.path.getmtime(self._path)) @@ -798,7 +798,7 @@ def dummy_factory (s): return None self._box = self._factory(self._path, dummy_factory) - + new_folder = self._box.add_folder('foo.bar') folder0 = self._box.get_folder('foo.bar') folder0.add(self._template % 'bar') @@ -894,7 +894,7 @@ self.assert_(self._box.get_sequences() == {'foo':[1, 2, 3, 4, 5], 'unseen':[1], 'bar':[3], 'replied':[3]}) - + def _get_lock_path(self): return os.path.join(self._path, '.mh_sequences.lock') @@ -939,7 +939,7 @@ self._delete_recursively(self._path) def test_initialize_with_eMM(self): - # Initialize based on email.Message.Message instance + # Initialize based on email.message.Message instance eMM = email.message_from_string(_sample_message) msg = self._factory(eMM) self._post_initialize_hook(msg) @@ -965,7 +965,7 @@ # Initialize without arguments msg = self._factory() self._post_initialize_hook(msg) - self.assert_(isinstance(msg, email.Message.Message)) + self.assert_(isinstance(msg, email.message.Message)) self.assert_(isinstance(msg, mailbox.Message)) self.assert_(isinstance(msg, self._factory)) self.assert_(msg.keys() == []) @@ -992,7 +992,7 @@ mailbox.BabylMessage, mailbox.MMDFMessage): other_msg = class_() msg._explain_to(other_msg) - other_msg = email.Message.Message() + other_msg = email.message.Message() self.assertRaises(TypeError, lambda: msg._explain_to(other_msg)) def _post_initialize_hook(self, msg): @@ -1732,11 +1732,11 @@ def test_unix_mbox(self): ### should be better! - import email.Parser + import email.parser fname = self.createMessage("cur", True) n = 0 for msg in mailbox.PortableUnixMailbox(open(fname), - email.Parser.Parser().parse): + email.parser.Parser().parse): n += 1 self.assertEqual(msg["subject"], "Simple Test") self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE)) Modified: python/branches/p3yk-noslice/Lib/test/test_marshal.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_marshal.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_marshal.py Fri Feb 23 18:29:35 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, @@ -167,7 +167,7 @@ os.unlink(test_support.TESTFN) def test_list(self): - lst = self.d.items() + lst = list(self.d.items()) new = marshal.loads(marshal.dumps(lst)) self.assertEqual(lst, new) marshal.dump(lst, open(test_support.TESTFN, "wb")) @@ -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**65)[:-1]) def test_version_argument(self): # Python 2.4.0 crashes for any call to marshal.dumps(x, y) Modified: python/branches/p3yk-noslice/Lib/test/test_mhlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_mhlib.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_mhlib.py Fri Feb 23 18:29:35 2007 @@ -46,7 +46,7 @@ return r def writeProfile(dict): - contents = [ "%s: %s\n" % (k, v) for k, v in dict.iteritems() ] + contents = [ "%s: %s\n" % (k, v) for k, v in dict.items() ] writeFile(_mhprofile, "".join(contents)) def writeContext(folder): @@ -61,7 +61,7 @@ def writeMessage(folder, n, headers, body): folder = normF(folder) - headers = "".join([ "%s: %s\n" % (k, v) for k, v in headers.iteritems() ]) + headers = "".join([ "%s: %s\n" % (k, v) for k, v in headers.items() ]) contents = "%s\n%s\n" % (headers,body) mkdirs(os.path.join(_mhpath, folder)) writeFile(os.path.join(_mhpath, folder, str(n)), contents) Modified: python/branches/p3yk-noslice/Lib/test/test_minidom.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_minidom.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_minidom.py Fri Feb 23 18:29:35 2007 @@ -24,7 +24,7 @@ def confirm(test, testname = "Test"): if not test: - print "Failed " + testname + print("Failed " + testname) raise Exception def testParseFromFile(): @@ -140,29 +140,29 @@ try: dom.appendChild(text) except xml.dom.HierarchyRequestErr: pass else: - print "dom.appendChild didn't raise HierarchyRequestErr" + print("dom.appendChild didn't raise HierarchyRequestErr") dom.appendChild(elem) try: dom.insertBefore(text, elem) except xml.dom.HierarchyRequestErr: pass else: - print "dom.appendChild didn't raise HierarchyRequestErr" + print("dom.appendChild didn't raise HierarchyRequestErr") try: dom.replaceChild(text, elem) except xml.dom.HierarchyRequestErr: pass else: - print "dom.appendChild didn't raise HierarchyRequestErr" + print("dom.appendChild didn't raise HierarchyRequestErr") nodemap = elem.attributes try: nodemap.setNamedItem(text) except xml.dom.HierarchyRequestErr: pass else: - print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr" + print("NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr") try: nodemap.setNamedItemNS(text) except xml.dom.HierarchyRequestErr: pass else: - print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr" + print("NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr") elem.appendChild(text) dom.unlink() @@ -457,8 +457,8 @@ except xml.dom.HierarchyRequestErr: pass else: - print "Failed to catch expected exception when" \ - " adding extra document element." + print("Failed to catch expected exception when" \ + " adding extra document element.") elem.unlink() doc.unlink() @@ -565,10 +565,8 @@ def _testCloneElementCopiesAttributes(e1, e2, test): attrs1 = e1.attributes attrs2 = e2.attributes - keys1 = attrs1.keys() - keys2 = attrs2.keys() - keys1.sort() - keys2.sort() + keys1 = sorted(attrs1.keys()) + keys2 = sorted(attrs2.keys()) confirm(keys1 == keys2, "clone of element has same attribute keys") for i in range(len(keys1)): a1 = attrs1.item(i) @@ -896,7 +894,7 @@ except UnicodeDecodeError: pass else: - print 'parsing with bad encoding should raise a UnicodeDecodeError' + print('parsing with bad encoding should raise a UnicodeDecodeError') doc.unlink() @@ -1008,7 +1006,7 @@ except xml.dom.NamespaceErr: pass else: - print "expected NamespaceErr" + print("expected NamespaceErr") checkRenameNodeSharedConstraints(doc, attr) doc.unlink() @@ -1063,7 +1061,7 @@ except xml.dom.NamespaceErr: pass else: - print "expected NamespaceErr" + print("expected NamespaceErr") doc2 = parseString("") try: @@ -1071,7 +1069,7 @@ except xml.dom.WrongDocumentErr: pass else: - print "expected WrongDocumentErr" + print("expected WrongDocumentErr") def testRenameOther(): # We have to create a comment node explicitly since not all DOM @@ -1084,7 +1082,7 @@ except xml.dom.NotSupportedErr: pass else: - print "expected NotSupportedErr when renaming comment node" + print("expected NotSupportedErr when renaming comment node") doc.unlink() def checkWholeText(node, s): @@ -1351,8 +1349,7 @@ # --- MAIN PROGRAM -names = globals().keys() -names.sort() +names = sorted(globals().keys()) failed = [] @@ -1368,13 +1365,13 @@ confirm(len(Node.allnodes) == 0, "assertion: len(Node.allnodes) == 0") if len(Node.allnodes): - print "Garbage left over:" + print("Garbage left over:") if verbose: - print Node.allnodes.items()[0:10] + print(Node.allnodes.items()[0:10]) else: # Don't print specific nodes if repeatable results # are needed - print len(Node.allnodes) + print(len(Node.allnodes)) Node.allnodes = {} for name in names: @@ -1385,13 +1382,13 @@ check_allnodes() except: failed.append(name) - print "Test Failed: ", name + print("Test Failed: ", name) sys.stdout.flush() traceback.print_exception(*sys.exc_info()) - print repr(sys.exc_info()[1]) + print(repr(sys.exc_info()[1])) Node.allnodes = {} if failed: - print "\n\n\n**** Check for failures in these tests:" + print("\n\n\n**** Check for failures in these tests:") for name in failed: - print " " + name + print(" " + name) Modified: python/branches/p3yk-noslice/Lib/test/test_module.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_module.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_module.py Fri Feb 23 18:29:35 2007 @@ -45,4 +45,4 @@ verify(foo.__dict__ is d) if verbose: - print "All OK" + print("All OK") Modified: python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py Fri Feb 23 18:29:35 2007 @@ -48,7 +48,7 @@ def test_codingspec(self): try: for enc in ALL_CJKENCODINGS: - print >> open(TESTFN, 'w'), '# coding:', enc + print('# coding:', enc, file=open(TESTFN, 'w')) execfile(TESTFN) finally: os.unlink(TESTFN) Modified: python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_mutants.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_mutants.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_mutants.py Fri Feb 23 18:29:35 2007 @@ -116,7 +116,7 @@ for i in xrange(numentries): d[Horrid(random.choice(candidates))] = \ Horrid(random.choice(candidates)) - return d.keys() + return list(d.keys()) # Test one pair of randomly generated dicts, each with n entries. # Note that dict comparison is trivial if they don't have the same number @@ -135,13 +135,13 @@ # same size. mutate = 1 if verbose: - print "trying w/ lengths", len(dict1), len(dict2), + print("trying w/ lengths", len(dict1), len(dict2), end=' ') while dict1 and len(dict1) == len(dict2): if verbose: - print ".", + print(".", end=' ') c = dict1 == dict2 if verbose: - print + print() # Run test_one n times. At the start (before the bugs were fixed), 20 # consecutive runs of this test each blew up on or before the sixth time @@ -186,7 +186,7 @@ # the expected-output file doesn't need to change. f = open(TESTFN, "w") -print >> f, Parent().__dict__ +print(Parent().__dict__, file=f) f.close() os.unlink(TESTFN) @@ -207,7 +207,7 @@ # Michael sez: "doesn't crash without this. don't know why." # Tim sez: "luck of the draw; crashes with or without for me." - print >> f + print(file=f) return repr("machiavelli") @@ -216,7 +216,7 @@ dict[Machiavelli()] = Machiavelli() -print >> f, str(dict) +print(str(dict), file=f) f.close() os.unlink(TESTFN) del f, dict @@ -280,7 +280,7 @@ f = open(TESTFN, "w") try: try: - print >> f, dict[Machiavelli3(2)] + print(dict[Machiavelli3(2)], file=f) except KeyError: pass finally: Modified: python/branches/p3yk-noslice/Lib/test/test_new.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_new.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_new.py Fri Feb 23 18:29:35 2007 @@ -1,180 +1,158 @@ -from test.test_support import verbose, verify, TestFailed -import sys -import new - -class Eggs: - def get_yolks(self): - return self.yolks - -print 'new.module()' -m = new.module('Spam') -if verbose: - print m -m.Eggs = Eggs -sys.modules['Spam'] = m -import Spam - -def get_more_yolks(self): - return self.yolks + 3 - -print 'new.classobj()' -C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks}) -if verbose: - print C - -def break_yolks(self): - self.yolks = self.yolks - 2 -print 'new.instancemethod()' -c = C() -c.yolks = 3 -im = new.instancemethod(break_yolks, c, C) -if verbose: - print im - -verify(c.get_yolks() == 3 and c.get_more_yolks() == 6, - 'Broken call of hand-crafted class instance') -im() -verify(c.get_yolks() == 1 and c.get_more_yolks() == 4, - 'Broken call of hand-crafted instance method') - -im = new.instancemethod(break_yolks, c) -im() -verify(c.get_yolks() == -1) -try: - new.instancemethod(break_yolks, None) -except TypeError: - pass -else: - raise TestFailed, "dangerous instance method creation allowed" - -# Verify that instancemethod() doesn't allow keyword args -try: - new.instancemethod(break_yolks, c, kw=1) -except TypeError: - pass -else: - raise TestFailed, "instancemethod shouldn't accept keyword args" - -# It's unclear what the semantics should be for a code object compiled at -# module scope, but bound and run in a function. In CPython, `c' is global -# (by accident?) while in Jython, `c' is local. The intent of the test -# clearly is to make `c' global, so let's be explicit about it. -codestr = ''' -global c -a = 1 -b = 2 -c = a + b -''' - -ccode = compile(codestr, '', 'exec') -# Jython doesn't have a __builtins__, so use a portable alternative -import __builtin__ -g = {'c': 0, '__builtins__': __builtin__} -# this test could be more robust -print 'new.function()' -func = new.function(ccode, g) -if verbose: - print func -func() -verify(g['c'] == 3, - 'Could not create a proper function object') - -# test the various extended flavors of function.new -def f(x): - def g(y): - return x + y - return g -g = f(4) -new.function(f.func_code, {}, "blah") -g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure) -verify(g2() == 6) -g3 = new.function(g.func_code, {}, "blah", None, g.func_closure) -verify(g3(5) == 9) -def test_closure(func, closure, exc): - try: - new.function(func.func_code, {}, "", None, closure) - except exc: - pass - else: - print "corrupt closure accepted" - -test_closure(g, None, TypeError) # invalid closure -test_closure(g, (1,), TypeError) # non-cell in closure -test_closure(g, (1, 1), ValueError) # closure is wrong size -test_closure(f, g.func_closure, ValueError) # no closure needed - -print 'new.code()' -# bogus test of new.code() -# Note: Jython will never have new.code() -if hasattr(new, 'code'): - def f(a): pass - - c = f.func_code - argcount = c.co_argcount - kwonlyargcount = c.co_kwonlyargcount - nlocals = c.co_nlocals - stacksize = c.co_stacksize - flags = c.co_flags - codestring = c.co_code - constants = c.co_consts - names = c.co_names - varnames = c.co_varnames - filename = c.co_filename - name = c.co_name - firstlineno = c.co_firstlineno - lnotab = c.co_lnotab - freevars = c.co_freevars - cellvars = c.co_cellvars - - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab, freevars, cellvars) - - # test backwards-compatibility version with no freevars or cellvars - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab) - - try: # this used to trigger a SystemError - d = new.code(-argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab) - except ValueError: - pass - else: - raise TestFailed, "negative co_argcount didn't trigger an exception" - - try: # this used to trigger a SystemError - d = new.code(argcount, kwonlyargcount, - -nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab) - except ValueError: - pass - else: - raise TestFailed, "negative co_nlocals didn't trigger an exception" - - try: # this used to trigger a Py_FatalError! - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, (5,), varnames, filename, name, - firstlineno, lnotab) - except TypeError: - pass - else: - raise TestFailed, "non-string co_name didn't trigger an exception" - - # new.code used to be a way to mutate a tuple... - class S(str): pass - t = (S("ab"),) - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, t, varnames, filename, name, - firstlineno, lnotab) - verify(type(t[0]) is S, "eek, tuple changed under us!") +import unittest +from test import test_support +import sys, new + +class NewTest(unittest.TestCase): + def test_spam(self): + class Eggs: + def get_yolks(self): + return self.yolks + + m = new.module('Spam') + m.Eggs = Eggs + sys.modules['Spam'] = m + import Spam + + def get_more_yolks(self): + return self.yolks + 3 + + # new.classobj() + C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks}) + + def break_yolks(self): + self.yolks = self.yolks - 2 + + # new.instancemethod() + c = C() + c.yolks = 3 + im = new.instancemethod(break_yolks, c, C) + + self.assertEqual(c.get_yolks(), 3, + 'Broken call of hand-crafted class instance') + self.assertEqual(c.get_more_yolks(), 6, + 'Broken call of hand-crafted class instance') + + im() + self.assertEqual(c.get_yolks(), 1, + 'Broken call of hand-crafted instance method') + self.assertEqual(c.get_more_yolks(), 4, + 'Broken call of hand-crafted instance method') + + im = new.instancemethod(break_yolks, c) + im() + self.assertEqual(c.get_yolks(), -1) + + # Verify that dangerous instance method creation is forbidden + self.assertRaises(TypeError, new.instancemethod, break_yolks, None) + + # Verify that instancemethod() doesn't allow keyword args + self.assertRaises(TypeError, new.instancemethod, break_yolks, c, kw=1) + + def test_scope(self): + # It's unclear what the semantics should be for a code object compiled + # at module scope, but bound and run in a function. In CPython, `c' is + # global (by accident?) while in Jython, `c' is local. The intent of + # the test clearly is to make `c' global, so let's be explicit about it. + codestr = ''' + global c + a = 1 + b = 2 + c = a + b + ''' + + codestr = "\n".join(l.strip() for l in codestr.splitlines()) + + ccode = compile(codestr, '', 'exec') + # Jython doesn't have a __builtins__, so use a portable alternative + import __builtin__ + g = {'c': 0, '__builtins__': __builtin__} + + # this test could be more robust + func = new.function(ccode, g) + func() + self.assertEqual(g['c'], 3, 'Could not create a proper function object') + + def test_function(self): + # test the various extended flavors of function.new + def f(x): + def g(y): + return x + y + return g + g = f(4) + new.function(f.func_code, {}, "blah") + g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure) + self.assertEqual(g2(), 6) + g3 = new.function(g.func_code, {}, "blah", None, g.func_closure) + self.assertEqual(g3(5), 9) + def test_closure(func, closure, exc): + self.assertRaises(exc, new.function, func.func_code, {}, "", None, closure) + + test_closure(g, None, TypeError) # invalid closure + test_closure(g, (1,), TypeError) # non-cell in closure + test_closure(g, (1, 1), ValueError) # closure is wrong size + test_closure(f, g.func_closure, ValueError) # no closure needed + + # Note: Jython will never have new.code() + if hasattr(new, 'code'): + def test_code(self): + # bogus test of new.code() + def f(a): pass + + c = f.func_code + argcount = c.co_argcount + kwonlyargcount = c.co_kwonlyargcount + nlocals = c.co_nlocals + stacksize = c.co_stacksize + flags = c.co_flags + codestring = c.co_code + constants = c.co_consts + names = c.co_names + varnames = c.co_varnames + filename = c.co_filename + name = c.co_name + firstlineno = c.co_firstlineno + lnotab = c.co_lnotab + freevars = c.co_freevars + cellvars = c.co_cellvars + + d = new.code(argcount, kwonlyargcount, nlocals, stacksize, flags, + codestring, constants, names, varnames, filename, + name, firstlineno, lnotab, freevars, cellvars) + + # test backwards-compatibility version with no freevars or cellvars + d = new.code(argcount, kwonlyargcount, nlocals, stacksize, + flags, codestring, constants, names, varnames, + filename, name, firstlineno, lnotab) + + # negative co_argcount used to trigger a SystemError + self.assertRaises(ValueError, new.code, + -argcount, kwonlyargcount, nlocals, stacksize, flags, + codestring, constants, names, varnames, filename, name, + firstlineno, lnotab) + + # negative co_nlocals used to trigger a SystemError + self.assertRaises(ValueError, new.code, + argcount, kwonlyargcount, -nlocals, stacksize, flags, + codestring, constants, names, varnames, filename, name, + firstlineno, lnotab) + + # non-string co_name used to trigger a Py_FatalError + self.assertRaises(TypeError, new.code, + argcount, kwonlyargcount, nlocals, stacksize, flags, + codestring, constants, (5,), varnames, filename, name, + firstlineno, lnotab) + + # new.code used to be a way to mutate a tuple... + class S(str): + pass + t = (S("ab"),) + d = new.code(argcount, kwonlyargcount, nlocals, stacksize, + flags, codestring, constants, t, varnames, + filename, name, firstlineno, lnotab) + self.assert_(type(t[0]) is S, "eek, tuple changed under us!") - if verbose: - print d +def test_main(): + test_support.run_unittest(NewTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk-noslice/Lib/test/test_normalization.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_normalization.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_normalization.py Fri Feb 23 18:29:35 2007 @@ -58,7 +58,7 @@ continue if verbose: - print line + print(line) # Perform tests verify(c2 == NFC(c1) == NFC(c2) == NFC(c3), line) Modified: python/branches/p3yk-noslice/Lib/test/test_ntpath.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_ntpath.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_ntpath.py Fri Feb 23 18:29:35 2007 @@ -9,11 +9,11 @@ fn = fn.replace("\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: - print "error!" - print "evaluated: " + str(fn) - print "should be: " + str(wantResult) - print " returned: " + str(gotResult) - print "" + print("error!") + print("evaluated: " + str(fn)) + print("should be: " + str(wantResult)) + print(" returned: " + str(gotResult)) + print("") errors = errors + 1 tester('ntpath.splitext("foo.ext")', ('foo', '.ext')) @@ -115,6 +115,28 @@ tester("ntpath.normpath('C:////a/b')", r'C:\a\b') tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b') +oldenv = os.environ.copy() +try: + os.environ.clear() + os.environ["foo"] = "bar" + os.environ["{foo"] = "baz1" + os.environ["{foo}"] = "baz2" + tester('ntpath.expandvars("foo")', "foo") + tester('ntpath.expandvars("$foo bar")', "bar bar") + tester('ntpath.expandvars("${foo}bar")', "barbar") + tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar") + tester('ntpath.expandvars("$bar bar")', "$bar bar") + tester('ntpath.expandvars("$?bar")', "$?bar") + tester('ntpath.expandvars("${foo}bar")', "barbar") + tester('ntpath.expandvars("$foo}bar")', "bar}bar") + tester('ntpath.expandvars("${foo")', "${foo") + tester('ntpath.expandvars("${{foo}}")', "baz1}") + tester('ntpath.expandvars("$foo$foo")', "barbar") + tester('ntpath.expandvars("$bar$bar")', "$bar$bar") +finally: + os.environ.clear() + os.environ.update(oldenv) + # ntpath.abspath() can only be used on a system with the "nt" module # (reasonably), so we protect this test with "import nt". This allows # the rest of the tests for the ntpath module to be run to completion @@ -130,4 +152,4 @@ if errors: raise TestFailed(str(errors) + " errors.") elif verbose: - print "No errors. Thank your lucky stars." + print("No errors. Thank your lucky stars.") Modified: python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py Fri Feb 23 18:29:35 2007 @@ -109,11 +109,44 @@ self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE)) self.assertEqual(n, 1) +class MboxTestCase(unittest.TestCase): + def setUp(self): + # create a new maildir mailbox to work with: + self._path = test_support.TESTFN + + def tearDown(self): + os.unlink(self._path) + + def test_from_regex (self): + # Testing new regex from bug #1633678 + f = open(self._path, 'w') + f.write("""From fred at example.com Mon May 31 13:24:50 2004 +0200 +Subject: message 1 + +body1 +From fred at example.com Mon May 31 13:24:50 2004 -0200 +Subject: message 2 + +body2 +From fred at example.com Mon May 31 13:24:50 2004 +Subject: message 3 + +body3 +From fred at example.com Mon May 31 13:24:50 2004 +Subject: message 4 + +body4 +""") + f.close() + box = mailbox.UnixMailbox(open(self._path, 'r')) + self.assert_(len(list(iter(box))) == 4) + + # XXX We still need more tests! def test_main(): - test_support.run_unittest(MaildirTestCase) + test_support.run_unittest(MaildirTestCase, MboxTestCase) if __name__ == "__main__": Modified: python/branches/p3yk-noslice/Lib/test/test_operations.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_operations.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_operations.py Fri Feb 23 18:29:35 2007 @@ -1,11 +1,11 @@ # Python test set -- part 3, built-in operations. -print '3. Operations' -print 'XXX Mostly not yet implemented' +print('3. Operations') +print('XXX Mostly not yet implemented') -print '3.1 Dictionary lookups fail if __cmp__() raises an exception' +print('3.1 Dictionary lookups fail if __cmp__() raises an exception') class BadDictKey: @@ -14,7 +14,7 @@ def __eq__(self, other): if isinstance(other, self.__class__): - print "raising error" + print("raising error") raise RuntimeError, "gotcha" return other @@ -32,9 +32,9 @@ try: exec(stmt) except RuntimeError: - print "%s: caught the RuntimeError outside" % (stmt,) + print("%s: caught the RuntimeError outside" % (stmt,)) else: - print "%s: No exception passed through!" % (stmt,) # old CPython behavior + print("%s: No exception passed through!" % (stmt,)) # old CPython behavior # Dict resizing bug, found by Jack Jansen in 2.2 CVS development. @@ -74,4 +74,4 @@ resizing = True d[9] = 6 -print 'resize bugs not triggered.' +print('resize bugs not triggered.') Modified: python/branches/p3yk-noslice/Lib/test/test_operator.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_operator.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_operator.py Fri Feb 23 18:29:35 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())) @@ -210,6 +210,8 @@ self.failUnless(operator.isSequenceType(xrange(10))) self.failUnless(operator.isSequenceType('yeahbuddy')) self.failIf(operator.isSequenceType(3)) + class Dict(dict): pass + self.failIf(operator.isSequenceType(Dict())) def test_lshift(self): self.failUnlessRaises(TypeError, operator.lshift) @@ -468,7 +470,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_optparse.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_optparse.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_optparse.py Fri Feb 23 18:29:35 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. @@ -1590,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( @@ -1598,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 long().*: '?0xOoops'?")) + 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"], @@ -1618,9 +1626,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-noslice/Lib/test/test_ossaudiodev.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py Fri Feb 23 18:29:35 2007 @@ -33,7 +33,7 @@ fp.close() if enc != SND_FORMAT_MULAW_8: - print "Expect .au file with 8-bit mu-law samples" + print("Expect .au file with 8-bit mu-law samples") return # Convert the data to 16-bit signed. @@ -78,8 +78,8 @@ # set parameters based on .au file headers dsp.setparameters(AFMT_S16_NE, nchannels, rate) - print ("playing test sound file (expected running time: %.2f sec)" - % expected_time) + print(("playing test sound file (expected running time: %.2f sec)" + % expected_time)) t1 = time.time() dsp.write(data) dsp.close() @@ -143,7 +143,7 @@ result = dsp.setparameters(fmt, channels, rate, True) raise AssertionError("setparameters: expected OSSAudioError") except ossaudiodev.OSSAudioError as err: - print "setparameters: got OSSAudioError as expected" + print("setparameters: got OSSAudioError as expected") def test(): (data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au')) Modified: python/branches/p3yk-noslice/Lib/test/test_parser.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_parser.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_parser.py Fri Feb 23 18:29:35 2007 @@ -85,14 +85,6 @@ self.check_expr("(x for x in range(10))") self.check_expr("foo(x for x in range(10))") - def test_print(self): - self.check_suite("print") - self.check_suite("print 1") - self.check_suite("print 1,") - self.check_suite("print >>fp") - self.check_suite("print >>fp, 1") - self.check_suite("print >>fp, 1,") - def test_simple_expression(self): # expr_stmt self.check_suite("a") @@ -359,29 +351,6 @@ (0, '')))) self.check_bad_tree(tree, "def f():\n return 1\n yield 1") - def test_print_chevron_comma(self): - # Illegal input: print >>fp, - tree = \ - (257, - (264, - (265, - (266, - (268, - (1, 'print'), - (35, '>>'), - (290, - (291, - (292, - (293, - (295, - (296, - (297, - (298, (299, (300, (301, (302, (303, (1, 'fp')))))))))))))), - (12, ','))), - (4, ''))), - (0, '')) - self.check_bad_tree(tree, "print >>fp,") - def test_a_comma_comma_c(self): # Illegal input: a,,c tree = \ Modified: python/branches/p3yk-noslice/Lib/test/test_peepholer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_peepholer.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_peepholer.py Fri Feb 23 18:29:35 2007 @@ -211,7 +211,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_pep247.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pep247.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pep247.py Fri Feb 23 18:29:35 2007 @@ -41,7 +41,7 @@ hd2 += "%02x" % ord(byte) assert hd2 == hexdigest, "hexdigest doesn't appear correct" - print 'Module', module.__name__, 'seems to comply with PEP 247' + print('Module', module.__name__, 'seems to comply with PEP 247') if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/test/test_pep277.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pep277.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pep277.py Fri Feb 23 18:29:35 2007 @@ -83,7 +83,7 @@ f2 = os.listdir(unicode(test_support.TESTFN, sys.getfilesystemencoding())) f2.sort() - print f2 + print(f2) def test_rename(self): for name in self.files: @@ -99,7 +99,7 @@ f = open(filename, 'w') f.write((filename + '\n').encode("utf-8")) f.close() - print repr(filename) + print(repr(filename)) os.access(filename,os.R_OK) os.remove(filename) os.chdir(oldwd) Modified: python/branches/p3yk-noslice/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pep352.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pep352.py Fri Feb 23 18:29:35 2007 @@ -2,7 +2,7 @@ import __builtin__ import exceptions import warnings -from test.test_support import run_unittest +from test.test_support import run_unittest, guard_warnings_filter import os from platform import system as platform_system @@ -113,13 +113,11 @@ """Test usage of exceptions""" - def setUp(self): - self._filters = warnings.filters[:] - - def tearDown(self): - warnings.filters = self._filters[:] - def test_raise_new_style_non_exception(self): + # You cannot raise a new-style class that does not inherit from + # BaseException; the ability was not possible until BaseException's + # introduction so no need to support new-style objects that do not + # inherit from it. class NewStyleClass(object): pass try: @@ -127,13 +125,51 @@ except TypeError: pass except: - self.fail("unable to raise new-style class") + self.fail("able to raise new-style class") try: raise NewStyleClass() except TypeError: pass except: - self.fail("unable to raise new-style class instance") + self.fail("able to raise new-style class instance") + + def test_raise_string(self): + # Raising a string raises TypeError. + try: + raise "spam" + except TypeError: + pass + except: + self.fail("was able to raise a string exception") + + def test_catch_string(self): + # Catching a string should trigger a DeprecationWarning. + with guard_warnings_filter(): + warnings.resetwarnings() + warnings.filterwarnings("error") + str_exc = "spam" + try: + try: + raise StandardError + except str_exc: + pass + except DeprecationWarning: + pass + except StandardError: + self.fail("catching a string exception did not raise " + "DeprecationWarning") + # Make sure that even if the string exception is listed in a tuple + # that a warning is raised. + try: + try: + raise StandardError + except (AssertionError, str_exc): + pass + except DeprecationWarning: + pass + except StandardError: + self.fail("catching a string exception specified in a tuple did " + "not raise DeprecationWarning") def test_main(): run_unittest(ExceptionClassTests, UsageTests) Modified: python/branches/p3yk-noslice/Lib/test/test_pkg.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pkg.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pkg.py Fri Feb 23 18:29:35 2007 @@ -18,7 +18,7 @@ if contents is None: mkdir(fullname) else: - if verbose: print "write", fullname + if verbose: print("write", fullname) f = open(fullname, "w") f.write(contents) if contents and contents[-1] != '\n': @@ -26,7 +26,7 @@ f.close() def mkdir(x): - if verbose: print "mkdir", x + if verbose: print("mkdir", x) os.mkdir(x) def cleanout(root): @@ -40,7 +40,7 @@ rmdir(root) def rmdir(x): - if verbose: print "rmdir", x + if verbose: print("rmdir", x) os.rmdir(x) def fixdir(lst): @@ -61,7 +61,7 @@ os.close(fd) try: sys.path.insert(0, root) - if verbose: print "sys.path =", sys.path + if verbose: print("sys.path =", sys.path) try: execfile(fname, globals(), {}) except: @@ -81,122 +81,122 @@ ("t2", [ ("t2", None), - ("t2 __init__"+os.extsep+"py", "'doc for t2'; print __name__, 'loading'"), + ("t2 __init__"+os.extsep+"py", "'doc for t2'; print(__name__, 'loading')"), ("t2 sub", None), ("t2 sub __init__"+os.extsep+"py", ""), ("t2 sub subsub", None), - ("t2 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t2 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ], """ import t2 -print t2.__doc__ +print(t2.__doc__) import t2.sub import t2.sub.subsub -print t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__ +print(t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__) import t2 from t2 import * -print dir() +print(dir()) from t2 import sub from t2.sub import subsub from t2.sub.subsub import spam -print sub.__name__, subsub.__name__ -print sub.subsub.__name__ -print dir() +print(sub.__name__, subsub.__name__) +print(sub.subsub.__name__) +print(dir()) import t2.sub import t2.sub.subsub -print t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__ +print(t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__) from t2 import * -print dir() +print(dir()) """), ("t3", [ ("t3", None), - ("t3 __init__"+os.extsep+"py", "print __name__, 'loading'"), + ("t3 __init__"+os.extsep+"py", "print(__name__, 'loading')"), ("t3 sub", None), ("t3 sub __init__"+os.extsep+"py", ""), ("t3 sub subsub", None), - ("t3 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t3 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ], """ import t3.sub.subsub -print t3.__name__, t3.sub.__name__, t3.sub.subsub.__name__ +print(t3.__name__, t3.sub.__name__, t3.sub.subsub.__name__) reload(t3) reload(t3.sub) reload(t3.sub.subsub) """), ("t4", [ - ("t4"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (t4"+os.extsep+"py)'"), + ("t4"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (t4"+os.extsep+"py)')"), ("t4", None), - ("t4 __init__"+os.extsep+"py", "print __name__, 'loading'"), - ("t4 sub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)'"), + ("t4 __init__"+os.extsep+"py", "print(__name__, 'loading')"), + ("t4 sub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)')"), ("t4 sub", None), ("t4 sub __init__"+os.extsep+"py", ""), - ("t4 sub subsub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)'"), + ("t4 sub subsub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)')"), ("t4 sub subsub", None), - ("t4 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t4 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ], """ from t4.sub.subsub import * -print "t4.sub.subsub.spam =", spam +print("t4.sub.subsub.spam =", spam) """), ("t5", [ ("t5", None), ("t5 __init__"+os.extsep+"py", "import t5.foo"), - ("t5 string"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t5 string"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ("t5 foo"+os.extsep+"py", - "print __name__, 'loading'; from . import string; print string.spam"), + "print(__name__, 'loading'); from . import string; print(string.spam)"), ], """ import t5 from t5 import * -print dir() +print(dir()) import t5 -print fixdir(dir(t5)) -print fixdir(dir(t5.foo)) -print fixdir(dir(t5.string)) +print(fixdir(dir(t5))) +print(fixdir(dir(t5.foo))) +print(fixdir(dir(t5.string))) """), ("t6", [ ("t6", None), ("t6 __init__"+os.extsep+"py", "__all__ = ['spam', 'ham', 'eggs']"), - ("t6 spam"+os.extsep+"py", "print __name__, 'loading'"), - ("t6 ham"+os.extsep+"py", "print __name__, 'loading'"), - ("t6 eggs"+os.extsep+"py", "print __name__, 'loading'"), + ("t6 spam"+os.extsep+"py", "print(__name__, 'loading')"), + ("t6 ham"+os.extsep+"py", "print(__name__, 'loading')"), + ("t6 eggs"+os.extsep+"py", "print(__name__, 'loading')"), ], """ import t6 -print fixdir(dir(t6)) +print(fixdir(dir(t6))) from t6 import * -print fixdir(dir(t6)) -print dir() +print(fixdir(dir(t6))) +print(dir()) """), ("t7", [ - ("t7"+os.extsep+"py", "print 'Importing t7"+os.extsep+"py'"), + ("t7"+os.extsep+"py", "print('Importing t7"+os.extsep+"py')"), ("t7", None), - ("t7 __init__"+os.extsep+"py", "print __name__, 'loading'"), - ("t7 sub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)'"), + ("t7 __init__"+os.extsep+"py", "print(__name__, 'loading')"), + ("t7 sub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)')"), ("t7 sub", None), ("t7 sub __init__"+os.extsep+"py", ""), - ("t7 sub subsub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)'"), + ("t7 sub subsub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)')"), ("t7 sub subsub", None), - ("t7 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t7 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ], """ t7, sub, subsub = None, None, None import t7 as tas -print fixdir(dir(tas)) +print(fixdir(dir(tas))) verify(not t7) from t7 import sub as subpar -print fixdir(dir(subpar)) +print(fixdir(dir(subpar))) verify(not t7 and not sub) from t7.sub import subsub as subsubsub -print fixdir(dir(subsubsub)) +print(fixdir(dir(subsubsub))) verify(not t7 and not sub and not subsub) from t7.sub.subsub import spam as ham -print "t7.sub.subsub.spam =", ham +print("t7.sub.subsub.spam =", ham) verify(not t7 and not sub and not subsub) """), @@ -242,9 +242,9 @@ for name, hier, code in tests: if args and name not in args: - print "skipping test", name + print("skipping test", name) continue - print "running test", name + print("running test", name) runtest(hier, code) # Test Modified: python/branches/p3yk-noslice/Lib/test/test_poll.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_poll.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_poll.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_popen.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_popen.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_popen.py Fri Feb 23 18:29:35 2007 @@ -4,10 +4,9 @@ Particularly useful for platforms that fake popen. """ -import os -import sys -from test.test_support import TestSkipped, reap_children -from os import popen +import unittest +from test import test_support +import os, sys # Test that command-lines get down as we expect. # To do this we execute: @@ -17,24 +16,32 @@ python = sys.executable if ' ' in python: python = '"' + python + '"' # quote embedded space for cmdline -def _do_test_commandline(cmdline, expected): - cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline) - data = popen(cmd).read() - got = eval(data)[1:] # strip off argv[0] - if got != expected: - print "Error in popen commandline handling." - print " executed '%s', expected '%r', but got '%r'" \ - % (cmdline, expected, got) - -def _test_commandline(): - _do_test_commandline("foo bar", ["foo", "bar"]) - _do_test_commandline('foo "spam and eggs" "silly walk"', ["foo", "spam and eggs", "silly walk"]) - _do_test_commandline('foo "a \\"quoted\\" arg" bar', ["foo", 'a "quoted" arg', "bar"]) - print "popen seemed to process the command-line correctly" - -def main(): - print "Test popen:" - _test_commandline() - reap_children() -main() +class PopenTest(unittest.TestCase): + def _do_test_commandline(self, cmdline, expected): + cmd = '%s -c "import sys; print(sys.argv)" %s' % (python, cmdline) + data = os.popen(cmd).read() + got = eval(data)[1:] # strip off argv[0] + self.assertEqual(got, expected) + + def test_popen(self): + self.assertRaises(TypeError, os.popen) + self._do_test_commandline( + "foo bar", + ["foo", "bar"] + ) + self._do_test_commandline( + 'foo "spam and eggs" "silly walk"', + ["foo", "spam and eggs", "silly walk"] + ) + self._do_test_commandline( + 'foo "a \\"quoted\\" arg" bar', + ["foo", 'a "quoted" arg', "bar"] + ) + test_support.reap_children() + +def test_main(): + test_support.run_unittest(PopenTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk-noslice/Lib/test/test_popen2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_popen2.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_popen2.py Fri Feb 23 18:29:35 2007 @@ -13,7 +13,7 @@ # subprocess. def main(): - print "Test popen2 module:" + print("Test popen2 module:") if (sys.platform[:4] == 'beos' or sys.platform[:6] == 'atheos') \ and __name__ != '__main__': # Locks get messed up or something. Generally we're supposed @@ -33,7 +33,7 @@ def _test(): # same test as popen2._test(), but using the os.popen*() API - print "Testing os module:" + print("Testing os module:") import popen2 # When the test runs, there shouldn't be any open pipes popen2._cleanup() @@ -46,14 +46,14 @@ # sometimes adding an extra newline at the start or the # end. So we strip whitespace off both ends for comparison. expected = teststr.strip() - print "testing popen2..." + print("testing popen2...") w, r = os.popen2(cmd) w.write(teststr) w.close() got = r.read() if got.strip() != expected: raise ValueError("wrote %r read %r" % (teststr, got)) - print "testing popen3..." + print("testing popen3...") try: w, r, e = os.popen3([cmd]) except: @@ -71,7 +71,7 @@ popen2._cleanup() if popen2._active: raise ValueError("_active not empty") - print "All OK" + print("All OK") main() _test() Modified: python/branches/p3yk-noslice/Lib/test/test_posix.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_posix.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_posix.py Fri Feb 23 18:29:35 2007 @@ -192,6 +192,18 @@ posix.utime(test_support.TESTFN, (int(now), int(now))) posix.utime(test_support.TESTFN, (now, now)) + def test_chflags(self): + if hasattr(posix, 'chflags'): + st = os.stat(test_support.TESTFN) + if hasattr(st, 'st_flags'): + posix.chflags(test_support.TESTFN, st.st_flags) + + def test_lchflags(self): + if hasattr(posix, 'lchflags'): + st = os.stat(test_support.TESTFN) + if hasattr(st, 'st_flags'): + posix.lchflags(test_support.TESTFN, st.st_flags) + def test_main(): test_support.run_unittest(PosixTester) Modified: python/branches/p3yk-noslice/Lib/test/test_posixpath.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_posixpath.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_posixpath.py Fri Feb 23 18:29:35 2007 @@ -374,6 +374,8 @@ self.assertEqual(posixpath.expandvars("$foo}bar"), "bar}bar") self.assertEqual(posixpath.expandvars("${foo"), "${foo") self.assertEqual(posixpath.expandvars("${{foo}}"), "baz1}") + self.assertEqual(posixpath.expandvars("$foo$foo"), "barbar") + self.assertEqual(posixpath.expandvars("$bar$bar"), "$bar$bar") finally: os.environ.clear() os.environ.update(oldenv) Modified: python/branches/p3yk-noslice/Lib/test/test_pow.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pow.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pow.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_pprint.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pprint.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pprint.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_pty.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pty.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pty.py Fri Feb 23 18:29:35 2007 @@ -6,7 +6,7 @@ if verbose: def debug(msg): - print msg + print(msg) else: def debug(msg): pass @@ -120,7 +120,7 @@ ##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)) @@ -140,8 +140,8 @@ ## pass ##else: ## raise TestFailed("Read from master_fd did not raise exception") - - + + os.close(master_fd) # pty.fork() passed. Modified: python/branches/p3yk-noslice/Lib/test/test_pwd.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pwd.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pwd.py Fri Feb 23 18:29:35 2007 @@ -55,7 +55,7 @@ bynames[n] = u byuids[u] = n - allnames = bynames.keys() + allnames = list(bynames.keys()) namei = 0 fakename = allnames[namei] while fakename in bynames: Modified: python/branches/p3yk-noslice/Lib/test/test_pyclbr.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pyclbr.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pyclbr.py Fri Feb 23 18:29:35 2007 @@ -28,13 +28,13 @@ ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' missing = (set(l1) ^ set(l2)) - set(ignore) if missing: - print >>sys.stderr, "l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore) + print("l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore), file=sys.stderr) self.fail("%r missing" % missing.pop()) def assertHasattr(self, obj, attr, ignore): ''' succeed iff hasattr(obj,attr) or attr in ignore. ''' if attr in ignore: return - if not hasattr(obj, attr): print "???", attr + if not hasattr(obj, attr): print("???", attr) self.failUnless(hasattr(obj, attr), 'expected hasattr(%r, %r)' % (obj, attr)) @@ -43,8 +43,8 @@ ''' succeed iff key in obj or key in ignore. ''' if key in ignore: return if key not in obj: - print >>sys.stderr, "***",key - self.failUnless(key) in obj + print("***",key, file=sys.stderr) + self.failUnless(key in obj) def assertEqualsOrIgnored(self, a, b, ignore): ''' succeed iff a == b or a in ignore or b in ignore ''' @@ -110,7 +110,7 @@ try: self.assertListEq(real_bases, pyclbr_bases, ignore) except: - print >>sys.stderr, "class=%s" % py_item + print("class=%s" % py_item, file=sys.stderr) raise actualMethods = [] @@ -132,7 +132,7 @@ ignore) # can't check file or lineno except: - print >>sys.stderr, "class=%s" % py_item + print("class=%s" % py_item, file=sys.stderr) raise # Now check for missing stuff. Modified: python/branches/p3yk-noslice/Lib/test/test_pyexpat.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_pyexpat.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_pyexpat.py Fri Feb 23 18:29:35 2007 @@ -10,50 +10,50 @@ class Outputter: def StartElementHandler(self, name, attrs): - print 'Start element:\n\t', repr(name), sortdict(attrs) + print('Start element:\n\t' + repr(name), sortdict(attrs)) def EndElementHandler(self, name): - print 'End element:\n\t', repr(name) + print('End element:\n\t' + repr(name)) def CharacterDataHandler(self, data): data = data.strip() if data: - print 'Character data:' - print '\t', repr(data) + print('Character data:') + print('\t' + repr(data)) def ProcessingInstructionHandler(self, target, data): - print 'PI:\n\t', repr(target), repr(data) + print('PI:\n\t' + repr(target), repr(data)) def StartNamespaceDeclHandler(self, prefix, uri): - print 'NS decl:\n\t', repr(prefix), repr(uri) + print('NS decl:\n\t' + repr(prefix), repr(uri)) def EndNamespaceDeclHandler(self, prefix): - print 'End of NS decl:\n\t', repr(prefix) + print('End of NS decl:\n\t' + repr(prefix)) def StartCdataSectionHandler(self): - print 'Start of CDATA section' + print('Start of CDATA section') def EndCdataSectionHandler(self): - print 'End of CDATA section' + print('End of CDATA section') def CommentHandler(self, text): - print 'Comment:\n\t', repr(text) + print('Comment:\n\t' + repr(text)) def NotationDeclHandler(self, *args): name, base, sysid, pubid = args - print 'Notation declared:', args + print('Notation declared:', args) def UnparsedEntityDeclHandler(self, *args): entityName, base, systemId, publicId, notationName = args - print 'Unparsed entity decl:\n\t', args + print('Unparsed entity decl:\n\t' + str(args)) def NotStandaloneHandler(self, userData): - print 'Not standalone' + print('Not standalone') return 1 def ExternalEntityRefHandler(self, *args): context, base, sysId, pubId = args - print 'External entity ref:', args[1:] + print('External entity ref:', args[1:]) return 1 def DefaultHandler(self, userData): @@ -65,9 +65,9 @@ def confirm(ok): if ok: - print "OK." + print("OK.") else: - print "Not OK." + print("Not OK.") out = Outputter() parser = expat.ParserCreate(namespace_separator='!') @@ -131,10 +131,10 @@ try: parser.Parse(data, 1) except expat.error: - print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode) - print '** Line', parser.ErrorLineNumber - print '** Column', parser.ErrorColumnNumber - print '** Byte', parser.ErrorByteIndex + print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)) + print('** Line', parser.ErrorLineNumber) + print('** Column', parser.ErrorColumnNumber) + print('** Byte', parser.ErrorByteIndex) # Try the parse again, this time producing Unicode output parser = expat.ParserCreate(namespace_separator='!') @@ -145,10 +145,10 @@ try: parser.Parse(data, 1) except expat.error: - print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode) - print '** Line', parser.ErrorLineNumber - print '** Column', parser.ErrorColumnNumber - print '** Byte', parser.ErrorByteIndex + print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)) + print('** Line', parser.ErrorLineNumber) + print('** Column', parser.ErrorColumnNumber) + print('** Byte', parser.ErrorByteIndex) # Try parsing a file parser = expat.ParserCreate(namespace_separator='!') @@ -161,35 +161,35 @@ try: parser.ParseFile(file) except expat.error: - print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode) - print '** Line', parser.ErrorLineNumber - print '** Column', parser.ErrorColumnNumber - print '** Byte', parser.ErrorByteIndex + print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)) + print('** Line', parser.ErrorLineNumber) + print('** Column', parser.ErrorColumnNumber) + print('** Byte', parser.ErrorByteIndex) # Tests that make sure we get errors when the namespace_separator value # is illegal, and that we don't for good values: -print -print "Testing constructor for proper handling of namespace_separator values:" +print() +print("Testing constructor for proper handling of namespace_separator values:") expat.ParserCreate() expat.ParserCreate(namespace_separator=None) expat.ParserCreate(namespace_separator=' ') -print "Legal values tested o.k." +print("Legal values tested o.k.") try: expat.ParserCreate(namespace_separator=42) except TypeError as e: - print "Caught expected TypeError:" - print e + print("Caught expected TypeError:") + print(e) else: - print "Failed to catch expected TypeError." + print("Failed to catch expected TypeError.") try: expat.ParserCreate(namespace_separator='too long') except ValueError as e: - print "Caught expected ValueError:" - print e + print("Caught expected ValueError:") + print(e) else: - print "Failed to catch expected ValueError." + print("Failed to catch expected ValueError.") # ParserCreate() needs to accept a namespace_separator of zero length # to satisfy the requirements of RDF applications that are required @@ -211,12 +211,12 @@ p.Parse(" ", 1) tag = L[0] if len(L) != 6: - print "L should only contain 6 entries; found", len(L) + print("L should only contain 6 entries; found", len(L)) for entry in L: if tag is not entry: - print "expected L to contain many references to the same string", - print "(it didn't)" - print "L =", repr(L) + print("expected L to contain many references to the same string", end=' ') + print("(it didn't)") + print("L =", repr(L)) break # Tests of the buffer_text attribute. @@ -323,9 +323,9 @@ parser.Parse("", 1) except RuntimeError as e: if e.args[0] != "a": - print "Expected RuntimeError for element 'a'; found %r" % e.args[0] + print("Expected RuntimeError for element 'a'; found %r" % e.args[0]) else: - print "Expected RuntimeError for 'a'" + print("Expected RuntimeError for 'a'") # Test Current* members: class PositionTest: Modified: python/branches/p3yk-noslice/Lib/test/test_queue.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_queue.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_queue.py Fri Feb 23 18:29:35 2007 @@ -271,11 +271,11 @@ SimpleQueueTest(q) SimpleQueueTest(q) if verbose: - print "Simple Queue tests seemed to work" + print("Simple Queue tests seemed to work") q = FailingQueue(QUEUE_SIZE) FailingQueueTest(q) FailingQueueTest(q) if verbose: - print "Failing Queue tests seemed to work" + print("Failing Queue tests seemed to work") test() Modified: python/branches/p3yk-noslice/Lib/test/test_random.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_random.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_random.py Fri Feb 23 18:29:35 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) @@ -517,6 +517,14 @@ # tests validity but not completeness of the __all__ list self.failUnless(set(random.__all__) <= set(dir(random))) + def test_random_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError + class Subclass(random.Random): + def __init__(self, newarg=None): + random.Random.__init__(self) + Subclass(newarg=1) + + def test_main(verbose=None): testclasses = [WichmannHill_TestBasicOps, MersenneTwister_TestBasicOps, @@ -539,7 +547,7 @@ for i in xrange(len(counts)): test_support.run_unittest(*testclasses) counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_re.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_re.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_re.py Fri Feb 23 18:29:35 2007 @@ -603,7 +603,7 @@ def run_re_tests(): from test.re_tests import benchmarks, tests, SUCCEED, FAIL, SYNTAX_ERROR if verbose: - print 'Running re_tests test suite' + print('Running re_tests test suite') else: # To save time, only run the first and last 10 tests #tests = tests[:10] + tests[-10:] @@ -624,23 +624,23 @@ except re.error: if outcome == SYNTAX_ERROR: pass # Expected a syntax error else: - print '=== Syntax error:', t + print('=== Syntax error:', t) except KeyboardInterrupt: raise KeyboardInterrupt except: - print '*** Unexpected error ***', t + print('*** Unexpected error ***', t) if verbose: traceback.print_exc(file=sys.stdout) else: try: result = obj.search(s) except re.error as msg: - print '=== Unexpected exception', t, repr(msg) + print('=== Unexpected exception', t, repr(msg)) if outcome == SYNTAX_ERROR: # This should have been a syntax error; forget it. pass elif outcome == FAIL: if result is None: pass # No match, as expected - else: print '=== Succeeded incorrectly', t + else: print('=== Succeeded incorrectly', t) elif outcome == SUCCEED: if result is not None: # Matched, as expected, so now we compute the @@ -668,17 +668,17 @@ vardict[i] = gi repl = eval(repl, vardict) if repl != expected: - print '=== grouping error', t, - print repr(repl) + ' should be ' + repr(expected) + print('=== grouping error', t, end=' ') + print(repr(repl) + ' should be ' + repr(expected)) else: - print '=== Failed incorrectly', t + print('=== Failed incorrectly', t) # Try the match on a unicode string, and check that it # still succeeds. try: result = obj.search(unicode(s, "latin-1")) if result is None: - print '=== Fails on unicode match', t + print('=== Fails on unicode match', t) except NameError: continue # 1.5.2 except TypeError: @@ -689,7 +689,7 @@ obj=re.compile(unicode(pattern, "latin-1")) result = obj.search(s) if result is None: - print '=== Fails on unicode pattern match', t + print('=== Fails on unicode pattern match', t) # Try the match with the search area limited to the extent # of the match and see if it still succeeds. \B will @@ -701,28 +701,28 @@ obj = re.compile(pattern) result = obj.search(s, result.start(0), result.end(0) + 1) if result is None: - print '=== Failed on range-limited match', t + print('=== Failed on range-limited match', t) # Try the match with IGNORECASE enabled, and check that it # still succeeds. obj = re.compile(pattern, re.IGNORECASE) result = obj.search(s) if result is None: - print '=== Fails on case-insensitive match', t + print('=== Fails on case-insensitive match', t) # Try the match with LOCALE enabled, and check that it # still succeeds. obj = re.compile(pattern, re.LOCALE) result = obj.search(s) if result is None: - print '=== Fails on locale-sensitive match', t + print('=== Fails on locale-sensitive match', t) # Try the match with UNICODE locale enabled, and check # that it still succeeds. obj = re.compile(pattern, re.UNICODE) result = obj.search(s) if result is None: - print '=== Fails on unicode-sensitive match', t + print('=== Fails on unicode-sensitive match', t) def test_main(): run_unittest(ReTests) Modified: python/branches/p3yk-noslice/Lib/test/test_repr.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_repr.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_repr.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_resource.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_resource.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_resource.py Fri Feb 23 18:29:35 2007 @@ -1,56 +1,96 @@ -import os -import resource +import unittest +from test import test_support -from test.test_support import TESTFN -# This test is checking a few specific problem spots. RLIMIT_FSIZE -# should be RLIM_INFINITY, which will be a really big number on a -# platform with large file support. On these platforms, we need to -# test that the get/setrlimit functions properly convert the number to -# a C long long and that the conversion doesn't raise an error. - -try: - cur, max = resource.getrlimit(resource.RLIMIT_FSIZE) -except AttributeError: - pass -else: - print resource.RLIM_INFINITY == max - resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) - -# Now check to see what happens when the RLIMIT_FSIZE is small. Some -# versions of Python were terminated by an uncaught SIGXFSZ, but -# pythonrun.c has been fixed to ignore that exception. If so, the -# write() should return EFBIG when the limit is exceeded. - -# At least one platform has an unlimited RLIMIT_FSIZE and attempts to -# change it raise ValueError instead. - -try: - try: - resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max)) - limit_set = 1 - except ValueError: - limit_set = 0 - f = open(TESTFN, "wb") - f.write("X" * 1024) - try: - f.write("Y") - f.flush() - except IOError: - if not limit_set: - raise - f.close() - os.unlink(TESTFN) -finally: - resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) - -# And be sure that setrlimit is checking for really large values -too_big = 10L**50 -try: - resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max)) -except (OverflowError, ValueError): - pass -try: - resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big)) -except (OverflowError, ValueError): - pass +import os, resource + +# This test is checking a few specific problem spots with the resource module. + +class ResourceTest(unittest.TestCase): + + def test_args(self): + self.assertRaises(TypeError, resource.getrlimit) + self.assertRaises(TypeError, resource.getrlimit, 42, 42) + self.assertRaises(TypeError, resource.setrlimit) + self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42) + + def test_fsize_ismax(self): + + try: + (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) + except AttributeError: + pass + else: + # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really big + # number on a platform with large file support. On these platforms, + # we need to test that the get/setrlimit functions properly convert + # the number to a C long long and that the conversion doesn't raise + # an error. + self.assertEqual(resource.RLIM_INFINITY, max) + resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) + + def test_fsize_enforced(self): + try: + (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) + except AttributeError: + pass + else: + # Check to see what happens when the RLIMIT_FSIZE is small. Some + # versions of Python were terminated by an uncaught SIGXFSZ, but + # pythonrun.c has been fixed to ignore that exception. If so, the + # write() should return EFBIG when the limit is exceeded. + + # At least one platform has an unlimited RLIMIT_FSIZE and attempts + # to change it raise ValueError instead. + try: + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max)) + limit_set = True + except ValueError: + limit_set = False + f = open(test_support.TESTFN, "wb") + f.write("X" * 1024) + try: + f.write("Y") + f.flush() + except IOError: + if not limit_set: + raise + f.close() + os.unlink(test_support.TESTFN) + finally: + resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) + + def test_fsize_toobig(self): + # Be sure that setrlimit is checking for really large values + too_big = 10**50 + try: + (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) + except AttributeError: + pass + else: + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max)) + except (OverflowError, ValueError): + pass + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big)) + except (OverflowError, ValueError): + pass + + def test_getrusage(self): + self.assertRaises(TypeError, resource.getrusage) + self.assertRaises(TypeError, resource.getrusage, 42, 42) + usageself = resource.getrusage(resource.RUSAGE_SELF) + usagechildren = resource.getrusage(resource.RUSAGE_CHILDREN) + # May not be available on all systems. + try: + usageboth = resource.getrusage(resource.RUSAGE_BOTH) + except (ValueError, AttributeError): + pass + +def test_main(verbose=None): + test_support.run_unittest(ResourceTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk-noslice/Lib/test/test_rfc822.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_rfc822.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_rfc822.py Fri Feb 23 18:29:35 2007 @@ -42,7 +42,7 @@ try: mn, ma = results[i][0], results[i][1] except IndexError: - print 'extra parsed address:', repr(n), repr(a) + print('extra parsed address:', repr(n), repr(a)) continue i = i + 1 self.assertEqual(mn, n, @@ -52,7 +52,7 @@ if mn == n and ma == a: pass else: - print 'not found:', repr(n), repr(a) + print('not found:', repr(n), repr(a)) out = m.getdate('date') if out: Modified: python/branches/p3yk-noslice/Lib/test/test_rgbimg.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_rgbimg.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_rgbimg.py Fri Feb 23 18:29:35 2007 @@ -14,7 +14,7 @@ class error(Exception): pass -print 'RGBimg test suite:' +print('RGBimg test suite:') def testimg(rgb_file, raw_file): rgb_file = findfile(rgb_file) @@ -40,11 +40,11 @@ source = findfile(source) target = findfile(target) if verbose: - print "uudecoding", source, "->", target, "..." + print("uudecoding", source, "->", target, "...") uu.decode(source, target) if verbose: - print "testing..." + print("testing...") ttob = rgbimg.ttob(0) if ttob != 0: Modified: python/branches/p3yk-noslice/Lib/test/test_richcmp.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_richcmp.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_richcmp.py Fri Feb 23 18:29:35 2007 @@ -131,7 +131,7 @@ self.checkequal("gt", a, b, [False, False, False, True, True ]) self.checkequal("ge", a, b, [False, False, True, True, True ]) - for ops in opmap.itervalues(): + for ops in opmap.values(): for op in ops: # calls __bool__, which should fail self.assertRaises(TypeError, bool, op(a, b)) @@ -150,7 +150,7 @@ continue # the combination int, int is useless ta = typea(a) tb = typeb(b) - for ops in opmap.itervalues(): + for ops in opmap.values(): for op in ops: realoutcome = op(a, b) testoutcome = op(ta, tb) @@ -265,7 +265,7 @@ imag1a = {} for i in range(50): imag1a[random.randrange(100)*1j] = random.randrange(100)*1j - items = imag1a.items() + items = list(imag1a.items()) random.shuffle(items) imag1b = {} for k, v in items: Modified: python/branches/p3yk-noslice/Lib/test/test_runpy.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_runpy.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_runpy.py Fri Feb 23 18:29:35 2007 @@ -92,22 +92,22 @@ init_fname = "__init__"+os.extsep+"py" test_fname = "runpy_test"+os.extsep+"py" pkg_dir = sub_dir = tempfile.mkdtemp() - if verbose: print " Package tree in:", sub_dir + if verbose: print(" Package tree in:", sub_dir) sys.path.insert(0, pkg_dir) - if verbose: print " Updated sys.path:", sys.path[0] + if verbose: print(" Updated sys.path:", sys.path[0]) for i in range(depth): sub_dir = os.path.join(sub_dir, pkg_name) os.mkdir(sub_dir) - if verbose: print " Next level in:", sub_dir + if verbose: print(" Next level in:", sub_dir) pkg_fname = os.path.join(sub_dir, init_fname) pkg_file = open(pkg_fname, "w") pkg_file.close() - if verbose: print " Created:", pkg_fname + if verbose: print(" Created:", pkg_fname) mod_fname = os.path.join(sub_dir, test_fname) mod_file = open(mod_fname, "w") mod_file.write(source) mod_file.close() - if verbose: print " Created:", mod_fname + if verbose: print(" Created:", mod_fname) mod_name = (pkg_name+".")*depth + "runpy_test" return pkg_dir, mod_fname, mod_name @@ -118,49 +118,49 @@ try: del sys.modules[entry] except KeyError as ex: - if verbose: print ex # Persist with cleaning up - if verbose: print " Removed sys.modules entries" + if verbose: print(ex) # Persist with cleaning up + if verbose: print(" Removed sys.modules entries") del sys.path[0] - if verbose: print " Removed sys.path entry" + if verbose: print(" Removed sys.path entry") for root, dirs, files in os.walk(top, topdown=False): for name in files: try: os.remove(os.path.join(root, name)) except OSError as ex: - if verbose: print ex # Persist with cleaning up + if verbose: print(ex) # Persist with cleaning up for name in dirs: fullname = os.path.join(root, name) try: os.rmdir(fullname) except OSError as ex: - if verbose: print ex # Persist with cleaning up + if verbose: print(ex) # Persist with cleaning up try: os.rmdir(top) - if verbose: print " Removed package tree" + if verbose: print(" Removed package tree") except OSError as ex: - if verbose: print ex # Persist with cleaning up + if verbose: print(ex) # Persist with cleaning up def _check_module(self, depth): pkg_dir, mod_fname, mod_name = ( self._make_pkg("x=1\n", depth)) try: - if verbose: print "Running from source:", mod_name + if verbose: print("Running from source:", mod_name) d1 = run_module(mod_name) # Read from source self.failUnless(d1["x"] == 1) del d1 # Ensure __loader__ entry doesn't keep file open __import__(mod_name) os.remove(mod_fname) - if verbose: print "Running from compiled:", mod_name + if verbose: print("Running from compiled:", mod_name) d2 = run_module(mod_name) # Read from bytecode self.failUnless(d2["x"] == 1) del d2 # Ensure __loader__ entry doesn't keep file open finally: self._del_pkg(pkg_dir, depth, mod_name) - if verbose: print "Module executed successfully" + if verbose: print("Module executed successfully") def test_run_module(self): for depth in range(4): - if verbose: print "Testing package depth:", depth + if verbose: print("Testing package depth:", depth) self._check_module(depth) Modified: python/branches/p3yk-noslice/Lib/test/test_sax.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_sax.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_sax.py Fri Feb 23 18:29:35 2007 @@ -27,7 +27,7 @@ tests = tests + 1 if outcome: if verbose: - print "Passed", name + print("Passed", name) else: failures.append(name) @@ -216,7 +216,44 @@ ('' % ns_uri) -# ===== XMLFilterBase +def test_1463026_1(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS((None, 'a'), 'a') + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_2(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping(None, 'qux') + gen.startElementNS(('qux', 'a'), 'a', {}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping(None) + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_3(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping('my', 'qux') + gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping('my') + gen.endDocument() + + return result.getvalue() == start+'' + +# ===== Xmlfilterbase def test_filter_basic(): result = StringIO() @@ -358,11 +395,11 @@ (attrs.getQNames() == [] or attrs.getQNames() == ["ns:attr"]) and \ len(attrs) == 1 and \ (ns_uri, "attr") in attrs and \ - attrs.keys() == [(ns_uri, "attr")] and \ + list(attrs.keys()) == [(ns_uri, "attr")] and \ attrs.get((ns_uri, "attr")) == "val" and \ attrs.get((ns_uri, "attr"), 25) == "val" and \ - attrs.items() == [((ns_uri, "attr"), "val")] and \ - attrs.values() == ["val"] and \ + list(attrs.items()) == [((ns_uri, "attr"), "val")] and \ + list(attrs.values()) == ["val"] and \ attrs.getValue((ns_uri, "attr")) == "val" and \ attrs[(ns_uri, "attr")] == "val" @@ -698,7 +735,7 @@ # Bug report: http://www.python.org/sf/1511497 import sys old_modules = sys.modules.copy() - for modname in sys.modules.keys(): + for modname in list(sys.modules.keys()): if modname.startswith("xml."): del sys.modules[modname] try: @@ -734,8 +771,7 @@ outf.write(result.getvalue()) outf.close() -items = locals().items() -items.sort() +items = sorted(locals().items()) for (name, value) in items: if name[ : 5] == "test_": confirm(value(), name) @@ -745,7 +781,7 @@ del items if verbose: - print "%d tests, %d failures" % (tests, len(failures)) + print("%d tests, %d failures" % (tests, len(failures))) if failures: raise TestFailed("%d of %d tests failed: %s" % (len(failures), tests, ", ".join(failures))) Modified: python/branches/p3yk-noslice/Lib/test/test_scope.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_scope.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_scope.py Fri Feb 23 18:29:35 2007 @@ -269,7 +269,7 @@ def testUnboundLocal(self): def errorInOuter(): - print y + print(y) def inner(): return y y = 1 @@ -530,18 +530,18 @@ def testListCompLocalVars(self): try: - print bad + print(bad) except NameError: pass else: - print "bad should not be defined" + print("bad should not be defined") def x(): [bad for s in 'a b' for bad in s.split()] x() try: - print bad + print(bad) except NameError: pass Modified: python/branches/p3yk-noslice/Lib/test/test_select.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_select.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_select.py Fri Feb 23 18:29:35 2007 @@ -9,7 +9,7 @@ except TypeError: pass else: - print 'expected TypeError exception not raised' + print('expected TypeError exception not raised') class Nope: pass @@ -23,47 +23,47 @@ except TypeError: pass else: - print 'expected TypeError exception not raised' + print('expected TypeError exception not raised') try: rfd, wfd, xfd = select.select([Almost()], [], []) except TypeError: pass else: - print 'expected TypeError exception not raised' + print('expected TypeError exception not raised') try: rfd, wfd, xfd = select.select([], [], [], 'not a number') except TypeError: pass else: - print 'expected TypeError exception not raised' + print('expected TypeError exception not raised') def test(): import sys if sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'): if verbose: - print "Can't test select easily on", sys.platform + print("Can't test select easily on", sys.platform) return cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' p = os.popen(cmd, 'r') for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: if verbose: - print 'timeout =', tout + print('timeout =', tout) rfd, wfd, xfd = select.select([p], [], [], tout) if (rfd, wfd, xfd) == ([], [], []): continue if (rfd, wfd, xfd) == ([p], [], []): line = p.readline() if verbose: - print repr(line) + print(repr(line)) if not line: if verbose: - print 'EOF' + print('EOF') break continue - print 'Unexpected return values from select():', rfd, wfd, xfd + print('Unexpected return values from select():', rfd, wfd, xfd) p.close() reap_children() Modified: python/branches/p3yk-noslice/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_set.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_set.py Fri Feb 23 18:29:35 2007 @@ -26,6 +26,14 @@ def __repr__(self): return repr(self.value) +class HashCountingInt(int): + 'int-like object that counts the number of times __hash__ is called' + def __init__(self, *args): + self.hash_count = 0 + def __hash__(self): + self.hash_count += 1 + return int.__hash__(self) + class TestJointOps(unittest.TestCase): # Tests common to both set and frozenset @@ -265,7 +273,7 @@ w.value = s try: fo = open(test_support.TESTFN, "wb") - print >> fo, s, + fo.write(str(s)) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(s)) @@ -273,6 +281,18 @@ fo.close() os.remove(test_support.TESTFN) + def test_do_not_rehash_dict_keys(self): + n = 10 + d = dict.fromkeys(map(HashCountingInt, xrange(n))) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s = self.thetype(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s.difference(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + if hasattr(s, 'symmetric_difference_update'): + s.symmetric_difference_update(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + class TestSet(TestJointOps): thetype = set @@ -476,6 +496,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 @@ -584,7 +614,7 @@ def test_print(self): try: fo = open(test_support.TESTFN, "wb") - print >> fo, self.set, + fo.write(str(self.set)) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(self.set)) @@ -1454,6 +1484,7 @@ test_classes = ( TestSet, TestSetSubclass, + TestSetSubclassWithKeywordArgs, TestFrozenSet, TestFrozenSetSubclass, TestSetOfSets, @@ -1495,7 +1526,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_signal.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_signal.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_signal.py Fri Feb 23 18:29:35 2007 @@ -15,7 +15,7 @@ pid = os.getpid() if verbose: - print "test runner's pid is", pid + print("test runner's pid is", pid) # Shell script that will send us asynchronous signals script = """ @@ -36,7 +36,7 @@ global a_called a_called = True if verbose: - print "handlerA invoked", args + print("handlerA invoked", args) class HandlerBCalled(Exception): pass @@ -45,7 +45,7 @@ global b_called b_called = True if verbose: - print "handlerB invoked", args + print("handlerB invoked", args) raise HandlerBCalled, args # Set up a child to send signals to us (the parent) after waiting long @@ -69,10 +69,10 @@ # time for the normal sequence of events to occur. This is # just a stop-gap to try to prevent the test from hanging. time.sleep(MAX_DURATION + 5) - print >> sys.__stdout__, ' child should not have to kill parent' + print(' child should not have to kill parent', file=sys.__stdout__) for signame in "SIGHUP", "SIGUSR1", "SIGUSR2", "SIGALRM": os.kill(pid, getattr(signal, signame)) - print >> sys.__stdout__, " child sent", signame, "to", pid + print(" child sent", signame, "to", pid, file=sys.__stdout__) time.sleep(1) finally: os._exit(0) @@ -126,27 +126,27 @@ # KeyboardInterrupt, finally getting us out of the loop. os.system(script) try: - print "starting pause() loop..." + print("starting pause() loop...") while 1: try: if verbose: - print "call pause()..." + print("call pause()...") signal.pause() if verbose: - print "pause() returned" + print("pause() returned") except HandlerBCalled: if verbose: - print "HandlerBCalled exception caught" + print("HandlerBCalled exception caught") except KeyboardInterrupt: if verbose: - print "KeyboardInterrupt (the alarm() went off)" + print("KeyboardInterrupt (the alarm() went off)") if not a_called: - print 'HandlerA not called' + print('HandlerA not called') if not b_called: - print 'HandlerB not called' + print('HandlerB not called') finally: # Forcibly kill the child we created to ping us if there was a test error. Modified: python/branches/p3yk-noslice/Lib/test/test_site.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_site.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_site.py Fri Feb 23 18:29:35 2007 @@ -119,11 +119,11 @@ """ FILE = open(self.file_path, 'w') try: - print>>FILE, "#import @bad module name" - print>>FILE, "\n" - print>>FILE, "import %s" % self.imported - print>>FILE, self.good_dirname - print>>FILE, self.bad_dirname + print("#import @bad module name", file=FILE) + print("\n", file=FILE) + print("import %s" % self.imported, file=FILE) + print(self.good_dirname, file=FILE) + print(self.bad_dirname, file=FILE) finally: FILE.close() os.mkdir(self.good_dir_path) @@ -204,7 +204,7 @@ if sys.platform == "win32": import locale if locale.getdefaultlocale()[1].startswith('cp'): - for value in encodings.aliases.aliases.itervalues(): + for value in encodings.aliases.aliases.values(): if value == "mbcs": break else: Modified: python/branches/p3yk-noslice/Lib/test/test_slice.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_slice.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_slice.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_socket.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_socket.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_socket.py Fri Feb 23 18:29:35 2007 @@ -302,13 +302,27 @@ sizes = {socket.htonl: 32, socket.ntohl: 32, socket.htons: 16, socket.ntohs: 16} for func, size in sizes.items(): - mask = (1L<> sys.stderr, """\ + print("""\ WARNING: an attempt to connect to %r %s, in test_timeout. That may be legitimate, but is not the outcome we hoped for. If this message is seen often, test_timeout should be changed to - use a more reliable address.""" % (ADDR, extra_msg) + use a more reliable address.""" % (ADDR, extra_msg), file=sys.stderr) if test_support.verbose: - print "test_timeout ..." + print("test_timeout ...") # A service which issues a welcome banner (without need to write # anything). @@ -73,7 +73,7 @@ def test_rude_shutdown(): if test_support.verbose: - print "test_rude_shutdown ..." + print("test_rude_shutdown ...") try: import threading Modified: python/branches/p3yk-noslice/Lib/test/test_socketserver.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_socketserver.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_socketserver.py Fri Feb 23 18:29:35 2007 @@ -77,16 +77,16 @@ def run(self): class svrcls(MyMixinServer, self.__svrcls): pass - if verbose: print "thread: creating server" + if verbose: print("thread: creating server") svr = svrcls(self.__addr, self.__hdlrcls) # pull the address out of the server in case it changed # this can happen if another process is using the port addr = getattr(svr, 'server_address') if addr: self.__addr = addr - if verbose: print "thread: serving three times" + if verbose: print("thread: serving three times") svr.serve_a_few() - if verbose: print "thread: done" + if verbose: print("thread: done") seed = 0 def pickport(): @@ -129,19 +129,19 @@ for svrcls in servers: addr = pickaddr(proto) if verbose: - print "ADDR =", addr - print "CLASS =", svrcls + print("ADDR =", addr) + print("CLASS =", svrcls) t = ServerThread(addr, svrcls, hdlrcls) - if verbose: print "server created" + if verbose: print("server created") t.start() - if verbose: print "server running" + if verbose: print("server running") for i in range(NREQ): time.sleep(DELAY) - if verbose: print "test client", i + if verbose: print("test client", i) testfunc(proto, addr) - if verbose: print "waiting for server" + if verbose: print("waiting for server") t.join() - if verbose: print "done" + if verbose: print("done") class ForgivingTCPServer(TCPServer): # prevent errors if another process is using the port we want @@ -159,8 +159,7 @@ (err, msg) = e if err != errno.EADDRINUSE: raise - print >>sys.__stderr__, \ - ' WARNING: failed to listen on port %d, trying another' % port + print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__) tcpservers = [ForgivingTCPServer, ThreadingTCPServer] if hasattr(os, 'fork') and os.name not in ('os2',): Deleted: /python/branches/p3yk-noslice/Lib/test/test_softspace.py ============================================================================== --- /python/branches/p3yk-noslice/Lib/test/test_softspace.py Fri Feb 23 18:29:35 2007 +++ (empty file) @@ -1,14 +0,0 @@ -from test import test_support -import StringIO - -# SF bug 480215: softspace confused in nested print -f = StringIO.StringIO() -class C: - def __str__(self): - print >> f, 'a' - return 'b' - -print >> f, C(), 'c ', 'd\t', 'e' -print >> f, 'f', 'g' -# In 2.2 & earlier, this printed ' a\nbc d\te\nf g\n' -test_support.vereq(f.getvalue(), 'a\nb c d\te\nf g\n') Modified: python/branches/p3yk-noslice/Lib/test/test_sort.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_sort.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_sort.py Fri Feb 23 18:29:35 2007 @@ -10,7 +10,7 @@ global nerrors if verbose: - print " checking", tag + print(" checking", tag) orig = raw[:] # save input in case of error if compare: @@ -19,22 +19,22 @@ raw.sort() if len(expected) != len(raw): - print "error in", tag - print "length mismatch;", len(expected), len(raw) - print expected - print orig - print raw + print("error in", tag) + print("length mismatch;", len(expected), len(raw)) + print(expected) + print(orig) + print(raw) nerrors += 1 return for i, good in enumerate(expected): maybe = raw[i] if good is not maybe: - print "error in", tag - print "out of order at index", i, good, maybe - print expected - print orig - print raw + print("error in", tag) + print("out of order at index", i, good, maybe) + print(expected) + print(orig) + print(raw) nerrors += 1 return @@ -56,7 +56,7 @@ def __lt__(self, other): if Complains.maybe_complain and random.random() < 0.001: if verbose: - print " complaining at", self, other + print(" complaining at", self, other) raise RuntimeError return self.i < other.i @@ -77,7 +77,7 @@ for n in sizes: x = range(n) if verbose: - print "Testing size", n + print("Testing size", n) s = x[:] check("identity", x, s) @@ -96,8 +96,8 @@ check("reversed via function", y, s, lambda a, b: cmp(b, a)) if verbose: - print " Checking against an insane comparison function." - print " If the implementation isn't careful, this may segfault." + print(" Checking against an insane comparison function.") + print(" If the implementation isn't careful, this may segfault.") s = x[:] s.sort(lambda a, b: int(random.random() * 3) - 1) check("an insane function left some permutation", x, s) @@ -285,7 +285,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk-noslice/Lib/test/test_strftime.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_strftime.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_strftime.py Fri Feb 23 18:29:35 2007 @@ -40,8 +40,8 @@ def strftest(now): if verbose: - print "strftime test for", time.ctime(now) - nowsecs = str(long(now))[:-1] + print("strftime test for", time.ctime(now)) + nowsecs = str(int(now))[:-1] gmt = time.gmtime(now) now = time.localtime(now) @@ -113,42 +113,42 @@ ) if verbose: - print "Strftime test, platform: %s, Python version: %s" % \ - (sys.platform, sys.version.split()[0]) + print("Strftime test, platform: %s, Python version: %s" % \ + (sys.platform, sys.version.split()[0])) for e in expectations: try: result = time.strftime(e[0], now) except ValueError as error: - print "Standard '%s' format gave error:" % e[0], error + print("Standard '%s' format gave error:" % e[0], error) continue if re.match(escapestr(e[1], ampm), result): continue if not result or result[0] == '%': - print "Does not support standard '%s' format (%s)" % (e[0], e[2]) + print("Does not support standard '%s' format (%s)" % (e[0], e[2])) else: - print "Conflict for %s (%s):" % (e[0], e[2]) - print " Expected %s, but got %s" % (e[1], result) + print("Conflict for %s (%s):" % (e[0], e[2])) + print(" Expected %s, but got %s" % (e[1], result)) for e in nonstandard_expectations: try: result = time.strftime(e[0], now) except ValueError as result: if verbose: - print "Error for nonstandard '%s' format (%s): %s" % \ - (e[0], e[2], str(result)) + print("Error for nonstandard '%s' format (%s): %s" % \ + (e[0], e[2], str(result))) continue if re.match(escapestr(e[1], ampm), result): if verbose: - print "Supports nonstandard '%s' format (%s)" % (e[0], e[2]) + print("Supports nonstandard '%s' format (%s)" % (e[0], e[2])) elif not result or result[0] == '%': if verbose: - print "Does not appear to support '%s' format (%s)" % (e[0], - e[2]) + print("Does not appear to support '%s' format (%s)" % (e[0], + e[2])) else: if verbose: - print "Conflict for nonstandard '%s' format (%s):" % (e[0], - e[2]) - print " Expected %s, but got %s" % (e[1], result) + print("Conflict for nonstandard '%s' format (%s):" % (e[0], + e[2])) + print(" Expected %s, but got %s" % (e[1], result)) def fixasctime(s): if s[8] == ' ': Modified: python/branches/p3yk-noslice/Lib/test/test_string.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_string.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_string.py Fri Feb 23 18:29:35 2007 @@ -83,7 +83,7 @@ self.assertRaises(ValueError, string.atoi, " x1 ") def test_atol(self): - self.assertEqual(string.atol(" 1 "), 1L) + self.assertEqual(string.atol(" 1 "), 1) self.assertRaises(ValueError, string.atol, " 1x ") self.assertRaises(ValueError, string.atol, " x1 ") Modified: python/branches/p3yk-noslice/Lib/test/test_strop.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_strop.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_strop.py Fri Feb 23 18:29:35 2007 @@ -15,7 +15,7 @@ self.assertRaises(ValueError, strop.atoi, " x1 ") def test_atol(self): - self.assert_(strop.atol(" 1 ") == 1L) + self.assert_(strop.atol(" 1 ") == 1) self.assertRaises(ValueError, strop.atol, " 1x") self.assertRaises(ValueError, strop.atol, " x1 ") Modified: python/branches/p3yk-noslice/Lib/test/test_strptime.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_strptime.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_strptime.py Fri Feb 23 18:29:35 2007 @@ -463,6 +463,10 @@ "of the year") test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and " "ending on Monday") + test_helper((2007, 01, 07), "First Sunday of 2007") + test_helper((2007, 01, 14), "Second Sunday of 2007") + test_helper((2006, 12, 31), "Last Sunday of 2006") + test_helper((2006, 12, 24), "Second to last Sunday of 2006") class CacheTests(unittest.TestCase): Modified: python/branches/p3yk-noslice/Lib/test/test_struct.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_struct.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_struct.py Fri Feb 23 18:29:35 2007 @@ -84,8 +84,8 @@ if sz * 3 != struct.calcsize('iii'): raise TestFailed, 'inconsistent sizes' -fmt = 'cbxxxxxxhhhhiillffd' -fmt3 = '3c3b18x12h6i6l6f3d' +fmt = 'cbxxxxxxhhhhiillffdt' +fmt3 = '3c3b18x12h6i6l6f3d3t' sz = struct.calcsize(fmt) sz3 = struct.calcsize(fmt3) if sz * 3 != sz3: @@ -108,19 +108,21 @@ l = 65536 f = 3.1415 d = 3.1415 +t = True for prefix in ('', '@', '<', '>', '=', '!'): - for format in ('xcbhilfd', 'xcBHILfd'): + for format in ('xcbhilfdt', 'xcBHILfdt'): format = prefix + format if verbose: - print "trying:", format - s = struct.pack(format, c, b, h, i, l, f, d) - cp, bp, hp, ip, lp, fp, dp = struct.unpack(format, s) + print("trying:", format) + s = struct.pack(format, c, b, h, i, l, f, d, t) + cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s) if (cp != c or bp != b or hp != h or ip != i or lp != l or - int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d)): + int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d) or + tp != t): # ^^^ calculate only to two decimal places raise TestFailed, "unpack/pack not transitive (%s, %s)" % ( - str(format), str((cp, bp, hp, ip, lp, fp, dp))) + str(format), str((cp, bp, hp, ip, lp, fp, dp, tp))) # Test some of the new features in detail @@ -146,23 +148,28 @@ ('H', 0x10000-700, '\375D', 'D\375', 0), ('i', 70000000, '\004,\035\200', '\200\035,\004', 0), ('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0), - ('I', 70000000L, '\004,\035\200', '\200\035,\004', 0), - ('I', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('I', 70000000, '\004,\035\200', '\200\035,\004', 0), + ('I', 0x100000000-70000000, '\373\323\342\200', '\200\342\323\373', 0), ('l', 70000000, '\004,\035\200', '\200\035,\004', 0), ('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0), - ('L', 70000000L, '\004,\035\200', '\200\035,\004', 0), - ('L', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('L', 70000000, '\004,\035\200', '\200\035,\004', 0), + ('L', 0x100000000-70000000, '\373\323\342\200', '\200\342\323\373', 0), ('f', 2.0, '@\000\000\000', '\000\000\000@', 0), ('d', 2.0, '@\000\000\000\000\000\000\000', '\000\000\000\000\000\000\000@', 0), ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0), ('d', -2.0, '\300\000\000\000\000\000\000\000', '\000\000\000\000\000\000\000\300', 0), + ('t', 0, '\0', '\0', 0), + ('t', 3, '\1', '\1', 1), + ('t', True, '\1', '\1', 0), + ('t', [], '\0', '\0', 1), + ('t', (1,), '\1', '\1', 1), ] for fmt, arg, big, lil, asy in tests: if verbose: - print "%r %r %r %r" % (fmt, arg, big, lil) + print("%r %r %r %r" % (fmt, arg, big, lil)) for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil), ('='+fmt, ISBIGENDIAN and big or lil)]: res = struct.pack(xfmt, arg) @@ -188,7 +195,7 @@ has_native_qQ = 0 if verbose: - print "Platform has native q/Q?", has_native_qQ and "Yes." or "No." + print("Platform has native q/Q?", has_native_qQ and "Yes." or "No.") any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless @@ -203,9 +210,9 @@ ('q', -1, '\xff' * bytes), ('q', 0, '\x00' * bytes), ('Q', 0, '\x00' * bytes), - ('q', 1L, '\x00' * (bytes-1) + '\x01'), - ('Q', (1L << (8*bytes))-1, '\xff' * bytes), - ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))): + ('q', 1, '\x00' * (bytes-1) + '\x01'), + ('Q', (1 << (8*bytes))-1, '\xff' * bytes), + ('q', (1 << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))): got = struct.pack(format, input) native_expected = bigendian_to_native(expected) verify(got == native_expected, @@ -243,23 +250,23 @@ self.bitsize = bytesize * 8 self.signed_code, self.unsigned_code = formatpair self.unsigned_min = 0 - self.unsigned_max = 2L**self.bitsize - 1 - self.signed_min = -(2L**(self.bitsize-1)) - self.signed_max = 2L**(self.bitsize-1) - 1 + self.unsigned_max = 2**self.bitsize - 1 + self.signed_min = -(2**(self.bitsize-1)) + self.signed_max = 2**(self.bitsize-1) - 1 def test_one(self, x, pack=struct.pack, unpack=struct.unpack, unhexlify=binascii.unhexlify): if verbose: - print "trying std", self.formatpair, "on", x, "==", hex(x) + print("trying std", self.formatpair, "on", x, "==", hex(x)) # Try signed. code = self.signed_code if self.signed_min <= x <= self.signed_max: # Try big-endian. - expected = long(x) + expected = int(x) if x < 0: - expected += 1L << self.bitsize + expected += 1 << self.bitsize assert expected > 0 expected = hex(expected)[2:] # chop "0x" if len(expected) & 1: @@ -306,7 +313,7 @@ # x is out of range -- verify pack realizes that. if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK: if verbose: - print "Skipping buggy range check for code", code + print("Skipping buggy range check for code", code) else: deprecated_err(pack, ">" + code, x) deprecated_err(pack, "<" + code, x) @@ -316,7 +323,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 @@ -361,7 +368,7 @@ # x is out of range -- verify pack realizes that. if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK: if verbose: - print "Skipping buggy range check for code", code + print("Skipping buggy range check for code", code) else: deprecated_err(pack, ">" + code, x) deprecated_err(pack, "<" + code, x) @@ -372,11 +379,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 +492,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() @@ -612,3 +619,50 @@ test_unpack_from() test_pack_into() test_pack_into_fn() + +def test_bool(): + for prefix in tuple("<>!=")+('',): + false = (), [], [], '', 0 + true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2 + + falseFormat = prefix + 't' * len(false) + if verbose: + print('trying bool pack/unpack on', false, 'using format', falseFormat) + packedFalse = struct.pack(falseFormat, *false) + unpackedFalse = struct.unpack(falseFormat, packedFalse) + + trueFormat = prefix + 't' * len(true) + if verbose: + print('trying bool pack/unpack on', true, 'using format', trueFormat) + packedTrue = struct.pack(trueFormat, *true) + unpackedTrue = struct.unpack(trueFormat, packedTrue) + + if len(true) != len(unpackedTrue): + raise TestFailed('unpacked true array is not of same size as input') + if len(false) != len(unpackedFalse): + raise TestFailed('unpacked false array is not of same size as input') + + for t in unpackedFalse: + if t is not False: + raise TestFailed('%r did not unpack as False' % t) + for t in unpackedTrue: + if t is not True: + raise TestFailed('%r did not unpack as false' % t) + + if prefix and verbose: + print('trying size of bool with format %r' % (prefix+'t')) + packed = struct.pack(prefix+'t', 1) + + if len(packed) != struct.calcsize(prefix+'t'): + raise TestFailed('packed length is not equal to calculated size') + + if len(packed) != 1 and prefix: + raise TestFailed('encoded bool is not one byte: %r' % packed) + elif not prefix and verbose: + print('size of bool in native format is %i' % (len(packed))) + + for c in '\x01\x7f\xff\x0f\xf0': + if struct.unpack('>t', c)[0] is not True: + raise TestFailed('%c did not unpack as True' % c) + +test_bool() Modified: python/branches/p3yk-noslice/Lib/test/test_subprocess.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_subprocess.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_subprocess.py Fri Feb 23 18:29:35 2007 @@ -84,7 +84,7 @@ def test_stdin_none(self): # .stdin is None when not redirected - p = subprocess.Popen([sys.executable, "-c", 'print "banana"'], + p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() self.assertEqual(p.stdin, None) @@ -92,16 +92,16 @@ def test_stdout_none(self): # .stdout is None when not redirected p = subprocess.Popen([sys.executable, "-c", - 'print " this bit of output is from a ' + 'print(" this bit of output is from a ' 'test of stdout in a different ' - 'process ..."'], + 'process ...")'], stdin=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() self.assertEqual(p.stdout, None) def test_stderr_none(self): # .stderr is None when not redirected - p = subprocess.Popen([sys.executable, "-c", 'print "banana"'], + p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) p.wait() self.assertEqual(p.stderr, None) @@ -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-noslice/Lib/test/test_sundry.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_sundry.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_sundry.py Fri Feb 23 18:29:35 2007 @@ -68,7 +68,7 @@ import tty # not available on Windows except ImportError: if verbose: - print "skipping tty" + print("skipping tty") # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it # can screw up all sorts of things (esp. if it prints!). Modified: python/branches/p3yk-noslice/Lib/test/test_support.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_support.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_support.py Fri Feb 23 18:29:35 2007 @@ -106,8 +106,7 @@ (err, msg) = e if err != errno.EADDRINUSE: raise - print >>sys.__stderr__, \ - ' WARNING: failed to listen on port %d, trying another' % port + print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__) raise TestFailed, 'unable to find port to listen on' FUZZ = 1e-6 @@ -178,10 +177,9 @@ except UnicodeEncodeError: pass else: - print \ - 'WARNING: The filename %r CAN be encoded by the filesystem. ' \ + print('WARNING: The filename %r CAN be encoded by the filesystem. ' \ 'Unicode filename tests may not be effective' \ - % TESTFN_UNICODE_UNENCODEABLE + % TESTFN_UNICODE_UNENCODEABLE) # Make sure we can write to TESTFN, try in /tmp if we can't fp = None @@ -194,8 +192,8 @@ TESTFN = TMP_TESTFN del TMP_TESTFN except IOError: - print ('WARNING: tests will fail, unable to write to: %s or %s' % - (TESTFN, TMP_TESTFN)) + print(('WARNING: tests will fail, unable to write to: %s or %s' % + (TESTFN, TMP_TESTFN))) if fp is not None: fp.close() unlink(TESTFN) @@ -241,8 +239,7 @@ def sortdict(dict): "Like repr(dict), but in sorted order." - items = dict.items() - items.sort() + items = sorted(dict.items()) reprpairs = ["%r: %r" % pair for pair in items] withcommas = ", ".join(reprpairs) return "{%s}" % withcommas @@ -267,10 +264,10 @@ return open(fn) requires('urlfetch') - print >> get_original_stdout(), '\tfetching %s ...' % url + print('\tfetching %s ...' % url, file=get_original_stdout()) fn, _ = urllib.urlretrieve(url, filename) return open(fn) - + @contextmanager def guard_warnings_filter(): """Guard the warnings filter from being permanently changed.""" @@ -307,7 +304,7 @@ return self def __exit__(self, *ignore_exc): - for envvar, value in self._reset.iteritems(): + for envvar, value in self._reset.items(): self._environ[envvar] = value for unset in self._unset: del self._environ[unset] @@ -511,7 +508,7 @@ finally: sys.stdout = save_stdout if verbose: - print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t) + print('doctest (%s) ... %d tests with zero failures' % (module.__name__, t)) return f, t #======================================================================= Modified: python/branches/p3yk-noslice/Lib/test/test_syntax.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_syntax.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_syntax.py Fri Feb 23 18:29:35 2007 @@ -247,7 +247,7 @@ ... finally: ... for abc in range(10): ... continue - ... print abc + ... print(abc) >>> test() 9 @@ -328,11 +328,11 @@ isn't, there should be a syntax error. >>> try: - ... print 1 + ... print(1) ... break - ... print 2 + ... print(2) ... finally: - ... print 3 + ... print(3) Traceback (most recent call last): ... SyntaxError: 'break' outside loop (, line 3) @@ -423,7 +423,7 @@ source = re.sub('(?m)^ *:', '', """\ :def foo(x): : def bar(): - : print x + : print(x) : del x :""") self._check_error(source, "nested scope") Modified: python/branches/p3yk-noslice/Lib/test/test_tarfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_tarfile.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_tarfile.py Fri Feb 23 18:29:35 2007 @@ -305,6 +305,61 @@ self.assertEqual(self.dst.getnames(), [], "added the archive to itself") +class AppendTest(unittest.TestCase): + # Test append mode (cp. patch #1652681). + + def setUp(self): + self.tarname = tmpname() + if os.path.exists(self.tarname): + os.remove(self.tarname) + + def _add_testfile(self, fileobj=None): + tar = tarfile.open(self.tarname, "a", fileobj=fileobj) + tar.addfile(tarfile.TarInfo("bar")) + tar.close() + + def _create_testtar(self): + src = tarfile.open(tarname()) + t = src.getmember("0-REGTYPE") + t.name = "foo" + f = src.extractfile(t) + tar = tarfile.open(self.tarname, "w") + tar.addfile(t, f) + tar.close() + + def _test(self, names=["bar"], fileobj=None): + tar = tarfile.open(self.tarname, fileobj=fileobj) + self.assert_(tar.getnames() == names) + + def test_non_existing(self): + self._add_testfile() + self._test() + + def test_empty(self): + open(self.tarname, "wb").close() + self._add_testfile() + self._test() + + def test_empty_fileobj(self): + fobj = StringIO.StringIO() + self._add_testfile(fobj) + fobj.seek(0) + self._test(fileobj=fobj) + + def test_fileobj(self): + self._create_testtar() + data = open(self.tarname, "rb").read() + fobj = StringIO.StringIO(data) + self._add_testfile(fobj) + fobj.seek(0) + self._test(names=["foo", "bar"], fileobj=fobj) + + def test_existing(self): + self._create_testtar() + self._add_testfile() + self._test(names=["foo", "bar"]) + + class Write100Test(BaseTest): # The name field in a tar header stores strings of at most 100 chars. # If a string is shorter than 100 chars it has to be padded with '\0', @@ -711,6 +766,7 @@ ReadAsteriskTest, ReadStreamAsteriskTest, WriteTest, + AppendTest, Write100Test, WriteSize0Test, WriteStreamTest, Modified: python/branches/p3yk-noslice/Lib/test/test_thread.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_thread.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_thread.py Fri Feb 23 18:29:35 2007 @@ -21,10 +21,10 @@ delay = random.random() * numtasks rmutex.release() if verbose: - print 'task', ident, 'will run for', round(delay, 1), 'sec' + print('task', ident, 'will run for', round(delay, 1), 'sec') time.sleep(delay) if verbose: - print 'task', ident, 'done' + print('task', ident, 'done') mutex.acquire() running = running - 1 if running == 0: @@ -37,7 +37,7 @@ mutex.acquire() next_ident = next_ident + 1 if verbose: - print 'creating task', next_ident + print('creating task', next_ident) thread.start_new_thread(task, (next_ident,)) running = running + 1 mutex.release() @@ -45,9 +45,9 @@ for i in range(numtasks): newtask() -print 'waiting for all tasks to complete' +print('waiting for all tasks to complete') done.acquire() -print 'all tasks done' +print('all tasks done') class barrier: def __init__(self, n): @@ -89,13 +89,13 @@ delay = random.random() * numtasks rmutex.release() if verbose: - print 'task', ident, 'will run for', round(delay, 1), 'sec' + print('task', ident, 'will run for', round(delay, 1), 'sec') time.sleep(delay) if verbose: - print 'task', ident, 'entering barrier', i + print('task', ident, 'entering barrier', i) bar.enter() if verbose: - print 'task', ident, 'leaving barrier', i + print('task', ident, 'leaving barrier', i) mutex.acquire() running -= 1 # Must release mutex before releasing done, else the main thread can @@ -106,7 +106,7 @@ if finished: done.release() -print '\n*** Barrier Test ***' +print('\n*** Barrier Test ***') if done.acquire(0): raise ValueError, "'done' should have remained acquired" bar = barrier(numtasks) @@ -114,10 +114,10 @@ for i in range(numtasks): thread.start_new_thread(task2, (i,)) done.acquire() -print 'all tasks done' +print('all tasks done') # not all platforms support changing thread stack size -print '\n*** Changing thread stack size ***' +print('\n*** Changing thread stack size ***') if thread.stack_size() != 0: raise ValueError, "initial stack_size not 0" @@ -132,10 +132,10 @@ try: thread.stack_size(4096) except ValueError: - print 'caught expected ValueError setting stack_size(4096)' + print('caught expected ValueError setting stack_size(4096)') except thread.error: tss_supported = 0 - print 'platform does not support changing thread stack size' + print('platform does not support changing thread stack size') if tss_supported: failed = lambda s, e: s != e @@ -144,17 +144,17 @@ thread.stack_size(tss) if failed(thread.stack_size(), tss): raise ValueError, fail_msg % tss - print 'successfully set stack_size(%d)' % tss + print('successfully set stack_size(%d)' % tss) for tss in (262144, 0x100000): - print 'trying stack_size = %d' % tss + print('trying stack_size = %d' % tss) next_ident = 0 for i in range(numtasks): newtask() - print 'waiting for all tasks to complete' + print('waiting for all tasks to complete') done.acquire() - print 'all tasks done' + print('all tasks done') # reset stack size to default thread.stack_size(0) Modified: python/branches/p3yk-noslice/Lib/test/test_threaded_import.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_threaded_import.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_threaded_import.py Fri Feb 23 18:29:35 2007 @@ -28,14 +28,14 @@ def test_import_hangers(): import sys if verbose: - print "testing import hangers ...", + print("testing import hangers ...", end=' ') import test.threaded_import_hangers try: if test.threaded_import_hangers.errors: raise TestFailed(test.threaded_import_hangers.errors) elif verbose: - print "OK." + print("OK.") finally: # In case this test is run again, make sure the helper module # gets loaded from scratch again. @@ -61,12 +61,12 @@ done.acquire() for N in (20, 50) * 3: if verbose: - print "Trying", N, "threads ...", + print("Trying", N, "threads ...", end=' ') for i in range(N): thread.start_new_thread(task, ()) done.acquire() if verbose: - print "OK." + print("OK.") done.release() test_import_hangers() Modified: python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py Fri Feb 23 18:29:35 2007 @@ -50,26 +50,26 @@ threads = [] thread_info = threading_setup() - print "Creating" + print("Creating") for i in range(NUM_THREADS): t = TempFileGreedy() threads.append(t) t.start() - print "Starting" + print("Starting") startEvent.set() - print "Reaping" + print("Reaping") ok = errors = 0 for t in threads: t.join() ok += t.ok_count errors += t.error_count if t.error_count: - print '%s errors:\n%s' % (t.getName(), t.errors.getvalue()) + print('%s errors:\n%s' % (t.getName(), t.errors.getvalue())) msg = "Done: errors %d ok %d" % (errors, ok) - print msg + print(msg) if errors: raise TestFailed(msg) Modified: python/branches/p3yk-noslice/Lib/test/test_threading.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_threading.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_threading.py Fri Feb 23 18:29:35 2007 @@ -30,27 +30,27 @@ def run(self): delay = random.random() * 2 if verbose: - print 'task', self.getName(), 'will run for', delay, 'sec' + print('task', self.getName(), 'will run for', delay, 'sec') self.sema.acquire() self.mutex.acquire() self.nrunning.inc() if verbose: - print self.nrunning.get(), 'tasks are running' + print(self.nrunning.get(), 'tasks are running') self.testcase.assert_(self.nrunning.get() <= 3) self.mutex.release() time.sleep(delay) if verbose: - print 'task', self.getName(), 'done' + print('task', self.getName(), 'done') self.mutex.acquire() self.nrunning.dec() self.testcase.assert_(self.nrunning.get() >= 0) if verbose: - print self.getName(), 'is finished.', self.nrunning.get(), \ - 'tasks are running' + print(self.getName(), 'is finished.', self.nrunning.get(), \ + 'tasks are running') self.mutex.release() self.sema.release() @@ -77,23 +77,23 @@ t.start() if verbose: - print 'waiting for all tasks to complete' + print('waiting for all tasks to complete') for t in threads: t.join(NUMTASKS) self.assert_(not t.isAlive()) if verbose: - print 'all tasks done' + print('all tasks done') self.assertEqual(numrunning.get(), 0) # run with a small(ish) thread stack size (256kB) def test_various_ops_small_stack(self): if verbose: - print 'with 256kB thread stack size...' + print('with 256kB thread stack size...') try: threading.stack_size(262144) except thread.error: if verbose: - print 'platform does not support changing thread stack size' + print('platform does not support changing thread stack size') return self.test_various_ops() threading.stack_size(0) @@ -101,12 +101,12 @@ # run with a large thread stack size (1MB) def test_various_ops_large_stack(self): if verbose: - print 'with 1MB thread stack size...' + print('with 1MB thread stack size...') try: threading.stack_size(0x100000) except thread.error: if verbose: - print 'platform does not support changing thread stack size' + print('platform does not support changing thread stack size') return self.test_various_ops() threading.stack_size(0) @@ -138,7 +138,7 @@ import ctypes except ImportError: if verbose: - print "test_PyThreadState_SetAsyncExc can't import ctypes" + print("test_PyThreadState_SetAsyncExc can't import ctypes") return # can't do anything set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc @@ -172,31 +172,31 @@ t.setDaemon(True) # so if this fails, we don't hang Python at shutdown t.start() if verbose: - print " started worker thread" + print(" started worker thread") # Try a thread id that doesn't make sense. if verbose: - print " trying nonsensical thread id" + print(" trying nonsensical thread id") result = set_async_exc(ctypes.c_long(-1), exception) self.assertEqual(result, 0) # no thread states modified # Now raise an exception in the worker thread. if verbose: - print " waiting for worker thread to get started" + print(" waiting for worker thread to get started") worker_started.wait() if verbose: - print " verifying worker hasn't exited" + print(" verifying worker hasn't exited") self.assert_(not t.finished) if verbose: - print " attempting to raise asynch exception in worker" + print(" attempting to raise asynch exception in worker") result = set_async_exc(ctypes.c_long(t.id), exception) self.assertEqual(result, 1) # one thread state modified if verbose: - print " waiting for worker to say it caught the exception" + print(" waiting for worker to say it caught the exception") worker_saw_exception.wait(timeout=10) self.assert_(t.finished) if verbose: - print " all OK -- joining worker" + print(" all OK -- joining worker") if t.finished: t.join() # else the thread is still running, and we have no way to kill it Modified: python/branches/p3yk-noslice/Lib/test/test_time.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_time.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_time.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_timeout.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_timeout.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_timeout.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_tokenize.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_tokenize.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_tokenize.py Fri Feb 23 18:29:35 2007 @@ -43,9 +43,9 @@ There are some standard formatting practices that are easy to get right. >>> roundtrip("if x == 1:\\n" -... " print x\\n") +... " print(x)\\n") if x == 1: - print x + print(x) Some people use different formatting conventions, which makes untokenize a little trickier. Note that this test involves trailing @@ -53,29 +53,29 @@ two trailing blanks apparent in the expected output. >>> roundtrip("if x == 1 : \\n" -... " print x\\n") +... " print(x)\\n") if x == 1 :\x20\x20 - print x + print(x) Comments need to go in the right place. >>> roundtrip("if x == 1:\\n" ... " # A comment by itself.\\n" -... " print x # Comment here, too.\\n" +... " print(x) # Comment here, too.\\n" ... " # Another comment.\\n" ... "after_if = True\\n") if x == 1: # A comment by itself. - print x # Comment here, too. + print(x) # Comment here, too. # Another comment. after_if = True >>> roundtrip("if (x # The comments need to go in the right place\\n" ... " == 1):\\n" -... " print 'x == 1'\\n") +... " print('x == 1')\\n") if (x # The comments need to go in the right place == 1): - print 'x == 1' + print('x == 1') """ @@ -118,21 +118,21 @@ if type == ENDMARKER: break type = tok_name[type] - print "%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals() + print("%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals()) def roundtrip(s): f = StringIO(s) source = untokenize(generate_tokens(f.readline)) - print source, + print(source, end="") # This is an example from the docs, set up as a doctest. def decistmt(s): """Substitute Decimals for floats in a string of statements. >>> from decimal import Decimal - >>> s = 'print +21.3e-5*-.1234/81.7' + >>> s = 'print(+21.3e-5*-.1234/81.7)' >>> decistmt(s) - "print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')" + "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))" The format of the exponent is inherited from the platform C library. Known cases are "e-007" (Windows) and "e-07" (not Windows). Since @@ -165,7 +165,7 @@ def test_main(): if verbose: - print 'starting...' + print('starting...') next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL @@ -191,7 +191,7 @@ # Print still working message since this test can be really slow if next_time <= time.time(): next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - print >>sys.__stdout__, ' test_main still working, be patient...' + print(' test_main still working, be patient...', file=sys.__stdout__) sys.__stdout__.flush() test_roundtrip(f) @@ -217,7 +217,7 @@ run_doctest(test_tokenize, verbose) if verbose: - print 'finished' + print('finished') def test_rarrow(): """ Modified: python/branches/p3yk-noslice/Lib/test/test_trace.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_trace.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_trace.py Fri Feb 23 18:29:35 2007 @@ -309,7 +309,7 @@ def test_trash_stack(self): def f(): for i in range(5): - print i # line tracing will raise an exception at this line + print(i) # line tracing will raise an exception at this line def g(frame, why, extra): if (why == 'line' and Modified: python/branches/p3yk-noslice/Lib/test/test_traceback.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_traceback.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_traceback.py Fri Feb 23 18:29:35 2007 @@ -25,7 +25,7 @@ import test.badsyntax_nocaret def syntax_error_bad_indentation(self): - compile("def spam():\n print 1\n print 2", "?", "exec") + compile("def spam():\n print(1)\n print(2)", "?", "exec") def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, @@ -48,9 +48,9 @@ err = self.get_exception_format(self.syntax_error_bad_indentation, IndentationError) self.assert_(len(err) == 4) - self.assert_(err[1].strip() == "print 2") + self.assert_(err[1].strip() == "print(2)") self.assert_("^" in err[2]) - self.assert_(err[1].find("2") == err[2].find("^")) + self.assert_(err[1].find(")") == err[2].find("^")) def test_bug737473(self): import sys, os, tempfile, time @@ -60,9 +60,9 @@ try: sys.path.insert(0, testdir) testfile = os.path.join(testdir, 'test_bug737473.py') - print >> open(testfile, 'w'), """ + print(""" def test(): - raise ValueError""" + raise ValueError""", file=open(testfile, 'w')) if 'test_bug737473' in sys.modules: del sys.modules['test_bug737473'] @@ -82,9 +82,9 @@ # three seconds are needed for this test to pass reliably :-( time.sleep(4) - print >> open(testfile, 'w'), """ + print(""" def test(): - raise NotImplementedError""" + raise NotImplementedError""", file=open(testfile, 'w')) reload(test_bug737473) try: test_bug737473.test() Modified: python/branches/p3yk-noslice/Lib/test/test_types.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_types.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_types.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_unary.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_unary.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_unary.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_unicode.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_unicode.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_unicode.py Fri Feb 23 18:29:35 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 @@ -732,15 +732,15 @@ pass out = BitBucket() - print >>out, u'abc' - print >>out, u'abc', u'def' - print >>out, u'abc', 'def' - print >>out, 'abc', u'def' - print >>out, u'abc\n' - print >>out, u'abc\n', - print >>out, u'abc\n', - print >>out, u'def\n' - print >>out, u'def\n' + print(u'abc', file=out) + print(u'abc', u'def', file=out) + print(u'abc', 'def', file=out) + print('abc', u'def', file=out) + print(u'abc\n', file=out) + print(u'abc\n', end=' ', file=out) + print(u'abc\n', end=' ', file=out) + print(u'def\n', file=out) + print(u'def\n', file=out) def test_ucs4(self): if sys.maxunicode == 0xFFFF: Modified: python/branches/p3yk-noslice/Lib/test/test_urllib2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_urllib2.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_urllib2.py Fri Feb 23 18:29:35 2007 @@ -90,8 +90,7 @@ >>> r.header_items() [('Spam-eggs', 'blah')] >>> r.add_header("Foo-Bar", "baz") - >>> items = r.header_items() - >>> items.sort() + >>> items = sorted(r.header_items()) >>> items [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')] @@ -101,7 +100,7 @@ >>> r.has_header("Not-there") False - >>> print r.get_header("Not-there") + >>> print(r.get_header("Not-there")) None >>> r.get_header("Not-there", "default") 'default' @@ -235,7 +234,7 @@ class MockHeaders(dict): def getheaders(self, name): - return self.values() + return list(self.values()) class MockResponse(StringIO.StringIO): def __init__(self, code, msg, headers, data, url=None): Modified: python/branches/p3yk-noslice/Lib/test/test_urllib2net.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_urllib2net.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_urllib2net.py Fri Feb 23 18:29:35 2007 @@ -64,6 +64,27 @@ # urllib2.urlopen, "http://evil:thing at example.com") +class CloseSocketTest(unittest.TestCase): + + def test_close(self): + import socket, httplib, gc + + # calling .close() on urllib2's response objects should close the + # underlying socket + + # delve deep into response to fetch socket._socketobject + response = urllib2.urlopen("http://www.python.org/") + abused_fileobject = response.fp + self.assert_(abused_fileobject.__class__ is socket._fileobject) + httpresponse = abused_fileobject._sock + self.assert_(httpresponse.__class__ is httplib.HTTPResponse) + fileobject = httpresponse.fp + self.assert_(fileobject.__class__ is socket._fileobject) + + self.assert_(not fileobject.closed) + response.close() + self.assert_(fileobject.closed) + class urlopenNetworkTests(unittest.TestCase): """Tests urllib2.urlopen using the network. @@ -263,8 +284,12 @@ def test_main(): test_support.requires("network") - test_support.run_unittest(URLTimeoutTest, urlopenNetworkTests, - AuthTests, OtherNetworkTests) + test_support.run_unittest(URLTimeoutTest, + urlopenNetworkTests, + AuthTests, + OtherNetworkTests, + CloseSocketTest, + ) if __name__ == "__main__": test_main() Modified: python/branches/p3yk-noslice/Lib/test/test_userdict.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_userdict.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_userdict.py Fri Feb 23 18:29:35 2007 @@ -79,7 +79,7 @@ self.assertEqual(u2b, u2c) class MyUserDict(UserDict.UserDict): - def display(self): print self + def display(self): print(self) m2 = MyUserDict(u2) m2a = m2.copy() @@ -92,7 +92,7 @@ # Test keys, items, values self.assertEqual(u2.keys(), d2.keys()) self.assertEqual(u2.items(), d2.items()) - self.assertEqual(u2.values(), d2.values()) + self.assertEqual(list(u2.values()), list(d2.values())) # Test "in". for i in u2.keys(): @@ -208,7 +208,7 @@ if other is not None: for (key, value) in other: self[key] = value - for (key, value) in kwargs.iteritems(): + for (key, value) in kwargs.items(): self[key] = value def __getitem__(self, key): try: @@ -234,7 +234,7 @@ return list(self.keylist) def copy(self): d = self.__class__() - for key, value in self.iteritems(): + for key, value in self.items(): d[key] = value return d @classmethod @@ -278,13 +278,13 @@ self.assertEqual(len(s), 2) # iteritems - self.assertEqual(list(s.iteritems()), [(10,'ten'), (30, 'thirty')]) + self.assertEqual(list(s.items()), [(10,'ten'), (30, 'thirty')]) # iterkeys - self.assertEqual(list(s.iterkeys()), [10, 30]) + self.assertEqual(list(s.keys()), [10, 30]) # itervalues - self.assertEqual(list(s.itervalues()), ['ten', 'thirty']) + self.assertEqual(list(s.values()), ['ten', 'thirty']) # values self.assertEqual(s.values(), ['ten', 'thirty']) Modified: python/branches/p3yk-noslice/Lib/test/test_uu.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_uu.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_uu.py Fri Feb 23 18:29:35 2007 @@ -114,11 +114,11 @@ def test_encode(self): try: - fin = open(self.tmpin, 'w') + fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() - fin = open(self.tmpin, 'r') + fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() Modified: python/branches/p3yk-noslice/Lib/test/test_uuid.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_uuid.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_uuid.py Fri Feb 23 18:29:35 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,21 +281,21 @@ 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: if TestUUID.last_node != node: msg = "different sources disagree on node:\n" - for s, n in TestUUID.source2node.iteritems(): + for s, n in TestUUID.source2node.items(): msg += " from source %r, node was %012x\n" % (s, n) # There's actually no reason to expect the MAC addresses # to agree across various methods -- e.g., a box may have @@ -307,9 +307,8 @@ def test_ifconfig_getnode(self): import sys - print >>sys.__stdout__, \ -""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms. - It is disabled until the code and/or test can be fixed properly.""" + print(""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms. + It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__) return import os @@ -332,13 +331,12 @@ 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 - print >>sys.__stdout__, \ -""" WARNING: uuid._unixdll_getnode is unreliable on many platforms. - It is disabled until the code and/or test can be fixed properly.""" + print(""" WARNING: uuid._unixdll_getnode is unreliable on many platforms. + It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__) return import os @@ -352,9 +350,8 @@ def test_getnode(self): import sys - print >>sys.__stdout__, \ -""" WARNING: uuid.getnode is unreliable on many platforms. - It is disabled until the code and/or test can be fixed properly.""" + print(""" WARNING: uuid.getnode is unreliable on many platforms. + It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__) return node1 = uuid.getnode() Modified: python/branches/p3yk-noslice/Lib/test/test_weakref.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_weakref.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_weakref.py Fri Feb 23 18:29:35 2007 @@ -6,6 +6,8 @@ from test import test_support +# Used in ReferencesTestCase.test_ref_created_during_del() . +ref_from_del = None class C: def method(self): @@ -630,6 +632,18 @@ finally: gc.set_threshold(*thresholds) + def test_ref_created_during_del(self): + # Bug #1377858 + # A weakref created in an object's __del__() would crash the + # interpreter when the weakref was cleaned up since it would refer to + # non-existent memory. This test should not segfault the interpreter. + class Target(object): + def __del__(self): + global ref_from_del + ref_from_del = weakref.ref(self) + + w = Target() + class SubclassableWeakrefTestCase(unittest.TestCase): @@ -825,25 +839,25 @@ def check_iters(self, dict): # item iterator: items = dict.items() - for item in dict.iteritems(): + for item in dict.items(): items.remove(item) self.assert_(len(items) == 0, "iteritems() did not touch all items") # key iterator, via __iter__(): - keys = dict.keys() + keys = list(dict.keys()) for k in dict: keys.remove(k) self.assert_(len(keys) == 0, "__iter__() did not touch all keys") # key iterator, via iterkeys(): - keys = dict.keys() - for k in dict.iterkeys(): + keys = list(dict.keys()) + for k in dict.keys(): keys.remove(k) self.assert_(len(keys) == 0, "iterkeys() did not touch all keys") # value iterator: - values = dict.values() - for v in dict.itervalues(): + values = list(dict.values()) + for v in dict.values(): values.remove(v) self.assert_(len(values) == 0, "itervalues() did not touch all values") @@ -1058,7 +1072,7 @@ ... >>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable >>> r = weakref.ref(obj) ->>> print r() is obj +>>> print(r() is obj) True >>> import weakref @@ -1071,7 +1085,7 @@ >>> o is o2 True >>> del o, o2 ->>> print r() +>>> print(r()) None >>> import weakref @@ -1079,7 +1093,7 @@ ... def __init__(self, ob, callback=None, **annotations): ... super(ExtendedRef, self).__init__(ob, callback) ... self.__counter = 0 -... for k, v in annotations.iteritems(): +... for k, v in annotations.items(): ... setattr(self, k, v) ... def __call__(self): ... '''Return a pair containing the referent and the number of @@ -1090,7 +1104,7 @@ ... self.__counter += 1 ... ob = (ob, self.__counter) ... return ob -... +... >>> class A: # not in docs from here, just testing the ExtendedRef ... pass ... @@ -1126,9 +1140,9 @@ >>> try: ... id2obj(a_id) ... except KeyError: -... print 'OK' +... print('OK') ... else: -... print 'WeakValueDictionary error' +... print('WeakValueDictionary error') OK """ Modified: python/branches/p3yk-noslice/Lib/test/test_winreg.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_winreg.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_winreg.py Fri Feb 23 18:29:35 2007 @@ -133,7 +133,7 @@ # Test on my local machine. TestAll(HKEY_CURRENT_USER) -print "Local registry tests worked" +print("Local registry tests worked") try: remote_name = sys.argv[sys.argv.index("--remote")+1] except (IndexError, ValueError): @@ -143,14 +143,14 @@ try: remote_key = ConnectRegistry(remote_name, HKEY_CURRENT_USER) except EnvironmentError as exc: - print "Could not connect to the remote machine -", exc.strerror + print("Could not connect to the remote machine -", exc.strerror) remote_key = None if remote_key is not None: TestAll(remote_key) - print "Remote registry tests worked" + print("Remote registry tests worked") else: - print "Remote registry calls can be tested using", - print "'test_winreg.py --remote \\\\machine_name'" + print("Remote registry calls can be tested using", end=' ') + print("'test_winreg.py --remote \\\\machine_name'") # perform minimal ConnectRegistry test which just invokes it h = ConnectRegistry(None, HKEY_LOCAL_MACHINE) h.Close() Modified: python/branches/p3yk-noslice/Lib/test/test_with.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_with.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_with.py Fri Feb 23 18:29:35 2007 @@ -550,13 +550,13 @@ def testSingleComplexTarget(self): targets = {1: [0, 1, 2]} with mock_contextmanager_generator() as targets[1][0]: - self.assertEqual(targets.keys(), [1]) + self.assertEqual(list(targets.keys()), [1]) self.assertEqual(targets[1][0].__class__, MockResource) - with mock_contextmanager_generator() as targets.values()[0][1]: - self.assertEqual(targets.keys(), [1]) + with mock_contextmanager_generator() as list(targets.values())[0][1]: + self.assertEqual(list(targets.keys()), [1]) self.assertEqual(targets[1][1].__class__, MockResource) with mock_contextmanager_generator() as targets[2]: - keys = targets.keys() + keys = list(targets.keys()) keys.sort() self.assertEqual(keys, [1, 2]) class C: pass @@ -571,7 +571,7 @@ targets = {1: [0, 1, 2]} with C() as (targets[1][0], targets[1][1], targets[1][2]): self.assertEqual(targets, {1: [1, 2, 3]}) - with C() as (targets.values()[0][2], targets.values()[0][1], targets.values()[0][0]): + with C() as (list(targets.values())[0][2], list(targets.values())[0][1], list(targets.values())[0][0]): self.assertEqual(targets, {1: [3, 2, 1]}) with C() as (targets[1], targets[2], targets[3]): self.assertEqual(targets, {1: 1, 2: 2, 3: 3}) Modified: python/branches/p3yk-noslice/Lib/test/test_xdrlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_xdrlib.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_xdrlib.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_xml_etree.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_xml_etree.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_xml_etree.py Fri Feb 23 18:29:35 2007 @@ -37,7 +37,7 @@ def check_method(method): if not callable(method): - print method, "not callable" + print(method, "not callable") def serialize(ET, elem, encoding=None): import StringIO @@ -184,9 +184,9 @@ >>> element = ET.fromstring("text") >>> ET.ElementTree(element).write(sys.stdout) text - >>> print ET.tostring(element) + >>> print(ET.tostring(element)) text - >>> print ET.tostring(element, "ascii") + >>> print(ET.tostring(element, "ascii")) text >>> _, ids = ET.XMLID("text") @@ -301,7 +301,7 @@ >>> document = xinclude_loader("C1.xml") >>> ElementInclude.include(document, xinclude_loader) - >>> print serialize(ET, document) # C1 + >>> print(serialize(ET, document)) # C1

120 Mz is adequate for an average home user.

@@ -315,7 +315,7 @@ >>> document = xinclude_loader("C2.xml") >>> ElementInclude.include(document, xinclude_loader) - >>> print serialize(ET, document) # C2 + >>> print(serialize(ET, document)) # C2

This document has been accessed 324387 times.

@@ -325,7 +325,7 @@ >>> document = xinclude_loader("C3.xml") >>> ElementInclude.include(document, xinclude_loader) - >>> print serialize(ET, document) # C3 + >>> print(serialize(ET, document)) # C3

The following is the source of the "data.xml" resource:

<?xml version='1.0'?> Modified: python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py Fri Feb 23 18:29:35 2007 @@ -35,7 +35,7 @@ def check_method(method): if not callable(method): - print method, "not callable" + print(method, "not callable") def serialize(ET, elem, encoding=None): import StringIO @@ -176,9 +176,9 @@ >>> element = ET.fromstring("text") >>> ET.ElementTree(element).write(sys.stdout) text - >>> print ET.tostring(element) + >>> print(ET.tostring(element)) text - >>> print ET.tostring(element, "ascii") + >>> print(ET.tostring(element, "ascii")) text >>> _, ids = ET.XMLID("text") Modified: python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py Fri Feb 23 18:29:35 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] @@ -145,7 +145,7 @@ if not setdefaultencoding_existed: del sys.setdefaultencoding - items = d.items() + items = list(d.items()) if have_unicode: self.assertEquals(s, u"abc \x95") self.assert_(isinstance(s, unicode)) Modified: python/branches/p3yk-noslice/Lib/test/test_xrange.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_xrange.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_xrange.py Fri Feb 23 18:29:35 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-noslice/Lib/test/test_zipfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_zipfile.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_zipfile.py Fri Feb 23 18:29:35 2007 @@ -282,11 +282,11 @@ os.mkdir(TESTFN2) try: fp = open(os.path.join(TESTFN2, "mod1.py"), "w") - fp.write("print 42\n") + fp.write("print(42)\n") fp.close() fp = open(os.path.join(TESTFN2, "mod2.py"), "w") - fp.write("print 42 * 42\n") + fp.write("print(42 * 42)\n") fp.close() fp = open(os.path.join(TESTFN2, "mod2.txt"), "w") @@ -307,6 +307,28 @@ class OtherTests(unittest.TestCase): + def testCreateNonExistentFileForAppend(self): + if os.path.exists(TESTFN): + os.unlink(TESTFN) + + filename = 'testfile.txt' + content = 'hello, world. this is some content.' + + try: + zf = zipfile.ZipFile(TESTFN, 'a') + zf.writestr(filename, content) + zf.close() + except IOError: + self.fail('Could not append data to a non-existent zip file.') + + self.assert_(os.path.exists(TESTFN)) + + zf = zipfile.ZipFile(TESTFN, 'r') + self.assertEqual(zf.read(filename), content) + zf.close() + + os.unlink(TESTFN) + def testCloseErroneousFile(self): # This test checks that the ZipFile constructor closes the file object # it opens if there's an error in the file. If it doesn't, the traceback @@ -349,8 +371,49 @@ # and report that the first file in the archive was corrupt. self.assertRaises(RuntimeError, zipf.testzip) + +class DecryptionTests(unittest.TestCase): + # This test checks that ZIP decryption works. Since the library does not + # support encryption at the moment, we use a pre-generated encrypted + # ZIP file + + data = ( + 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00' + '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y' + '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl' + 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00' + '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81' + '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00' + '\x00\x00L\x00\x00\x00\x00\x00' ) + + plain = 'zipfile.py encryption test' + + def setUp(self): + fp = open(TESTFN, "wb") + fp.write(self.data) + fp.close() + self.zip = zipfile.ZipFile(TESTFN, "r") + + def tearDown(self): + self.zip.close() + os.unlink(TESTFN) + + def testNoPassword(self): + # Reading the encrypted file without password + # must generate a RunTime exception + self.assertRaises(RuntimeError, self.zip.read, "test.txt") + + def testBadPassword(self): + self.zip.setpassword("perl") + self.assertRaises(RuntimeError, self.zip.read, "test.txt") + + def testGoodPassword(self): + self.zip.setpassword("python") + self.assertEquals(self.zip.read("test.txt"), self.plain) + def test_main(): - run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, PyZipFileTests) + run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, + PyZipFileTests, DecryptionTests) #run_unittest(TestZip64InSmallFiles) if __name__ == "__main__": Modified: python/branches/p3yk-noslice/Lib/test/test_zipfile64.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_zipfile64.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_zipfile64.py Fri Feb 23 18:29:35 2007 @@ -57,9 +57,9 @@ # Print still working message since this test can be really slow if next_time <= time.time(): next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - print >>sys.__stdout__, ( + print(( ' zipTest still writing %d of %d, be patient...' % - (num, filecount)) + (num, filecount)), file=sys.__stdout__) sys.__stdout__.flush() zipfp.close() @@ -70,9 +70,9 @@ # Print still working message since this test can be really slow if next_time <= time.time(): next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - print >>sys.__stdout__, ( + print(( ' zipTest still reading %d of %d, be patient...' % - (num, filecount)) + (num, filecount)), file=sys.__stdout__) sys.__stdout__.flush() zipfp.close() Modified: python/branches/p3yk-noslice/Lib/test/test_zipimport.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_zipimport.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_zipimport.py Fri Feb 23 18:29:35 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(" 3: import _hashlib exec('creatorFunc = _hashlib.%s' % sys.argv[2]) - print "testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2]) + print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])) elif hName == '_hashlib' and len(sys.argv) == 3: import _hashlib exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2]) - print "testing speed of _hashlib.new(%r)" % sys.argv[2] + print("testing speed of _hashlib.new(%r)" % sys.argv[2]) elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)): creatorFunc = getattr(hashlib, hName) - print "testing speed of hashlib."+hName, getattr(hashlib, hName) + print("testing speed of hashlib."+hName, getattr(hashlib, hName)) else: exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName) - print "testing speed of hashlib.new(%r)" % hName + print("testing speed of hashlib.new(%r)" % hName) try: test_create() except ValueError: - print - print "pass argument(s) naming the hash to run a speed test on:" - print " '_md5' and '_sha' test the legacy builtin md5 and sha" - print " '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib" - print " '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)" - print " 'hName' tests the hashlib.hName() implementation if it exists" - print " otherwise it uses hashlib.new(hName)." - print + print() + print("pass argument(s) naming the hash to run a speed test on:") + print(" '_md5' and '_sha' test the legacy builtin md5 and sha") + print(" '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib") + print(" '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)") + print(" 'hName' tests the hashlib.hName() implementation if it exists") + print(" otherwise it uses hashlib.new(hName).") + print() raise test_zero() Modified: python/branches/p3yk-noslice/Lib/textwrap.py ============================================================================== --- python/branches/p3yk-noslice/Lib/textwrap.py (original) +++ python/branches/p3yk-noslice/Lib/textwrap.py Fri Feb 23 18:29:35 2007 @@ -371,4 +371,4 @@ if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") - print dedent("Hello there.\n This is indented.") + print(dedent("Hello there.\n This is indented.")) Modified: python/branches/p3yk-noslice/Lib/this.py ============================================================================== --- python/branches/p3yk-noslice/Lib/this.py (original) +++ python/branches/p3yk-noslice/Lib/this.py Fri Feb 23 18:29:35 2007 @@ -25,4 +25,4 @@ for i in range(26): d[chr(i+c)] = chr((i+13) % 26 + c) -print "".join([d.get(c, c) for c in s]) +print("".join([d.get(c, c) for c in s])) Modified: python/branches/p3yk-noslice/Lib/threading.py ============================================================================== --- python/branches/p3yk-noslice/Lib/threading.py (original) +++ python/branches/p3yk-noslice/Lib/threading.py Fri Feb 23 18:29:35 2007 @@ -477,19 +477,19 @@ # Lib/traceback.py) exc_type, exc_value, exc_tb = self.__exc_info() try: - print>>self.__stderr, ( + print(( "Exception in thread " + self.getName() + - " (most likely raised during interpreter shutdown):") - print>>self.__stderr, ( - "Traceback (most recent call last):") + " (most likely raised during interpreter shutdown):"), file=self.__stderr) + print(( + "Traceback (most recent call last):"), file=self.__stderr) while exc_tb: - print>>self.__stderr, ( + print(( ' File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, - exc_tb.tb_frame.f_code.co_name)) + exc_tb.tb_frame.f_code.co_name)), file=self.__stderr) exc_tb = exc_tb.tb_next - print>>self.__stderr, ("%s: %s" % (exc_type, exc_value)) + print(("%s: %s" % (exc_type, exc_value)), file=self.__stderr) # Make sure that exc_tb gets deleted since it is a memory # hog; deleting everything else is just for thoroughness finally: @@ -707,7 +707,7 @@ def enumerate(): _active_limbo_lock.acquire() - active = _active.values() + _limbo.values() + active = list(_active.values()) + list(_limbo.values()) _active_limbo_lock.release() return active @@ -790,7 +790,7 @@ def run(self): while self.count > 0: item = self.queue.get() - print item + print(item) self.count = self.count - 1 NP = 3 Modified: python/branches/p3yk-noslice/Lib/timeit.py ============================================================================== --- python/branches/p3yk-noslice/Lib/timeit.py (original) +++ python/branches/p3yk-noslice/Lib/timeit.py Fri Feb 23 18:29:35 2007 @@ -210,8 +210,8 @@ ["number=", "setup=", "repeat=", "time", "clock", "verbose", "help"]) except getopt.error as err: - print err - print "use -h/--help for command line help" + print(err) + print("use -h/--help for command line help") return 2 timer = default_timer stmt = "\n".join(args) or "pass" @@ -238,7 +238,7 @@ precision += 1 verbose += 1 if o in ("-h", "--help"): - print __doc__, + print(__doc__, end=' ') return 0 setup = "\n".join(setup) or "pass" # Include the current directory, so that local imports work (sys.path @@ -257,7 +257,7 @@ t.print_exc() return 1 if verbose: - print "%d loops -> %.*g secs" % (number, precision, x) + print("%d loops -> %.*g secs" % (number, precision, x)) if x >= 0.2: break try: @@ -267,18 +267,18 @@ return 1 best = min(r) if verbose: - print "raw times:", " ".join(["%.*g" % (precision, x) for x in r]) - print "%d loops," % number, + print("raw times:", " ".join(["%.*g" % (precision, x) for x in r])) + print("%d loops," % number, end=' ') usec = best * 1e6 / number if usec < 1000: - print "best of %d: %.*g usec per loop" % (repeat, precision, usec) + print("best of %d: %.*g usec per loop" % (repeat, precision, usec)) else: msec = usec / 1000 if msec < 1000: - print "best of %d: %.*g msec per loop" % (repeat, precision, msec) + print("best of %d: %.*g msec per loop" % (repeat, precision, msec)) else: sec = msec / 1000 - print "best of %d: %.*g sec per loop" % (repeat, precision, sec) + print("best of %d: %.*g sec per loop" % (repeat, precision, sec)) return None if __name__ == "__main__": Modified: python/branches/p3yk-noslice/Lib/token.py ============================================================================== --- python/branches/p3yk-noslice/Lib/token.py (original) +++ python/branches/p3yk-noslice/Lib/token.py Fri Feb 23 18:29:35 2007 @@ -68,7 +68,7 @@ #--end constants-- tok_name = {} -for _name, _value in globals().items(): +for _name, _value in list(globals().items()): if type(_value) is type(0): tok_name[_value] = _name Modified: python/branches/p3yk-noslice/Lib/tokenize.py ============================================================================== --- python/branches/p3yk-noslice/Lib/tokenize.py (original) +++ python/branches/p3yk-noslice/Lib/tokenize.py Fri Feb 23 18:29:35 2007 @@ -133,8 +133,8 @@ class StopTokenizing(Exception): pass def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing - print "%d,%d-%d,%d:\t%s\t%s" % \ - (srow, scol, erow, ecol, tok_name[type], repr(token)) + print("%d,%d-%d,%d:\t%s\t%s" % \ + (srow, scol, erow, ecol, tok_name[type], repr(token))) def tokenize(readline, tokeneater=printtoken): """ Modified: python/branches/p3yk-noslice/Lib/trace.py ============================================================================== --- python/branches/p3yk-noslice/Lib/trace.py (original) +++ python/branches/p3yk-noslice/Lib/trace.py Fri Feb 23 18:29:35 2007 @@ -221,8 +221,8 @@ pickle.load(open(self.infile, 'rb')) self.update(self.__class__(counts, calledfuncs, callers)) except (IOError, EOFError, ValueError) as err: - print >> sys.stderr, ("Skipping counts file %r: %s" - % (self.infile, err)) + print(("Skipping counts file %r: %s" + % (self.infile, err)), file=sys.stderr) def update(self, other): """Merge in the data from another CoverageResults""" @@ -247,30 +247,30 @@ @param coverdir """ if self.calledfuncs: - print - print "functions called:" + print() + print("functions called:") calls = self.calledfuncs.keys() calls.sort() for filename, modulename, funcname in calls: - print ("filename: %s, modulename: %s, funcname: %s" - % (filename, modulename, funcname)) + print(("filename: %s, modulename: %s, funcname: %s" + % (filename, modulename, funcname))) if self.callers: - print - print "calling relationships:" + print() + print("calling relationships:") calls = self.callers.keys() calls.sort() lastfile = lastcfile = "" for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls: if pfile != lastfile: - print - print "***", pfile, "***" + print() + print("***", pfile, "***") lastfile = pfile lastcfile = "" if cfile != pfile and lastcfile != cfile: - print " -->", cfile + print(" -->", cfile) lastcfile = cfile - print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc) + print(" %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)) # turn the counts data ("(filename, lineno) = count") into something # accessible on a per-file basis @@ -282,7 +282,7 @@ # accumulate summary info, if needed sums = {} - for filename, count in per_file.iteritems(): + for filename, count in per_file.items(): # skip some "files" we don't care about... if filename == "": continue @@ -318,10 +318,10 @@ if summary and sums: mods = sums.keys() mods.sort() - print "lines cov% module (path)" + print("lines cov% module (path)") for m in mods: n_lines, percent, modulename, filename = sums[m] - print "%5d %3d%% %s (%s)" % sums[m] + print("%5d %3d%% %s (%s)" % sums[m]) if self.outfile: # try and store counts and module info into self.outfile @@ -329,7 +329,7 @@ pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1) except IOError as err: - print >> sys.stderr, "Can't save counts files because %s" % err + print("Can't save counts files because %s" % err, file=sys.stderr) def write_results_file(self, path, lines, lnotab, lines_hit): """Return a coverage results file in path.""" @@ -337,8 +337,8 @@ try: outfile = open(path, "w") except IOError as err: - print >> sys.stderr, ("trace: Could not open %r for writing: %s" - "- skipping" % (path, err)) + print(("trace: Could not open %r for writing: %s" + "- skipping" % (path, err)), file=sys.stderr) return 0, 0 n_lines = 0 @@ -423,8 +423,8 @@ try: prog = open(filename, "rU").read() except IOError as err: - print >> sys.stderr, ("Not printing coverage data for %r: %s" - % (filename, err)) + print(("Not printing coverage data for %r: %s" + % (filename, err)), file=sys.stderr) return {} code = compile(prog, filename, "exec") strs = find_strings(filename) @@ -587,7 +587,7 @@ """ if why == 'call': code = frame.f_code - filename = code.co_filename + filename = frame.f_globals.get('__file__', None) if filename: # XXX modname() doesn't work right for packages, so # the ignore support won't work right for packages @@ -596,8 +596,8 @@ ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: - print (" --- modulename: %s, funcname: %s" - % (modulename, code.co_name)) + print((" --- modulename: %s, funcname: %s" + % (modulename, code.co_name))) return self.localtrace else: return None @@ -611,8 +611,8 @@ self.counts[key] = self.counts.get(key, 0) + 1 bname = os.path.basename(filename) - print "%s(%d): %s" % (bname, lineno, - linecache.getline(filename, lineno)), + print("%s(%d): %s" % (bname, lineno, + linecache.getline(filename, lineno)), end=' ') return self.localtrace def localtrace_trace(self, frame, why, arg): @@ -622,8 +622,8 @@ lineno = frame.f_lineno bname = os.path.basename(filename) - print "%s(%d): %s" % (bname, lineno, - linecache.getline(filename, lineno)), + print("%s(%d): %s" % (bname, lineno, + linecache.getline(filename, lineno)), end=' ') return self.localtrace def localtrace_count(self, frame, why, arg): Modified: python/branches/p3yk-noslice/Lib/types.py ============================================================================== --- python/branches/p3yk-noslice/Lib/types.py (original) +++ python/branches/p3yk-noslice/Lib/types.py Fri Feb 23 18:29:35 2007 @@ -14,7 +14,7 @@ ObjectType = object IntType = int -LongType = long +LongType = int FloatType = float BooleanType = bool try: Modified: python/branches/p3yk-noslice/Lib/unittest.py ============================================================================== --- python/branches/p3yk-noslice/Lib/unittest.py (original) +++ python/branches/p3yk-noslice/Lib/unittest.py Fri Feb 23 18:29:35 2007 @@ -759,8 +759,8 @@ self.runTests() def usageExit(self, msg=None): - if msg: print msg - print self.USAGE % self.__dict__ + if msg: print(msg) + print(self.USAGE % self.__dict__) sys.exit(2) def parseArgs(self, argv): Modified: python/branches/p3yk-noslice/Lib/urllib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/urllib.py (original) +++ python/branches/p3yk-noslice/Lib/urllib.py Fri Feb 23 18:29:35 2007 @@ -452,7 +452,7 @@ def open_local_file(self, url): """Use local file.""" - import mimetypes, mimetools, email.Utils + import mimetypes, mimetools, email.utils try: from cStringIO import StringIO except ImportError: @@ -464,7 +464,7 @@ 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) + modified = email.utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % @@ -777,7 +777,7 @@ (user, realm, host)) return user, passwd except KeyboardInterrupt: - print + print() return None, None @@ -1453,17 +1453,17 @@ uqs = unquote(qs) t1 = time.time() if uqs != s: - print 'Wrong!' - print repr(s) - print repr(qs) - print repr(uqs) - print round(t1 - t0, 3), 'sec' + print('Wrong!') + print(repr(s)) + print(repr(qs)) + print(repr(uqs)) + print(round(t1 - t0, 3), 'sec') def reporthook(blocknum, blocksize, totalsize): # Report during remote transfers - print "Block number: %d, Block size: %d, Total size: %d" % ( - blocknum, blocksize, totalsize) + print("Block number: %d, Block size: %d, Total size: %d" % ( + blocknum, blocksize, totalsize)) # Test program def test(args=[]): @@ -1480,22 +1480,22 @@ args.append('https://synergy.as.cmu.edu/~geek/') try: for url in args: - print '-'*10, url, '-'*10 + print('-'*10, url, '-'*10) fn, h = urlretrieve(url, None, reporthook) - print fn + print(fn) if h: - print '======' - for k in h.keys(): print k + ':', h[k] - print '======' + print('======') + for k in h.keys(): print(k + ':', h[k]) + print('======') fp = open(fn, 'rb') data = fp.read() del fp if '\r' in data: table = string.maketrans("", "") data = data.translate(table, "\r") - print data + print(data) fn, h = None, None - print '-'*40 + print('-'*40) finally: urlcleanup() @@ -1504,17 +1504,17 @@ try: opts, args = getopt.getopt(sys.argv[1:], "th") except getopt.error as msg: - print msg - print "Use -h for help" + print(msg) + print("Use -h for help") return t = 0 for o, a in opts: if o == '-t': t = t + 1 if o == '-h': - print "Usage: python urllib.py [-t] [url ...]" - print "-t runs self-test;", - print "otherwise, contents of urls are printed" + print("Usage: python urllib.py [-t] [url ...]") + print("-t runs self-test;", end=' ') + print("otherwise, contents of urls are printed") return if t: if t > 1: @@ -1522,9 +1522,9 @@ test(args) else: if not args: - print "Use -h for help" + print("Use -h for help") for url in args: - print urlopen(url).read(), + print(urlopen(url).read(), end=' ') # Run test program when run as a script if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/urllib2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/urllib2.py (original) +++ python/branches/p3yk-noslice/Lib/urllib2.py Fri Feb 23 18:29:35 2007 @@ -281,7 +281,7 @@ def header_items(self): hdrs = self.unredirected_hdrs.copy() hdrs.update(self.headers) - return hdrs.items() + return list(hdrs.items()) class OpenerDirector: def __init__(self): @@ -710,7 +710,7 @@ domains = self.passwd.get(realm, {}) for default_port in True, False: reduced_authuri = self.reduce_uri(authuri, default_port) - for uris, authinfo in domains.iteritems(): + for uris, authinfo in domains.items(): for uri in uris: if self.is_suburi(uri, reduced_authuri): return authinfo @@ -1087,7 +1087,7 @@ # out of socket._fileobject() and into a base class. r.recv = r.read - fp = socket._fileobject(r) + fp = socket._fileobject(r, close=True) resp = addinfourl(fp, r.msg, req.get_full_url()) resp.code = r.status @@ -1209,14 +1209,14 @@ # not entirely sure what the rules are here def open_local_file(self, req): - import email.Utils + import email.utils import mimetypes host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats.st_size - modified = email.Utils.formatdate(stats.st_mtime, usegmt=True) + modified = email.utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(file)[0] headers = mimetools.Message(StringIO( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % @@ -1318,21 +1318,21 @@ # first check for old ones t = time.time() if self.soonest <= t: - for k, v in self.timeout.items(): + for k, v in list(self.timeout.items()): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] - self.soonest = min(self.timeout.values()) + self.soonest = min(list(self.timeout.values())) # then check the size if len(self.cache) == self.max_conns: - for k, v in self.timeout.items(): + for k, v in list(self.timeout.items()): if v == self.soonest: del self.cache[k] del self.timeout[k] break - self.soonest = min(self.timeout.values()) + self.soonest = min(list(self.timeout.values())) class GopherHandler(BaseHandler): def gopher_open(self, req): Modified: python/branches/p3yk-noslice/Lib/urlparse.py ============================================================================== --- python/branches/p3yk-noslice/Lib/urlparse.py (original) +++ python/branches/p3yk-noslice/Lib/urlparse.py Fri Feb 23 18:29:35 2007 @@ -361,15 +361,15 @@ continue url = words[0] parts = urlparse(url) - print '%-10s : %s' % (url, parts) + print('%-10s : %s' % (url, parts)) abs = urljoin(base, url) if not base: base = abs wrapped = '' % abs - print '%-10s = %s' % (url, wrapped) + print('%-10s = %s' % (url, wrapped)) if len(words) == 3 and words[1] == '=': if wrapped != words[2]: - print 'EXPECTED', words[2], '!!!!!!!!!!' + print('EXPECTED', words[2], '!!!!!!!!!!') if __name__ == '__main__': test() Modified: python/branches/p3yk-noslice/Lib/uu.py ============================================================================== --- python/branches/p3yk-noslice/Lib/uu.py (original) +++ python/branches/p3yk-noslice/Lib/uu.py Fri Feb 23 18:29:35 2007 @@ -170,7 +170,7 @@ if isinstance(output, basestring): output = open(output, 'w') else: - print sys.argv[0], ': cannot do -t to stdout' + print(sys.argv[0], ': cannot do -t to stdout') sys.exit(1) decode(input, output) else: @@ -178,7 +178,7 @@ if isinstance(input, basestring): input = open(input, 'r') else: - print sys.argv[0], ': cannot do -t from stdin' + print(sys.argv[0], ': cannot do -t from stdin') sys.exit(1) encode(input, output) Modified: python/branches/p3yk-noslice/Lib/uuid.py ============================================================================== --- python/branches/p3yk-noslice/Lib/uuid.py (original) +++ python/branches/p3yk-noslice/Lib/uuid.py Fri Feb 23 18:29:35 2007 @@ -50,6 +50,8 @@ 'reserved for NCS compatibility', 'specified in RFC 4122', 'reserved for Microsoft compatibility', 'reserved for future definition'] +int_ = int # The built-in int function + class UUID(object): """Instances of the UUID class represent UUIDs as specified in RFC 4122. UUID objects are immutable, hashable, and usable as dictionary keys. @@ -132,7 +134,7 @@ hex = hex.strip('{}').replace('-', '') if len(hex) != 32: raise ValueError('badly formed hexadecimal UUID string') - int = long(hex, 16) + int = int_(hex, 16) if bytes_le is not None: if len(bytes_le) != 16: raise ValueError('bytes_le is not a 16-char string') @@ -142,39 +144,39 @@ if bytes is not None: if len(bytes) != 16: raise ValueError('bytes is not a 16-char string') - int = long(('%02x'*16) % tuple(map(ord, bytes)), 16) + int = int_(('%02x'*16) % tuple(map(ord, bytes)), 16) if fields is not None: if len(fields) != 6: raise ValueError('fields is not a 6-tuple') (time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node) = fields - if not 0 <= time_low < 1<<32L: + if not 0 <= time_low < 1<<32: raise ValueError('field 1 out of range (need a 32-bit value)') - if not 0 <= time_mid < 1<<16L: + if not 0 <= time_mid < 1<<16: raise ValueError('field 2 out of range (need a 16-bit value)') - if not 0 <= time_hi_version < 1<<16L: + if not 0 <= time_hi_version < 1<<16: raise ValueError('field 3 out of range (need a 16-bit value)') - if not 0 <= clock_seq_hi_variant < 1<<8L: + if not 0 <= clock_seq_hi_variant < 1<<8: raise ValueError('field 4 out of range (need an 8-bit value)') - if not 0 <= clock_seq_low < 1<<8L: + if not 0 <= clock_seq_low < 1<<8: raise ValueError('field 5 out of range (need an 8-bit value)') - if not 0 <= node < 1<<48L: + if not 0 <= node < 1<<48: raise ValueError('field 6 out of range (need a 48-bit value)') - clock_seq = (clock_seq_hi_variant << 8L) | clock_seq_low - int = ((time_low << 96L) | (time_mid << 80L) | - (time_hi_version << 64L) | (clock_seq << 48L) | node) + clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low + int = ((time_low << 96) | (time_mid << 80) | + (time_hi_version << 64) | (clock_seq << 48) | node) if int is not None: - if not 0 <= int < 1<<128L: + if not 0 <= int < 1<<128: raise ValueError('int is out of range (need a 128-bit value)') if version is not None: if not 1 <= version <= 5: raise ValueError('illegal version number') # Set the variant to RFC 4122. - int &= ~(0xc000 << 48L) - int |= 0x8000 << 48L + int &= ~(0xc000 << 48) + int |= 0x8000 << 48 # Set the version number. - int &= ~(0xf000 << 64L) - int |= version << 76L + int &= ~(0xf000 << 64) + int |= version << 76 self.__dict__['int'] = int def __eq__(self, other): @@ -248,38 +250,38 @@ fields = property(get_fields) def get_time_low(self): - return self.int >> 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-noslice/Lib/warnings.py ============================================================================== --- python/branches/p3yk-noslice/Lib/warnings.py (original) +++ python/branches/p3yk-noslice/Lib/warnings.py Fri Feb 23 18:29:35 2007 @@ -193,7 +193,7 @@ try: _setoption(arg) except _OptionError as msg: - print >>sys.stderr, "Invalid -W option ignored:", msg + print("Invalid -W option ignored:", msg, file=sys.stderr) # Helper for _processoptions() def _setoption(arg): Modified: python/branches/p3yk-noslice/Lib/weakref.py ============================================================================== --- python/branches/p3yk-noslice/Lib/weakref.py (original) +++ python/branches/p3yk-noslice/Lib/weakref.py Fri Feb 23 18:29:35 2007 @@ -100,16 +100,16 @@ return L def iteritems(self): - for wr in self.data.itervalues(): + for wr in self.data.values(): value = wr() if value is not None: yield wr.key, value def iterkeys(self): - return self.data.iterkeys() + return iter(self.data.keys()) def __iter__(self): - return self.data.iterkeys() + return iter(self.data.keys()) def itervaluerefs(self): """Return an iterator that yields the weak references to the values. @@ -121,10 +121,10 @@ keep the values around longer than needed. """ - return self.data.itervalues() + return self.data.values() def itervalues(self): - for wr in self.data.itervalues(): + for wr in self.data.values(): obj = wr() if obj is not None: yield obj @@ -268,7 +268,7 @@ return L def iteritems(self): - for wr, value in self.data.iteritems(): + for wr, value in self.data.items(): key = wr() if key is not None: yield key, value @@ -283,19 +283,19 @@ keep the keys around longer than needed. """ - return self.data.iterkeys() + return self.data.keys() def iterkeys(self): - for wr in self.data.iterkeys(): + for wr in self.data.keys(): obj = wr() if obj is not None: yield obj def __iter__(self): - return self.iterkeys() + return iter(self.keys()) def itervalues(self): - return self.data.itervalues() + return iter(self.data.values()) def keyrefs(self): """Return a list of weak references to the keys. Modified: python/branches/p3yk-noslice/Lib/webbrowser.py ============================================================================== --- python/branches/p3yk-noslice/Lib/webbrowser.py (original) +++ python/branches/p3yk-noslice/Lib/webbrowser.py Fri Feb 23 18:29:35 2007 @@ -626,21 +626,21 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'ntd') except getopt.error as msg: - print >>sys.stderr, msg - print >>sys.stderr, usage + print(msg, file=sys.stderr) + print(usage, file=sys.stderr) sys.exit(1) new_win = 0 for o, a in opts: if o == '-n': new_win = 1 elif o == '-t': new_win = 2 if len(args) != 1: - print >>sys.stderr, usage + print(usage, file=sys.stderr) sys.exit(1) url = args[0] open(url, new_win) - print "\a" + print("\a") if __name__ == "__main__": main() Modified: python/branches/p3yk-noslice/Lib/whichdb.py ============================================================================== --- python/branches/p3yk-noslice/Lib/whichdb.py (original) +++ python/branches/p3yk-noslice/Lib/whichdb.py Fri Feb 23 18:29:35 2007 @@ -114,4 +114,4 @@ if __name__ == "__main__": for filename in sys.argv[1:]: - print whichdb(filename) or "UNKNOWN", filename + print(whichdb(filename) or "UNKNOWN", filename) Modified: python/branches/p3yk-noslice/Lib/wsgiref/simple_server.py ============================================================================== --- python/branches/p3yk-noslice/Lib/wsgiref/simple_server.py (original) +++ python/branches/p3yk-noslice/Lib/wsgiref/simple_server.py Fri Feb 23 18:29:35 2007 @@ -165,11 +165,11 @@ def demo_app(environ,start_response): from StringIO import StringIO stdout = StringIO() - print >>stdout, "Hello world!" - print >>stdout + print("Hello world!", file=stdout) + print(file=stdout) h = environ.items(); h.sort() for k,v in h: - print >>stdout, k,'=',repr(v) + print(k,'=',repr(v), file=stdout) start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] @@ -186,7 +186,7 @@ if __name__ == '__main__': httpd = make_server('', 8000, demo_app) sa = httpd.socket.getsockname() - print "Serving HTTP on", sa[0], "port", sa[1], "..." + print("Serving HTTP on", sa[0], "port", sa[1], "...") import webbrowser webbrowser.open('http://localhost:8000/xyz?abc') httpd.handle_request() # serve one request, then exit Modified: python/branches/p3yk-noslice/Lib/xdrlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xdrlib.py (original) +++ python/branches/p3yk-noslice/Lib/xdrlib.py Fri Feb 23 18:29:35 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-noslice/Lib/xml/dom/NodeFilter.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xml/dom/NodeFilter.py (original) +++ python/branches/p3yk-noslice/Lib/xml/dom/NodeFilter.py Fri Feb 23 18:29:35 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-noslice/Lib/xml/dom/minidom.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xml/dom/minidom.py (original) +++ python/branches/p3yk-noslice/Lib/xml/dom/minidom.py Fri Feb 23 18:29:35 2007 @@ -256,7 +256,7 @@ def _call_user_data_handler(self, operation, src, dst): if hasattr(self, "_user_data"): - for key, (data, handler) in self._user_data.items(): + for key, (data, handler) in list(self._user_data.items()): if handler is not None: handler.handle(operation, key, data, src, dst) @@ -480,7 +480,7 @@ def item(self, index): try: - return self[self._attrs.keys()[index]] + return self[list(self._attrs.keys())[index]] except IndexError: return None @@ -672,7 +672,7 @@ return self.tagName def unlink(self): - for attr in self._attrs.values(): + for attr in list(self._attrs.values()): attr.unlink() self._attrs = None self._attrsNS = None @@ -805,8 +805,7 @@ writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() - a_names = attrs.keys() - a_names.sort() + a_names = sorted(attrs.keys()) for a_name in a_names: writer.write(" %s=\"" % a_name) Modified: python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py (original) +++ python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py Fri Feb 23 18:29:35 2007 @@ -201,7 +201,7 @@ class ErrorHandler: def warning(self, exception): - print exception + print(exception) def error(self, exception): raise exception def fatalError(self, exception): Modified: python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py (original) +++ python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py Fri Feb 23 18:29:35 2007 @@ -645,7 +645,7 @@ elif tag is ProcessingInstruction: file.write("" % _escape_cdata(node.text, encoding)) else: - items = node.items() + items = list(node.items()) xmlns_items = [] # new namespaces in this scope try: if isinstance(tag, QName) or tag[:1] == "{": Modified: python/branches/p3yk-noslice/Lib/xml/sax/handler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xml/sax/handler.py (original) +++ python/branches/p3yk-noslice/Lib/xml/sax/handler.py Fri Feb 23 18:29:35 2007 @@ -39,7 +39,7 @@ def warning(self, exception): "Handle a warning." - print exception + print(exception) # ===== CONTENTHANDLER ===== Modified: python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py (original) +++ python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py Fri Feb 23 18:29:35 2007 @@ -100,6 +100,17 @@ else: self._out.write(text.encode(self._encoding, _error_handling)) + def _qname(self, name): + """Builds a qualified name from a (ns_url, localname) pair""" + if name[0]: + # The name is in a non-empty namespace + prefix = self._current_context[name[0]] + if prefix: + # If it is not the default namespace, prepend the prefix + return prefix + ":" + name[1] + # Return the unqualified name + return name[1] + # ContentHandler methods def startDocument(self): @@ -125,29 +136,21 @@ self._write('' % name) def startElementNS(self, name, qname, attrs): - if name[0] is None: - # if the name was not namespace-scoped, use the unqualified part - name = name[1] - else: - # else try to restore the original prefix from the namespace - name = self._current_context[name[0]] + ":" + name[1] - self._write('<' + name) + self._write('<' + self._qname(name)) - for pair in self._undeclared_ns_maps: - self._write(' xmlns:%s="%s"' % pair) + for prefix, uri in self._undeclared_ns_maps: + if prefix: + self._out.write(' xmlns:%s="%s"' % (prefix, uri)) + else: + self._out.write(' xmlns="%s"' % uri) self._undeclared_ns_maps = [] for (name, value) in attrs.items(): - name = self._current_context[name[0]] + ":" + name[1] - self._write(' %s=%s' % (name, quoteattr(value))) + self._write(' %s=%s' % (self._qname(name), quoteattr(value))) self._write('>') def endElementNS(self, name, qname): - if name[0] is None: - name = name[1] - else: - name = self._current_context[name[0]] + ":" + name[1] - self._write('' % name) + self._write('' % self._qname(name)) def characters(self, content): self._write(escape(content)) Modified: python/branches/p3yk-noslice/Lib/xml/sax/xmlreader.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xml/sax/xmlreader.py (original) +++ python/branches/p3yk-noslice/Lib/xml/sax/xmlreader.py Fri Feb 23 18:29:35 2007 @@ -304,10 +304,10 @@ return name def getNames(self): - return self._attrs.keys() + return list(self._attrs.keys()) def getQNames(self): - return self._attrs.keys() + return list(self._attrs.keys()) def __len__(self): return len(self._attrs) @@ -316,7 +316,7 @@ return self._attrs[name] def keys(self): - return self._attrs.keys() + return list(self._attrs.keys()) def __contains__(self, name): return name in self._attrs @@ -328,10 +328,10 @@ return self.__class__(self._attrs) def items(self): - return self._attrs.items() + return list(self._attrs.items()) def values(self): - return self._attrs.values() + return list(self._attrs.values()) # ===== ATTRIBUTESNSIMPL ===== @@ -363,7 +363,7 @@ return self._qnames[name] def getQNames(self): - return self._qnames.values() + return list(self._qnames.values()) def copy(self): return self.__class__(self._attrs, self._qnames) Modified: python/branches/p3yk-noslice/Lib/xmllib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xmllib.py (original) +++ python/branches/p3yk-noslice/Lib/xmllib.py Fri Feb 23 18:29:35 2007 @@ -809,11 +809,11 @@ def handle_xml(self, encoding, standalone): self.flush() - print 'xml: encoding =',encoding,'standalone =',standalone + print('xml: encoding =',encoding,'standalone =',standalone) def handle_doctype(self, tag, pubid, syslit, data): self.flush() - print 'DOCTYPE:',tag, repr(data) + print('DOCTYPE:',tag, repr(data)) def handle_data(self, data): self.testdata = self.testdata + data @@ -824,47 +824,47 @@ data = self.testdata if data: self.testdata = "" - print 'data:', repr(data) + print('data:', repr(data)) def handle_cdata(self, data): self.flush() - print 'cdata:', repr(data) + print('cdata:', repr(data)) def handle_proc(self, name, data): self.flush() - print 'processing:',name,repr(data) + print('processing:',name,repr(data)) def handle_comment(self, data): self.flush() r = repr(data) if len(r) > 68: r = r[:32] + '...' + r[-32:] - print 'comment:', r + print('comment:', r) def syntax_error(self, message): - print 'error at line %d:' % self.lineno, message + print('error at line %d:' % self.lineno, message) def unknown_starttag(self, tag, attrs): self.flush() if not attrs: - print 'start tag: <' + tag + '>' + print('start tag: <' + tag + '>') else: - print 'start tag: <' + tag, + print('start tag: <' + tag, end=' ') for name, value in attrs.items(): - print name + '=' + '"' + value + '"', - print '>' + print(name + '=' + '"' + value + '"', end=' ') + print('>') def unknown_endtag(self, tag): self.flush() - print 'end tag: ' + print('end tag: ') def unknown_entityref(self, ref): self.flush() - print '*** unknown entity ref: &' + ref + ';' + print('*** unknown entity ref: &' + ref + ';') def unknown_charref(self, ref): self.flush() - print '*** unknown char ref: &#' + ref + ';' + print('*** unknown char ref: &#' + ref + ';') def close(self): XMLParser.close(self) @@ -897,7 +897,7 @@ try: f = open(file, 'r') except IOError as msg: - print file, ":", msg + print(file, ":", msg) sys.exit(1) data = f.read() @@ -916,13 +916,13 @@ x.close() except Error as msg: t1 = time() - print msg + print(msg) if do_time: - print 'total time: %g' % (t1-t0) + print('total time: %g' % (t1-t0)) sys.exit(1) t1 = time() if do_time: - print 'total time: %g' % (t1-t0) + print('total time: %g' % (t1-t0)) if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Lib/xmlrpclib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xmlrpclib.py (original) +++ python/branches/p3yk-noslice/Lib/xmlrpclib.py Fri Feb 23 18:29:35 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 @@ -1310,7 +1310,7 @@ if not response: break if self.verbose: - print "body:", repr(response) + print("body:", repr(response)) p.feed(response) file.close() @@ -1450,18 +1450,18 @@ # server = ServerProxy("http://localhost:8000") # local server server = ServerProxy("http://time.xmlrpc.com/RPC2") - print server + print(server) try: - print server.currentTime.getCurrentTime() + print(server.currentTime.getCurrentTime()) except Error as v: - print "ERROR", v + print("ERROR", v) multi = MultiCall(server) multi.currentTime.getCurrentTime() multi.currentTime.getCurrentTime() try: for response in multi(): - print response + print(response) except Error as v: - print "ERROR", v + print("ERROR", v) Modified: python/branches/p3yk-noslice/Lib/zipfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/zipfile.py (original) +++ python/branches/p3yk-noslice/Lib/zipfile.py Fri Feb 23 18:29:35 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 @@ -296,6 +296,65 @@ extra = extra[ln+4:] +class _ZipDecrypter: + """Class to handle decryption of files stored within a ZIP archive. + + ZIP supports a password-based form of encryption. Even though known + plaintext attacks have been found against it, it is still useful + for low-level securicy. + + Usage: + zd = _ZipDecrypter(mypwd) + plain_char = zd(cypher_char) + plain_text = map(zd, cypher_text) + """ + + def _GenerateCRCTable(): + """Generate a CRC-32 table. + + ZIP encryption uses the CRC32 one-byte primitive for scrambling some + internal keys. We noticed that a direct implementation is faster than + relying on binascii.crc32(). + """ + poly = 0xedb88320 + table = [0] * 256 + for i in range(256): + crc = i + for j in range(8): + if crc & 1: + crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly + else: + crc = ((crc >> 1) & 0x7FFFFFFF) + table[i] = crc + return table + crctable = _GenerateCRCTable() + + def _crc32(self, ch, crc): + """Compute the CRC32 primitive on one byte.""" + return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] + + def __init__(self, pwd): + self.key0 = 305419896 + self.key1 = 591751049 + self.key2 = 878082192 + for p in pwd: + self._UpdateKeys(p) + + def _UpdateKeys(self, c): + self.key0 = self._crc32(c, self.key0) + self.key1 = (self.key1 + (self.key0 & 255)) & 4294967295 + self.key1 = (self.key1 * 134775813 + 1) & 4294967295 + self.key2 = self._crc32(chr((self.key1 >> 24) & 255), self.key2) + + def __call__(self, c): + """Decrypt a single character.""" + c = ord(c) + k = self.key2 | 2 + c = c ^ (((k * (k^1)) >> 8) & 255) + c = chr(c) + self._UpdateKeys(c) + return c + class ZipFile: """ Class with methods to open, read, write, close, list zip files. @@ -330,13 +389,21 @@ self.filelist = [] # List of ZipInfo instances for archive self.compression = compression # Method of compression self.mode = key = mode.replace('b', '')[0] + self.pwd = None # Check if we were passed a file-like object if isinstance(file, basestring): self._filePassed = 0 self.filename = file modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'} - self.fp = open(file, modeDict[mode]) + try: + self.fp = open(file, modeDict[mode]) + except IOError: + if mode == 'a': + mode = key = 'w' + self.fp = open(file, modeDict[mode]) + else: + raise else: self._filePassed = 1 self.fp = file @@ -377,7 +444,7 @@ if not endrec: raise BadZipfile, "File is not a zip file" if self.debug > 1: - print endrec + print(endrec) size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory self.comment = endrec[8] # archive comment @@ -389,7 +456,7 @@ # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: - print "given, inferred, offset", offset_cd, x, concat + print("given, inferred, offset", offset_cd, x, concat) # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) @@ -403,7 +470,7 @@ raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: - print centdir + print(centdir) filename = fp.read(centdir[_CD_FILENAME_LENGTH]) # Create ZipInfo instance to store file information x = ZipInfo(filename) @@ -426,7 +493,7 @@ self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: - print "total", total + print("total", total) def namelist(self): @@ -443,10 +510,10 @@ def printdir(self): """Print a table of contents for the zip file.""" - print "%-46s %19s %12s" % ("File Name", "Modified ", "Size") + print("%-46s %19s %12s" % ("File Name", "Modified ", "Size")) for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time - print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size) + print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)) def testzip(self): """Read all the files and check the CRC.""" @@ -461,7 +528,11 @@ """Return the instance of ZipInfo given 'name'.""" return self.NameToInfo[name] - def read(self, name): + def setpassword(self, pwd): + """Set default password for encrypted files.""" + self.pwd = pwd + + def read(self, name, pwd=None): """Return file bytes (as a string) for name.""" if self.mode not in ("r", "a"): raise RuntimeError, 'read() requires mode "r" or "a"' @@ -469,6 +540,13 @@ raise RuntimeError, \ "Attempt to read ZIP archive that was already closed" zinfo = self.getinfo(name) + is_encrypted = zinfo.flag_bits & 0x1 + if is_encrypted: + if not pwd: + pwd = self.pwd + if not pwd: + raise RuntimeError, "File %s is encrypted, " \ + "password required for extraction" % name filepos = self.fp.tell() self.fp.seek(zinfo.header_offset, 0) @@ -489,6 +567,18 @@ zinfo.orig_filename, fname) bytes = self.fp.read(zinfo.compress_size) + # Go with decryption + if is_encrypted: + zd = _ZipDecrypter(pwd) + # The first 12 bytes in the cypher stream is an encryption header + # used to strengthen the algorithm. The first 11 bytes are + # completely random, while the 12th contains the MSB of the CRC, + # and is used to check the correctness of the password. + h = map(zd, bytes[0:12]) + if ord(h[11]) != ((zinfo.CRC>>24)&255): + raise RuntimeError, "Bad password for file %s" % name + bytes = "".join(map(zd, bytes[12:])) + # Go with decompression self.fp.seek(filepos, 0) if zinfo.compress_type == ZIP_STORED: pass @@ -516,7 +606,7 @@ """Check for errors before writing a file to the archive.""" if zinfo.filename in self.NameToInfo: if self.debug: # Warning for duplicate names - print "Duplicate name:", zinfo.filename + print("Duplicate name:", zinfo.filename) if self.mode not in ("w", "a"): raise RuntimeError, 'write() requires mode "w" or "a"' if not self.fp: @@ -548,7 +638,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: @@ -749,10 +839,10 @@ else: basename = name if self.debug: - print "Adding package in", pathname, "as", basename + print("Adding package in", pathname, "as", basename) fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: - print "Adding", arcname + print("Adding", arcname) self.write(fname, arcname) dirlist = os.listdir(pathname) dirlist.remove("__init__.py") @@ -768,12 +858,12 @@ fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: - print "Adding", arcname + print("Adding", arcname) self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: - print "Adding files from directory", pathname + print("Adding files from directory", pathname) for filename in os.listdir(pathname): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) @@ -781,7 +871,7 @@ fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: - print "Adding", arcname + print("Adding", arcname) self.write(fname, arcname) else: if pathname[-3:] != ".py": @@ -789,7 +879,7 @@ 'Files added with writepy() must end with ".py"' fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: - print "Adding file", arcname + print("Adding file", arcname) self.write(fname, arcname) def _get_codename(self, pathname, basename): @@ -809,11 +899,11 @@ os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime: import py_compile if self.debug: - print "Compiling", file_py + print("Compiling", file_py) try: py_compile.compile(file_py, file_pyc, None, True) except py_compile.PyCompileError as err: - print err.msg + print(err.msg) fname = file_pyc else: fname = file_pyc @@ -836,12 +926,12 @@ args = sys.argv[1:] if not args or args[0] not in ('-l', '-c', '-e', '-t'): - print USAGE + print(USAGE) sys.exit(1) if args[0] == '-l': if len(args) != 2: - print USAGE + print(USAGE) sys.exit(1) zf = ZipFile(args[1], 'r') zf.printdir() @@ -849,15 +939,15 @@ elif args[0] == '-t': if len(args) != 2: - print USAGE + print(USAGE) sys.exit(1) zf = ZipFile(args[1], 'r') zf.testzip() - print "Done testing" + print("Done testing") elif args[0] == '-e': if len(args) != 3: - print USAGE + print(USAGE) sys.exit(1) zf = ZipFile(args[1], 'r') @@ -878,7 +968,7 @@ elif args[0] == '-c': if len(args) < 3: - print USAGE + print(USAGE) sys.exit(1) def addToZip(zf, path, zippath): Modified: python/branches/p3yk-noslice/Makefile.pre.in ============================================================================== --- python/branches/p3yk-noslice/Makefile.pre.in (original) +++ python/branches/p3yk-noslice/Makefile.pre.in Fri Feb 23 18:29:35 2007 @@ -341,7 +341,7 @@ $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) platform: $(BUILDPYTHON) - $(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from distutils.util import get_platform ; print get_platform()+"-"+sys.version[0:3]' >platform + $(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from distutils.util import get_platform ; print(get_platform()+"-"+sys.version[0:3])' >platform # Build the shared modules @@ -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-noslice/Misc/ACKS ============================================================================== --- python/branches/p3yk-noslice/Misc/ACKS (original) +++ python/branches/p3yk-noslice/Misc/ACKS Fri Feb 23 18:29:35 2007 @@ -377,6 +377,7 @@ Kip Lehman Joerg Lehmann Marc-Andre Lemburg +Mark Levinson William Lewis Robert van Liere Martin Ligr @@ -521,6 +522,7 @@ Nicholas Riley Jean-Claude Rimbault Anthony Roach +Mark Roberts Andy Robinson Jim Robinson Kevin Rodgers Modified: python/branches/p3yk-noslice/Misc/NEWS ============================================================================== --- python/branches/p3yk-noslice/Misc/NEWS (original) +++ python/branches/p3yk-noslice/Misc/NEWS Fri Feb 23 18:29:35 2007 @@ -14,28 +14,42 @@ - See PEP 3000, 3100. -- Test merging certain changes from the 2.5 HEAD code. - - Weed really old/weird stuff from the library. - Unify range() and xrange(). -- Revamp the dict API: keys(), values(), items() return iterators, etc. - -- Add the bytes type. - - Rework the standard I/O library to use bytes for binary files. - Make strings all Unicode. -- Get rid of classic class implementation. - - Get rid of various compatibility-related flags (e.g. division flags). Core and Builtins ----------------- +- PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone; + and .keys(), .items(), .values() return dict views. + +- PEP 3105: print is now a function. Also (not in the PEP) the + 'softspace' attribute of files is now gone (since print() doesn't use + it). A side effect of this change is that you can get incomplete + output lines in interactive sessions: + + >>> print(42, end="") + 42>>> + + We may be able to fix this after the I/O library rewrite. + +- PEP 3102: keyword-only arguments. + +- Int/Long unification is 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. + - Added function annotations per PEP 3107. - Moved intern() to sys.intern(). Modified: python/branches/p3yk-noslice/Modules/_csv.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_csv.c (original) +++ python/branches/p3yk-noslice/Modules/_csv.c Fri Feb 23 18:29:35 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-noslice/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c (original) +++ python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c Fri Feb 23 18:29:35 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"); @@ -4979,7 +4979,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-noslice/Modules/_ctypes/_ctypes_test.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_ctypes/_ctypes_test.c (original) +++ python/branches/p3yk-noslice/Modules/_ctypes/_ctypes_test.c Fri Feb 23 18:29:35 2007 @@ -68,22 +68,25 @@ EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d) { -// printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", -// b, h, i, l, f, d); +/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ return (int)(b + h + i + l + f + d); } EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d) { -// printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", -// b, h, i, l, f, d); +/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ return (float)(b + h + i + l + f + d); } EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d) { -// printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", -// b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ return (double)(b + h + i + l + f + d); } @@ -378,8 +381,9 @@ } PyMethodDef module_methods[] = { -// {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, -// {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, + {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +*/ {"func_si", py_func_si, METH_VARARGS}, {"func", py_func, METH_NOARGS}, { NULL, NULL, 0, NULL}, Modified: python/branches/p3yk-noslice/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_ctypes/callproc.c (original) +++ python/branches/p3yk-noslice/Modules/_ctypes/callproc.c Fri Feb 23 18:29:35 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-noslice/Modules/_ctypes/cfield.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_ctypes/cfield.c (original) +++ python/branches/p3yk-noslice/Modules/_ctypes/cfield.c Fri Feb 23 18:29:35 2007 @@ -1432,10 +1432,19 @@ #endif #ifdef MS_WIN32 +/* We cannot use SysFreeString as the PyCObject_FromVoidPtr + because of different calling convention +*/ +static void _my_SysFreeString(void *p) +{ + SysFreeString((BSTR)p); +} + static PyObject * BSTR_set(void *ptr, PyObject *value, unsigned size) { BSTR bstr; + PyObject *result; /* convert value into a PyUnicodeObject or NULL */ if (Py_None == value) { @@ -1463,15 +1472,19 @@ } else bstr = NULL; - /* free the previous contents, if any */ - if (*(BSTR *)ptr) - SysFreeString(*(BSTR *)ptr); - - /* and store it */ - *(BSTR *)ptr = bstr; + if (bstr) { + result = PyCObject_FromVoidPtr((void *)bstr, _my_SysFreeString); + if (result == NULL) { + SysFreeString(bstr); + return NULL; + } + } else { + result = Py_None; + Py_INCREF(result); + } - /* We don't need to keep any other object */ - _RET(value); + *(BSTR *)ptr = bstr; + return result; } Modified: python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffi.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffi.c (original) +++ python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffi.c Fri Feb 23 18:29:35 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-noslice/Modules/_cursesmodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_cursesmodule.c (original) +++ python/branches/p3yk-noslice/Modules/_cursesmodule.c Fri Feb 23 18:29:35 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-noslice/Modules/_randommodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_randommodule.c (original) +++ python/branches/p3yk-noslice/Modules/_randommodule.c Fri Feb 23 18:29:35 2007 @@ -481,7 +481,7 @@ RandomObject *self; PyObject *tmp; - if (!_PyArg_NoKeywords("Random()", kwds)) + if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds)) return NULL; self = (RandomObject *)type->tp_alloc(type, 0); Modified: python/branches/p3yk-noslice/Modules/_sqlite/cache.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/cache.c (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/cache.c Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/cache.h ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/cache.h (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/cache.h Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/connection.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/connection.c (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/connection.c Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/connection.h ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/connection.h (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/connection.h Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/cursor.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/cursor.c (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/cursor.c Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/cursor.h ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/cursor.h (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/cursor.h Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/microprotocols.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.c (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.c Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/microprotocols.h ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.h (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.h Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/module.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/module.c (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/module.c Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/module.h ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/module.h (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/module.h Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/prepare_protocol.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.c (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.c Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/prepare_protocol.h ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.h (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.h Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/row.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/row.c (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/row.c Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/row.h ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/row.h (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/row.h Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/statement.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/statement.c (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/statement.c Fri Feb 23 18:29:35 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; @@ -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 @@ -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-noslice/Modules/_sqlite/statement.h ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/statement.h (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/statement.h Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/util.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/util.c (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/util.c Fri Feb 23 18:29:35 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-noslice/Modules/_sqlite/util.h ============================================================================== --- python/branches/p3yk-noslice/Modules/_sqlite/util.h (original) +++ python/branches/p3yk-noslice/Modules/_sqlite/util.h Fri Feb 23 18:29:35 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-noslice/Modules/_sre.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_sre.c (original) +++ python/branches/p3yk-noslice/Modules/_sre.c Fri Feb 23 18:29:35 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-noslice/Modules/_struct.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_struct.c (original) +++ python/branches/p3yk-noslice/Modules/_struct.c Fri Feb 23 18:29:35 2007 @@ -104,6 +104,15 @@ #define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG)) #endif +#ifdef HAVE_C99_BOOL +#define BOOL_TYPE _Bool +typedef struct { char c; _Bool x; } s_bool; +#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE)) +#else +#define BOOL_TYPE char +#define BOOL_ALIGN 0 +#endif + #define STRINGIFY(x) #x #ifdef __powerc @@ -118,8 +127,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; @@ -536,6 +543,15 @@ #endif static PyObject * +nu_bool(const char *p, const formatdef *f) +{ + BOOL_TYPE x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); +} + + +static PyObject * nu_float(const char *p, const formatdef *f) { float x; @@ -711,6 +727,16 @@ } #endif + +static int +np_bool(char *p, PyObject *v, const formatdef *f) +{ + BOOL_TYPE y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; +} + static int np_float(char *p, PyObject *v, const formatdef *f) { @@ -771,6 +797,7 @@ {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, #endif + {'t', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, @@ -865,6 +892,14 @@ return unpack_double(p, 0); } +static PyObject * +bu_bool(const char *p, const formatdef *f) +{ + char x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); +} + static int bp_int(char *p, PyObject *v, const formatdef *f) { @@ -969,6 +1004,15 @@ return _PyFloat_Pack8(x, (unsigned char *)p, 0); } +static int +bp_bool(char *p, PyObject *v, const formatdef *f) +{ + char y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; +} + static formatdef bigendian_table[] = { {'x', 1, 0, NULL}, #ifdef PY_STRUCT_OVERFLOW_MASKING @@ -990,6 +1034,7 @@ {'L', 4, 0, bu_uint, bp_uint}, {'q', 8, 0, bu_longlong, bp_longlong}, {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, + {'t', 1, 0, bu_bool, bp_bool}, {'f', 4, 0, bu_float, bp_float}, {'d', 8, 0, bu_double, bp_double}, {0} @@ -1208,6 +1253,8 @@ {'L', 4, 0, lu_uint, lp_uint}, {'q', 8, 0, lu_longlong, lp_longlong}, {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, + {'t', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, + but potentially different from native rep -- reuse bx_bool funcs. */ {'f', 4, 0, lu_float, lp_float}, {'d', 8, 0, lu_double, lp_double}, {0} Modified: python/branches/p3yk-noslice/Modules/_testcapimodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_testcapimodule.c (original) +++ python/branches/p3yk-noslice/Modules/_testcapimodule.c Fri Feb 23 18:29:35 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-noslice/Modules/_tkinter.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_tkinter.c (original) +++ python/branches/p3yk-noslice/Modules/_tkinter.c Fri Feb 23 18:29:35 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-noslice/Modules/arraymodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/arraymodule.c (original) +++ python/branches/p3yk-noslice/Modules/arraymodule.c Fri Feb 23 18:29:35 2007 @@ -1846,7 +1846,7 @@ PyObject *initial = NULL, *it = NULL; struct arraydescr *descr; - if (!_PyArg_NoKeywords("array.array()", kwds)) + if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds)) return NULL; if (!PyArg_ParseTuple(args, "c|O:array", &c, &initial)) Modified: python/branches/p3yk-noslice/Modules/bz2module.c ============================================================================== --- python/branches/p3yk-noslice/Modules/bz2module.c (original) +++ python/branches/p3yk-noslice/Modules/bz2module.c Fri Feb 23 18:29:35 2007 @@ -102,8 +102,6 @@ char* f_bufend; /* Points after last occupied position */ char* f_bufptr; /* Current buffer position */ - int f_softspace; /* Flag used by 'print' command */ - int f_univ_newline; /* Handle any newline convention */ int f_newlinetypes; /* Types of newlines seen */ int f_skipnextlf; /* Skip next \n */ @@ -813,8 +811,6 @@ goto cleanup; } - self->f_softspace = 0; - Py_BEGIN_ALLOW_THREADS BZ2_bzWrite (&bzerror, self->fp, buf, len); self->pos += len; @@ -934,8 +930,6 @@ } } - self->f_softspace = 0; - /* Since we are releasing the global lock, the following code may *not* execute Python code. */ Py_BEGIN_ALLOW_THREADS @@ -1265,18 +1259,6 @@ /* ===================================================================== */ -/* Members of BZ2File_Type. */ - -#undef OFF -#define OFF(x) offsetof(BZ2FileObject, x) - -static PyMemberDef BZ2File_members[] = { - {"softspace", T_INT, OFF(f_softspace), 0, - "flag indicating that a space needs to be printed; used by print"}, - {NULL} /* Sentinel */ -}; - -/* ===================================================================== */ /* Slot definitions for BZ2File_Type. */ static int @@ -1501,7 +1483,7 @@ (getiterfunc)BZ2File_getiter, /*tp_iter*/ (iternextfunc)BZ2File_iternext, /*tp_iternext*/ BZ2File_methods, /*tp_methods*/ - BZ2File_members, /*tp_members*/ + 0, /*tp_members*/ BZ2File_getset, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ Modified: python/branches/p3yk-noslice/Modules/cPickle.c ============================================================================== --- python/branches/p3yk-noslice/Modules/cPickle.c (original) +++ python/branches/p3yk-noslice/Modules/cPickle.c Fri Feb 23 18:29:35 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; @@ -1744,7 +1752,7 @@ int res = -1; char s[3]; int len; - PyObject *iter; + PyObject *items, *iter; if (self->fast && !fast_save_enter(self, args)) goto finally; @@ -1776,7 +1784,11 @@ goto finally; /* Materialize the dict items. */ - iter = PyObject_CallMethod(args, "iteritems", "()"); + items = PyObject_CallMethod(args, "items", "()"); + if (items == NULL) + goto finally; + iter = PyObject_GetIter(items); + Py_DECREF(items); if (iter == NULL) goto finally; res = batch_dict(self, iter); @@ -2184,13 +2196,6 @@ } 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); goto finally; @@ -2486,7 +2491,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 +2513,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 +2544,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 +2561,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-noslice/Modules/cStringIO.c ============================================================================== --- python/branches/p3yk-noslice/Modules/cStringIO.c (original) +++ python/branches/p3yk-noslice/Modules/cStringIO.c Fri Feb 23 18:29:35 2007 @@ -57,7 +57,6 @@ Py_ssize_t pos, string_size; Py_ssize_t buf_size; - int softspace; } Oobject; /* Declarations for objects of type StringI */ @@ -489,13 +488,6 @@ {NULL, NULL} /* sentinel */ }; -static PyMemberDef O_memberlist[] = { - {"softspace", T_INT, offsetof(Oobject, softspace), 0, - "flag indicating that a space needs to be printed; used by print"}, - /* getattr(f, "closed") is implemented without this table */ - {NULL} /* Sentinel */ -}; - static void O_dealloc(Oobject *self) { if (self->buf != NULL) @@ -536,7 +528,7 @@ PyObject_SelfIter, /*tp_iter */ (iternextfunc)IO_iternext, /*tp_iternext */ O_methods, /*tp_methods */ - O_memberlist, /*tp_members */ + 0, /*tp_members */ file_getsetlist, /*tp_getset */ }; @@ -549,7 +541,6 @@ return NULL; self->pos=0; self->string_size = 0; - self->softspace = 0; self->buf = (char *)malloc(size); if (!self->buf) { Modified: python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c ============================================================================== --- python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c (original) +++ python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c Fri Feb 23 18:29:35 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-noslice/Modules/collectionsmodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/collectionsmodule.c (original) +++ python/branches/p3yk-noslice/Modules/collectionsmodule.c Fri Feb 23 18:29:35 2007 @@ -95,7 +95,7 @@ dequeobject *deque; block *b; - if (!_PyArg_NoKeywords("deque()", kwds)) + if (type == &deque_type && !_PyArg_NoKeywords("deque()", kwds)) return NULL; /* create dequeobject structure */ @@ -1140,6 +1140,7 @@ */ PyObject *args; PyObject *items; + PyObject *iteritems; PyObject *result; if (dd->default_factory == NULL || dd->default_factory == Py_None) args = PyTuple_New(0); @@ -1147,14 +1148,20 @@ args = PyTuple_Pack(1, dd->default_factory); if (args == NULL) return NULL; - items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()"); + items = PyObject_CallMethod((PyObject *)dd, "items", "()"); if (items == NULL) { Py_DECREF(args); return NULL; } - result = PyTuple_Pack(5, dd->dict.ob_type, args, - Py_None, Py_None, items); + iteritems = PyObject_GetIter(items); Py_DECREF(items); + if (iteritems == NULL) { + Py_DECREF(args); + return NULL; + } + result = PyTuple_Pack(5, dd->dict.ob_type, args, + Py_None, Py_None, iteritems); + Py_DECREF(iteritems); Py_DECREF(args); return result; } @@ -1252,8 +1259,14 @@ newargs = PyTuple_New(0); else { Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n > 0) + if (n > 0) { newdefault = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(newdefault)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return -1; + } + } newargs = PySequence_GetSlice(args, 1, n); } if (newargs == NULL) Modified: python/branches/p3yk-noslice/Modules/datetimemodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/datetimemodule.c (original) +++ python/branches/p3yk-noslice/Modules/datetimemodule.c Fri Feb 23 18:29:35 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); @@ -3141,7 +3138,7 @@ } static PyObject * -time_isoformat(PyDateTime_Time *self) +time_isoformat(PyDateTime_Time *self, PyObject *unused) { char buf[100]; PyObject *result; @@ -3377,7 +3374,7 @@ static PyMethodDef time_methods[] = { - {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, + {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" "[+HH:MM].")}, @@ -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-noslice/Modules/dlmodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/dlmodule.c (original) +++ python/branches/p3yk-noslice/Modules/dlmodule.c Fri Feb 23 18:29:35 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-noslice/Modules/itertoolsmodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/itertoolsmodule.c (original) +++ python/branches/p3yk-noslice/Modules/itertoolsmodule.c Fri Feb 23 18:29:35 2007 @@ -681,7 +681,7 @@ PyObject *saved; cycleobject *lz; - if (!_PyArg_NoKeywords("cycle()", kwds)) + if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable)) @@ -831,7 +831,7 @@ PyObject *it; dropwhileobject *lz; - if (!_PyArg_NoKeywords("dropwhile()", kwds)) + if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq)) @@ -975,7 +975,7 @@ PyObject *it; takewhileobject *lz; - if (!_PyArg_NoKeywords("takewhile()", kwds)) + if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq)) @@ -1120,7 +1120,7 @@ Py_ssize_t numargs; isliceobject *lz; - if (!_PyArg_NoKeywords("islice()", kwds)) + if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3)) @@ -1311,7 +1311,7 @@ PyObject *it; starmapobject *lz; - if (!_PyArg_NoKeywords("starmap()", kwds)) + if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq)) @@ -1443,7 +1443,7 @@ imapobject *lz; Py_ssize_t numargs, i; - if (!_PyArg_NoKeywords("imap()", kwds)) + if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds)) return NULL; numargs = PyTuple_Size(args); @@ -1625,7 +1625,7 @@ Py_ssize_t i; PyObject *ittuple; - if (!_PyArg_NoKeywords("chain()", kwds)) + if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) return NULL; /* obtain iterators */ @@ -1768,7 +1768,7 @@ PyObject *it; ifilterobject *lz; - if (!_PyArg_NoKeywords("ifilter()", kwds)) + if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq)) @@ -1912,7 +1912,8 @@ PyObject *it; ifilterfalseobject *lz; - if (!_PyArg_NoKeywords("ifilterfalse()", kwds)) + if (type == &ifilterfalse_type && + !_PyArg_NoKeywords("ifilterfalse()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq)) @@ -2054,7 +2055,7 @@ countobject *lz; Py_ssize_t cnt = 0; - if (!_PyArg_NoKeywords("count()", kwds)) + if (type == &count_type && !_PyArg_NoKeywords("count()", kwds)) return NULL; if (!PyArg_ParseTuple(args, "|n:count", &cnt)) @@ -2072,6 +2073,11 @@ static PyObject * count_next(countobject *lz) { + if (lz->cnt == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot count beyond LONG_MAX"); + return NULL; + } return PyInt_FromSsize_t(lz->cnt++); } @@ -2153,7 +2159,7 @@ PyObject *result; Py_ssize_t tuplesize = PySequence_Length(args); - if (!_PyArg_NoKeywords("izip()", kwds)) + if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds)) return NULL; /* args must be a tuple */ @@ -2336,7 +2342,7 @@ PyObject *element; Py_ssize_t cnt = -1; - if (!_PyArg_NoKeywords("repeat()", kwds)) + if (type == &repeat_type && !_PyArg_NoKeywords("repeat()", kwds)) return NULL; if (!PyArg_ParseTuple(args, "O|n:repeat", &element, &cnt)) @@ -2466,6 +2472,234 @@ PyObject_GC_Del, /* tp_free */ }; +/* iziplongest object ************************************************************/ + +#include "Python.h" + +typedef struct { + PyObject_HEAD + Py_ssize_t tuplesize; + Py_ssize_t numactive; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue; +} iziplongestobject; + +static PyTypeObject iziplongest_type; + +static PyObject * +izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + iziplongestobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue = Py_None; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { + fillvalue = PyDict_GetItemString(kwds, "fillvalue"); + if (fillvalue == NULL || PyDict_Size(kwds) > 1) { + PyErr_SetString(PyExc_TypeError, + "izip_longest() got an unexpected keyword argument"); + return NULL; + } + } + + /* args must be a tuple */ + assert(PyTuple_Check(args)); + + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "izip_longest argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } + + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create iziplongestobject structure */ + lz = (iziplongestobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->numactive = tuplesize; + lz->result = result; + Py_INCREF(fillvalue); + lz->fillvalue = fillvalue; + return (PyObject *)lz; +} + +static void +izip_longest_dealloc(iziplongestobject *lz) +{ + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_XDECREF(lz->fillvalue); + lz->ob_type->tp_free(lz); +} + +static int +izip_longest_traverse(iziplongestobject *lz, visitproc visit, void *arg) +{ + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + Py_VISIT(lz->fillvalue); + return 0; +} + +static PyObject * +izip_longest_next(iziplongestobject *lz) +{ + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (lz->numactive == 0) + return NULL; + if (result->ob_refcnt == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } + PyTuple_SET_ITEM(result, i, item); + } + } + return result; +} + +PyDoc_STRVAR(izip_longest_doc, +"izip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> izip_longest object\n\ +\n\ +Return an izip_longest object whose .next() method returns a tuple where\n\ +the i-th element comes from the i-th iterable argument. The .next()\n\ +method continues until the longest iterable in the argument sequence\n\ +is exhausted and then it raises StopIteration. When the shorter iterables\n\ +are exhausted, the fillvalue is substituted in their place. The fillvalue\n\ +defaults to None or can be specified by a keyword argument.\n\ +"); + +static PyTypeObject iziplongest_type = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + "itertools.izip_longest", /* tp_name */ + sizeof(iziplongestobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)izip_longest_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + izip_longest_doc, /* tp_doc */ + (traverseproc)izip_longest_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)izip_longest_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + izip_longest_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ +}; /* module level code ********************************************************/ @@ -2479,6 +2713,7 @@ \n\ Iterators terminating on the shortest input sequence:\n\ izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ +izip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ ifilter(pred, seq) --> elements of seq where pred(elem) is True\n\ ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\ islice(seq, [start,] stop [, step]) --> elements from\n\ @@ -2516,6 +2751,7 @@ &ifilterfalse_type, &count_type, &izip_type, + &iziplongest_type, &repeat_type, &groupby_type, NULL Modified: python/branches/p3yk-noslice/Modules/parsermodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/parsermodule.c (original) +++ python/branches/p3yk-noslice/Modules/parsermodule.c Fri Feb 23 18:29:35 2007 @@ -857,7 +857,7 @@ VALIDATER(vfpdef); VALIDATER(vfplist); VALIDATER(stmt); VALIDATER(simple_stmt); VALIDATER(expr_stmt); VALIDATER(power); -VALIDATER(print_stmt); VALIDATER(del_stmt); +VALIDATER(del_stmt); VALIDATER(return_stmt); VALIDATER(list_iter); VALIDATER(raise_stmt); VALIDATER(import_stmt); VALIDATER(import_name); VALIDATER(import_from); @@ -1545,7 +1545,6 @@ int ntype = TYPE(CHILD(tree, 0)); if ( (ntype == expr_stmt) - || (ntype == print_stmt) || (ntype == del_stmt) || (ntype == pass_stmt) || (ntype == flow_stmt) @@ -1650,54 +1649,6 @@ } -/* print_stmt: - * - * 'print' ( [ test (',' test)* [','] ] - * | '>>' test [ (',' test)+ [','] ] ) - */ -static int -validate_print_stmt(node *tree) -{ - int nch = NCH(tree); - int res = (validate_ntype(tree, print_stmt) - && (nch > 0) - && validate_name(CHILD(tree, 0), "print")); - - if (res && nch > 1) { - int sym = TYPE(CHILD(tree, 1)); - int i = 1; - int allow_trailing_comma = 1; - - if (sym == test) - res = validate_test(CHILD(tree, i++)); - else { - if (nch < 3) - res = validate_numnodes(tree, 3, "print_stmt"); - else { - res = (validate_ntype(CHILD(tree, i), RIGHTSHIFT) - && validate_test(CHILD(tree, i+1))); - i += 2; - allow_trailing_comma = 0; - } - } - if (res) { - /* ... (',' test)* [','] */ - while (res && i+2 <= nch) { - res = (validate_comma(CHILD(tree, i)) - && validate_test(CHILD(tree, i+1))); - allow_trailing_comma = 1; - i += 2; - } - if (res && !allow_trailing_comma) - res = validate_numnodes(tree, i, "print_stmt"); - else if (res && i < nch) - res = validate_comma(CHILD(tree, i)); - } - } - return (res); -} - - static int validate_del_stmt(node *tree) { @@ -2977,7 +2928,7 @@ break; case small_stmt: /* - * expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt + * expr_stmt | del_stmt | pass_stmt | flow_stmt * | import_stmt | global_stmt | assert_stmt */ res = validate_small_stmt(tree); @@ -3012,9 +2963,6 @@ case expr_stmt: res = validate_expr_stmt(tree); break; - case print_stmt: - res = validate_print_stmt(tree); - break; case del_stmt: res = validate_del_stmt(tree); break; Modified: python/branches/p3yk-noslice/Modules/posixmodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/posixmodule.c (original) +++ python/branches/p3yk-noslice/Modules/posixmodule.c Fri Feb 23 18:29:35 2007 @@ -1462,7 +1462,7 @@ /* POSIX methods */ PyDoc_STRVAR(posix_access__doc__, -"access(path, mode) -> 1 if granted, 0 otherwise\n\n\ +"access(path, mode) -> True if granted, False otherwise\n\n\ Use the real uid/gid to test for access to a path. Note that most\n\ operations will use the effective uid/gid, therefore this routine can\n\ be used in a suid/sgid environment to test if the invoking user has the\n\ @@ -1692,6 +1692,57 @@ } +#ifdef HAVE_CHFLAGS +PyDoc_STRVAR(posix_chflags__doc__, +"chflags(path, flags)\n\n\ +Set file flags."); + +static PyObject * +posix_chflags(PyObject *self, PyObject *args) +{ + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:chflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +} +#endif /* HAVE_CHFLAGS */ + +#ifdef HAVE_LCHFLAGS +PyDoc_STRVAR(posix_lchflags__doc__, +"lchflags(path, flags)\n\n\ +Set file flags.\n\ +This function will not follow symbolic links."); + +static PyObject * +posix_lchflags(PyObject *self, PyObject *args) +{ + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:lchflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +} +#endif /* HAVE_LCHFLAGS */ + #ifdef HAVE_CHROOT PyDoc_STRVAR(posix_chroot__doc__, "chroot(path)\n\n\ @@ -5437,32 +5488,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"); @@ -8081,10 +8121,16 @@ {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, #endif {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, +#ifdef HAVE_CHFLAGS + {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, +#endif /* HAVE_CHFLAGS */ {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, #ifdef HAVE_CHOWN {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, #endif /* HAVE_CHOWN */ +#ifdef HAVE_LCHFLAGS + {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, +#endif /* HAVE_LCHFLAGS */ #ifdef HAVE_LCHOWN {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, #endif /* HAVE_LCHOWN */ Modified: python/branches/p3yk-noslice/Modules/socketmodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/socketmodule.c (original) +++ python/branches/p3yk-noslice/Modules/socketmodule.c Fri Feb 23 18:29:35 2007 @@ -362,20 +362,25 @@ #if defined(__FreeBSD__) #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM +#define BTPROTO_HCI BLUETOOTH_PROTO_HCI #define sockaddr_l2 sockaddr_l2cap #define sockaddr_rc sockaddr_rfcomm #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb) #elif defined(__NetBSD__) #define sockaddr_l2 sockaddr_bt #define sockaddr_rc sockaddr_bt +#define sockaddr_hci sockaddr_bt #define sockaddr_sco sockaddr_bt #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb) #else #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb) #endif #endif @@ -1119,6 +1124,14 @@ return ret; } + case BTPROTO_HCI: + { + struct sockaddr_hci *a = (struct sockaddr_hci *) addr; + PyObject *ret = NULL; + ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); + return ret; + } + #if !defined(__FreeBSD__) case BTPROTO_SCO: { @@ -1347,6 +1360,18 @@ *len_ret = sizeof *addr; return 1; } + case BTPROTO_HCI: + { + struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; + _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + *len_ret = sizeof *addr; + return 1; + } #if !defined(__FreeBSD__) case BTPROTO_SCO: { @@ -1485,6 +1510,9 @@ case BTPROTO_RFCOMM: *len_ret = sizeof (struct sockaddr_rc); return 1; + case BTPROTO_HCI: + *len_ret = sizeof (struct sockaddr_hci); + return 1; #if !defined(__FreeBSD__) case BTPROTO_SCO: *len_ret = sizeof (struct sockaddr_sco); @@ -3468,7 +3496,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); } @@ -3483,12 +3516,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; @@ -3510,7 +3538,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, @@ -3527,7 +3555,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); } @@ -3542,12 +3575,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; @@ -3567,7 +3595,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, @@ -3827,7 +3855,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)) { @@ -4363,7 +4391,9 @@ PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); #endif PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); +#ifdef NETLINK_DNRTMSG PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); +#endif #ifdef NETLINK_TAPBASE PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); #endif @@ -4408,6 +4438,11 @@ #ifdef USE_BLUETOOTH PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); + PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); + PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); + PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); + PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); + PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); #if !defined(__FreeBSD__) PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); #endif Modified: python/branches/p3yk-noslice/Modules/socketmodule.h ============================================================================== --- python/branches/p3yk-noslice/Modules/socketmodule.h (original) +++ python/branches/p3yk-noslice/Modules/socketmodule.h Fri Feb 23 18:29:35 2007 @@ -46,6 +46,7 @@ #include #include #include +#include #endif #ifdef HAVE_BLUETOOTH_H @@ -98,6 +99,7 @@ struct sockaddr_l2 bt_l2; struct sockaddr_rc bt_rc; struct sockaddr_sco bt_sco; + struct sockaddr_hci bt_hci; #endif #ifdef HAVE_NETPACKET_PACKET_H struct sockaddr_ll ll; Modified: python/branches/p3yk-noslice/Modules/timemodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/timemodule.c (original) +++ python/branches/p3yk-noslice/Modules/timemodule.c Fri Feb 23 18:29:35 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-noslice/Objects/abstract.c ============================================================================== --- python/branches/p3yk-noslice/Objects/abstract.c (original) +++ python/branches/p3yk-noslice/Objects/abstract.c Fri Feb 23 18:29:35 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); } @@ -1029,6 +980,8 @@ int PySequence_Check(PyObject *s) { + if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type)) + return 0; return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } @@ -1671,6 +1624,54 @@ return 0; } +PyObject * +PyMapping_Keys(PyObject *o) +{ + PyObject *keys; + PyObject *fast; + + if (PyDict_CheckExact(o)) + return PyDict_Keys(o); + keys = PyObject_CallMethod(o, "keys", NULL); + if (keys == NULL) + return NULL; + fast = PySequence_Fast(keys, "o.keys() are not iterable"); + Py_DECREF(keys); + return fast; +} + +PyObject * +PyMapping_Items(PyObject *o) +{ + PyObject *items; + PyObject *fast; + + if (PyDict_CheckExact(o)) + return PyDict_Items(o); + items = PyObject_CallMethod(o, "items", NULL); + if (items == NULL) + return NULL; + fast = PySequence_Fast(items, "o.items() are not iterable"); + Py_DECREF(items); + return fast; +} + +PyObject * +PyMapping_Values(PyObject *o) +{ + PyObject *values; + PyObject *fast; + + if (PyDict_CheckExact(o)) + return PyDict_Values(o); + values = PyObject_CallMethod(o, "values", NULL); + if (values == NULL) + return NULL; + fast = PySequence_Fast(values, "o.values() are not iterable"); + Py_DECREF(values); + return fast; +} + /* Operations on callable objects */ /* XXX PyCallable_Check() is in object.c */ Modified: python/branches/p3yk-noslice/Objects/boolobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/boolobject.c (original) +++ python/branches/p3yk-noslice/Objects/boolobject.c Fri Feb 23 18:29:35 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-noslice/Objects/complexobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/complexobject.c (original) +++ python/branches/p3yk-noslice/Objects/complexobject.c Fri Feb 23 18:29:35 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-noslice/Objects/dictnotes.txt ============================================================================== --- python/branches/p3yk-noslice/Objects/dictnotes.txt (original) +++ python/branches/p3yk-noslice/Objects/dictnotes.txt Fri Feb 23 18:29:35 2007 @@ -98,6 +98,17 @@ depending on the size of the dictionary. Setting to *4 eliminates every other resize step. +* Maximum sparseness (minimum dictionary load). What percentage + of entries can be unused before the dictionary shrinks to + free up memory and speed up iteration? (The current CPython + code does not represent this parameter directly.) + +* Shrinkage rate upon exceeding maximum sparseness. The current + CPython code never even checks sparseness when deleting a + key. When a new key is added, it resizes based on the number + of active keys, so that the addition may trigger shrinkage + rather than growth. + Tune-ups should be measured across a broad range of applications and use cases. A change to any parameter will help in some situations and hurt in others. The key is to find settings that help the most common @@ -115,6 +126,15 @@ Also, every dictionary iterates at least twice, once for the memset() when it is created and once by dealloc(). +Dictionary operations involving only a single key can be O(1) unless +resizing is possible. By checking for a resize only when the +dictionary can grow (and may *require* resizing), other operations +remain O(1), and the odds of resize thrashing or memory fragmentation +are reduced. In particular, an algorithm that empties a dictionary +by repeatedly invoking .pop will see no resizing, which might +not be necessary at all because the dictionary is eventually +discarded entirely. + Results of Cache Locality Experiments ------------------------------------- Modified: python/branches/p3yk-noslice/Objects/dictobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/dictobject.c (original) +++ python/branches/p3yk-noslice/Objects/dictobject.c Fri Feb 23 18:29:35 2007 @@ -833,6 +833,34 @@ return 1; } +/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/ +int +_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash) +{ + register Py_ssize_t i; + register Py_ssize_t mask; + register dictentry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((dictobject *)op)->ma_table; + mask = ((dictobject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + *phash = (long)(ep[i].me_hash); + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; +} + /* Methods */ static void @@ -1336,7 +1364,7 @@ return -1; } mp = (dictobject*)a; - if (PyDict_Check(b)) { + if (PyDict_CheckExact(b)) { other = (dictobject*)b; if (other == mp || other->ma_used == 0) /* a.update(a) or a.update({}); nothing to do */ @@ -1760,6 +1788,7 @@ extern PyTypeObject PyDictIterItem_Type; /* Forward */ static PyObject *dictiter_new(dictobject *, PyTypeObject *); +#if 0 static PyObject * dict_iterkeys(dictobject *dict) { @@ -1777,6 +1806,7 @@ { return dictiter_new(dict, &PyDictIterItem_Type); } +#endif PyDoc_STRVAR(contains__doc__, @@ -1798,6 +1828,7 @@ "D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\ 2-tuple; but raise KeyError if D is empty"); +#if 0 PyDoc_STRVAR(keys__doc__, "D.keys() -> list of D's keys"); @@ -1806,10 +1837,11 @@ PyDoc_STRVAR(values__doc__, "D.values() -> list of D's values"); +#endif PyDoc_STRVAR(update__doc__, -"D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\n\ -(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]"); +"D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\ +\n(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]"); PyDoc_STRVAR(fromkeys__doc__, "dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\ @@ -1821,6 +1853,7 @@ PyDoc_STRVAR(copy__doc__, "D.copy() -> a shallow copy of D"); +#if 0 PyDoc_STRVAR(iterkeys__doc__, "D.iterkeys() -> an iterator over the keys of D"); @@ -1829,6 +1862,16 @@ PyDoc_STRVAR(iteritems__doc__, "D.iteritems() -> an iterator over the (key, value) items of D"); +#endif + +/* Forward */ +static PyObject *dictkeys_new(PyObject *); +static PyObject *dictitems_new(PyObject *); +static PyObject *dictvalues_new(PyObject *); + +PyDoc_STRVAR(KEYS__doc__, "D.KEYS() -> a set-like object for D's keys"); +PyDoc_STRVAR(ITEMS__doc__, "D.ITEMS() -> a set-like object for D's items"); +PyDoc_STRVAR(VALUES__doc__, "D.VALUES() -> a set-like object for D's values"); static PyMethodDef mapp_methods[] = { {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, @@ -1843,12 +1886,20 @@ pop__doc__}, {"popitem", (PyCFunction)dict_popitem, METH_NOARGS, popitem__doc__}, +#if 0 {"keys", (PyCFunction)dict_keys, METH_NOARGS, keys__doc__}, {"items", (PyCFunction)dict_items, METH_NOARGS, items__doc__}, {"values", (PyCFunction)dict_values, METH_NOARGS, values__doc__}, +#endif + {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, + KEYS__doc__}, + {"items", (PyCFunction)dictitems_new, METH_NOARGS, + ITEMS__doc__}, + {"values", (PyCFunction)dictvalues_new, METH_NOARGS, + VALUES__doc__}, {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, update__doc__}, {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, @@ -1857,12 +1908,14 @@ clear__doc__}, {"copy", (PyCFunction)dict_copy, METH_NOARGS, copy__doc__}, +#if 0 {"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS, iterkeys__doc__}, {"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS, itervalues__doc__}, {"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS, iteritems__doc__}, +#endif {NULL, NULL} /* sentinel */ }; @@ -1884,6 +1937,17 @@ return ep == NULL ? -1 : (ep->me_value != NULL); } +/* Internal version of PyDict_Contains used when the hash value is already known */ +int +_PyDict_Contains(PyObject *op, PyObject *key, long hash) +{ + dictobject *mp = (dictobject *)op; + dictentry *ep; + + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); +} + /* Hack to implement "key in dict" */ static PySequenceMethods dict_as_sequence = { 0, /* sq_length */ @@ -2078,10 +2142,12 @@ return PyInt_FromSize_t(len); } -PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); +PyDoc_STRVAR(length_hint_doc, + "Private method returning an estimate of len(list(it))."); static PyMethodDef dictiter_methods[] = { - {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, length_hint_doc}, + {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, + length_hint_doc}, {NULL, NULL} /* sentinel */ }; @@ -2317,3 +2383,359 @@ dictiter_methods, /* tp_methods */ 0, }; + + +/***********************************************/ +/* View objects for keys(), items(), values(). */ +/***********************************************/ + +/* While this is incomplete, we use KEYS(), ITEMS(), VALUES(). */ + +/* The instance lay-out is the same for all three; but the type differs. */ + +typedef struct { + PyObject_HEAD + dictobject *dv_dict; +} dictviewobject; + + +static void +dictview_dealloc(dictviewobject *dv) +{ + Py_XDECREF(dv->dv_dict); + PyObject_Del(dv); +} + +static Py_ssize_t +dictview_len(dictviewobject *dv) +{ + Py_ssize_t len = 0; + if (dv->dv_dict != NULL) + len = dv->dv_dict->ma_used; + return len; +} + +static PyObject * +dictview_new(PyObject *dict, PyTypeObject *type) +{ + dictviewobject *dv; + if (dict == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyDict_Check(dict)) { + /* XXX Get rid of this restriction later */ + PyErr_Format(PyExc_TypeError, + "%s() requires a dict argument, not '%s'", + type->tp_name, dict->ob_type->tp_name); + return NULL; + } + dv = PyObject_New(dictviewobject, type); + if (dv == NULL) + return NULL; + Py_INCREF(dict); + dv->dv_dict = (dictobject *)dict; + return (PyObject *)dv; +} + +/* Forward */ +PyTypeObject PyDictKeys_Type; +PyTypeObject PyDictItems_Type; +PyTypeObject PyDictValues_Type; + +#define PyDictKeys_Check(obj) ((obj)->ob_type == &PyDictKeys_Type) +#define PyDictItems_Check(obj) ((obj)->ob_type == &PyDictItems_Type) +#define PyDictValues_Check(obj) ((obj)->ob_type == &PyDictValues_Type) + +/* This excludes Values, since they are not sets. */ +# define PyDictViewSet_Check(obj) \ + (PyDictKeys_Check(obj) || PyDictItems_Check(obj)) + +static int +all_contained_in(PyObject *self, PyObject *other) +{ + PyObject *iter = PyObject_GetIter(self); + int ok = 1; + + if (iter == NULL) + return -1; + for (;;) { + PyObject *next = PyIter_Next(iter); + if (next == NULL) { + if (PyErr_Occurred()) + ok = -1; + break; + } + ok = PySequence_Contains(other, next); + Py_DECREF(next); + if (ok <= 0) + break; + } + Py_DECREF(iter); + return ok; +} + +static PyObject * +dictview_richcompare(PyObject *self, PyObject *other, int op) +{ + assert(self != NULL); + assert(PyDictViewSet_Check(self)); + assert(other != NULL); + if ((op == Py_EQ || op == Py_NE) && + (PyAnySet_Check(other) || PyDictViewSet_Check(other))) + { + Py_ssize_t len_self, len_other; + int ok; + PyObject *result; + + len_self = PyObject_Size(self); + if (len_self < 0) + return NULL; + len_other = PyObject_Size(other); + if (len_other < 0) + return NULL; + if (len_self != len_other) + ok = 0; + else if (len_self == 0) + ok = 1; + else + ok = all_contained_in(self, other); + if (ok < 0) + return NULL; + if (ok == (op == Py_EQ)) + result = Py_True; + else + result = Py_False; + Py_INCREF(result); + return result; + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } +} + +/*** dict_keys ***/ + +static PyObject * +dictkeys_iter(dictviewobject *dv) +{ + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); +} + +static int +dictkeys_contains(dictviewobject *dv, PyObject *obj) +{ + if (dv->dv_dict == NULL) + return 0; + return PyDict_Contains((PyObject *)dv->dv_dict, obj); +} + +static PySequenceMethods dictkeys_as_sequence = { + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictkeys_contains, /* sq_contains */ +}; + +static PyMethodDef dictkeys_methods[] = { + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyDictKeys_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "dict_keys", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &dictkeys_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictkeys_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictkeys_methods, /* tp_methods */ + 0, +}; + +static PyObject * +dictkeys_new(PyObject *dict) +{ + return dictview_new(dict, &PyDictKeys_Type); +} + +/*** dict_items ***/ + +static PyObject * +dictitems_iter(dictviewobject *dv) +{ + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); +} + +static int +dictitems_contains(dictviewobject *dv, PyObject *obj) +{ + PyObject *key, *value, *found; + if (dv->dv_dict == NULL) + return 0; + if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) + return 0; + key = PyTuple_GET_ITEM(obj, 0); + value = PyTuple_GET_ITEM(obj, 1); + found = PyDict_GetItem((PyObject *)dv->dv_dict, key); + if (found == NULL) { + if (PyErr_Occurred()) + return -1; + return 0; + } + return PyObject_RichCompareBool(value, found, Py_EQ); +} + +static PySequenceMethods dictitems_as_sequence = { + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictitems_contains, /* sq_contains */ +}; + +static PyMethodDef dictitems_methods[] = { + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyDictItems_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "dict_items", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &dictitems_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictitems_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictitems_methods, /* tp_methods */ + 0, +}; + +static PyObject * +dictitems_new(PyObject *dict) +{ + return dictview_new(dict, &PyDictItems_Type); +} + +/*** dict_values ***/ + +static PyObject * +dictvalues_iter(dictviewobject *dv) +{ + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); +} + +static PySequenceMethods dictvalues_as_sequence = { + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)0, /* sq_contains */ +}; + +static PyMethodDef dictvalues_methods[] = { + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyDictValues_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "dict_values", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &dictvalues_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictvalues_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictvalues_methods, /* tp_methods */ + 0, +}; + +static PyObject * +dictvalues_new(PyObject *dict) +{ + return dictview_new(dict, &PyDictValues_Type); +} Modified: python/branches/p3yk-noslice/Objects/enumobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/enumobject.c (original) +++ python/branches/p3yk-noslice/Objects/enumobject.c Fri Feb 23 18:29:35 2007 @@ -62,6 +62,12 @@ PyObject *result = en->en_result; PyObject *it = en->en_sit; + if (en->en_index == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "enumerate() is limited to LONG_MAX items"); + return NULL; + } + next_item = (*it->ob_type->tp_iternext)(it); if (next_item == NULL) return NULL; Modified: python/branches/p3yk-noslice/Objects/exceptions.c ============================================================================== --- python/branches/p3yk-noslice/Objects/exceptions.c (original) +++ python/branches/p3yk-noslice/Objects/exceptions.c Fri Feb 23 18:29:35 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-noslice/Objects/fileobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/fileobject.c (original) +++ python/branches/p3yk-noslice/Objects/fileobject.c Fri Feb 23 18:29:35 2007 @@ -118,7 +118,6 @@ f->f_mode = PyString_FromString(mode); f->f_close = close; - f->f_softspace = 0; f->f_binary = strchr(mode,'b') != NULL; f->f_buf = NULL; f->f_univ_newline = (strchr(mode, 'U') != NULL); @@ -354,6 +353,8 @@ { PyFileObject *file = (PyFileObject*)f; PyObject *str = PyString_FromString(enc); + + assert(PyFile_Check(f)); if (!str) return 0; Py_DECREF(file->f_encoding); @@ -1521,7 +1522,6 @@ return err_closed(); if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n)) return NULL; - f->f_softspace = 0; Py_BEGIN_ALLOW_THREADS errno = 0; n2 = fwrite(s, 1, n, f->f_fp); @@ -1624,7 +1624,6 @@ /* Since we are releasing the global lock, the following code may *not* execute Python code. */ Py_BEGIN_ALLOW_THREADS - f->f_softspace = 0; errno = 0; for (i = 0; i < j; i++) { line = PyList_GET_ITEM(list, i); @@ -1784,8 +1783,6 @@ #define OFF(x) offsetof(PyFileObject, x) static PyMemberDef file_memberlist[] = { - {"softspace", T_INT, OFF(f_softspace), 0, - "flag indicating that a space needs to be printed; used by print"}, {"mode", T_OBJECT, OFF(f_mode), RO, "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"}, {"name", T_OBJECT, OFF(f_name), RO, @@ -2092,8 +2089,7 @@ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ - /* softspace is writable: we must supply tp_setattro */ - PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ file_doc, /* tp_doc */ @@ -2117,42 +2113,6 @@ PyObject_Del, /* tp_free */ }; -/* Interface for the 'soft space' between print items. */ - -int -PyFile_SoftSpace(PyObject *f, int newflag) -{ - long oldflag = 0; - if (f == NULL) { - /* Do nothing */ - } - else if (PyFile_Check(f)) { - oldflag = ((PyFileObject *)f)->f_softspace; - ((PyFileObject *)f)->f_softspace = newflag; - } - else { - PyObject *v; - v = PyObject_GetAttrString(f, "softspace"); - if (v == NULL) - PyErr_Clear(); - else { - if (PyInt_Check(v)) - oldflag = PyInt_AsLong(v); - assert(oldflag < INT_MAX); - Py_DECREF(v); - } - v = PyInt_FromLong((long)newflag); - if (v == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(f, "softspace", v) != 0) - PyErr_Clear(); - Py_DECREF(v); - } - } - return (int)oldflag; -} - /* Interfaces to write objects/strings to file-like objects */ int @@ -2301,6 +2261,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-noslice/Objects/floatobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/floatobject.c (original) +++ python/branches/p3yk-noslice/Objects/floatobject.c Fri Feb 23 18:29:35 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-noslice/Objects/frameobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/frameobject.c (original) +++ python/branches/p3yk-noslice/Objects/frameobject.c Fri Feb 23 18:29:35 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-noslice/Objects/intobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/intobject.c (original) +++ python/branches/p3yk-noslice/Objects/intobject.c Fri Feb 23 18:29:35 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.) @@ -1049,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*/ @@ -1254,3 +1256,4 @@ } } } +#endif /* if 0 */ Modified: python/branches/p3yk-noslice/Objects/iterobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/iterobject.c (original) +++ python/branches/p3yk-noslice/Objects/iterobject.c Fri Feb 23 18:29:35 2007 @@ -302,7 +302,6 @@ zipiter->result = (PyTupleObject*) result; zipiter->resultsize = tuplesize; - Py_INCREF(ziptuple); zipiter->it_tuple = (PyTupleObject *) ziptuple; _PyObject_GC_TRACK(zipiter); return (PyObject *)zipiter; Modified: python/branches/p3yk-noslice/Objects/listobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/listobject.c (original) +++ python/branches/p3yk-noslice/Objects/listobject.c Fri Feb 23 18:29:35 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-noslice/Objects/longobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/longobject.c (original) +++ python/branches/p3yk-noslice/Objects/longobject.c Fri Feb 23 18:29:35 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"); + "Python int too large to convert to C long"); 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"); + "Python int too large to convert to C ssize_t"); 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, + "python int too large to convert to C unsigned long"); + 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, - "long int too large to convert"); + "Python int too large to convert to C size_t"); 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"); + "Python int too large to convert to C double"); 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; } @@ -1907,8 +2147,12 @@ long_richcompare(PyObject *self, PyObject *other, int op) { PyLongObject *a, *b; + PyObject *result; CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b); - return Py_CmpToRich(op, long_compare(a, b)); + result = Py_CmpToRich(op, long_compare(a, b)); + Py_DECREF(a); + Py_DECREF(b); + return result; } static long @@ -1922,6 +2166,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 +2276,7 @@ } assert(borrow == 0); if (sign < 0) - z->ob_size = -(z->ob_size); + NEGATE(z); return long_normalize(z); } @@ -2038,6 +2287,13 @@ CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); + if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) { + PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) + + MEDIUM_VALUE(b)); + Py_DECREF(a); + Py_DECREF(b); + return result; + } if (a->ob_size < 0) { if (b->ob_size < 0) { z = x_add(a, b); @@ -2065,6 +2321,13 @@ CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); + if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) { + PyObject* r; + r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); + Py_DECREF(a); + Py_DECREF(b); + return r; + } if (a->ob_size < 0) { if (b->ob_size < 0) z = x_sub(a, b); @@ -2494,10 +2757,18 @@ return Py_NotImplemented; } + if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) { + PyObject *r; + r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w)); + Py_DECREF(a); + Py_DECREF(b); + return r; + } + 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 +2874,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 +2893,7 @@ overflow: PyErr_SetString(PyExc_OverflowError, - "long/long too large for a float"); + "int/int too large for a float"); return NULL; } @@ -2691,11 +2962,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 +3007,7 @@ Py_DECREF(c); c = temp; temp = NULL; - c->ob_size = - c->ob_size; + NEGATE(c); } /* if modulus == 1: @@ -2862,6 +3128,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 +3156,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 +3281,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 +3459,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 +3496,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 +3523,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 +3572,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 +3623,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 +3639,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 +3664,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-noslice/Objects/object.c ============================================================================== --- python/branches/p3yk-noslice/Objects/object.c (original) +++ python/branches/p3yk-noslice/Objects/object.c Fri Feb 23 18:29:35 2007 @@ -314,7 +314,7 @@ /* For debugging convenience. Set a breakpoint here and call it from your DLL */ void -_Py_Break(void) +_Py_BreakPoint(void) { } Modified: python/branches/p3yk-noslice/Objects/setobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/setobject.c (original) +++ python/branches/p3yk-noslice/Objects/setobject.c Fri Feb 23 18:29:35 2007 @@ -932,14 +932,31 @@ { PyObject *key, *it; - if (PyAnySet_Check(other)) + if (PyAnySet_CheckExact(other)) return set_merge(so, other); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; - while (PyDict_Next(other, &pos, &key, &value)) { - if (set_add_key(so, key) == -1) + long hash; + Py_ssize_t dictsize = PyDict_Size(other); + + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if (dictsize == -1) + return -1; + if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + dictsize)*2) != 0) + return -1; + } + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { + setentry an_entry; + + an_entry.hash = hash; + an_entry.key = key; + if (set_add_entry(so, &an_entry) == -1) return -1; } return 0; @@ -1024,7 +1041,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 +1085,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); @@ -1210,7 +1227,7 @@ if (result == NULL) return NULL; - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_ssize_t pos = 0; setentry *entry; @@ -1334,7 +1351,7 @@ if ((PyObject *)so == other) return set_clear_internal(so); - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { setentry *entry; Py_ssize_t pos = 0; @@ -1383,7 +1400,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other) && !PyDict_Check(other)) { + if (!PyAnySet_CheckExact(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1397,12 +1414,12 @@ if (result == NULL) return NULL; - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { while (set_next(so, &pos, &entry)) { setentry entrycopy; entrycopy.hash = entry->hash; entrycopy.key = entry->key; - if (!PyDict_Contains(other, entry->key)) { + if (!_PyDict_Contains(other, entry->key, entry->hash)) { if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { Py_DECREF(result); return NULL; @@ -1470,15 +1487,13 @@ if ((PyObject *)so == other) return set_clear(so); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; int rv; - while (PyDict_Next(other, &pos, &key, &value)) { + long hash; + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { setentry an_entry; - long hash = PyObject_Hash(key); - if (hash == -1) - return NULL; an_entry.hash = hash; an_entry.key = key; rv = set_discard_entry(so, &an_entry); @@ -1492,7 +1507,7 @@ Py_RETURN_NONE; } - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_INCREF(other); otherset = (PySetObject *)other; } else { @@ -1575,7 +1590,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { PyObject *tmp, *result; tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) @@ -1604,7 +1619,7 @@ { PyObject *tmp, *result; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) return NULL; Modified: python/branches/p3yk-noslice/Objects/stringobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/stringobject.c (original) +++ python/branches/p3yk-noslice/Objects/stringobject.c Fri Feb 23 18:29:35 2007 @@ -4209,6 +4209,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': @@ -4553,6 +4561,8 @@ goto error; } width = PyInt_AsLong(v); + if (width == -1 && PyErr_Occurred()) + goto error; if (width < 0) { flags |= F_LJUST; width = -width; @@ -4590,6 +4600,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-noslice/Objects/typeobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/typeobject.c (original) +++ python/branches/p3yk-noslice/Objects/typeobject.c Fri Feb 23 18:29:35 2007 @@ -655,6 +655,17 @@ goto endlabel; /* resurrected */ else _PyObject_GC_UNTRACK(self); + /* New weakrefs could be created during the finalizer call. + If this occurs, clear them out without calling their + finalizers since they might rely on part of the object + being finalized that has already been destroyed. */ + if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { + /* Modeled after GET_WEAKREFS_LISTPTR() */ + PyWeakReference **list = (PyWeakReference **) \ + PyObject_GET_WEAKREFS_LISTPTR(self); + while (*list) + _PyWeakref_ClearRef(*list); + } } /* Clear slots up to the nearest base with a different tp_dealloc */ @@ -2589,7 +2600,11 @@ Py_INCREF(dictitems); } else { - dictitems = PyObject_CallMethod(obj, "iteritems", ""); + PyObject *items = PyObject_CallMethod(obj, "items", ""); + if (items == NULL) + goto end; + dictitems = PyObject_GetIter(items); + Py_DECREF(items); if (dictitems == NULL) goto end; } @@ -4197,7 +4212,13 @@ SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O") SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O") SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O") -SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O") +/* Can't use SLOT1 here, because nb_inplace_power is ternary */ +static PyObject * +slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) +{ + static PyObject *cache_str; + return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); +} SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O") SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O") SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O") Modified: python/branches/p3yk-noslice/Objects/unicodeobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/unicodeobject.c (original) +++ python/branches/p3yk-noslice/Objects/unicodeobject.c Fri Feb 23 18:29:35 2007 @@ -7569,6 +7569,8 @@ goto onError; } width = PyInt_AsLong(v); + if (width == -1 && PyErr_Occurred()) + goto onError; if (width < 0) { flags |= F_LJUST; width = -width; @@ -7604,6 +7606,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-noslice/Objects/weakrefobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/weakrefobject.c (original) +++ python/branches/p3yk-noslice/Objects/weakrefobject.c Fri Feb 23 18:29:35 2007 @@ -57,6 +57,9 @@ PyWeakref_GET_OBJECT(self)); if (*list == self) + /* If 'self' is the end of the list (and thus self->wr_next == NULL) + then the weakref list itself (and thus the value of *list) will + end up being set to NULL. */ *list = self->wr_next; self->wr_object = Py_None; if (self->wr_prev != NULL) Modified: python/branches/p3yk-noslice/PC/_msi.c ============================================================================== --- python/branches/p3yk-noslice/PC/_msi.c (original) +++ python/branches/p3yk-noslice/PC/_msi.c Fri Feb 23 18:29:35 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-noslice/PCbuild/_bsddb.vcproj ============================================================================== --- python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj (original) +++ python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj Fri Feb 23 18:29:35 2007 @@ -130,7 +130,7 @@ ATLMinimizesCRunTimeLibraryUsage="FALSE"> > f, auto_gen_msg + print >> f, c_file_msg % parse_version(mod) print >> f, '#include "Python.h"' print >> f, '#include "%s-ast.h"' % mod.name print >> f Modified: python/branches/p3yk-noslice/Parser/tokenizer.c ============================================================================== --- python/branches/p3yk-noslice/Parser/tokenizer.c (original) +++ python/branches/p3yk-noslice/Parser/tokenizer.c Fri Feb 23 18:29:35 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-noslice/Python/Python-ast.c ============================================================================== --- python/branches/p3yk-noslice/Python/Python-ast.c (original) +++ python/branches/p3yk-noslice/Python/Python-ast.c Fri Feb 23 18:29:35 2007 @@ -1,4 +1,13 @@ -/* File automatically generated by Parser/asdl_c.py */ +/* File automatically generated by Parser/asdl_c.py. */ + + +/* + __version__ 53731. + + This module must be committed separately after each AST grammar change; + The __version__ number is set to the revision number of the commit + containing the grammar change. +*/ #include "Python.h" #include "Python-ast.h" @@ -61,12 +70,6 @@ "op", "value", }; -static PyTypeObject *Print_type; -static char *Print_fields[]={ - "dest", - "values", - "nl", -}; static PyTypeObject *For_type; static char *For_fields[]={ "target", @@ -480,8 +483,6 @@ if (!Assign_type) return 0; AugAssign_type = make_type("AugAssign", stmt_type, AugAssign_fields, 3); if (!AugAssign_type) return 0; - Print_type = make_type("Print", stmt_type, Print_fields, 3); - if (!Print_type) return 0; For_type = make_type("For", stmt_type, For_fields, 4); if (!For_type) return 0; While_type = make_type("While", stmt_type, While_fields, 3); @@ -949,25 +950,6 @@ } stmt_ty -Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int col_offset, - PyArena *arena) -{ - stmt_ty p; - p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); - return NULL; - } - p->kind = Print_kind; - p->v.Print.dest = dest; - p->v.Print.values = values; - p->v.Print.nl = nl; - p->lineno = lineno; - p->col_offset = col_offset; - return p; -} - -stmt_ty For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena) { @@ -2118,25 +2100,6 @@ goto failed; Py_DECREF(value); break; - case Print_kind: - result = PyType_GenericNew(Print_type, NULL, NULL); - if (!result) goto failed; - value = ast2obj_expr(o->v.Print.dest); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "dest", value) == -1) - goto failed; - Py_DECREF(value); - value = ast2obj_list(o->v.Print.values, ast2obj_expr); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "values", value) == -1) - goto failed; - Py_DECREF(value); - value = ast2obj_bool(o->v.Print.nl); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "nl", value) == -1) - goto failed; - Py_DECREF(value); - break; case For_kind: result = PyType_GenericNew(For_type, NULL, NULL); if (!result) goto failed; @@ -3126,7 +3089,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__", "53363") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53731") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) @@ -3149,7 +3112,6 @@ return; if (PyDict_SetItemString(d, "AugAssign", (PyObject*)AugAssign_type) < 0) return; - if (PyDict_SetItemString(d, "Print", (PyObject*)Print_type) < 0) return; if (PyDict_SetItemString(d, "For", (PyObject*)For_type) < 0) return; if (PyDict_SetItemString(d, "While", (PyObject*)While_type) < 0) return; if (PyDict_SetItemString(d, "If", (PyObject*)If_type) < 0) return; Modified: python/branches/p3yk-noslice/Python/ast.c ============================================================================== --- python/branches/p3yk-noslice/Python/ast.c (original) +++ python/branches/p3yk-noslice/Python/ast.c Fri Feb 23 18:29:35 2007 @@ -2218,37 +2218,6 @@ } } -static stmt_ty -ast_for_print_stmt(struct compiling *c, const node *n) -{ - /* print_stmt: 'print' ( [ test (',' test)* [','] ] - | '>>' test [ (',' test)+ [','] ] ) - */ - expr_ty dest = NULL, expression; - asdl_seq *seq; - bool nl; - int i, j, start = 1; - - REQ(n, print_stmt); - if (NCH(n) >= 2 && TYPE(CHILD(n, 1)) == RIGHTSHIFT) { - dest = ast_for_expr(c, CHILD(n, 2)); - if (!dest) - return NULL; - start = 4; - } - seq = asdl_seq_new((NCH(n) + 1 - start) / 2, c->c_arena); - if (!seq) - return NULL; - for (i = start, j = 0; i < NCH(n); i += 2, ++j) { - expression = ast_for_expr(c, CHILD(n, i)); - if (!expression) - return NULL; - asdl_seq_SET(seq, j, expression); - } - nl = (TYPE(CHILD(n, NCH(n) - 1)) == COMMA) ? false : true; - return Print(dest, seq, nl, LINENO(n), n->n_col_offset, c->c_arena); -} - static asdl_seq * ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context) { @@ -3089,14 +3058,12 @@ if (TYPE(n) == small_stmt) { REQ(n, small_stmt); n = CHILD(n, 0); - /* small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt + /* small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | assert_stmt */ switch (TYPE(n)) { case expr_stmt: return ast_for_expr_stmt(c, n); - case print_stmt: - return ast_for_print_stmt(c, n); case del_stmt: return ast_for_del_stmt(c, n); case pass_stmt: Modified: python/branches/p3yk-noslice/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk-noslice/Python/bltinmodule.c (original) +++ python/branches/p3yk-noslice/Python/bltinmodule.c Fri Feb 23 18:29:35 2007 @@ -1398,7 +1398,7 @@ if (dummy_args == NULL) return NULL; - if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:Print", + if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print", kwlist, &sep, &end, &file)) return NULL; if (file == NULL || file == Py_None) @@ -1446,7 +1446,7 @@ } PyDoc_STRVAR(print_doc, -"Print(value, ..., file=None, sep=' ', end='\\n')\n\ +"print(value, ..., file=None, sep=' ', end='\\n')\n\ \n\ Prints the values to a stream, or to sys.stdout by default.\n\ Optional keyword arguments:\n\ @@ -2056,7 +2056,7 @@ {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc}, {"ord", builtin_ord, METH_O, ord_doc}, {"pow", builtin_pow, METH_VARARGS, pow_doc}, - {"Print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, + {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, {"range", builtin_range, METH_VARARGS, range_doc}, {"reload", builtin_reload, METH_O, reload_doc}, {"repr", builtin_repr, METH_O, repr_doc}, @@ -2124,9 +2124,8 @@ 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); SETBUILTIN("reversed", &PyReversed_Type); SETBUILTIN("set", &PySet_Type); Modified: python/branches/p3yk-noslice/Python/ceval.c ============================================================================== --- python/branches/p3yk-noslice/Python/ceval.c (original) +++ python/branches/p3yk-noslice/Python/ceval.c Fri Feb 23 18:29:35 2007 @@ -520,7 +520,6 @@ register PyObject *v; /* Temporary objects popped off stack */ register PyObject *w; register PyObject *u; - register PyObject *stream = NULL; /* for PRINT opcodes */ register PyObject **fastlocals, **freevars; PyObject *retval = NULL; /* Return value */ PyThreadState *tstate = PyThreadState_GET(); @@ -1440,81 +1439,6 @@ Py_XDECREF(x); break; - case PRINT_ITEM_TO: - w = stream = POP(); - /* fall through to PRINT_ITEM */ - - case PRINT_ITEM: - v = POP(); - if (stream == NULL || stream == Py_None) { - w = PySys_GetObject("stdout"); - if (w == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "lost sys.stdout"); - err = -1; - } - } - /* PyFile_SoftSpace() can exececute arbitrary code - if sys.stdout is an instance with a __getattr__. - If __getattr__ raises an exception, w will - be freed, so we need to prevent that temporarily. */ - Py_XINCREF(w); - if (w != NULL && PyFile_SoftSpace(w, 0)) - err = PyFile_WriteString(" ", w); - if (err == 0) - err = PyFile_WriteObject(v, w, Py_PRINT_RAW); - if (err == 0) { - /* XXX move into writeobject() ? */ - if (PyString_Check(v)) { - char *s = PyString_AS_STRING(v); - Py_ssize_t len = PyString_GET_SIZE(v); - if (len == 0 || - !isspace(Py_CHARMASK(s[len-1])) || - s[len-1] == ' ') - PyFile_SoftSpace(w, 1); - } -#ifdef Py_USING_UNICODE - else if (PyUnicode_Check(v)) { - Py_UNICODE *s = PyUnicode_AS_UNICODE(v); - Py_ssize_t len = PyUnicode_GET_SIZE(v); - if (len == 0 || - !Py_UNICODE_ISSPACE(s[len-1]) || - s[len-1] == ' ') - PyFile_SoftSpace(w, 1); - } -#endif - else - PyFile_SoftSpace(w, 1); - } - Py_XDECREF(w); - Py_DECREF(v); - Py_XDECREF(stream); - stream = NULL; - if (err == 0) - continue; - break; - - case PRINT_NEWLINE_TO: - w = stream = POP(); - /* fall through to PRINT_NEWLINE */ - - case PRINT_NEWLINE: - if (stream == NULL || stream == Py_None) { - w = PySys_GetObject("stdout"); - if (w == NULL) - PyErr_SetString(PyExc_RuntimeError, - "lost sys.stdout"); - } - if (w != NULL) { - err = PyFile_WriteString("\n", w); - if (err == 0) - PyFile_SoftSpace(w, 0); - } - Py_XDECREF(stream); - stream = NULL; - break; - - #ifdef CASE_TOO_BIG default: switch (opcode) { #endif @@ -2106,8 +2030,9 @@ case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: - /* NOTE: If you add any new block-setup opcodes that are not try/except/finally - handlers, you may need to update the PyGen_NeedsFinalizing() function. */ + /* NOTE: If you add any new block-setup opcodes that are + not try/except/finally handlers, you may need to + update the PyGen_NeedsFinalizing() function. */ PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, STACK_LEVEL()); @@ -2705,7 +2630,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; @@ -3357,17 +3282,6 @@ return result; } -int -Py_FlushLine(void) -{ - PyObject *f = PySys_GetObject("stdout"); - if (f == NULL) - return 0; - if (!PyFile_SoftSpace(f, 0)) - return 0; - return PyFile_WriteString("\n", f); -} - /* External interface to call any callable object. The arg must be a tuple or NULL. */ @@ -3833,7 +3747,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. @@ -3879,6 +3793,35 @@ res = !res; break; case PyCmp_EXC_MATCH: + if (PyTuple_Check(w)) { + Py_ssize_t i, length; + length = PyTuple_Size(w); + for (i = 0; i < length; i += 1) { + PyObject *exc = PyTuple_GET_ITEM(w, i); + if (PyString_Check(exc)) { + int ret_val; + ret_val = PyErr_WarnEx( + PyExc_DeprecationWarning, + "catching of string " + "exceptions is " + "deprecated", 1); + if (ret_val == -1) + return NULL; + } + } + } + else { + if (PyString_Check(w)) { + int ret_val; + ret_val = PyErr_WarnEx( + PyExc_DeprecationWarning, + "catching of string " + "exceptions is deprecated", + 1); + if (ret_val == -1) + return NULL; + } + } res = PyErr_GivenExceptionMatches(v, w); break; default: Modified: python/branches/p3yk-noslice/Python/compile.c ============================================================================== --- python/branches/p3yk-noslice/Python/compile.c (original) +++ python/branches/p3yk-noslice/Python/compile.c Fri Feb 23 18:29:35 2007 @@ -707,14 +707,6 @@ case PRINT_EXPR: return -1; - case PRINT_ITEM: - return -1; - case PRINT_NEWLINE: - return 0; - case PRINT_ITEM_TO: - return -2; - case PRINT_NEWLINE_TO: - return -1; case INPLACE_LSHIFT: case INPLACE_RSHIFT: case INPLACE_AND: @@ -1599,43 +1591,6 @@ } static int -compiler_print(struct compiler *c, stmt_ty s) -{ - int i, n; - bool dest; - - assert(s->kind == Print_kind); - n = asdl_seq_LEN(s->v.Print.values); - dest = false; - if (s->v.Print.dest) { - VISIT(c, expr, s->v.Print.dest); - dest = true; - } - for (i = 0; i < n; i++) { - expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i); - if (dest) { - ADDOP(c, DUP_TOP); - VISIT(c, expr, e); - ADDOP(c, ROT_TWO); - ADDOP(c, PRINT_ITEM_TO); - } - else { - VISIT(c, expr, e); - ADDOP(c, PRINT_ITEM); - } - } - if (s->v.Print.nl) { - if (dest) - ADDOP(c, PRINT_NEWLINE_TO) - else - ADDOP(c, PRINT_NEWLINE) - } - else if (dest) - ADDOP(c, POP_TOP); - return 1; -} - -static int compiler_if(struct compiler *c, stmt_ty s) { basicblock *end, *next; @@ -2209,8 +2164,6 @@ break; case AugAssign_kind: return compiler_augassign(c, s); - case Print_kind: - return compiler_print(c, s); case For_kind: return compiler_for(c, s); case While_kind: Modified: python/branches/p3yk-noslice/Python/frozen.c ============================================================================== --- python/branches/p3yk-noslice/Python/frozen.c (original) +++ python/branches/p3yk-noslice/Python/frozen.c Fri Feb 23 18:29:35 2007 @@ -12,14 +12,15 @@ the appropriate bytes from M___main__.c. */ static unsigned char M___hello__[] = { - 99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, - 0,64,0,0,0,115,9,0,0,0,100,0,0,71,72,100, - 1,0,83,40,2,0,0,0,115,14,0,0,0,72,101,108, - 108,111,32,119,111,114,108,100,46,46,46,78,40,0,0,0, - 0,40,0,0,0,0,40,0,0,0,0,40,0,0,0,0, - 115,8,0,0,0,104,101,108,108,111,46,112,121,115,8,0, - 0,0,60,109,111,100,117,108,101,62,1,0,0,0,115,0, - 0,0,0, + 99,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0, + 0,64,0,0,0,115,14,0,0,0,101,0,0,100,0,0, + 131,1,0,1,100,1,0,83,40,2,0,0,0,115,14,0, + 0,0,72,101,108,108,111,32,119,111,114,108,100,46,46,46, + 78,40,1,0,0,0,116,5,0,0,0,112,114,105,110,116, + 40,0,0,0,0,40,0,0,0,0,40,0,0,0,0,115, + 8,0,0,0,104,101,108,108,111,46,112,121,115,8,0,0, + 0,60,109,111,100,117,108,101,62,1,0,0,0,115,0,0, + 0,0, }; #define SIZE (int)sizeof(M___hello__) Modified: python/branches/p3yk-noslice/Python/getargs.c ============================================================================== --- python/branches/p3yk-noslice/Python/getargs.c (original) +++ python/branches/p3yk-noslice/Python/getargs.c Fri Feb 23 18:29:35 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-noslice/Python/graminit.c ============================================================================== --- python/branches/p3yk-noslice/Python/graminit.c (original) +++ python/branches/p3yk-noslice/Python/graminit.c Fri Feb 23 18:29:35 2007 @@ -403,7 +403,7 @@ {2, arcs_16_2}, {1, arcs_16_3}, }; -static arc arcs_17_0[8] = { +static arc arcs_17_0[7] = { {39, 1}, {40, 1}, {41, 1}, @@ -411,29 +411,28 @@ {43, 1}, {44, 1}, {45, 1}, - {46, 1}, }; static arc arcs_17_1[1] = { {0, 1}, }; static state states_17[2] = { - {8, arcs_17_0}, + {7, arcs_17_0}, {1, arcs_17_1}, }; static arc arcs_18_0[1] = { {9, 1}, }; static arc arcs_18_1[3] = { - {47, 2}, + {46, 2}, {27, 3}, {0, 1}, }; static arc arcs_18_2[2] = { - {48, 4}, + {47, 4}, {9, 4}, }; static arc arcs_18_3[2] = { - {48, 5}, + {47, 5}, {9, 5}, }; static arc arcs_18_4[1] = { @@ -452,6 +451,7 @@ {2, arcs_18_5}, }; static arc arcs_19_0[12] = { + {48, 1}, {49, 1}, {50, 1}, {51, 1}, @@ -463,7 +463,6 @@ {57, 1}, {58, 1}, {59, 1}, - {60, 1}, }; static arc arcs_19_1[1] = { {0, 1}, @@ -473,90 +472,55 @@ {1, arcs_19_1}, }; static arc arcs_20_0[1] = { - {61, 1}, + {60, 1}, }; -static arc arcs_20_1[3] = { - {22, 2}, - {62, 3}, - {0, 1}, +static arc arcs_20_1[1] = { + {61, 2}, }; -static arc arcs_20_2[2] = { - {28, 4}, +static arc arcs_20_2[1] = { {0, 2}, }; -static arc arcs_20_3[1] = { - {22, 5}, -}; -static arc arcs_20_4[2] = { - {22, 2}, - {0, 4}, -}; -static arc arcs_20_5[2] = { - {28, 6}, - {0, 5}, -}; -static arc arcs_20_6[1] = { - {22, 7}, -}; -static arc arcs_20_7[2] = { - {28, 8}, - {0, 7}, -}; -static arc arcs_20_8[2] = { - {22, 7}, - {0, 8}, -}; -static state states_20[9] = { +static state states_20[3] = { {1, arcs_20_0}, - {3, arcs_20_1}, - {2, arcs_20_2}, - {1, arcs_20_3}, - {2, arcs_20_4}, - {2, arcs_20_5}, - {1, arcs_20_6}, - {2, arcs_20_7}, - {2, arcs_20_8}, + {1, arcs_20_1}, + {1, arcs_20_2}, }; static arc arcs_21_0[1] = { - {63, 1}, + {62, 1}, }; static arc arcs_21_1[1] = { - {64, 2}, -}; -static arc arcs_21_2[1] = { - {0, 2}, + {0, 1}, }; -static state states_21[3] = { +static state states_21[2] = { {1, arcs_21_0}, {1, arcs_21_1}, - {1, arcs_21_2}, }; -static arc arcs_22_0[1] = { +static arc arcs_22_0[5] = { + {63, 1}, + {64, 1}, {65, 1}, + {66, 1}, + {67, 1}, }; static arc arcs_22_1[1] = { {0, 1}, }; static state states_22[2] = { - {1, arcs_22_0}, + {5, arcs_22_0}, {1, arcs_22_1}, }; -static arc arcs_23_0[5] = { - {66, 1}, - {67, 1}, +static arc arcs_23_0[1] = { {68, 1}, - {69, 1}, - {70, 1}, }; static arc arcs_23_1[1] = { {0, 1}, }; static state states_23[2] = { - {5, arcs_23_0}, + {1, arcs_23_0}, {1, arcs_23_1}, }; static arc arcs_24_0[1] = { - {71, 1}, + {69, 1}, }; static arc arcs_24_1[1] = { {0, 1}, @@ -566,142 +530,151 @@ {1, arcs_24_1}, }; static arc arcs_25_0[1] = { - {72, 1}, + {70, 1}, }; -static arc arcs_25_1[1] = { +static arc arcs_25_1[2] = { + {9, 2}, {0, 1}, }; -static state states_25[2] = { +static arc arcs_25_2[1] = { + {0, 2}, +}; +static state states_25[3] = { {1, arcs_25_0}, - {1, arcs_25_1}, + {2, arcs_25_1}, + {1, arcs_25_2}, }; static arc arcs_26_0[1] = { - {73, 1}, + {47, 1}, }; -static arc arcs_26_1[2] = { - {9, 2}, +static arc arcs_26_1[1] = { {0, 1}, }; -static arc arcs_26_2[1] = { - {0, 2}, -}; -static state states_26[3] = { +static state states_26[2] = { {1, arcs_26_0}, - {2, arcs_26_1}, - {1, arcs_26_2}, + {1, arcs_26_1}, }; static arc arcs_27_0[1] = { - {48, 1}, -}; -static arc arcs_27_1[1] = { - {0, 1}, -}; -static state states_27[2] = { - {1, arcs_27_0}, - {1, arcs_27_1}, -}; -static arc arcs_28_0[1] = { - {74, 1}, + {71, 1}, }; -static arc arcs_28_1[2] = { +static arc arcs_27_1[2] = { {22, 2}, {0, 1}, }; -static arc arcs_28_2[2] = { +static arc arcs_27_2[2] = { {28, 3}, {0, 2}, }; -static arc arcs_28_3[1] = { +static arc arcs_27_3[1] = { {22, 4}, }; -static arc arcs_28_4[2] = { +static arc arcs_27_4[2] = { {28, 5}, {0, 4}, }; -static arc arcs_28_5[1] = { +static arc arcs_27_5[1] = { {22, 6}, }; -static arc arcs_28_6[1] = { +static arc arcs_27_6[1] = { {0, 6}, }; -static state states_28[7] = { - {1, arcs_28_0}, - {2, arcs_28_1}, - {2, arcs_28_2}, - {1, arcs_28_3}, - {2, arcs_28_4}, - {1, arcs_28_5}, - {1, arcs_28_6}, +static state states_27[7] = { + {1, arcs_27_0}, + {2, arcs_27_1}, + {2, arcs_27_2}, + {1, arcs_27_3}, + {2, arcs_27_4}, + {1, arcs_27_5}, + {1, arcs_27_6}, }; -static arc arcs_29_0[2] = { - {75, 1}, - {76, 1}, +static arc arcs_28_0[2] = { + {72, 1}, + {73, 1}, }; -static arc arcs_29_1[1] = { +static arc arcs_28_1[1] = { {0, 1}, }; -static state states_29[2] = { - {2, arcs_29_0}, - {1, arcs_29_1}, +static state states_28[2] = { + {2, arcs_28_0}, + {1, arcs_28_1}, }; -static arc arcs_30_0[1] = { - {77, 1}, +static arc arcs_29_0[1] = { + {74, 1}, }; -static arc arcs_30_1[1] = { - {78, 2}, +static arc arcs_29_1[1] = { + {75, 2}, }; -static arc arcs_30_2[1] = { +static arc arcs_29_2[1] = { {0, 2}, }; -static state states_30[3] = { - {1, arcs_30_0}, - {1, arcs_30_1}, - {1, arcs_30_2}, +static state states_29[3] = { + {1, arcs_29_0}, + {1, arcs_29_1}, + {1, arcs_29_2}, }; -static arc arcs_31_0[1] = { - {79, 1}, +static arc arcs_30_0[1] = { + {76, 1}, }; -static arc arcs_31_1[2] = { - {80, 2}, +static arc arcs_30_1[2] = { + {77, 2}, {12, 3}, }; -static arc arcs_31_2[3] = { - {80, 2}, +static arc arcs_30_2[3] = { + {77, 2}, {12, 3}, - {77, 4}, + {74, 4}, }; -static arc arcs_31_3[1] = { - {77, 4}, +static arc arcs_30_3[1] = { + {74, 4}, }; -static arc arcs_31_4[3] = { +static arc arcs_30_4[3] = { {29, 5}, {13, 6}, - {81, 5}, + {78, 5}, }; -static arc arcs_31_5[1] = { +static arc arcs_30_5[1] = { {0, 5}, }; -static arc arcs_31_6[1] = { - {81, 7}, +static arc arcs_30_6[1] = { + {78, 7}, }; -static arc arcs_31_7[1] = { +static arc arcs_30_7[1] = { {15, 5}, }; -static state states_31[8] = { +static state states_30[8] = { + {1, arcs_30_0}, + {2, arcs_30_1}, + {3, arcs_30_2}, + {1, arcs_30_3}, + {3, arcs_30_4}, + {1, arcs_30_5}, + {1, arcs_30_6}, + {1, arcs_30_7}, +}; +static arc arcs_31_0[1] = { + {19, 1}, +}; +static arc arcs_31_1[2] = { + {80, 2}, + {0, 1}, +}; +static arc arcs_31_2[1] = { + {19, 3}, +}; +static arc arcs_31_3[1] = { + {0, 3}, +}; +static state states_31[4] = { {1, arcs_31_0}, {2, arcs_31_1}, - {3, arcs_31_2}, + {1, arcs_31_2}, {1, arcs_31_3}, - {3, arcs_31_4}, - {1, arcs_31_5}, - {1, arcs_31_6}, - {1, arcs_31_7}, }; static arc arcs_32_0[1] = { - {19, 1}, + {12, 1}, }; static arc arcs_32_1[2] = { - {83, 2}, + {80, 2}, {0, 1}, }; static arc arcs_32_2[1] = { @@ -717,45 +690,37 @@ {1, arcs_32_3}, }; static arc arcs_33_0[1] = { - {12, 1}, + {79, 1}, }; static arc arcs_33_1[2] = { - {83, 2}, + {28, 2}, {0, 1}, }; -static arc arcs_33_2[1] = { - {19, 3}, -}; -static arc arcs_33_3[1] = { - {0, 3}, +static arc arcs_33_2[2] = { + {79, 1}, + {0, 2}, }; -static state states_33[4] = { +static state states_33[3] = { {1, arcs_33_0}, {2, arcs_33_1}, - {1, arcs_33_2}, - {1, arcs_33_3}, + {2, arcs_33_2}, }; static arc arcs_34_0[1] = { - {82, 1}, + {81, 1}, }; static arc arcs_34_1[2] = { - {28, 2}, + {28, 0}, {0, 1}, }; -static arc arcs_34_2[2] = { - {82, 1}, - {0, 2}, -}; -static state states_34[3] = { +static state states_34[2] = { {1, arcs_34_0}, {2, arcs_34_1}, - {2, arcs_34_2}, }; static arc arcs_35_0[1] = { - {84, 1}, + {19, 1}, }; static arc arcs_35_1[2] = { - {28, 0}, + {77, 0}, {0, 1}, }; static state states_35[2] = { @@ -763,69 +728,94 @@ {2, arcs_35_1}, }; static arc arcs_36_0[1] = { - {19, 1}, + {82, 1}, }; -static arc arcs_36_1[2] = { - {80, 0}, - {0, 1}, +static arc arcs_36_1[1] = { + {19, 2}, }; -static state states_36[2] = { +static arc arcs_36_2[2] = { + {28, 1}, + {0, 2}, +}; +static state states_36[3] = { {1, arcs_36_0}, - {2, arcs_36_1}, + {1, arcs_36_1}, + {2, arcs_36_2}, }; static arc arcs_37_0[1] = { - {85, 1}, + {83, 1}, }; static arc arcs_37_1[1] = { - {19, 2}, + {22, 2}, }; static arc arcs_37_2[2] = { - {28, 1}, + {28, 3}, {0, 2}, }; -static state states_37[3] = { +static arc arcs_37_3[1] = { + {22, 4}, +}; +static arc arcs_37_4[1] = { + {0, 4}, +}; +static state states_37[5] = { {1, arcs_37_0}, {1, arcs_37_1}, {2, arcs_37_2}, + {1, arcs_37_3}, + {1, arcs_37_4}, }; -static arc arcs_38_0[1] = { +static arc arcs_38_0[7] = { + {84, 1}, + {85, 1}, {86, 1}, + {87, 1}, + {88, 1}, + {17, 1}, + {89, 1}, }; static arc arcs_38_1[1] = { + {0, 1}, +}; +static state states_38[2] = { + {7, arcs_38_0}, + {1, arcs_38_1}, +}; +static arc arcs_39_0[1] = { + {90, 1}, +}; +static arc arcs_39_1[1] = { {22, 2}, }; -static arc arcs_38_2[2] = { - {28, 3}, - {0, 2}, +static arc arcs_39_2[1] = { + {23, 3}, }; -static arc arcs_38_3[1] = { - {22, 4}, +static arc arcs_39_3[1] = { + {24, 4}, }; -static arc arcs_38_4[1] = { +static arc arcs_39_4[3] = { + {91, 1}, + {92, 5}, {0, 4}, }; -static state states_38[5] = { - {1, arcs_38_0}, - {1, arcs_38_1}, - {2, arcs_38_2}, - {1, arcs_38_3}, - {1, arcs_38_4}, +static arc arcs_39_5[1] = { + {23, 6}, }; -static arc arcs_39_0[7] = { - {87, 1}, - {88, 1}, - {89, 1}, - {90, 1}, - {91, 1}, - {17, 1}, - {92, 1}, +static arc arcs_39_6[1] = { + {24, 7}, }; -static arc arcs_39_1[1] = { - {0, 1}, +static arc arcs_39_7[1] = { + {0, 7}, }; -static state states_39[2] = { - {7, arcs_39_0}, +static state states_39[8] = { + {1, arcs_39_0}, {1, arcs_39_1}, + {1, arcs_39_2}, + {1, arcs_39_3}, + {3, arcs_39_4}, + {1, arcs_39_5}, + {1, arcs_39_6}, + {1, arcs_39_7}, }; static arc arcs_40_0[1] = { {93, 1}, @@ -839,9 +829,8 @@ static arc arcs_40_3[1] = { {24, 4}, }; -static arc arcs_40_4[3] = { - {94, 1}, - {95, 5}, +static arc arcs_40_4[2] = { + {92, 5}, {0, 4}, }; static arc arcs_40_5[1] = { @@ -858,404 +847,380 @@ {1, arcs_40_1}, {1, arcs_40_2}, {1, arcs_40_3}, - {3, arcs_40_4}, + {2, arcs_40_4}, {1, arcs_40_5}, {1, arcs_40_6}, {1, arcs_40_7}, }; static arc arcs_41_0[1] = { - {96, 1}, + {94, 1}, }; static arc arcs_41_1[1] = { - {22, 2}, + {61, 2}, }; static arc arcs_41_2[1] = { - {23, 3}, + {95, 3}, }; static arc arcs_41_3[1] = { - {24, 4}, + {9, 4}, }; -static arc arcs_41_4[2] = { - {95, 5}, - {0, 4}, +static arc arcs_41_4[1] = { + {23, 5}, }; static arc arcs_41_5[1] = { - {23, 6}, + {24, 6}, }; -static arc arcs_41_6[1] = { - {24, 7}, +static arc arcs_41_6[2] = { + {92, 7}, + {0, 6}, }; static arc arcs_41_7[1] = { - {0, 7}, + {23, 8}, +}; +static arc arcs_41_8[1] = { + {24, 9}, +}; +static arc arcs_41_9[1] = { + {0, 9}, }; -static state states_41[8] = { +static state states_41[10] = { {1, arcs_41_0}, {1, arcs_41_1}, {1, arcs_41_2}, {1, arcs_41_3}, - {2, arcs_41_4}, + {1, arcs_41_4}, {1, arcs_41_5}, - {1, arcs_41_6}, + {2, arcs_41_6}, {1, arcs_41_7}, + {1, arcs_41_8}, + {1, arcs_41_9}, }; static arc arcs_42_0[1] = { - {97, 1}, + {96, 1}, }; static arc arcs_42_1[1] = { - {64, 2}, + {23, 2}, }; static arc arcs_42_2[1] = { - {98, 3}, + {24, 3}, }; -static arc arcs_42_3[1] = { - {9, 4}, +static arc arcs_42_3[2] = { + {97, 4}, + {98, 5}, }; static arc arcs_42_4[1] = { - {23, 5}, + {23, 6}, }; static arc arcs_42_5[1] = { - {24, 6}, + {23, 7}, }; -static arc arcs_42_6[2] = { - {95, 7}, - {0, 6}, +static arc arcs_42_6[1] = { + {24, 8}, }; static arc arcs_42_7[1] = { - {23, 8}, -}; -static arc arcs_42_8[1] = { {24, 9}, }; +static arc arcs_42_8[4] = { + {97, 4}, + {92, 10}, + {98, 5}, + {0, 8}, +}; static arc arcs_42_9[1] = { {0, 9}, }; -static state states_42[10] = { +static arc arcs_42_10[1] = { + {23, 11}, +}; +static arc arcs_42_11[1] = { + {24, 12}, +}; +static arc arcs_42_12[2] = { + {98, 5}, + {0, 12}, +}; +static state states_42[13] = { {1, arcs_42_0}, {1, arcs_42_1}, {1, arcs_42_2}, - {1, arcs_42_3}, + {2, arcs_42_3}, {1, arcs_42_4}, {1, arcs_42_5}, - {2, arcs_42_6}, + {1, arcs_42_6}, {1, arcs_42_7}, - {1, arcs_42_8}, + {4, arcs_42_8}, {1, arcs_42_9}, + {1, arcs_42_10}, + {1, arcs_42_11}, + {2, arcs_42_12}, }; static arc arcs_43_0[1] = { {99, 1}, }; static arc arcs_43_1[1] = { - {23, 2}, + {22, 2}, }; -static arc arcs_43_2[1] = { - {24, 3}, +static arc arcs_43_2[2] = { + {100, 3}, + {23, 4}, }; -static arc arcs_43_3[2] = { - {100, 4}, - {101, 5}, +static arc arcs_43_3[1] = { + {23, 4}, }; static arc arcs_43_4[1] = { - {23, 6}, + {24, 5}, }; static arc arcs_43_5[1] = { - {23, 7}, -}; -static arc arcs_43_6[1] = { - {24, 8}, -}; -static arc arcs_43_7[1] = { - {24, 9}, -}; -static arc arcs_43_8[4] = { - {100, 4}, - {95, 10}, - {101, 5}, - {0, 8}, -}; -static arc arcs_43_9[1] = { - {0, 9}, -}; -static arc arcs_43_10[1] = { - {23, 11}, -}; -static arc arcs_43_11[1] = { - {24, 12}, -}; -static arc arcs_43_12[2] = { - {101, 5}, - {0, 12}, + {0, 5}, }; -static state states_43[13] = { +static state states_43[6] = { {1, arcs_43_0}, {1, arcs_43_1}, - {1, arcs_43_2}, - {2, arcs_43_3}, + {2, arcs_43_2}, + {1, arcs_43_3}, {1, arcs_43_4}, {1, arcs_43_5}, - {1, arcs_43_6}, - {1, arcs_43_7}, - {4, arcs_43_8}, - {1, arcs_43_9}, - {1, arcs_43_10}, - {1, arcs_43_11}, - {2, arcs_43_12}, }; static arc arcs_44_0[1] = { - {102, 1}, + {80, 1}, }; static arc arcs_44_1[1] = { - {22, 2}, -}; -static arc arcs_44_2[2] = { - {103, 3}, - {23, 4}, + {101, 2}, }; -static arc arcs_44_3[1] = { - {23, 4}, -}; -static arc arcs_44_4[1] = { - {24, 5}, -}; -static arc arcs_44_5[1] = { - {0, 5}, +static arc arcs_44_2[1] = { + {0, 2}, }; -static state states_44[6] = { +static state states_44[3] = { {1, arcs_44_0}, {1, arcs_44_1}, - {2, arcs_44_2}, - {1, arcs_44_3}, - {1, arcs_44_4}, - {1, arcs_44_5}, + {1, arcs_44_2}, }; static arc arcs_45_0[1] = { - {83, 1}, + {102, 1}, }; -static arc arcs_45_1[1] = { - {104, 2}, +static arc arcs_45_1[2] = { + {22, 2}, + {0, 1}, }; -static arc arcs_45_2[1] = { +static arc arcs_45_2[2] = { + {80, 3}, {0, 2}, }; -static state states_45[3] = { +static arc arcs_45_3[1] = { + {19, 4}, +}; +static arc arcs_45_4[1] = { + {0, 4}, +}; +static state states_45[5] = { {1, arcs_45_0}, - {1, arcs_45_1}, - {1, arcs_45_2}, + {2, arcs_45_1}, + {2, arcs_45_2}, + {1, arcs_45_3}, + {1, arcs_45_4}, }; -static arc arcs_46_0[1] = { - {105, 1}, +static arc arcs_46_0[2] = { + {3, 1}, + {2, 2}, }; -static arc arcs_46_1[2] = { - {22, 2}, +static arc arcs_46_1[1] = { {0, 1}, }; -static arc arcs_46_2[2] = { - {83, 3}, - {0, 2}, +static arc arcs_46_2[1] = { + {103, 3}, }; static arc arcs_46_3[1] = { - {19, 4}, + {6, 4}, }; -static arc arcs_46_4[1] = { - {0, 4}, +static arc arcs_46_4[2] = { + {6, 4}, + {104, 1}, }; static state states_46[5] = { - {1, arcs_46_0}, - {2, arcs_46_1}, - {2, arcs_46_2}, + {2, arcs_46_0}, + {1, arcs_46_1}, + {1, arcs_46_2}, {1, arcs_46_3}, - {1, arcs_46_4}, + {2, arcs_46_4}, }; -static arc arcs_47_0[2] = { - {3, 1}, - {2, 2}, +static arc arcs_47_0[1] = { + {106, 1}, }; -static arc arcs_47_1[1] = { +static arc arcs_47_1[2] = { + {28, 2}, {0, 1}, }; static arc arcs_47_2[1] = { {106, 3}, }; -static arc arcs_47_3[1] = { - {6, 4}, +static arc arcs_47_3[2] = { + {28, 4}, + {0, 3}, }; static arc arcs_47_4[2] = { - {6, 4}, - {107, 1}, + {106, 3}, + {0, 4}, }; static state states_47[5] = { - {2, arcs_47_0}, - {1, arcs_47_1}, + {1, arcs_47_0}, + {2, arcs_47_1}, {1, arcs_47_2}, - {1, arcs_47_3}, + {2, arcs_47_3}, {2, arcs_47_4}, }; -static arc arcs_48_0[1] = { - {109, 1}, +static arc arcs_48_0[2] = { + {107, 1}, + {108, 1}, }; -static arc arcs_48_1[2] = { - {28, 2}, +static arc arcs_48_1[1] = { {0, 1}, }; -static arc arcs_48_2[1] = { - {109, 3}, +static state states_48[2] = { + {2, arcs_48_0}, + {1, arcs_48_1}, }; -static arc arcs_48_3[2] = { - {28, 4}, - {0, 3}, +static arc arcs_49_0[1] = { + {109, 1}, }; -static arc arcs_48_4[2] = { - {109, 3}, - {0, 4}, +static arc arcs_49_1[2] = { + {33, 2}, + {23, 3}, }; -static state states_48[5] = { - {1, arcs_48_0}, - {2, arcs_48_1}, - {1, arcs_48_2}, - {2, arcs_48_3}, - {2, arcs_48_4}, +static arc arcs_49_2[1] = { + {23, 3}, }; -static arc arcs_49_0[2] = { - {110, 1}, - {111, 1}, +static arc arcs_49_3[1] = { + {106, 4}, }; -static arc arcs_49_1[1] = { - {0, 1}, +static arc arcs_49_4[1] = { + {0, 4}, }; -static state states_49[2] = { - {2, arcs_49_0}, - {1, arcs_49_1}, +static state states_49[5] = { + {1, arcs_49_0}, + {2, arcs_49_1}, + {1, arcs_49_2}, + {1, arcs_49_3}, + {1, arcs_49_4}, }; -static arc arcs_50_0[1] = { - {112, 1}, +static arc arcs_50_0[2] = { + {107, 1}, + {110, 2}, }; static arc arcs_50_1[2] = { - {33, 2}, - {23, 3}, + {90, 3}, + {0, 1}, }; static arc arcs_50_2[1] = { - {23, 3}, + {0, 2}, }; static arc arcs_50_3[1] = { - {109, 4}, + {107, 4}, }; static arc arcs_50_4[1] = { - {0, 4}, + {92, 5}, +}; +static arc arcs_50_5[1] = { + {22, 2}, }; -static state states_50[5] = { - {1, arcs_50_0}, +static state states_50[6] = { + {2, arcs_50_0}, {2, arcs_50_1}, {1, arcs_50_2}, {1, arcs_50_3}, {1, arcs_50_4}, + {1, arcs_50_5}, }; -static arc arcs_51_0[2] = { - {110, 1}, - {113, 2}, +static arc arcs_51_0[1] = { + {111, 1}, }; static arc arcs_51_1[2] = { - {93, 3}, + {112, 0}, {0, 1}, }; -static arc arcs_51_2[1] = { - {0, 2}, -}; -static arc arcs_51_3[1] = { - {110, 4}, -}; -static arc arcs_51_4[1] = { - {95, 5}, -}; -static arc arcs_51_5[1] = { - {22, 2}, -}; -static state states_51[6] = { - {2, arcs_51_0}, +static state states_51[2] = { + {1, arcs_51_0}, {2, arcs_51_1}, - {1, arcs_51_2}, - {1, arcs_51_3}, - {1, arcs_51_4}, - {1, arcs_51_5}, }; static arc arcs_52_0[1] = { - {114, 1}, + {113, 1}, }; static arc arcs_52_1[2] = { - {115, 0}, + {114, 0}, {0, 1}, }; static state states_52[2] = { {1, arcs_52_0}, {2, arcs_52_1}, }; -static arc arcs_53_0[1] = { - {116, 1}, -}; -static arc arcs_53_1[2] = { - {117, 0}, - {0, 1}, -}; -static state states_53[2] = { - {1, arcs_53_0}, - {2, arcs_53_1}, -}; -static arc arcs_54_0[2] = { - {118, 1}, - {119, 2}, -}; -static arc arcs_54_1[1] = { +static arc arcs_53_0[2] = { + {115, 1}, {116, 2}, }; -static arc arcs_54_2[1] = { +static arc arcs_53_1[1] = { + {113, 2}, +}; +static arc arcs_53_2[1] = { {0, 2}, }; -static state states_54[3] = { - {2, arcs_54_0}, - {1, arcs_54_1}, - {1, arcs_54_2}, +static state states_53[3] = { + {2, arcs_53_0}, + {1, arcs_53_1}, + {1, arcs_53_2}, }; -static arc arcs_55_0[1] = { - {104, 1}, +static arc arcs_54_0[1] = { + {101, 1}, }; -static arc arcs_55_1[2] = { - {120, 0}, +static arc arcs_54_1[2] = { + {117, 0}, {0, 1}, }; -static state states_55[2] = { - {1, arcs_55_0}, - {2, arcs_55_1}, +static state states_54[2] = { + {1, arcs_54_0}, + {2, arcs_54_1}, }; -static arc arcs_56_0[9] = { +static arc arcs_55_0[9] = { + {118, 1}, + {119, 1}, + {120, 1}, {121, 1}, {122, 1}, {123, 1}, - {124, 1}, - {125, 1}, - {126, 1}, - {98, 1}, - {118, 2}, - {127, 3}, + {95, 1}, + {115, 2}, + {124, 3}, }; -static arc arcs_56_1[1] = { +static arc arcs_55_1[1] = { {0, 1}, }; -static arc arcs_56_2[1] = { - {98, 1}, +static arc arcs_55_2[1] = { + {95, 1}, }; -static arc arcs_56_3[2] = { - {118, 1}, +static arc arcs_55_3[2] = { + {115, 1}, {0, 3}, }; -static state states_56[4] = { - {9, arcs_56_0}, - {1, arcs_56_1}, - {1, arcs_56_2}, - {2, arcs_56_3}, +static state states_55[4] = { + {9, arcs_55_0}, + {1, arcs_55_1}, + {1, arcs_55_2}, + {2, arcs_55_3}, +}; +static arc arcs_56_0[1] = { + {125, 1}, +}; +static arc arcs_56_1[2] = { + {126, 0}, + {0, 1}, +}; +static state states_56[2] = { + {1, arcs_56_0}, + {2, arcs_56_1}, }; static arc arcs_57_0[1] = { - {128, 1}, + {127, 1}, }; static arc arcs_57_1[2] = { - {129, 0}, + {128, 0}, {0, 1}, }; static state states_57[2] = { @@ -1263,10 +1228,10 @@ {2, arcs_57_1}, }; static arc arcs_58_0[1] = { - {130, 1}, + {129, 1}, }; static arc arcs_58_1[2] = { - {131, 0}, + {130, 0}, {0, 1}, }; static state states_58[2] = { @@ -1274,22 +1239,23 @@ {2, arcs_58_1}, }; static arc arcs_59_0[1] = { - {132, 1}, + {131, 1}, }; -static arc arcs_59_1[2] = { +static arc arcs_59_1[3] = { + {132, 0}, {133, 0}, {0, 1}, }; static state states_59[2] = { {1, arcs_59_0}, - {2, arcs_59_1}, + {3, arcs_59_1}, }; static arc arcs_60_0[1] = { {134, 1}, }; static arc arcs_60_1[3] = { {135, 0}, - {62, 0}, + {136, 0}, {0, 1}, }; static state states_60[2] = { @@ -1297,300 +1263,304 @@ {3, arcs_60_1}, }; static arc arcs_61_0[1] = { - {136, 1}, + {137, 1}, }; -static arc arcs_61_1[3] = { - {137, 0}, +static arc arcs_61_1[5] = { + {29, 0}, {138, 0}, + {139, 0}, + {140, 0}, {0, 1}, }; static state states_61[2] = { {1, arcs_61_0}, - {3, arcs_61_1}, + {5, arcs_61_1}, }; -static arc arcs_62_0[1] = { - {139, 1}, -}; -static arc arcs_62_1[5] = { - {29, 0}, - {140, 0}, - {141, 0}, - {142, 0}, - {0, 1}, -}; -static state states_62[2] = { - {1, arcs_62_0}, - {5, arcs_62_1}, -}; -static arc arcs_63_0[4] = { - {137, 1}, - {138, 1}, - {143, 1}, - {144, 2}, +static arc arcs_62_0[4] = { + {135, 1}, + {136, 1}, + {141, 1}, + {142, 2}, }; -static arc arcs_63_1[1] = { - {139, 2}, +static arc arcs_62_1[1] = { + {137, 2}, }; -static arc arcs_63_2[1] = { +static arc arcs_62_2[1] = { {0, 2}, }; -static state states_63[3] = { - {4, arcs_63_0}, - {1, arcs_63_1}, - {1, arcs_63_2}, +static state states_62[3] = { + {4, arcs_62_0}, + {1, arcs_62_1}, + {1, arcs_62_2}, }; -static arc arcs_64_0[1] = { - {145, 1}, +static arc arcs_63_0[1] = { + {143, 1}, }; -static arc arcs_64_1[3] = { - {146, 1}, +static arc arcs_63_1[3] = { + {144, 1}, {31, 2}, {0, 1}, }; -static arc arcs_64_2[1] = { - {139, 3}, +static arc arcs_63_2[1] = { + {137, 3}, }; -static arc arcs_64_3[1] = { +static arc arcs_63_3[1] = { {0, 3}, }; -static state states_64[4] = { - {1, arcs_64_0}, - {3, arcs_64_1}, - {1, arcs_64_2}, - {1, arcs_64_3}, +static state states_63[4] = { + {1, arcs_63_0}, + {3, arcs_63_1}, + {1, arcs_63_2}, + {1, arcs_63_3}, }; -static arc arcs_65_0[7] = { +static arc arcs_64_0[7] = { {13, 1}, - {148, 2}, - {151, 3}, + {146, 2}, + {149, 3}, {19, 4}, - {154, 4}, - {155, 5}, - {80, 6}, + {152, 4}, + {153, 5}, + {77, 6}, }; -static arc arcs_65_1[3] = { - {48, 7}, - {147, 7}, +static arc arcs_64_1[3] = { + {47, 7}, + {145, 7}, {15, 4}, }; -static arc arcs_65_2[2] = { - {149, 8}, - {150, 4}, -}; -static arc arcs_65_3[2] = { - {152, 9}, - {153, 4}, +static arc arcs_64_2[2] = { + {147, 8}, + {148, 4}, +}; +static arc arcs_64_3[2] = { + {150, 9}, + {151, 4}, }; -static arc arcs_65_4[1] = { +static arc arcs_64_4[1] = { {0, 4}, }; -static arc arcs_65_5[2] = { - {155, 5}, +static arc arcs_64_5[2] = { + {153, 5}, {0, 5}, }; -static arc arcs_65_6[1] = { - {80, 10}, +static arc arcs_64_6[1] = { + {77, 10}, }; -static arc arcs_65_7[1] = { +static arc arcs_64_7[1] = { {15, 4}, }; -static arc arcs_65_8[1] = { - {150, 4}, +static arc arcs_64_8[1] = { + {148, 4}, }; -static arc arcs_65_9[1] = { - {153, 4}, +static arc arcs_64_9[1] = { + {151, 4}, }; -static arc arcs_65_10[1] = { - {80, 4}, +static arc arcs_64_10[1] = { + {77, 4}, }; -static state states_65[11] = { - {7, arcs_65_0}, - {3, arcs_65_1}, - {2, arcs_65_2}, - {2, arcs_65_3}, - {1, arcs_65_4}, - {2, arcs_65_5}, - {1, arcs_65_6}, - {1, arcs_65_7}, - {1, arcs_65_8}, - {1, arcs_65_9}, - {1, arcs_65_10}, +static state states_64[11] = { + {7, arcs_64_0}, + {3, arcs_64_1}, + {2, arcs_64_2}, + {2, arcs_64_3}, + {1, arcs_64_4}, + {2, arcs_64_5}, + {1, arcs_64_6}, + {1, arcs_64_7}, + {1, arcs_64_8}, + {1, arcs_64_9}, + {1, arcs_64_10}, }; -static arc arcs_66_0[1] = { +static arc arcs_65_0[1] = { {22, 1}, }; -static arc arcs_66_1[3] = { - {156, 2}, +static arc arcs_65_1[3] = { + {154, 2}, {28, 3}, {0, 1}, }; -static arc arcs_66_2[1] = { +static arc arcs_65_2[1] = { {0, 2}, }; -static arc arcs_66_3[2] = { +static arc arcs_65_3[2] = { {22, 4}, {0, 3}, }; -static arc arcs_66_4[2] = { +static arc arcs_65_4[2] = { {28, 3}, {0, 4}, }; -static state states_66[5] = { - {1, arcs_66_0}, - {3, arcs_66_1}, - {1, arcs_66_2}, - {2, arcs_66_3}, - {2, arcs_66_4}, +static state states_65[5] = { + {1, arcs_65_0}, + {3, arcs_65_1}, + {1, arcs_65_2}, + {2, arcs_65_3}, + {2, arcs_65_4}, }; -static arc arcs_67_0[1] = { +static arc arcs_66_0[1] = { {22, 1}, }; -static arc arcs_67_1[3] = { - {157, 2}, +static arc arcs_66_1[3] = { + {155, 2}, {28, 3}, {0, 1}, }; -static arc arcs_67_2[1] = { +static arc arcs_66_2[1] = { {0, 2}, }; -static arc arcs_67_3[2] = { +static arc arcs_66_3[2] = { {22, 4}, {0, 3}, }; -static arc arcs_67_4[2] = { +static arc arcs_66_4[2] = { {28, 3}, {0, 4}, }; -static state states_67[5] = { - {1, arcs_67_0}, - {3, arcs_67_1}, - {1, arcs_67_2}, - {2, arcs_67_3}, - {2, arcs_67_4}, +static state states_66[5] = { + {1, arcs_66_0}, + {3, arcs_66_1}, + {1, arcs_66_2}, + {2, arcs_66_3}, + {2, arcs_66_4}, }; -static arc arcs_68_0[1] = { - {112, 1}, +static arc arcs_67_0[1] = { + {109, 1}, }; -static arc arcs_68_1[2] = { +static arc arcs_67_1[2] = { {33, 2}, {23, 3}, }; -static arc arcs_68_2[1] = { +static arc arcs_67_2[1] = { {23, 3}, }; -static arc arcs_68_3[1] = { +static arc arcs_67_3[1] = { {22, 4}, }; -static arc arcs_68_4[1] = { +static arc arcs_67_4[1] = { {0, 4}, }; -static state states_68[5] = { - {1, arcs_68_0}, - {2, arcs_68_1}, - {1, arcs_68_2}, - {1, arcs_68_3}, - {1, arcs_68_4}, +static state states_67[5] = { + {1, arcs_67_0}, + {2, arcs_67_1}, + {1, arcs_67_2}, + {1, arcs_67_3}, + {1, arcs_67_4}, }; -static arc arcs_69_0[3] = { +static arc arcs_68_0[3] = { {13, 1}, - {148, 2}, - {80, 3}, + {146, 2}, + {77, 3}, }; -static arc arcs_69_1[2] = { +static arc arcs_68_1[2] = { {14, 4}, {15, 5}, }; -static arc arcs_69_2[1] = { - {158, 6}, +static arc arcs_68_2[1] = { + {156, 6}, }; -static arc arcs_69_3[1] = { +static arc arcs_68_3[1] = { {19, 5}, }; -static arc arcs_69_4[1] = { +static arc arcs_68_4[1] = { {15, 5}, }; -static arc arcs_69_5[1] = { +static arc arcs_68_5[1] = { {0, 5}, }; -static arc arcs_69_6[1] = { - {150, 5}, +static arc arcs_68_6[1] = { + {148, 5}, }; -static state states_69[7] = { - {3, arcs_69_0}, - {2, arcs_69_1}, - {1, arcs_69_2}, - {1, arcs_69_3}, - {1, arcs_69_4}, - {1, arcs_69_5}, - {1, arcs_69_6}, +static state states_68[7] = { + {3, arcs_68_0}, + {2, arcs_68_1}, + {1, arcs_68_2}, + {1, arcs_68_3}, + {1, arcs_68_4}, + {1, arcs_68_5}, + {1, arcs_68_6}, }; -static arc arcs_70_0[1] = { - {159, 1}, +static arc arcs_69_0[1] = { + {157, 1}, }; -static arc arcs_70_1[2] = { +static arc arcs_69_1[2] = { {28, 2}, {0, 1}, }; -static arc arcs_70_2[2] = { - {159, 1}, +static arc arcs_69_2[2] = { + {157, 1}, {0, 2}, }; -static state states_70[3] = { - {1, arcs_70_0}, - {2, arcs_70_1}, - {2, arcs_70_2}, +static state states_69[3] = { + {1, arcs_69_0}, + {2, arcs_69_1}, + {2, arcs_69_2}, }; -static arc arcs_71_0[2] = { +static arc arcs_70_0[2] = { {22, 1}, {23, 2}, }; -static arc arcs_71_1[2] = { +static arc arcs_70_1[2] = { {23, 2}, {0, 1}, }; -static arc arcs_71_2[3] = { +static arc arcs_70_2[3] = { {22, 3}, - {160, 4}, + {158, 4}, {0, 2}, }; -static arc arcs_71_3[2] = { - {160, 4}, +static arc arcs_70_3[2] = { + {158, 4}, {0, 3}, }; -static arc arcs_71_4[1] = { +static arc arcs_70_4[1] = { {0, 4}, }; -static state states_71[5] = { - {2, arcs_71_0}, +static state states_70[5] = { + {2, arcs_70_0}, + {2, arcs_70_1}, + {3, arcs_70_2}, + {2, arcs_70_3}, + {1, arcs_70_4}, +}; +static arc arcs_71_0[1] = { + {23, 1}, +}; +static arc arcs_71_1[2] = { + {22, 2}, + {0, 1}, +}; +static arc arcs_71_2[1] = { + {0, 2}, +}; +static state states_71[3] = { + {1, arcs_71_0}, {2, arcs_71_1}, - {3, arcs_71_2}, - {2, arcs_71_3}, - {1, arcs_71_4}, + {1, arcs_71_2}, }; static arc arcs_72_0[1] = { - {23, 1}, + {101, 1}, }; static arc arcs_72_1[2] = { - {22, 2}, + {28, 2}, {0, 1}, }; -static arc arcs_72_2[1] = { +static arc arcs_72_2[2] = { + {101, 1}, {0, 2}, }; static state states_72[3] = { {1, arcs_72_0}, {2, arcs_72_1}, - {1, arcs_72_2}, + {2, arcs_72_2}, }; static arc arcs_73_0[1] = { - {104, 1}, + {22, 1}, }; static arc arcs_73_1[2] = { {28, 2}, {0, 1}, }; static arc arcs_73_2[2] = { - {104, 1}, + {22, 1}, {0, 2}, }; static state states_73[3] = { @@ -1601,500 +1571,482 @@ static arc arcs_74_0[1] = { {22, 1}, }; -static arc arcs_74_1[2] = { - {28, 2}, - {0, 1}, -}; -static arc arcs_74_2[2] = { - {22, 1}, - {0, 2}, -}; -static state states_74[3] = { - {1, arcs_74_0}, - {2, arcs_74_1}, - {2, arcs_74_2}, -}; -static arc arcs_75_0[1] = { - {22, 1}, -}; -static arc arcs_75_1[3] = { +static arc arcs_74_1[3] = { {23, 2}, {28, 3}, {0, 1}, }; -static arc arcs_75_2[1] = { +static arc arcs_74_2[1] = { {22, 4}, }; -static arc arcs_75_3[2] = { +static arc arcs_74_3[2] = { {22, 5}, {0, 3}, }; -static arc arcs_75_4[2] = { +static arc arcs_74_4[2] = { {28, 6}, {0, 4}, }; -static arc arcs_75_5[2] = { +static arc arcs_74_5[2] = { {28, 3}, {0, 5}, }; -static arc arcs_75_6[2] = { +static arc arcs_74_6[2] = { {22, 7}, {0, 6}, }; -static arc arcs_75_7[1] = { +static arc arcs_74_7[1] = { {23, 2}, }; -static state states_75[8] = { - {1, arcs_75_0}, - {3, arcs_75_1}, - {1, arcs_75_2}, - {2, arcs_75_3}, - {2, arcs_75_4}, - {2, arcs_75_5}, - {2, arcs_75_6}, - {1, arcs_75_7}, +static state states_74[8] = { + {1, arcs_74_0}, + {3, arcs_74_1}, + {1, arcs_74_2}, + {2, arcs_74_3}, + {2, arcs_74_4}, + {2, arcs_74_5}, + {2, arcs_74_6}, + {1, arcs_74_7}, }; -static arc arcs_76_0[1] = { - {161, 1}, +static arc arcs_75_0[1] = { + {159, 1}, }; -static arc arcs_76_1[1] = { +static arc arcs_75_1[1] = { {19, 2}, }; -static arc arcs_76_2[2] = { +static arc arcs_75_2[2] = { {13, 3}, {23, 4}, }; -static arc arcs_76_3[2] = { +static arc arcs_75_3[2] = { {9, 5}, {15, 6}, }; -static arc arcs_76_4[1] = { +static arc arcs_75_4[1] = { {24, 7}, }; -static arc arcs_76_5[1] = { +static arc arcs_75_5[1] = { {15, 6}, }; -static arc arcs_76_6[1] = { +static arc arcs_75_6[1] = { {23, 4}, }; -static arc arcs_76_7[1] = { +static arc arcs_75_7[1] = { {0, 7}, }; -static state states_76[8] = { - {1, arcs_76_0}, - {1, arcs_76_1}, - {2, arcs_76_2}, - {2, arcs_76_3}, - {1, arcs_76_4}, - {1, arcs_76_5}, - {1, arcs_76_6}, - {1, arcs_76_7}, +static state states_75[8] = { + {1, arcs_75_0}, + {1, arcs_75_1}, + {2, arcs_75_2}, + {2, arcs_75_3}, + {1, arcs_75_4}, + {1, arcs_75_5}, + {1, arcs_75_6}, + {1, arcs_75_7}, }; -static arc arcs_77_0[3] = { - {162, 1}, +static arc arcs_76_0[3] = { + {160, 1}, {29, 2}, {31, 3}, }; -static arc arcs_77_1[2] = { +static arc arcs_76_1[2] = { {28, 4}, {0, 1}, }; -static arc arcs_77_2[1] = { +static arc arcs_76_2[1] = { {22, 5}, }; -static arc arcs_77_3[1] = { +static arc arcs_76_3[1] = { {22, 6}, }; -static arc arcs_77_4[4] = { - {162, 1}, +static arc arcs_76_4[4] = { + {160, 1}, {29, 2}, {31, 3}, {0, 4}, }; -static arc arcs_77_5[2] = { +static arc arcs_76_5[2] = { {28, 7}, {0, 5}, }; -static arc arcs_77_6[1] = { +static arc arcs_76_6[1] = { {0, 6}, }; -static arc arcs_77_7[1] = { +static arc arcs_76_7[1] = { {31, 3}, }; -static state states_77[8] = { - {3, arcs_77_0}, - {2, arcs_77_1}, - {1, arcs_77_2}, - {1, arcs_77_3}, - {4, arcs_77_4}, - {2, arcs_77_5}, - {1, arcs_77_6}, - {1, arcs_77_7}, +static state states_76[8] = { + {3, arcs_76_0}, + {2, arcs_76_1}, + {1, arcs_76_2}, + {1, arcs_76_3}, + {4, arcs_76_4}, + {2, arcs_76_5}, + {1, arcs_76_6}, + {1, arcs_76_7}, }; -static arc arcs_78_0[1] = { +static arc arcs_77_0[1] = { {22, 1}, }; -static arc arcs_78_1[3] = { - {157, 2}, +static arc arcs_77_1[3] = { + {155, 2}, {27, 3}, {0, 1}, }; -static arc arcs_78_2[1] = { +static arc arcs_77_2[1] = { {0, 2}, }; -static arc arcs_78_3[1] = { +static arc arcs_77_3[1] = { {22, 2}, }; -static state states_78[4] = { - {1, arcs_78_0}, - {3, arcs_78_1}, - {1, arcs_78_2}, - {1, arcs_78_3}, +static state states_77[4] = { + {1, arcs_77_0}, + {3, arcs_77_1}, + {1, arcs_77_2}, + {1, arcs_77_3}, }; -static arc arcs_79_0[2] = { - {156, 1}, - {164, 1}, +static arc arcs_78_0[2] = { + {154, 1}, + {162, 1}, }; -static arc arcs_79_1[1] = { +static arc arcs_78_1[1] = { {0, 1}, }; -static state states_79[2] = { - {2, arcs_79_0}, - {1, arcs_79_1}, +static state states_78[2] = { + {2, arcs_78_0}, + {1, arcs_78_1}, }; -static arc arcs_80_0[1] = { - {97, 1}, +static arc arcs_79_0[1] = { + {94, 1}, }; -static arc arcs_80_1[1] = { - {64, 2}, +static arc arcs_79_1[1] = { + {61, 2}, }; -static arc arcs_80_2[1] = { - {98, 3}, +static arc arcs_79_2[1] = { + {95, 3}, }; -static arc arcs_80_3[1] = { - {108, 4}, +static arc arcs_79_3[1] = { + {105, 4}, }; -static arc arcs_80_4[2] = { - {163, 5}, +static arc arcs_79_4[2] = { + {161, 5}, {0, 4}, }; -static arc arcs_80_5[1] = { +static arc arcs_79_5[1] = { {0, 5}, }; -static state states_80[6] = { - {1, arcs_80_0}, - {1, arcs_80_1}, - {1, arcs_80_2}, - {1, arcs_80_3}, - {2, arcs_80_4}, - {1, arcs_80_5}, +static state states_79[6] = { + {1, arcs_79_0}, + {1, arcs_79_1}, + {1, arcs_79_2}, + {1, arcs_79_3}, + {2, arcs_79_4}, + {1, arcs_79_5}, }; -static arc arcs_81_0[1] = { - {93, 1}, +static arc arcs_80_0[1] = { + {90, 1}, }; -static arc arcs_81_1[1] = { - {109, 2}, +static arc arcs_80_1[1] = { + {106, 2}, }; -static arc arcs_81_2[2] = { - {163, 3}, +static arc arcs_80_2[2] = { + {161, 3}, {0, 2}, }; -static arc arcs_81_3[1] = { +static arc arcs_80_3[1] = { {0, 3}, }; -static state states_81[4] = { - {1, arcs_81_0}, - {1, arcs_81_1}, - {2, arcs_81_2}, - {1, arcs_81_3}, +static state states_80[4] = { + {1, arcs_80_0}, + {1, arcs_80_1}, + {2, arcs_80_2}, + {1, arcs_80_3}, }; -static arc arcs_82_0[2] = { - {157, 1}, - {166, 1}, +static arc arcs_81_0[2] = { + {155, 1}, + {164, 1}, }; -static arc arcs_82_1[1] = { +static arc arcs_81_1[1] = { {0, 1}, }; -static state states_82[2] = { - {2, arcs_82_0}, - {1, arcs_82_1}, +static state states_81[2] = { + {2, arcs_81_0}, + {1, arcs_81_1}, }; -static arc arcs_83_0[1] = { - {97, 1}, +static arc arcs_82_0[1] = { + {94, 1}, }; -static arc arcs_83_1[1] = { - {64, 2}, +static arc arcs_82_1[1] = { + {61, 2}, }; -static arc arcs_83_2[1] = { - {98, 3}, +static arc arcs_82_2[1] = { + {95, 3}, }; -static arc arcs_83_3[1] = { - {110, 4}, +static arc arcs_82_3[1] = { + {107, 4}, }; -static arc arcs_83_4[2] = { - {165, 5}, +static arc arcs_82_4[2] = { + {163, 5}, {0, 4}, }; -static arc arcs_83_5[1] = { +static arc arcs_82_5[1] = { {0, 5}, }; -static state states_83[6] = { - {1, arcs_83_0}, - {1, arcs_83_1}, - {1, arcs_83_2}, - {1, arcs_83_3}, - {2, arcs_83_4}, - {1, arcs_83_5}, +static state states_82[6] = { + {1, arcs_82_0}, + {1, arcs_82_1}, + {1, arcs_82_2}, + {1, arcs_82_3}, + {2, arcs_82_4}, + {1, arcs_82_5}, }; -static arc arcs_84_0[1] = { - {93, 1}, +static arc arcs_83_0[1] = { + {90, 1}, }; -static arc arcs_84_1[1] = { - {109, 2}, +static arc arcs_83_1[1] = { + {106, 2}, }; -static arc arcs_84_2[2] = { - {165, 3}, +static arc arcs_83_2[2] = { + {163, 3}, {0, 2}, }; -static arc arcs_84_3[1] = { +static arc arcs_83_3[1] = { {0, 3}, }; -static state states_84[4] = { - {1, arcs_84_0}, - {1, arcs_84_1}, - {2, arcs_84_2}, - {1, arcs_84_3}, +static state states_83[4] = { + {1, arcs_83_0}, + {1, arcs_83_1}, + {2, arcs_83_2}, + {1, arcs_83_3}, }; -static arc arcs_85_0[1] = { +static arc arcs_84_0[1] = { {22, 1}, }; -static arc arcs_85_1[2] = { +static arc arcs_84_1[2] = { {28, 0}, {0, 1}, }; -static state states_85[2] = { - {1, arcs_85_0}, - {2, arcs_85_1}, +static state states_84[2] = { + {1, arcs_84_0}, + {2, arcs_84_1}, }; -static arc arcs_86_0[1] = { +static arc arcs_85_0[1] = { {19, 1}, }; -static arc arcs_86_1[1] = { +static arc arcs_85_1[1] = { {0, 1}, }; -static state states_86[2] = { - {1, arcs_86_0}, - {1, arcs_86_1}, +static state states_85[2] = { + {1, arcs_85_0}, + {1, arcs_85_1}, }; -static arc arcs_87_0[1] = { - {169, 1}, +static arc arcs_86_0[1] = { + {167, 1}, }; -static arc arcs_87_1[2] = { +static arc arcs_86_1[2] = { {9, 2}, {0, 1}, }; -static arc arcs_87_2[1] = { +static arc arcs_86_2[1] = { {0, 2}, }; -static state states_87[3] = { - {1, arcs_87_0}, - {2, arcs_87_1}, - {1, arcs_87_2}, +static state states_86[3] = { + {1, arcs_86_0}, + {2, arcs_86_1}, + {1, arcs_86_2}, }; -static dfa dfas[88] = { +static dfa dfas[87] = { {256, "single_input", 0, 3, states_0, - "\004\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"}, + "\004\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"}, {257, "file_input", 0, 2, states_1, - "\204\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"}, + "\204\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"}, {258, "eval_input", 0, 3, states_2, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, {259, "decorator", 0, 7, states_3, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {260, "decorators", 0, 2, states_4, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {261, "funcdef", 0, 9, states_5, - "\000\010\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\010\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {262, "parameters", 0, 4, states_6, - "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {263, "typedargslist", 0, 12, states_7, - "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {264, "tname", 0, 4, states_8, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {265, "tfpdef", 0, 4, states_9, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {266, "tfplist", 0, 3, states_10, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {267, "varargslist", 0, 12, states_11, - "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {268, "vname", 0, 2, states_12, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {269, "vfpdef", 0, 4, states_13, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {270, "vfplist", 0, 3, states_14, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {271, "stmt", 0, 2, states_15, - "\000\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"}, + "\000\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"}, {272, "simple_stmt", 0, 4, states_16, - "\000\040\010\000\000\000\000\240\202\247\141\000\000\000\101\000\000\206\220\014\000\002"}, + "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"}, {273, "small_stmt", 0, 2, states_17, - "\000\040\010\000\000\000\000\240\202\247\141\000\000\000\101\000\000\206\220\014\000\002"}, + "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"}, {274, "expr_stmt", 0, 6, states_18, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, {275, "augassign", 0, 2, states_19, - "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {276, "print_stmt", 0, 9, states_20, - "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {277, "del_stmt", 0, 3, states_21, - "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "pass_stmt", 0, 2, states_22, - "\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {279, "flow_stmt", 0, 2, states_23, - "\000\000\000\000\000\000\000\000\200\007\000\000\000\000\000\000\000\000\000\000\000\002"}, - {280, "break_stmt", 0, 2, states_24, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {281, "continue_stmt", 0, 2, states_25, - "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "return_stmt", 0, 3, states_26, - "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000"}, - {283, "yield_stmt", 0, 2, states_27, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, - {284, "raise_stmt", 0, 7, states_28, - "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, - {285, "import_stmt", 0, 2, states_29, - "\000\000\000\000\000\000\000\000\000\240\000\000\000\000\000\000\000\000\000\000\000\000"}, - {286, "import_name", 0, 3, states_30, - "\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, - {287, "import_from", 0, 8, states_31, - "\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, - {288, "import_as_name", 0, 4, states_32, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {289, "dotted_as_name", 0, 4, states_33, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {290, "import_as_names", 0, 3, states_34, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {291, "dotted_as_names", 0, 2, states_35, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {292, "dotted_name", 0, 2, states_36, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {293, "global_stmt", 0, 3, states_37, - "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000"}, - {294, "assert_stmt", 0, 5, states_38, - "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000"}, - {295, "compound_stmt", 0, 2, states_39, - "\000\010\004\000\000\000\000\000\000\000\000\040\113\000\000\000\000\000\000\000\002\000"}, - {296, "if_stmt", 0, 8, states_40, - "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {297, "while_stmt", 0, 8, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, - {298, "for_stmt", 0, 10, states_42, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, - {299, "try_stmt", 0, 13, states_43, - "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"}, - {300, "with_stmt", 0, 6, states_44, - "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {301, "with_var", 0, 3, states_45, - "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000"}, - {302, "except_clause", 0, 5, states_46, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000"}, - {303, "suite", 0, 5, states_47, - "\004\040\010\000\000\000\000\240\202\247\141\000\000\000\101\000\000\206\220\014\000\002"}, - {304, "testlist_safe", 0, 5, states_48, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {305, "old_test", 0, 2, states_49, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {306, "old_lambdef", 0, 5, states_50, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, - {307, "test", 0, 6, states_51, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {308, "or_test", 0, 2, states_52, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\100\000\000\206\220\014\000\000"}, - {309, "and_test", 0, 2, states_53, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\100\000\000\206\220\014\000\000"}, - {310, "not_test", 0, 3, states_54, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\100\000\000\206\220\014\000\000"}, - {311, "comparison", 0, 2, states_55, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {312, "comp_op", 0, 4, states_56, - "\000\000\000\000\000\000\000\000\000\000\000\000\004\000\100\376\000\000\000\000\000\000"}, - {313, "expr", 0, 2, states_57, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {314, "xor_expr", 0, 2, states_58, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {315, "and_expr", 0, 2, states_59, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {316, "shift_expr", 0, 2, states_60, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {317, "arith_expr", 0, 2, states_61, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {318, "term", 0, 2, states_62, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {319, "factor", 0, 3, states_63, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {320, "power", 0, 4, states_64, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\220\014\000\000"}, - {321, "atom", 0, 11, states_65, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\220\014\000\000"}, - {322, "listmaker", 0, 5, states_66, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {323, "testlist_gexp", 0, 5, states_67, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {324, "lambdef", 0, 5, states_68, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, - {325, "trailer", 0, 7, states_69, - "\000\040\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\020\000\000\000"}, - {326, "subscriptlist", 0, 3, states_70, - "\000\040\210\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {327, "subscript", 0, 5, states_71, - "\000\040\210\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {328, "sliceop", 0, 3, states_72, - "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {329, "exprlist", 0, 3, states_73, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {330, "testlist", 0, 3, states_74, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {331, "dictsetmaker", 0, 8, states_75, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {332, "classdef", 0, 8, states_76, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002\000"}, - {333, "arglist", 0, 8, states_77, - "\000\040\010\240\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {334, "argument", 0, 4, states_78, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {335, "list_iter", 0, 2, states_79, - "\000\000\000\000\000\000\000\000\000\000\000\040\002\000\000\000\000\000\000\000\000\000"}, - {336, "list_for", 0, 6, states_80, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, - {337, "list_if", 0, 4, states_81, - "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {338, "gen_iter", 0, 2, states_82, - "\000\000\000\000\000\000\000\000\000\000\000\040\002\000\000\000\000\000\000\000\000\000"}, - {339, "gen_for", 0, 6, states_83, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, - {340, "gen_if", 0, 4, states_84, - "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {341, "testlist1", 0, 2, states_85, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {342, "encoding_decl", 0, 2, states_86, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {343, "yield_expr", 0, 3, states_87, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, + "\000\000\000\000\000\000\377\017\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {276, "del_stmt", 0, 3, states_20, + "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {277, "pass_stmt", 0, 2, states_21, + "\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {278, "flow_stmt", 0, 2, states_22, + "\000\000\000\000\000\000\000\000\360\000\000\000\000\000\000\000\000\000\000\000\200"}, + {279, "break_stmt", 0, 2, states_23, + "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, + {280, "continue_stmt", 0, 2, states_24, + "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, + {281, "return_stmt", 0, 3, states_25, + "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, + {282, "yield_stmt", 0, 2, states_26, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {283, "raise_stmt", 0, 7, states_27, + "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, + {284, "import_stmt", 0, 2, states_28, + "\000\000\000\000\000\000\000\000\000\024\000\000\000\000\000\000\000\000\000\000\000"}, + {285, "import_name", 0, 3, states_29, + "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, + {286, "import_from", 0, 8, states_30, + "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"}, + {287, "import_as_name", 0, 4, states_31, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {288, "dotted_as_name", 0, 4, states_32, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {289, "import_as_names", 0, 3, states_33, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {290, "dotted_as_names", 0, 2, states_34, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {291, "dotted_name", 0, 2, states_35, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {292, "global_stmt", 0, 3, states_36, + "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000"}, + {293, "assert_stmt", 0, 5, states_37, + "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000"}, + {294, "compound_stmt", 0, 2, states_38, + "\000\010\004\000\000\000\000\000\000\000\000\144\011\000\000\000\000\000\000\200\000"}, + {295, "if_stmt", 0, 8, states_39, + "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, + {296, "while_stmt", 0, 8, states_40, + "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"}, + {297, "for_stmt", 0, 10, states_41, + "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {298, "try_stmt", 0, 13, states_42, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, + {299, "with_stmt", 0, 6, states_43, + "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000"}, + {300, "with_var", 0, 3, states_44, + "\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000"}, + {301, "except_clause", 0, 5, states_45, + "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000"}, + {302, "suite", 0, 5, states_46, + "\004\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"}, + {303, "testlist_safe", 0, 5, states_47, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {304, "old_test", 0, 2, states_48, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {305, "old_lambdef", 0, 5, states_49, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, + {306, "test", 0, 6, states_50, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {307, "or_test", 0, 2, states_51, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"}, + {308, "and_test", 0, 2, states_52, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"}, + {309, "not_test", 0, 3, states_53, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"}, + {310, "comparison", 0, 2, states_54, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {311, "comp_op", 0, 4, states_55, + "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\310\037\000\000\000\000\000"}, + {312, "expr", 0, 2, states_56, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {313, "xor_expr", 0, 2, states_57, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {314, "and_expr", 0, 2, states_58, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {315, "shift_expr", 0, 2, states_59, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {316, "arith_expr", 0, 2, states_60, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {317, "term", 0, 2, states_61, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {318, "factor", 0, 3, states_62, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {319, "power", 0, 4, states_63, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"}, + {320, "atom", 0, 11, states_64, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"}, + {321, "listmaker", 0, 5, states_65, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {322, "testlist_gexp", 0, 5, states_66, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {323, "lambdef", 0, 5, states_67, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, + {324, "trailer", 0, 7, states_68, + "\000\040\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\004\000\000"}, + {325, "subscriptlist", 0, 3, states_69, + "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {326, "subscript", 0, 5, states_70, + "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {327, "sliceop", 0, 3, states_71, + "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {328, "exprlist", 0, 3, states_72, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {329, "testlist", 0, 3, states_73, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {330, "dictsetmaker", 0, 8, states_74, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {331, "classdef", 0, 8, states_75, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000"}, + {332, "arglist", 0, 8, states_76, + "\000\040\010\240\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {333, "argument", 0, 4, states_77, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {334, "list_iter", 0, 2, states_78, + "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"}, + {335, "list_for", 0, 6, states_79, + "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {336, "list_if", 0, 4, states_80, + "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, + {337, "gen_iter", 0, 2, states_81, + "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"}, + {338, "gen_for", 0, 6, states_82, + "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {339, "gen_if", 0, 4, states_83, + "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, + {340, "testlist1", 0, 2, states_84, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {341, "encoding_decl", 0, 2, states_85, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {342, "yield_expr", 0, 3, states_86, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, }; -static label labels[170] = { +static label labels[168] = { {0, "EMPTY"}, {256, 0}, {4, 0}, {272, 0}, - {295, 0}, + {294, 0}, {257, 0}, {271, 0}, {0, 0}, {258, 0}, - {330, 0}, + {329, 0}, {259, 0}, {50, 0}, - {292, 0}, + {291, 0}, {7, 0}, - {333, 0}, + {332, 0}, {8, 0}, {260, 0}, {261, 0}, @@ -2102,9 +2054,9 @@ {1, 0}, {262, 0}, {51, 0}, - {307, 0}, + {306, 0}, {11, 0}, - {303, 0}, + {302, 0}, {263, 0}, {265, 0}, {22, 0}, @@ -2123,12 +2075,11 @@ {276, 0}, {277, 0}, {278, 0}, - {279, 0}, - {285, 0}, + {284, 0}, + {292, 0}, {293, 0}, - {294, 0}, {275, 0}, - {343, 0}, + {342, 0}, {37, 0}, {38, 0}, {39, 0}, @@ -2141,38 +2092,36 @@ {46, 0}, {47, 0}, {49, 0}, - {1, "print"}, - {35, 0}, {1, "del"}, - {329, 0}, + {328, 0}, {1, "pass"}, + {279, 0}, {280, 0}, {281, 0}, - {282, 0}, - {284, 0}, {283, 0}, + {282, 0}, {1, "break"}, {1, "continue"}, {1, "return"}, {1, "raise"}, + {285, 0}, {286, 0}, - {287, 0}, {1, "import"}, - {291, 0}, + {290, 0}, {1, "from"}, {23, 0}, - {290, 0}, - {288, 0}, - {1, "as"}, {289, 0}, + {287, 0}, + {1, "as"}, + {288, 0}, {1, "global"}, {1, "assert"}, + {295, 0}, {296, 0}, {297, 0}, {298, 0}, {299, 0}, - {300, 0}, - {332, 0}, + {331, 0}, {1, "if"}, {1, "elif"}, {1, "else"}, @@ -2180,27 +2129,27 @@ {1, "for"}, {1, "in"}, {1, "try"}, - {302, 0}, + {301, 0}, {1, "finally"}, {1, "with"}, - {301, 0}, - {313, 0}, + {300, 0}, + {312, 0}, {1, "except"}, {5, 0}, {6, 0}, + {303, 0}, {304, 0}, + {307, 0}, {305, 0}, - {308, 0}, - {306, 0}, {1, "lambda"}, - {324, 0}, - {309, 0}, + {323, 0}, + {308, 0}, {1, "or"}, - {310, 0}, + {309, 0}, {1, "and"}, {1, "not"}, + {310, 0}, {311, 0}, - {312, 0}, {20, 0}, {21, 0}, {28, 0}, @@ -2208,52 +2157,53 @@ {30, 0}, {29, 0}, {1, "is"}, - {314, 0}, + {313, 0}, {18, 0}, - {315, 0}, + {314, 0}, {33, 0}, - {316, 0}, + {315, 0}, {19, 0}, - {317, 0}, + {316, 0}, {34, 0}, - {318, 0}, + {35, 0}, + {317, 0}, {14, 0}, {15, 0}, - {319, 0}, + {318, 0}, {17, 0}, {24, 0}, {48, 0}, {32, 0}, + {319, 0}, {320, 0}, - {321, 0}, - {325, 0}, - {323, 0}, - {9, 0}, + {324, 0}, {322, 0}, + {9, 0}, + {321, 0}, {10, 0}, {26, 0}, - {331, 0}, + {330, 0}, {27, 0}, {2, 0}, {3, 0}, - {336, 0}, - {339, 0}, + {335, 0}, + {338, 0}, + {325, 0}, {326, 0}, {327, 0}, - {328, 0}, {1, "class"}, + {333, 0}, {334, 0}, - {335, 0}, + {336, 0}, {337, 0}, - {338, 0}, + {339, 0}, {340, 0}, {341, 0}, - {342, 0}, {1, "yield"}, }; grammar _PyParser_Grammar = { - 88, + 87, dfas, - {170, labels}, + {168, labels}, 256 }; Modified: python/branches/p3yk-noslice/Python/import.c ============================================================================== --- python/branches/p3yk-noslice/Python/import.c (original) +++ python/branches/p3yk-noslice/Python/import.c Fri Feb 23 18:29:35 2007 @@ -71,9 +71,10 @@ 3020 (added BUILD_SET) 3030 (added keyword-only parameters) 3040 (added signature annotations) + 3050 (print becomes a function) . */ -#define MAGIC (3040 | ((long)'\r'<<16) | ((long)'\n'<<24)) +#define MAGIC (3050 | ((long)'\r'<<16) | ((long)'\n'<<24)) /* Magic word as global; note that _PyImport_Init() can change the value of this global to accommodate for alterations of how the Modified: python/branches/p3yk-noslice/Python/marshal.c ============================================================================== --- python/branches/p3yk-noslice/Python/marshal.c (original) +++ python/branches/p3yk-noslice/Python/marshal.c Fri Feb 23 18:29:35 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-noslice/Python/pythonrun.c ============================================================================== --- python/branches/p3yk-noslice/Python/pythonrun.c (original) +++ python/branches/p3yk-noslice/Python/pythonrun.c Fri Feb 23 18:29:35 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(); @@ -271,7 +273,8 @@ sys_isatty = PyObject_CallMethod(sys_stream, "isatty", ""); if (!sys_isatty) PyErr_Clear(); - if(sys_isatty && PyObject_IsTrue(sys_isatty)) { + if(sys_isatty && PyObject_IsTrue(sys_isatty) && + PyFile_Check(sys_stream)) { if (!PyFile_SetEncoding(sys_stream, codeset)) Py_FatalError("Cannot set codeset of stdin"); } @@ -281,7 +284,8 @@ sys_isatty = PyObject_CallMethod(sys_stream, "isatty", ""); if (!sys_isatty) PyErr_Clear(); - if(sys_isatty && PyObject_IsTrue(sys_isatty)) { + if(sys_isatty && PyObject_IsTrue(sys_isatty) && + PyFile_Check(sys_stream)) { if (!PyFile_SetEncoding(sys_stream, codeset)) Py_FatalError("Cannot set codeset of stdout"); } @@ -291,7 +295,8 @@ sys_isatty = PyObject_CallMethod(sys_stream, "isatty", ""); if (!sys_isatty) PyErr_Clear(); - if(sys_isatty && PyObject_IsTrue(sys_isatty)) { + if(sys_isatty && PyObject_IsTrue(sys_isatty) && + PyFile_Check(sys_stream)) { if (!PyFile_SetEncoding(sys_stream, codeset)) Py_FatalError("Cannot set codeset of stderr"); } @@ -453,7 +458,7 @@ PyList_Fini(); PySet_Fini(); PyString_Fini(); - PyInt_Fini(); + PyLong_Fini(); PyFloat_Fini(); #ifdef Py_USING_UNICODE @@ -790,8 +795,6 @@ return -1; } Py_DECREF(v); - if (Py_FlushLine()) - PyErr_Clear(); return 0; } @@ -878,8 +881,6 @@ return -1; } Py_DECREF(v); - if (Py_FlushLine()) - PyErr_Clear(); return 0; } @@ -897,8 +898,6 @@ return -1; } Py_DECREF(v); - if (Py_FlushLine()) - PyErr_Clear(); return 0; } @@ -1013,8 +1012,6 @@ int exitcode = 0; PyErr_Fetch(&exception, &value, &tb); - if (Py_FlushLine()) - PyErr_Clear(); fflush(stdout); if (value == NULL || value == Py_None) goto done; @@ -1092,8 +1089,6 @@ v2 = Py_None; Py_INCREF(v2); } - if (Py_FlushLine()) - PyErr_Clear(); fflush(stdout); PySys_WriteStderr("Error in sys.excepthook:\n"); PyErr_Display(exception2, v2, tb2); @@ -1123,8 +1118,6 @@ if (f == NULL) fprintf(stderr, "lost sys.stderr\n"); else { - if (Py_FlushLine()) - PyErr_Clear(); fflush(stdout); if (tb && tb != Py_None) err = PyTraceBack_Print(tb, f); @@ -1592,8 +1585,6 @@ Py_DECREF(exitfunc); } - if (Py_FlushLine()) - PyErr_Clear(); } static void @@ -1850,4 +1841,3 @@ #ifdef __cplusplus } #endif - Modified: python/branches/p3yk-noslice/Python/symtable.c ============================================================================== --- python/branches/p3yk-noslice/Python/symtable.c (original) +++ python/branches/p3yk-noslice/Python/symtable.c Fri Feb 23 18:29:35 2007 @@ -990,11 +990,6 @@ VISIT(st, expr, s->v.AugAssign.target); VISIT(st, expr, s->v.AugAssign.value); break; - case Print_kind: - if (s->v.Print.dest) - VISIT(st, expr, s->v.Print.dest); - VISIT_SEQ(st, expr, s->v.Print.values); - break; case For_kind: VISIT(st, expr, s->v.For.target); VISIT(st, expr, s->v.For.iter); Modified: python/branches/p3yk-noslice/Python/sysmodule.c ============================================================================== --- python/branches/p3yk-noslice/Python/sysmodule.c (original) +++ python/branches/p3yk-noslice/Python/sysmodule.c Fri Feb 23 18:29:35 2007 @@ -104,8 +104,6 @@ } if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) return NULL; - if (Py_FlushLine() != 0) - return NULL; outf = PySys_GetObject("stdout"); if (outf == NULL) { PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); @@ -113,8 +111,7 @@ } if (PyFile_WriteObject(o, outf, 0) != 0) return NULL; - PyFile_SoftSpace(outf, 1); - if (Py_FlushLine() != 0) + if (PyFile_WriteString("\n", outf) != 0) return NULL; if (PyObject_SetAttrString(builtins, "_", o) != 0) return NULL; @@ -904,7 +901,7 @@ Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\ \n\ stdin -- standard input file object; used by raw_input() and input()\n\ -stdout -- standard output file object; used by the print statement\n\ +stdout -- standard output file object; used by print()\n\ stderr -- standard error object; used for error messages\n\ By assigning other file objects (or objects that behave like files)\n\ to these, it is possible to redirect all of the interpreter's I/O.\n\ @@ -1110,17 +1107,17 @@ if (PyErr_Occurred()) return NULL; #ifdef MS_WINDOWS - if(isatty(_fileno(stdin))){ + if(isatty(_fileno(stdin)) && PyFile_Check(sysin)) { sprintf(buf, "cp%d", GetConsoleCP()); if (!PyFile_SetEncoding(sysin, buf)) return NULL; } - if(isatty(_fileno(stdout))) { + if(isatty(_fileno(stdout)) && PyFile_Check(sysout)) { sprintf(buf, "cp%d", GetConsoleOutputCP()); if (!PyFile_SetEncoding(sysout, buf)) return NULL; } - if(isatty(_fileno(stderr))) { + if(isatty(_fileno(stderr)) && PyFile_Check(syserr)) { sprintf(buf, "cp%d", GetConsoleOutputCP()); if (!PyFile_SetEncoding(syserr, buf)) return NULL; Modified: python/branches/p3yk-noslice/Python/traceback.c ============================================================================== --- python/branches/p3yk-noslice/Python/traceback.c (original) +++ python/branches/p3yk-noslice/Python/traceback.c Fri Feb 23 18:29:35 2007 @@ -113,7 +113,7 @@ int PyTraceBack_Here(PyFrameObject *frame) { - PyThreadState *tstate = frame->f_tstate; + PyThreadState *tstate = PyThreadState_GET(); PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback; PyTracebackObject *tb = newtracebackobject(oldtb, frame); if (tb == NULL) @@ -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; Modified: python/branches/p3yk-noslice/Tools/compiler/ast.txt ============================================================================== --- python/branches/p3yk-noslice/Tools/compiler/ast.txt (original) +++ python/branches/p3yk-noslice/Tools/compiler/ast.txt Fri Feb 23 18:29:35 2007 @@ -34,8 +34,6 @@ Return: value Yield: value Const: value* -Print: nodes!, dest& -Printnl: nodes!, dest& Discard: expr AugAssign: node, op*, expr Assign: nodes!, expr Modified: python/branches/p3yk-noslice/Tools/freeze/bkfile.py ============================================================================== --- python/branches/p3yk-noslice/Tools/freeze/bkfile.py (original) +++ python/branches/p3yk-noslice/Tools/freeze/bkfile.py Fri Feb 23 18:29:35 2007 @@ -25,7 +25,6 @@ self.readline = self.__file.readline self.readlines = self.__file.readlines self.seek = self.__file.seek - self.softspace = self.__file.softspace self.tell = self.__file.tell self.truncate = self.__file.truncate self.write = self.__file.write Modified: python/branches/p3yk-noslice/Tools/freeze/freeze.py ============================================================================== --- python/branches/p3yk-noslice/Tools/freeze/freeze.py (original) +++ python/branches/p3yk-noslice/Tools/freeze/freeze.py Fri Feb 23 18:29:35 2007 @@ -162,7 +162,7 @@ # proces option arguments for o, a in opts: if o == '-h': - print __doc__ + print(__doc__) return if o == '-d': debug = debug + 1 @@ -222,7 +222,7 @@ if win: extensions_c = 'frozen_extensions.c' if ishome: - print "(Using Python source directory)" + print("(Using Python source directory)") binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_h_dir = exec_prefix @@ -310,7 +310,7 @@ if odir and not os.path.isdir(odir): try: os.mkdir(odir) - print "Created output directory", odir + print("Created output directory", odir) except os.error as msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) base = '' @@ -371,7 +371,7 @@ if debug > 0: mf.report() - print + print() dict = mf.modules if error_if_any_missing: @@ -479,18 +479,18 @@ # Done! if odir: - print 'Now run "make" in', odir, - print 'to build the target:', base_target + print('Now run "make" in', odir, end=' ') + print('to build the target:', base_target) else: - print 'Now run "make" to build the target:', base_target + print('Now run "make" to build the target:', base_target) # Print usage message and exit def usage(msg): sys.stdout = sys.stderr - print "Error:", msg - print "Use ``%s -h'' for help" % sys.argv[0] + print("Error:", msg) + print("Use ``%s -h'' for help" % sys.argv[0]) sys.exit(2) Modified: python/branches/p3yk-noslice/Tools/freeze/hello.py ============================================================================== --- python/branches/p3yk-noslice/Tools/freeze/hello.py (original) +++ python/branches/p3yk-noslice/Tools/freeze/hello.py Fri Feb 23 18:29:35 2007 @@ -1 +1 @@ -print 'Hello world...' +print('Hello world...') Modified: python/branches/p3yk-noslice/Tools/freeze/makeconfig.py ============================================================================== --- python/branches/p3yk-noslice/Tools/freeze/makeconfig.py (original) +++ python/branches/p3yk-noslice/Tools/freeze/makeconfig.py Fri Feb 23 18:29:35 2007 @@ -40,8 +40,8 @@ def test(): import sys if not sys.argv[3:]: - print 'usage: python makeconfig.py config.c.in outputfile', - print 'modulename ...' + print('usage: python makeconfig.py config.c.in outputfile', end=' ') + print('modulename ...') sys.exit(2) if sys.argv[1] == '-': infp = sys.stdin Modified: python/branches/p3yk-noslice/Tools/freeze/makefreeze.py ============================================================================== --- python/branches/p3yk-noslice/Tools/freeze/makefreeze.py (original) +++ python/branches/p3yk-noslice/Tools/freeze/makefreeze.py Fri Feb 23 18:29:35 2007 @@ -43,7 +43,7 @@ outfp = bkfile.open(base + file, 'w') files.append(file) if debug: - print "freezing", mod, "..." + print("freezing", mod, "...") str = marshal.dumps(m.__code__) size = len(str) if m.__path__: @@ -53,7 +53,7 @@ writecode(outfp, mangled, str) outfp.close() if debug: - print "generating table of frozen modules" + print("generating table of frozen modules") outfp = bkfile.open(base + 'frozen.c', 'w') for mod, mangled, size in done: outfp.write('extern unsigned char M_%s[];\n' % mangled) Modified: python/branches/p3yk-noslice/Tools/freeze/parsesetup.py ============================================================================== --- python/branches/p3yk-noslice/Tools/freeze/parsesetup.py (original) +++ python/branches/p3yk-noslice/Tools/freeze/parsesetup.py Fri Feb 23 18:29:35 2007 @@ -84,29 +84,29 @@ import sys import os if not sys.argv[1:]: - print 'usage: python parsesetup.py Makefile*|Setup* ...' + print('usage: python parsesetup.py Makefile*|Setup* ...') sys.exit(2) for arg in sys.argv[1:]: base = os.path.basename(arg) if base[:8] == 'Makefile': - print 'Make style parsing:', arg + print('Make style parsing:', arg) v = getmakevars(arg) prdict(v) elif base[:5] == 'Setup': - print 'Setup style parsing:', arg + print('Setup style parsing:', arg) m, v = getsetupinfo(arg) prdict(m) prdict(v) else: - print arg, 'is neither a Makefile nor a Setup file' - print '(name must begin with "Makefile" or "Setup")' + print(arg, 'is neither a Makefile nor a Setup file') + print('(name must begin with "Makefile" or "Setup")') def prdict(d): keys = d.keys() keys.sort() for key in keys: value = d[key] - print "%-15s" % key, str(value) + print("%-15s" % key, str(value)) if __name__ == '__main__': test() Modified: python/branches/p3yk-noslice/Tools/freeze/winmakemakefile.py ============================================================================== --- python/branches/p3yk-noslice/Tools/freeze/winmakemakefile.py (original) +++ python/branches/p3yk-noslice/Tools/freeze/winmakemakefile.py Fri Feb 23 18:29:35 2007 @@ -52,29 +52,29 @@ def realwork(vars, moddefns, target): version_suffix = "%r%r" % sys.version_info[:2] - print "# Makefile for Microsoft Visual C++ generated by freeze.py script" - print - print 'target = %s' % target - print 'pythonhome = %s' % vars['prefix'] - print - print 'DEBUG=0 # Set to 1 to use the _d versions of Python.' - print '!IF $(DEBUG)' - print 'debug_suffix=_d' - print 'c_debug=/Zi /Od /DDEBUG /D_DEBUG' - print 'l_debug=/DEBUG' - print 'temp_dir=Build\\Debug' - print '!ELSE' - print 'debug_suffix=' - print 'c_debug=/Ox' - print 'l_debug=' - print 'temp_dir=Build\\Release' - print '!ENDIF' - print - - print '# The following line assumes you have built Python using the standard instructions' - print '# Otherwise fix the following line to point to the library.' - print 'pythonlib = "$(pythonhome)/pcbuild/python%s$(debug_suffix).lib"' % version_suffix - print + print("# Makefile for Microsoft Visual C++ generated by freeze.py script") + print() + print('target = %s' % target) + print('pythonhome = %s' % vars['prefix']) + print() + print('DEBUG=0 # Set to 1 to use the _d versions of Python.') + print('!IF $(DEBUG)') + print('debug_suffix=_d') + print('c_debug=/Zi /Od /DDEBUG /D_DEBUG') + print('l_debug=/DEBUG') + print('temp_dir=Build\\Debug') + print('!ELSE') + print('debug_suffix=') + print('c_debug=/Ox') + print('l_debug=') + print('temp_dir=Build\\Release') + print('!ENDIF') + print() + + print('# The following line assumes you have built Python using the standard instructions') + print('# Otherwise fix the following line to point to the library.') + print('pythonlib = "$(pythonhome)/pcbuild/python%s$(debug_suffix).lib"' % version_suffix) + print() # We only ever write one "entry point" symbol - either # "main" or "WinMain". Therefore, there is no need to @@ -88,59 +88,59 @@ target_ext = ".dll" - print "# As the target uses Python%s.dll, we must use this compiler option!" % version_suffix - print "cdl = /MD" - print - print "all: $(target)$(debug_suffix)%s" % (target_ext) - print - - print '$(temp_dir):' - print ' if not exist $(temp_dir)\. mkdir $(temp_dir)' - print + print("# As the target uses Python%s.dll, we must use this compiler option!" % version_suffix) + print("cdl = /MD") + print() + print("all: $(target)$(debug_suffix)%s" % (target_ext)) + print() + + print('$(temp_dir):') + print(' if not exist $(temp_dir)\. mkdir $(temp_dir)') + print() objects = [] libs = ["shell32.lib", "comdlg32.lib", "wsock32.lib", "user32.lib", "oleaut32.lib"] for moddefn in moddefns: - print "# Module", moddefn.name + print("# Module", moddefn.name) for file in moddefn.sourceFiles: base = os.path.basename(file) base, ext = os.path.splitext(base) objects.append(base + ".obj") - print '$(temp_dir)\%s.obj: "%s"' % (base, file) - print "\t@$(CC) -c -nologo /Fo$* $(cdl) $(c_debug) /D BUILD_FREEZE", - print '"-I$(pythonhome)/Include" "-I$(pythonhome)/PC" \\' - print "\t\t$(cflags) $(cdebug) $(cinclude) \\" + print('$(temp_dir)\%s.obj: "%s"' % (base, file)) + print("\t@$(CC) -c -nologo /Fo$* $(cdl) $(c_debug) /D BUILD_FREEZE", end=' ') + print('"-I$(pythonhome)/Include" "-I$(pythonhome)/PC" \\') + print("\t\t$(cflags) $(cdebug) $(cinclude) \\") extra = moddefn.GetCompilerOptions() if extra: - print "\t\t%s \\" % (' '.join(extra),) - print '\t\t"%s"' % file - print + print("\t\t%s \\" % (' '.join(extra),)) + print('\t\t"%s"' % file) + print() # Add .lib files this module needs for modlib in moddefn.GetLinkerLibs(): if modlib not in libs: libs.append(modlib) - print "ADDN_LINK_FILES=", - for addn in vars['addn_link']: print '"%s"' % (addn), - print ; print - - print "OBJS=", - for obj in objects: print '"$(temp_dir)\%s"' % (obj), - print ; print - - print "LIBS=", - for lib in libs: print '"%s"' % (lib), - print ; print - - print "$(target)$(debug_suffix)%s: $(temp_dir) $(OBJS)" % (target_ext) - print "\tlink -out:$(target)$(debug_suffix)%s %s" % (target_ext, target_link_flags), - print "\t$(OBJS) \\" - print "\t$(LIBS) \\" - print "\t$(ADDN_LINK_FILES) \\" - print "\t$(pythonlib) $(lcustom) $(l_debug)\\" - print "\t$(resources)" - print - print "clean:" - print "\t-rm -f *.obj" - print "\t-rm -f $(target).exe" + print("ADDN_LINK_FILES=", end=' ') + for addn in vars['addn_link']: print('"%s"' % (addn), end=' ') + print() ; print() + + print("OBJS=", end=' ') + for obj in objects: print('"$(temp_dir)\%s"' % (obj), end=' ') + print() ; print() + + print("LIBS=", end=' ') + for lib in libs: print('"%s"' % (lib), end=' ') + print() ; print() + + print("$(target)$(debug_suffix)%s: $(temp_dir) $(OBJS)" % (target_ext)) + print("\tlink -out:$(target)$(debug_suffix)%s %s" % (target_ext, target_link_flags), end=' ') + print("\t$(OBJS) \\") + print("\t$(LIBS) \\") + print("\t$(ADDN_LINK_FILES) \\") + print("\t$(pythonlib) $(lcustom) $(l_debug)\\") + print("\t$(resources)") + print() + print("clean:") + print("\t-rm -f *.obj") + print("\t-rm -f $(target).exe") Modified: python/branches/p3yk-noslice/Tools/msi/uuids.py ============================================================================== --- python/branches/p3yk-noslice/Tools/msi/uuids.py (original) +++ python/branches/p3yk-noslice/Tools/msi/uuids.py Fri Feb 23 18:29:35 2007 @@ -33,4 +33,8 @@ '2.5.121': '{8e9321bc-6b24-48a3-8fd4-c95f8e531e5f}', # 2.5c1 '2.5.122': '{a6cd508d-9599-45da-a441-cbffa9f7e070}', # 2.5c2 '2.5.150': '{0a2c5854-557e-48c8-835a-3b9f074bdcaa}', # 2.5.0 + '2.5.1121':'{0378b43e-6184-4c2f-be1a-4a367781cd54}', # 2.5.1c1 + '2.5.1150':'{31800004-6386-4999-a519-518f2d78d8f0}', # 2.5.1 + '2.5.2150':'{6304a7da-1132-4e91-a343-a296269eab8a}', # 2.5.2c1 + '2.5.2150':'{6b976adf-8ae8-434e-b282-a06c7f624d2f}', # 2.5.2 } Modified: python/branches/p3yk-noslice/Tools/pybench/CommandLine.py ============================================================================== --- python/branches/p3yk-noslice/Tools/pybench/CommandLine.py (original) +++ python/branches/p3yk-noslice/Tools/pybench/CommandLine.py Fri Feb 23 18:29:35 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-noslice/Tools/pybench/Dict.py ============================================================================== --- python/branches/p3yk-noslice/Tools/pybench/Dict.py (original) +++ python/branches/p3yk-noslice/Tools/pybench/Dict.py Fri Feb 23 18:29:35 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-noslice/Tools/pybench/Exceptions.py ============================================================================== --- python/branches/p3yk-noslice/Tools/pybench/Exceptions.py (original) +++ python/branches/p3yk-noslice/Tools/pybench/Exceptions.py Fri Feb 23 18:29:35 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-noslice/Tools/pybench/Lookups.py ============================================================================== --- python/branches/p3yk-noslice/Tools/pybench/Lookups.py (original) +++ python/branches/p3yk-noslice/Tools/pybench/Lookups.py Fri Feb 23 18:29:35 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 Modified: python/branches/p3yk-noslice/Tools/pybench/pybench.py ============================================================================== --- python/branches/p3yk-noslice/Tools/pybench/pybench.py (original) +++ python/branches/p3yk-noslice/Tools/pybench/pybench.py Fri Feb 23 18:29:35 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 Modified: python/branches/p3yk-noslice/configure ============================================================================== --- python/branches/p3yk-noslice/configure (original) +++ python/branches/p3yk-noslice/configure Fri Feb 23 18:29:35 2007 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 51211 . +# From configure.in Revision: 53610 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -10608,6 +10608,467 @@ fi +{ echo "$as_me:$LINENO: checking for _Bool support" >&5 +echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; } +have_c99_bool=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +_Bool x; x = (_Bool)0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + + +cat >>confdefs.h <<\_ACEOF +#define HAVE_C99_BOOL 1 +_ACEOF + + have_c99_bool=yes + +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5 +echo "${ECHO_T}$have_c99_bool" >&6; } +if test "$have_c99_bool" = yes ; then +{ echo "$as_me:$LINENO: checking for _Bool" >&5 +echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } +if test "${ac_cv_type__Bool+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +typedef _Bool ac__type_new_; +int +main () +{ +if ((ac__type_new_ *) 0) + return 0; +if (sizeof (ac__type_new_)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type__Bool=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type__Bool=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 +echo "${ECHO_T}$ac_cv_type__Bool" >&6; } + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ echo "$as_me:$LINENO: checking size of _Bool" >&5 +echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; } +if test "${ac_cv_sizeof__Bool+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then + # Depending upon the size, compute the lo and hi bounds. +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_lo=0 ac_mid=0 + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=$ac_mid; break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo=`expr $ac_mid + 1` + if test $ac_lo -le $ac_mid; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid + 1` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=-1 ac_mid=-1 + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_lo=$ac_mid; break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_hi=`expr '(' $ac_mid ')' - 1` + if test $ac_mid -le $ac_hi; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo= ac_hi= +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# Binary search between lo and hi bounds. +while test "x$ac_lo" != "x$ac_hi"; do + ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=$ac_mid +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo=`expr '(' $ac_mid ')' + 1` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +done +case $ac_lo in +?*) ac_cv_sizeof__Bool=$ac_lo;; +'') if test "$ac_cv_type__Bool" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } + else + ac_cv_sizeof__Bool=0 + fi ;; +esac +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } +static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +#include +#include +int +main () +{ + + FILE *f = fopen ("conftest.val", "w"); + if (! f) + return 1; + if (((long int) (sizeof (ac__type_sizeof_))) < 0) + { + long int i = longval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; + fprintf (f, "%ld\n", i); + } + else + { + unsigned long int i = ulongval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; + fprintf (f, "%lu\n", i); + } + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_sizeof__Bool=`cat conftest.val` +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +if test "$ac_cv_type__Bool" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } + else + ac_cv_sizeof__Bool=0 + fi +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi +rm -f conftest.val +fi +{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 +echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF__BOOL $ac_cv_sizeof__Bool +_ACEOF + + +fi + { echo "$as_me:$LINENO: checking for uintptr_t" >&5 echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } if test "${ac_cv_type_uintptr_t+set}" = set; then @@ -14607,11 +15068,13 @@ -for ac_func in alarm bind_textdomain_codeset chown clock confstr ctermid \ - execv fork fpathconf ftime ftruncate \ + + +for ac_func in alarm bind_textdomain_codeset chflags chown clock confstr \ + ctermid execv fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ - kill killpg lchown lstat mkfifo mknod mktime \ + kill killpg lchflags lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink realpath \ select setegid seteuid setgid \ Modified: python/branches/p3yk-noslice/configure.in ============================================================================== --- python/branches/p3yk-noslice/configure.in (original) +++ python/branches/p3yk-noslice/configure.in Fri Feb 23 18:29:35 2007 @@ -1218,6 +1218,17 @@ AC_CHECK_SIZEOF(long long, 8) fi +AC_MSG_CHECKING(for _Bool support) +have_c99_bool=no +AC_TRY_COMPILE([], [_Bool x; x = (_Bool)0;], [ + AC_DEFINE(HAVE_C99_BOOL, 1, [Define this if you have the type _Bool.]) + have_c99_bool=yes +]) +AC_MSG_RESULT($have_c99_bool) +if test "$have_c99_bool" = yes ; then +AC_CHECK_SIZEOF(_Bool, 1) +fi + AC_CHECK_TYPES(uintptr_t, [AC_CHECK_SIZEOF(uintptr_t, 4)], [], [#ifdef HAVE_STDINT_H @@ -2271,11 +2282,11 @@ AC_MSG_RESULT(MACHDEP_OBJS) # checks for library functions -AC_CHECK_FUNCS(alarm bind_textdomain_codeset chown clock confstr ctermid \ - execv fork fpathconf ftime ftruncate \ +AC_CHECK_FUNCS(alarm bind_textdomain_codeset chflags chown clock confstr \ + ctermid execv fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ - kill killpg lchown lstat mkfifo mknod mktime \ + kill killpg lchflags lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink realpath \ select setegid seteuid setgid \ Modified: python/branches/p3yk-noslice/pyconfig.h.in ============================================================================== --- python/branches/p3yk-noslice/pyconfig.h.in (original) +++ python/branches/p3yk-noslice/pyconfig.h.in Fri Feb 23 18:29:35 2007 @@ -64,6 +64,12 @@ /* Define if pthread_sigmask() does not work on your system. */ #undef HAVE_BROKEN_PTHREAD_SIGMASK +/* Define this if you have the type _Bool. */ +#undef HAVE_C99_BOOL + +/* Define to 1 if you have the `chflags' function. */ +#undef HAVE_CHFLAGS + /* Define to 1 if you have the `chown' function. */ #undef HAVE_CHOWN @@ -287,6 +293,9 @@ Solaris and Linux, the necessary defines are already defined.) */ #undef HAVE_LARGEFILE_SUPPORT +/* Define to 1 if you have the `lchflags' function. */ +#undef HAVE_LCHFLAGS + /* Define to 1 if you have the `lchown' function. */ #undef HAVE_LCHOWN @@ -835,6 +844,9 @@ /* The size of a `wchar_t', as computed by sizeof. */ #undef SIZEOF_WCHAR_T +/* The size of a `_Bool', as computed by sizeof. */ +#undef SIZEOF__BOOL + /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS Modified: python/branches/p3yk-noslice/setup.py ============================================================================== --- python/branches/p3yk-noslice/setup.py (original) +++ python/branches/p3yk-noslice/setup.py Fri Feb 23 18:29:35 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) @@ -664,7 +664,7 @@ # search path. for d in inc_dirs + db_inc_paths: f = os.path.join(d, "db.h") - if db_setup_debug: print "db: looking for db.h in", f + if db_setup_debug: print("db: looking for db.h in", f) if os.path.exists(f): f = open(f).read() m = re.search(r"#define\WDB_VERSION_MAJOR\W(\d+)", f) @@ -680,16 +680,15 @@ # (first occurrance only) db_ver_inc_map[db_ver] = d if db_setup_debug: - print "db.h: found", db_ver, "in", d + print("db.h: found", db_ver, "in", d) else: # we already found a header for this library version - if db_setup_debug: print "db.h: ignoring", d + if db_setup_debug: print("db.h: ignoring", d) else: # ignore this header, it didn't contain a version number - if db_setup_debug: print "db.h: unsupported version", db_ver, "in", d + if db_setup_debug: print("db.h: unsupported version", db_ver, "in", d) - db_found_vers = db_ver_inc_map.keys() - db_found_vers.sort() + db_found_vers = sorted(db_ver_inc_map.keys()) while db_found_vers: db_ver = db_found_vers.pop() @@ -717,12 +716,12 @@ dblib_dir = [ os.path.abspath(os.path.dirname(dblib_file)) ] raise db_found else: - if db_setup_debug: print "db lib: ", dblib, "not found" + if db_setup_debug: print("db lib: ", dblib, "not found") except db_found: if db_setup_debug: - print "db lib: using", db_ver, dblib - print "db: lib dir", dblib_dir, "inc dir", db_incdir + print("db lib: using", db_ver, dblib) + print("db: lib dir", dblib_dir, "inc dir", db_incdir) db_incs = [db_incdir] dblibs = [dblib] # We add the runtime_library_dirs argument because the @@ -737,7 +736,7 @@ include_dirs=db_incs, libraries=dblibs)) else: - if db_setup_debug: print "db: no appropriate library found" + if db_setup_debug: print("db: no appropriate library found") db_incs = None dblibs = [] dblib_dir = None @@ -765,7 +764,7 @@ for d in inc_dirs + sqlite_inc_paths: f = os.path.join(d, "sqlite3.h") if os.path.exists(f): - if sqlite_setup_debug: print "sqlite: found %s"%f + if sqlite_setup_debug: print("sqlite: found %s"%f) incf = open(f).read() m = re.search( r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"(.*)"', incf) @@ -776,15 +775,15 @@ if sqlite_version_tuple >= MIN_SQLITE_VERSION_NUMBER: # we win! if sqlite_setup_debug: - print "%s/sqlite3.h: version %s"%(d, sqlite_version) + print("%s/sqlite3.h: version %s"%(d, sqlite_version)) sqlite_incdir = d break else: if sqlite_setup_debug: - print "%s: version %d is too old, need >= %s"%(d, - sqlite_version, MIN_SQLITE_VERSION) + print("%s: version %d is too old, need >= %s"%(d, + sqlite_version, MIN_SQLITE_VERSION)) elif sqlite_setup_debug: - print "sqlite: %s had no SQLITE_VERSION"%(f,) + print("sqlite: %s had no SQLITE_VERSION"%(f,)) if sqlite_incdir: sqlite_dirs_to_check = [ @@ -1319,7 +1318,8 @@ from distutils.dep_util import newer_group config_sources = [os.path.join(ffi_srcdir, fname) - for fname in os.listdir(ffi_srcdir)] + for fname in os.listdir(ffi_srcdir) + if os.path.isfile(os.path.join(ffi_srcdir, fname))] if self.force or newer_group(config_sources, ffi_configfile): from distutils.dir_util import mkpath @@ -1333,7 +1333,7 @@ res = os.system(cmd) if res or not os.path.exists(ffi_configfile): - print "Failed to configure _ctypes module" + print("Failed to configure _ctypes module") return False fficonfig = {} From python-checkins at python.org Fri Feb 23 20:22:56 2007 From: python-checkins at python.org (phillip.eby) Date: Fri, 23 Feb 2007 20:22:56 +0100 (CET) Subject: [Python-checkins] r53868 - sandbox/trunk/setuptools/setuptools/command/easy_install.py Message-ID: <20070223192256.B47C01E4008@bag.python.org> Author: phillip.eby Date: Fri Feb 23 20:22:54 2007 New Revision: 53868 Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py Log: Indicate when dependency processing is finished, so that you can tell which dependencies go with what. (Suggested by Ian Bicking) Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/easy_install.py (original) +++ sandbox/trunk/setuptools/setuptools/command/easy_install.py Fri Feb 23 20:22:54 2007 @@ -532,6 +532,7 @@ for dist in distros: if dist.key not in self.installed_projects: self.easy_install(dist.as_requirement()) + log.info("Finished processing dependencies for %s", requirement) def should_unzip(self, dist): if self.zip_ok is not None: @@ -571,7 +572,6 @@ - def install_script(self, dist, script_name, script_text, dev_path=None): """Generate a legacy script wrapper and install it""" spec = str(dist.as_requirement()) From python-checkins at python.org Fri Feb 23 20:24:01 2007 From: python-checkins at python.org (phillip.eby) Date: Fri, 23 Feb 2007 20:24:01 +0100 (CET) Subject: [Python-checkins] r53869 - sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Message-ID: <20070223192401.B73C61E4008@bag.python.org> Author: phillip.eby Date: Fri Feb 23 20:23:57 2007 New Revision: 53869 Modified: sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Log: Indicate when dependency processing is finished, so that you can tell which dependencies go with what. (Suggested by Ian Bicking) (backport from trunk) Modified: sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Fri Feb 23 20:23:57 2007 @@ -532,6 +532,7 @@ for dist in distros: if dist.key not in self.installed_projects: self.easy_install(dist.as_requirement()) + log.info("Finished processing dependencies for %s", requirement) def should_unzip(self, dist): if self.zip_ok is not None: @@ -571,7 +572,6 @@ - def install_script(self, dist, script_name, script_text, dev_path=None): """Generate a legacy script wrapper and install it""" spec = str(dist.as_requirement()) From python-checkins at python.org Fri Feb 23 20:24:59 2007 From: python-checkins at python.org (phillip.eby) Date: Fri, 23 Feb 2007 20:24:59 +0100 (CET) Subject: [Python-checkins] r53870 - in sandbox/trunk/setuptools: pkg_resources.py setuptools/tests/test_resources.py Message-ID: <20070223192459.7E07E1E4008@bag.python.org> Author: phillip.eby Date: Fri Feb 23 20:24:57 2007 New Revision: 53870 Modified: sandbox/trunk/setuptools/pkg_resources.py sandbox/trunk/setuptools/setuptools/tests/test_resources.py Log: Get rid of 'sets' module usage under Python 2.4+, so that no warnings are issued by Python 2.6. Modified: sandbox/trunk/setuptools/pkg_resources.py ============================================================================== --- sandbox/trunk/setuptools/pkg_resources.py (original) +++ sandbox/trunk/setuptools/pkg_resources.py Fri Feb 23 20:24:57 2007 @@ -14,10 +14,31 @@ """ import sys, os, zipimport, time, re, imp, new, pkgutil # XXX -from sets import ImmutableSet + +try: + frozenset +except NameError: + from sets import ImmutableSet as frozenset + from os import utime, rename, unlink # capture these to bypass sandboxing from os import open as os_open + + + + + + + + + + + + + + + + def get_supported_platform(): """Return this platform's maximum compatible version. @@ -39,6 +60,26 @@ pass # not Mac OS X return plat + + + + + + + + + + + + + + + + + + + + __all__ = [ # Basic resource access and distribution/entry point discovery 'require', 'run_script', 'get_provider', 'get_distribution', @@ -2305,7 +2346,7 @@ self.index, self.extras = index, tuple(map(safe_extra,extras)) self.hashCmp = ( self.key, tuple([(op,parsed) for parsed,trans,op,ver in index]), - ImmutableSet(self.extras) + frozenset(self.extras) ) self.__hash = hash(self.hashCmp) Modified: sandbox/trunk/setuptools/setuptools/tests/test_resources.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/tests/test_resources.py (original) +++ sandbox/trunk/setuptools/setuptools/tests/test_resources.py Fri Feb 23 20:24:57 2007 @@ -1,7 +1,10 @@ from unittest import TestCase, makeSuite from pkg_resources import * import pkg_resources, sys -from sets import ImmutableSet +try: + frozenset +except NameError: + from sets import ImmutableSet as frozenset class Metadata(EmptyProvider): """Mock object to return metadata as if from an on-disk distribution""" @@ -18,7 +21,6 @@ def get_metadata_lines(self,name): return yield_lines(self.get_metadata(name)) - class DistroTests(TestCase): def testCollection(self): @@ -337,7 +339,7 @@ self.assertEqual(hash(r1), hash(r2)) self.assertEqual( hash(r1), hash(("twisted", ((">=",parse_version("1.2")),), - ImmutableSet(["foo","bar"]))) + frozenset(["foo","bar"]))) ) def testVersionEquality(self): From python-checkins at python.org Fri Feb 23 20:28:26 2007 From: python-checkins at python.org (phillip.eby) Date: Fri, 23 Feb 2007 20:28:26 +0100 (CET) Subject: [Python-checkins] r53871 - in sandbox/branches/setuptools-0.6: pkg_resources.py setuptools/tests/test_resources.py Message-ID: <20070223192826.9FF9D1E4008@bag.python.org> Author: phillip.eby Date: Fri Feb 23 20:28:25 2007 New Revision: 53871 Modified: sandbox/branches/setuptools-0.6/pkg_resources.py sandbox/branches/setuptools-0.6/setuptools/tests/test_resources.py Log: Get rid of 'sets' module usage under Python 2.4+, so that no warnings are issued by Python 2.6. (backport from trunk) Modified: sandbox/branches/setuptools-0.6/pkg_resources.py ============================================================================== --- sandbox/branches/setuptools-0.6/pkg_resources.py (original) +++ sandbox/branches/setuptools-0.6/pkg_resources.py Fri Feb 23 20:28:25 2007 @@ -14,10 +14,31 @@ """ import sys, os, zipimport, time, re, imp, new -from sets import ImmutableSet + +try: + frozenset +except NameError: + from sets import ImmutableSet as frozenset + from os import utime, rename, unlink # capture these to bypass sandboxing from os import open as os_open + + + + + + + + + + + + + + + + def get_supported_platform(): """Return this platform's maximum compatible version. @@ -39,6 +60,26 @@ pass # not Mac OS X return plat + + + + + + + + + + + + + + + + + + + + __all__ = [ # Basic resource access and distribution/entry point discovery 'require', 'run_script', 'get_provider', 'get_distribution', @@ -2387,7 +2428,7 @@ self.index, self.extras = index, tuple(map(safe_extra,extras)) self.hashCmp = ( self.key, tuple([(op,parsed) for parsed,trans,op,ver in index]), - ImmutableSet(self.extras) + frozenset(self.extras) ) self.__hash = hash(self.hashCmp) Modified: sandbox/branches/setuptools-0.6/setuptools/tests/test_resources.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/tests/test_resources.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/tests/test_resources.py Fri Feb 23 20:28:25 2007 @@ -1,7 +1,10 @@ from unittest import TestCase, makeSuite from pkg_resources import * import pkg_resources, sys -from sets import ImmutableSet +try: + frozenset +except NameError: + from sets import ImmutableSet as frozenset class Metadata(EmptyProvider): """Mock object to return metadata as if from an on-disk distribution""" @@ -18,7 +21,6 @@ def get_metadata_lines(self,name): return yield_lines(self.get_metadata(name)) - class DistroTests(TestCase): def testCollection(self): @@ -337,7 +339,7 @@ self.assertEqual(hash(r1), hash(r2)) self.assertEqual( hash(r1), hash(("twisted", ((">=",parse_version("1.2")),), - ImmutableSet(["foo","bar"]))) + frozenset(["foo","bar"]))) ) def testVersionEquality(self): From python-checkins at python.org Fri Feb 23 21:24:25 2007 From: python-checkins at python.org (thomas.wouters) Date: Fri, 23 Feb 2007 21:24:25 +0100 (CET) Subject: [Python-checkins] r53875 - in python/branches/p3yk: Lib/test/test_pep352.py Message-ID: <20070223202425.061161E4008@bag.python.org> Author: thomas.wouters Date: Fri Feb 23 21:24:22 2007 New Revision: 53875 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Lib/test/test_pep352.py Log: Merged revisions 53859-53874 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53861 | neal.norwitz | 2007-02-23 01:22:39 +0100 (Fri, 23 Feb 2007) | 1 line Fix typo in comment ........ r53864 | brett.cannon | 2007-02-23 15:28:25 +0100 (Fri, 23 Feb 2007) | 3 lines Refactor PEP 352 tests to make it easier in the future to make sure certain things cannot be raised or caught. ........ Modified: python/branches/p3yk/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep352.py (original) +++ python/branches/p3yk/Lib/test/test_pep352.py Fri Feb 23 21:24:22 2007 @@ -113,6 +113,37 @@ """Test usage of exceptions""" + def raise_fails(self, object_): + """Make sure that raising 'object_' triggers a TypeError.""" + try: + raise object_ + except TypeError: + return # What is expected. + self.fail("TypeError expected for raising %s" % type(object_)) + + def catch_fails(self, object_): + """Catching 'object_' should raise a TypeError.""" + try: + try: + raise StandardError + except object_: + pass + except TypeError: + pass + except StandardError: + self.fail("TypeError expected when catching %s" % type(object_)) + + try: + try: + raise StandardError + except (object_,): + pass + except TypeError: + return + except StandardError: + self.fail("TypeError expected when catching %s as specified in a " + "tuple" % type(object_)) + def test_raise_new_style_non_exception(self): # You cannot raise a new-style class that does not inherit from # BaseException; the ability was not possible until BaseException's @@ -120,27 +151,12 @@ # inherit from it. class NewStyleClass(object): pass - try: - raise NewStyleClass - except TypeError: - pass - except: - self.fail("able to raise new-style class") - try: - raise NewStyleClass() - except TypeError: - pass - except: - self.fail("able to raise new-style class instance") + self.raise_fails(NewStyleClass) + self.raise_fails(NewStyleClass()) def test_raise_string(self): # Raising a string raises TypeError. - try: - raise "spam" - except TypeError: - pass - except: - self.fail("was able to raise a string exception") + self.raise_fails("spam") def test_catch_string(self): # Catching a string should trigger a DeprecationWarning. From python-checkins at python.org Fri Feb 23 21:27:31 2007 From: python-checkins at python.org (phillip.eby) Date: Fri, 23 Feb 2007 21:27:31 +0100 (CET) Subject: [Python-checkins] r53876 - in sandbox/trunk/setuptools: EasyInstall.txt doc/formats.txt pkg_resources.py setuptools/command/develop.py setuptools/command/easy_install.py setuptools/package_index.py Message-ID: <20070223202731.E9F281E4008@bag.python.org> Author: phillip.eby Date: Fri Feb 23 21:27:29 2007 New Revision: 53876 Modified: sandbox/trunk/setuptools/EasyInstall.txt sandbox/trunk/setuptools/doc/formats.txt sandbox/trunk/setuptools/pkg_resources.py sandbox/trunk/setuptools/setuptools/command/develop.py sandbox/trunk/setuptools/setuptools/command/easy_install.py sandbox/trunk/setuptools/setuptools/package_index.py Log: Add --local-snapshots-ok flag, to allow building eggs from projects installed using "setup.py develop". Modified: sandbox/trunk/setuptools/EasyInstall.txt ============================================================================== --- sandbox/trunk/setuptools/EasyInstall.txt (original) +++ sandbox/trunk/setuptools/EasyInstall.txt Fri Feb 23 21:27:29 2007 @@ -383,6 +383,13 @@ even if they're installed elsewhere on the machine, and ``-d`` indicates the directory to place the eggs in.) +You can also build the eggs from local development packages that were installed +with the ``setup.py develop`` command, by including the ``-l`` option, e.g.:: + + easy_install -zmaxld somedir SomePackage + +This will use locally-available source distributions to build the eggs. + Packaging Others' Projects As Eggs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -887,6 +894,25 @@ script directories, and does not override the ones set on the command line or in a configuration file. +``--local-snapshots-ok, -l`` (New in 0.6c6) + Normally, EasyInstall prefers to only install *released* versions of + projects, not in-development ones, because such projects may not + have a currently-valid version number. So, it usually only installs them + when their ``setup.py`` directory is explicitly passed on the command line. + + However, if this option is used, then any in-development projects that were + installed using the ``setup.py develop`` command, will be used to build + eggs, effectively upgrading the "in-development" project to a snapshot + release. Normally, this option is used only in conjunction with the + ``--always-copy`` option to create a distributable snapshot of every egg + needed to run an application. + + Note that if you use this option, you must make sure that there is a valid + version number (such as an SVN revision number tag) for any in-development + projects that may be used, as otherwise EasyInstall may not be able to tell + what version of the project is "newer" when future installations or + upgrades are attempted. + .. _non-root installation: Modified: sandbox/trunk/setuptools/doc/formats.txt ============================================================================== --- sandbox/trunk/setuptools/doc/formats.txt (original) +++ sandbox/trunk/setuptools/doc/formats.txt Fri Feb 23 21:27:29 2007 @@ -220,8 +220,14 @@ with no newlines. This filename should be the base location of one or more eggs. That is, the name must either end in ``.egg``, or else it should be the parent directory of one or more ``.egg-info`` format eggs. -As of setuptools 0.6c6, the path may be specified as a relative path -from the directory containing the ``.egg-link`` file. + +As of setuptools 0.6c6, the path may be specified as a platform-independent +(i.e. ``/``-separated) relative path from the directory containing the +``.egg-link`` file, and a second line may appear in the file, specifying a +platform-independent relative path from the egg's base directory to its +setup script directory. This allows installation tools such as EasyInstall +to find the project's setup directory and build eggs or perform other setup +commands on it. ----------------- Modified: sandbox/trunk/setuptools/pkg_resources.py ============================================================================== --- sandbox/trunk/setuptools/pkg_resources.py (original) +++ sandbox/trunk/setuptools/pkg_resources.py Fri Feb 23 21:27:29 2007 @@ -1594,7 +1594,7 @@ if not line.strip(): continue for item in find_distributions(os.path.join(path_item,line.rstrip())): yield item - + break register_finder(pkgutil.ImpImporter, find_on_path) _namespace_handlers = {} Modified: sandbox/trunk/setuptools/setuptools/command/develop.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/develop.py (original) +++ sandbox/trunk/setuptools/setuptools/command/develop.py Fri Feb 23 21:27:29 2007 @@ -31,7 +31,7 @@ self.uninstall = None self.egg_path = None easy_install.initialize_options(self) - + self.setup_path = None @@ -61,6 +61,7 @@ " directory to "+target ) + # Make a distribution for the package's source self.dist = Distribution( target, @@ -68,16 +69,15 @@ project_name = ei.egg_name ) - - - - - - - - - - + p = self.egg_base.replace(os.sep,'/') + if p!= os.curdir: + p = '../' * (p.count('/')+1) + self.setup_path = p + p = normalize_path(os.path.join(self.install_dir, self.egg_path, p)) + if p != normalize_path(os.curdir): + raise DistutilsOptionError( + "Can't get a consistent path to setup script from" + " installation directory", p, normalize_path(os.curdir)) def install_for_development(self): @@ -95,7 +95,7 @@ log.info("Creating %s (link to %s)", self.egg_link, self.egg_base) if not self.dry_run: f = open(self.egg_link,"w") - f.write(self.egg_path) + f.write(self.egg_path + "\n" + self.setup_path) f.close() # postprocess the installed distro, fixing up .pth, installing scripts, # and handling requirements @@ -106,7 +106,7 @@ if os.path.exists(self.egg_link): log.info("Removing %s (link to %s)", self.egg_link, self.egg_base) contents = [line.rstrip() for line in file(self.egg_link)] - if contents != [self.egg_path]: + if contents not in ([self.egg_path], [self.egg_path, self.setup_path]): log.warn("Link points to %s: uninstall aborted", contents) return if not self.dry_run: Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/easy_install.py (original) +++ sandbox/trunk/setuptools/setuptools/command/easy_install.py Fri Feb 23 21:27:29 2007 @@ -70,18 +70,18 @@ ('editable', 'e', "Install specified packages in editable form"), ('no-deps', 'N', "don't install dependencies"), ('allow-hosts=', 'H', "pattern(s) that hostnames must match"), + ('local-snapshots-ok', 'l', "allow building eggs from local checkouts"), ] boolean_options = [ 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'delete-conflicting', 'ignore-conflicts-at-my-risk', 'editable', - 'no-deps', + 'no-deps', 'local-snapshots-ok', ] negative_opt = {'always-unzip': 'zip-ok'} create_index = PackageIndex - def initialize_options(self): - self.zip_ok = None + self.zip_ok = self.local_snapshots_ok = None self.install_dir = self.script_dir = self.exclude_scripts = None self.index_url = None self.find_links = None @@ -177,7 +177,8 @@ self.find_links = self.find_links.split() else: self.find_links = [] - + if self.local_snapshots_ok: + self.package_index.scan_egg_links(self.shadow_path+sys.path) self.package_index.add_find_links(self.find_links) self.set_undefined_options('install_lib', ('optimize','optimize')) if not isinstance(self.optimize,int): @@ -202,7 +203,6 @@ self.outputs = [] - def run(self): if self.verbose<>self.distribution.verbose: log.set_verbosity(self.verbose) Modified: sandbox/trunk/setuptools/setuptools/package_index.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/package_index.py (original) +++ sandbox/trunk/setuptools/setuptools/package_index.py Fri Feb 23 21:27:29 2007 @@ -228,20 +228,20 @@ else: self.warn(msg, url) - - - - - - - - - - - - - - + def scan_egg_links(self, search_path): + for item in search_path: + if os.path.isdir(item): + for entry in os.listdir(item): + if entry.endswith('.egg-link'): + self.scan_egg_link(item, entry) + + def scan_egg_link(self, path, entry): + lines = filter(None, map(str.strip, file(os.path.join(path, entry)))) + if len(lines)==2: + for dist in find_distributions(os.path.join(path, lines[0])): + dist.location = os.path.join(path, *lines) + dist.precedence = SOURCE_DIST + self.add(dist) def process_index(self,url,page): From python-checkins at python.org Fri Feb 23 21:30:01 2007 From: python-checkins at python.org (phillip.eby) Date: Fri, 23 Feb 2007 21:30:01 +0100 (CET) Subject: [Python-checkins] r53877 - in sandbox/branches/setuptools-0.6: EasyInstall.txt pkg_resources.py setuptools/command/develop.py setuptools/command/easy_install.py setuptools/package_index.py Message-ID: <20070223203001.A4D3D1E4014@bag.python.org> Author: phillip.eby Date: Fri Feb 23 21:29:58 2007 New Revision: 53877 Modified: sandbox/branches/setuptools-0.6/EasyInstall.txt sandbox/branches/setuptools-0.6/pkg_resources.py sandbox/branches/setuptools-0.6/setuptools/command/develop.py sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py sandbox/branches/setuptools-0.6/setuptools/package_index.py Log: Added ``--local-snapshots-ok`` flag, to allow building eggs from projects installed using ``setup.py develop``. (backport from trunk) Modified: sandbox/branches/setuptools-0.6/EasyInstall.txt ============================================================================== --- sandbox/branches/setuptools-0.6/EasyInstall.txt (original) +++ sandbox/branches/setuptools-0.6/EasyInstall.txt Fri Feb 23 21:29:58 2007 @@ -383,6 +383,13 @@ even if they're installed elsewhere on the machine, and ``-d`` indicates the directory to place the eggs in.) +You can also build the eggs from local development packages that were installed +with the ``setup.py develop`` command, by including the ``-l`` option, e.g.:: + + easy_install -zmaxld somedir SomePackage + +This will use locally-available source distributions to build the eggs. + Packaging Others' Projects As Eggs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -887,6 +894,25 @@ script directories, and does not override the ones set on the command line or in a configuration file. +``--local-snapshots-ok, -l`` (New in 0.6c6) + Normally, EasyInstall prefers to only install *released* versions of + projects, not in-development ones, because such projects may not + have a currently-valid version number. So, it usually only installs them + when their ``setup.py`` directory is explicitly passed on the command line. + + However, if this option is used, then any in-development projects that were + installed using the ``setup.py develop`` command, will be used to build + eggs, effectively upgrading the "in-development" project to a snapshot + release. Normally, this option is used only in conjunction with the + ``--always-copy`` option to create a distributable snapshot of every egg + needed to run an application. + + Note that if you use this option, you must make sure that there is a valid + version number (such as an SVN revision number tag) for any in-development + projects that may be used, as otherwise EasyInstall may not be able to tell + what version of the project is "newer" when future installations or + upgrades are attempted. + .. _non-root installation: @@ -1201,6 +1227,9 @@ * Fixed distutils-style scripts originally built on Windows having their line endings doubled when installed on any platform. + + * Added ``--local-snapshots-ok`` flag, to allow building eggs from projects + installed using ``setup.py develop``. 0.6c5 * Fixed ``.dll`` files on Cygwin not having executable permisions when an egg Modified: sandbox/branches/setuptools-0.6/pkg_resources.py ============================================================================== --- sandbox/branches/setuptools-0.6/pkg_resources.py (original) +++ sandbox/branches/setuptools-0.6/pkg_resources.py Fri Feb 23 21:29:58 2007 @@ -1676,7 +1676,7 @@ if not line.strip(): continue for item in find_distributions(os.path.join(path_item,line.rstrip())): yield item - + break register_finder(ImpWrapper,find_on_path) _namespace_handlers = {} Modified: sandbox/branches/setuptools-0.6/setuptools/command/develop.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/develop.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/develop.py Fri Feb 23 21:29:58 2007 @@ -31,7 +31,7 @@ self.uninstall = None self.egg_path = None easy_install.initialize_options(self) - + self.setup_path = None @@ -61,6 +61,7 @@ " directory to "+target ) + # Make a distribution for the package's source self.dist = Distribution( target, @@ -68,16 +69,15 @@ project_name = ei.egg_name ) - - - - - - - - - - + p = self.egg_base.replace(os.sep,'/') + if p!= os.curdir: + p = '../' * (p.count('/')+1) + self.setup_path = p + p = normalize_path(os.path.join(self.install_dir, self.egg_path, p)) + if p != normalize_path(os.curdir): + raise DistutilsOptionError( + "Can't get a consistent path to setup script from" + " installation directory", p, normalize_path(os.curdir)) def install_for_development(self): @@ -95,7 +95,7 @@ log.info("Creating %s (link to %s)", self.egg_link, self.egg_base) if not self.dry_run: f = open(self.egg_link,"w") - f.write(self.egg_path) + f.write(self.egg_path + "\n" + self.setup_path) f.close() # postprocess the installed distro, fixing up .pth, installing scripts, # and handling requirements @@ -106,7 +106,7 @@ if os.path.exists(self.egg_link): log.info("Removing %s (link to %s)", self.egg_link, self.egg_base) contents = [line.rstrip() for line in file(self.egg_link)] - if contents != [self.egg_path]: + if contents not in ([self.egg_path], [self.egg_path, self.setup_path]): log.warn("Link points to %s: uninstall aborted", contents) return if not self.dry_run: Modified: sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py Fri Feb 23 21:29:58 2007 @@ -70,18 +70,18 @@ ('editable', 'e', "Install specified packages in editable form"), ('no-deps', 'N', "don't install dependencies"), ('allow-hosts=', 'H', "pattern(s) that hostnames must match"), + ('local-snapshots-ok', 'l', "allow building eggs from local checkouts"), ] boolean_options = [ 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'delete-conflicting', 'ignore-conflicts-at-my-risk', 'editable', - 'no-deps', + 'no-deps', 'local-snapshots-ok', ] negative_opt = {'always-unzip': 'zip-ok'} create_index = PackageIndex - def initialize_options(self): - self.zip_ok = None + self.zip_ok = self.local_snapshots_ok = None self.install_dir = self.script_dir = self.exclude_scripts = None self.index_url = None self.find_links = None @@ -177,7 +177,8 @@ self.find_links = self.find_links.split() else: self.find_links = [] - + if self.local_snapshots_ok: + self.package_index.scan_egg_links(self.shadow_path+sys.path) self.package_index.add_find_links(self.find_links) self.set_undefined_options('install_lib', ('optimize','optimize')) if not isinstance(self.optimize,int): @@ -202,7 +203,6 @@ self.outputs = [] - def run(self): if self.verbose<>self.distribution.verbose: log.set_verbosity(self.verbose) Modified: sandbox/branches/setuptools-0.6/setuptools/package_index.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/package_index.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/package_index.py Fri Feb 23 21:29:58 2007 @@ -228,20 +228,20 @@ else: self.warn(msg, url) - - - - - - - - - - - - - - + def scan_egg_links(self, search_path): + for item in search_path: + if os.path.isdir(item): + for entry in os.listdir(item): + if entry.endswith('.egg-link'): + self.scan_egg_link(item, entry) + + def scan_egg_link(self, path, entry): + lines = filter(None, map(str.strip, file(os.path.join(path, entry)))) + if len(lines)==2: + for dist in find_distributions(os.path.join(path, lines[0])): + dist.location = os.path.join(path, *lines) + dist.precedence = SOURCE_DIST + self.add(dist) def process_index(self,url,page): From python-checkins at python.org Fri Feb 23 23:39:55 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 23 Feb 2007 23:39:55 +0100 (CET) Subject: [Python-checkins] r53878 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070223223955.704141E4016@bag.python.org> Author: brett.cannon Date: Fri Feb 23 23:39:52 2007 New Revision: 53878 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Add support for keyword-only arguments in Signature. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Fri Feb 23 23:39:52 2007 @@ -81,13 +81,17 @@ """Initialize from a function or method object.""" if hasattr(func, 'im_func'): func = func.im_func + func_code = func.func_code + self.name = func.__name__ argspec = inspect.getargspec(func) + # Variable parameters. self.var_args = argspec[1] if (argspec[1] is not None) else '' self.var_kw_args = argspec[2] if (argspec[2] is not None) else '' + # Non-keyword-only arguments. arg_count = len(argspec[0]) defaults_start = (arg_count - len(argspec[3]) if argspec[3] else arg_count) @@ -102,6 +106,23 @@ else: parameters.append(Parameter(arg_name, index, False)) + # Keyword-only arguments. + if hasattr(func_code, 'co_kwonlyargcount'): + non_keyword_count = func_code.co_argcount + keyword_count = func_code.co_kwonlyargcount + keyword_only_params = func_code.co_varnames[non_keyword_count: + (non_keyword_count+keyword_count)] + for index, param_name in enumerate(keyword_only_params): + has_default = False + default_value = None + if func.func_kwdefaults and param_name in func.func_kwdefaults: + has_default = True + default_value = func.func_kwdefaults[param_name] + parameters.append(Parameter(param_name, + index+non_keyword_count, + has_default, default_value, + keyword_only=True)) + self.parameters = tuple(parameters) @classmethod Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Fri Feb 23 23:39:52 2007 @@ -3,6 +3,16 @@ import unittest from test import test_support import pep362_fodder +from sys import version_info +if version_info[0] >= 3: + import pep362_py3k_fodder + +def py3k_test(fxn): + if version_info[0] >= 3: + return fxn + else: + return lambda self: self + class ParameterObjectTests(unittest.TestCase): @@ -52,14 +62,6 @@ self.failUnlessEqual(param.has_annotation, True) self.failUnlessEqual(param.annotation, annotation) - def test_str(self): - # Test __str__(). - name = "X" - param = pep362.Parameter(name, 0, False) - self.failUnlessEqual(name, str(param)) - default_value = 42 - param = pep362.Parameter(name, 0, True, default_value) - self.failUnlessEqual("%s=%s" % (name, default_value), str(param)) class SignatureObjectTests(unittest.TestCase): @@ -89,6 +91,7 @@ self.failUnlessEqual('', sig.var_kw_args) def test_parameter_positional(self): + # A function with positional arguments should work. sig = pep362.Signature(pep362_fodder.no_default_args) self.failUnlessEqual('no_default_args', sig.name) param = sig.parameters[0] @@ -98,6 +101,7 @@ self.failUnless(not hasattr(param, 'default_value')) def test_parameter_default(self): + # Default parameters for a function should work. sig = pep362.Signature(pep362_fodder.default_args) self.failUnlessEqual('default_args', sig.name) param = sig.parameters[0] @@ -107,6 +111,7 @@ self.failUnlessEqual(42, param.default_value) def test_parameter_tuple(self): + # A function with a tuple as a parameter should work. sig = pep362.Signature(pep362_fodder.tuple_args) self.failUnlessEqual('tuple_args', sig.name) param = sig.parameters[0] @@ -117,6 +122,7 @@ self.failUnless(not hasattr(param, 'default_value')) def test_parameter_tuple_default(self): + # A default argument for a tuple parameter needs to work. sig = pep362.Signature(pep362_fodder.default_tuple_args) self.failUnlessEqual('default_tuple_args', sig.name) param = sig.parameters[0] @@ -125,11 +131,33 @@ self.failUnless(param.has_default) self.failUnlessEqual((1, (2,)), param.default_value) - def test_positioning(self): + def test_getitem(self): + # Signature objects should have __getitem__ defined. sig = pep362.Signature(pep362_fodder.all_args) param = sig.parameters[2] self.failUnlessEqual('d', param.name) + @py3k_test + def test_keyword_only(self): + # Is a function containing keyword-only parameters handled properly? + sig = pep362.Signature(pep362_py3k_fodder.keyword_only) + param = sig.parameters[0] + self.failUnlessEqual(param.name, 'a') + self.failUnless(param.keyword_only) + self.failUnlessEqual(param.position, 0) + + @py3k_test + def test_keyword_only_default(self): + # Default arguments can work for keyword-only parameters. + sig = pep362.Signature(pep362_py3k_fodder.keyword_only_default) + param = sig.parameters[0] + self.failUnlessEqual(param.name, 'a') + self.failUnless(param.keyword_only) + self.failUnlessEqual(param.position, 0) + self.failUnless(param.has_default) + self.failUnlessEqual(param.default_value, 42) + + def test_signature(self): def fresh_func(): pass @@ -144,27 +172,6 @@ sig = pep362.signature(FreshClass.fresh_method) self.failUnlessEqual(sig, FreshClass.fresh_method.im_func.__signature__) - def test_str(self): - # Test __str__(). - sig = pep362.Signature(pep362_fodder.no_args) - self.failUnlessEqual("no_args()", str(sig)) - sig = pep362.Signature(pep362_fodder.var_args) - self.failUnlessEqual("var_args(*args)", str(sig)) - sig = pep362.Signature(pep362_fodder.var_kw_args) - self.failUnlessEqual("var_kw_args(**kwargs)", str(sig)) - sig = pep362.Signature(pep362_fodder.default_args) - self.failUnlessEqual("default_args(a=42)", str(sig)) - sig = pep362.Signature(pep362_fodder.no_default_args) - self.failUnlessEqual("no_default_args(a)", str(sig)) - sig = pep362.Signature(pep362_fodder.tuple_args) - self.failUnlessEqual("tuple_args((a, (b,)))", str(sig)) - sig = pep362.Signature(pep362_fodder.default_tuple_args) - self.failUnlessEqual("default_tuple_args((a, (b,))=(1, (2,)))", - str(sig)) - sig = pep362.Signature(pep362_fodder.all_args) - self.failUnlessEqual("all_args(a, (b, (c,)), d=0, " - "(e, (f,))=(1, (2,)), *g, **h)", - str(sig)) class SignatureBindTests(unittest.TestCase): From python-checkins at python.org Sat Feb 24 00:18:21 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 24 Feb 2007 00:18:21 +0100 (CET) Subject: [Python-checkins] r53879 - sandbox/trunk/pep362/pep362_fodder.py sandbox/trunk/pep362/pep362_py3k_fodder.py Message-ID: <20070223231821.C02651E4008@bag.python.org> Author: brett.cannon Date: Sat Feb 24 00:18:14 2007 New Revision: 53879 Added: sandbox/trunk/pep362/pep362_fodder.py (contents, props changed) sandbox/trunk/pep362/pep362_py3k_fodder.py (contents, props changed) Log: Add fodder files that were accidentally left out of previous checkins. Added: sandbox/trunk/pep362/pep362_fodder.py ============================================================================== --- (empty file) +++ sandbox/trunk/pep362/pep362_fodder.py Sat Feb 24 00:18:14 2007 @@ -0,0 +1,23 @@ +def no_args(): + pass + +def var_args(*args): + pass + +def var_kw_args(**kwargs): + pass + +def no_default_args(a): + pass + +def default_args(a=42): + pass + +def tuple_args((a, (b,))): + pass + +def default_tuple_args((a, (b,))=(1, (2,))): + pass + +def all_args(a, (b, (c,)), d=0, (e, (f,))=(1, (2,)), *g, **h): + pass Added: sandbox/trunk/pep362/pep362_py3k_fodder.py ============================================================================== --- (empty file) +++ sandbox/trunk/pep362/pep362_py3k_fodder.py Sat Feb 24 00:18:14 2007 @@ -0,0 +1,17 @@ +def keyword_only(*, a): + pass + +def keyword_only_default(*, a=42): + pass + +def arg_annotation(a:int): + pass + +def arg_annotation_default(a:int=42): + pass + +def arg_annotation_keyword_only(*, a:int): + pass + +def return_annotation() -> int: + pass From python-checkins at python.org Sat Feb 24 00:19:05 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 24 Feb 2007 00:19:05 +0100 (CET) Subject: [Python-checkins] r53880 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070223231905.B77B11E4008@bag.python.org> Author: brett.cannon Date: Sat Feb 24 00:19:04 2007 New Revision: 53880 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Add support for annotations. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sat Feb 24 00:19:04 2007 @@ -97,14 +97,22 @@ if argspec[3] else arg_count) parameters = [] for index, arg_name in enumerate(argspec[0]): + kwargs = dict.fromkeys(('has_default', 'default_value', + 'has_annotation', 'annotation'), False) if isinstance(arg_name, list): arg_name = self.__list2tuple(arg_name) + # Default values. if index >= defaults_start: - parameters.append(Parameter(arg_name, index, True, - argspec[3][index - defaults_start])) - else: - parameters.append(Parameter(arg_name, index, False)) + kwargs['has_default'] = True + kwargs['default_value'] = argspec[3][index - defaults_start] + # Parameter annotations. + if hasattr(func, 'func_annotations'): + if arg_name in func.func_annotations: + kwargs['has_annotation'] = True + kwargs['annotation'] = func.func_annotations[arg_name] + param = Parameter(arg_name, index, **kwargs) + parameters.append(param) # Keyword-only arguments. if hasattr(func_code, 'co_kwonlyargcount'): @@ -113,18 +121,28 @@ keyword_only_params = func_code.co_varnames[non_keyword_count: (non_keyword_count+keyword_count)] for index, param_name in enumerate(keyword_only_params): - has_default = False - default_value = None + kwargs = dict.fromkeys(('has_default', 'default_value', + 'has_annotation', 'annotation'), False) + # Default values. if func.func_kwdefaults and param_name in func.func_kwdefaults: - has_default = True - default_value = func.func_kwdefaults[param_name] + kwargs['has_default'] = True + kwargs['default_value'] = func.func_kwdefaults[param_name] + if param_name in func.func_annotations: + kwargs['has_annotation'] = True + kwargs['annotation'] = func.func_annotations[param_name] parameters.append(Parameter(param_name, index+non_keyword_count, - has_default, default_value, - keyword_only=True)) + keyword_only=True, **kwargs)) self.parameters = tuple(parameters) + # Return annotation. + self.has_annotation = False + if hasattr(func, 'func_annotations'): + if 'return' in func.func_annotations: + self.has_annotation = True + self.annotation = func.func_annotations['return'] + @classmethod def __list2tuple(cls, list_): if not isinstance(list_, list): Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sat Feb 24 00:19:04 2007 @@ -157,6 +157,41 @@ self.failUnless(param.has_default) self.failUnlessEqual(param.default_value, 42) + @py3k_test + def test_annotations(self): + # Make sure the proper annotation is found. + sig = pep362.Signature(pep362_py3k_fodder.arg_annotation) + param = sig.parameters[0] + self.failUnlessEqual(param.name, 'a') + self.failUnless(param.has_annotation) + self.failUnlessEqual(param.annotation, int) + + @py3k_test + def test_annotations_default(self): + # Annotations with a default value should work. + sig = pep362.Signature(pep362_py3k_fodder.arg_annotation_default) + param = sig.parameters[0] + self.failUnlessEqual(param.name, 'a') + self.failUnless(param.has_annotation) + self.failUnlessEqual(param.annotation, int) + self.failUnless(param.has_default) + self.failUnlessEqual(param.default_value, 42) + + @py3k_test + def test_annotation_keyword_only(self): + # Keyword-only parameters can have an annotation. + sig = pep362.Signature(pep362_py3k_fodder.arg_annotation_keyword_only) + param = sig.parameters[0] + self.failUnlessEqual(param.name, 'a') + self.failUnless(param.has_annotation) + self.failUnlessEqual(param.annotation, int) + self.failUnless(param.keyword_only) + + @py3k_test + def test_return_annotation(self): + sig = pep362.Signature(pep362_py3k_fodder.return_annotation) + self.failUnless(sig.has_annotation) + self.failUnlessEqual(sig.annotation, int) def test_signature(self): def fresh_func(): From thomas at python.org Sat Feb 24 00:58:50 2007 From: thomas at python.org (Thomas Wouters) Date: Fri, 23 Feb 2007 15:58:50 -0800 Subject: [Python-checkins] r53824 - python/trunk/Doc/lib/libcollections.tex In-Reply-To: <20070219091410.002D61E4006@bag.python.org> References: <20070219091410.002D61E4006@bag.python.org> Message-ID: <9e804ac0702231558i5d05c583n20ae51b06ee5559e@mail.gmail.com> On 2/19/07, raymond.hettinger wrote: > +>>> def constant_factory(value): > +... return itertools.repeat(value).next Ehm, no offense, Raymond (I know you love itertools, and so do I) but could we maybe write this as: >>> def constant_factory(value): ... return lambda: value (or the two-line inner-function way to write the same thing.) It is, after all, documentation of defaultdict, not of weird-ways-to-use-itertools ;) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-checkins/attachments/20070223/10ca70cf/attachment.html From python-checkins at python.org Sat Feb 24 06:41:43 2007 From: python-checkins at python.org (guido.van.rossum) Date: Sat, 24 Feb 2007 06:41:43 +0100 (CET) Subject: [Python-checkins] r53881 - peps/trunk/pep-3106.txt Message-ID: <20070224054143.359ED1E4019@bag.python.org> Author: guido.van.rossum Date: Sat Feb 24 06:41:38 2007 New Revision: 53881 Modified: peps/trunk/pep-3106.txt Log: Restore the previous definition of __eq__ for d_values. There was a reason I did it by modifying a list! Modified: peps/trunk/pep-3106.txt ============================================================================== --- peps/trunk/pep-3106.txt (original) +++ peps/trunk/pep-3106.txt Sat Feb 24 06:41:38 2007 @@ -247,9 +247,13 @@ # XXX Sometimes this could be optimized, but these are the # semantics: we can't depend on the values to be hashable # or comparable. + olist = list(other) for x in self: - if not o in other: + try: + olist.remove(x) + except ValueError: return False + assert olist == [] return True def __ne__(self, other): From python-checkins at python.org Sat Feb 24 06:42:55 2007 From: python-checkins at python.org (guido.van.rossum) Date: Sat, 24 Feb 2007 06:42:55 +0100 (CET) Subject: [Python-checkins] r53882 - peps/trunk/pep-0000.txt peps/trunk/pep-0358.txt peps/trunk/pep-3112.txt Message-ID: <20070224054255.8B4A11E4005@bag.python.org> Author: guido.van.rossum Date: Sat Feb 24 06:42:52 2007 New Revision: 53882 Added: peps/trunk/pep-3112.txt (contents, props changed) Modified: peps/trunk/pep-0000.txt peps/trunk/pep-0358.txt Log: Add the bytes literal PEP, by Jason Orendorff. And accept it! Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Sat Feb 24 06:42:52 2007 @@ -83,6 +83,7 @@ SA 3109 Raising Exceptions in Python 3000 Winter SA 3110 Catching Exceptions in Python 3000 Winter SA 3111 Simple input built-in in Python 3000 Roberge + SA 3112 Bytes literals in Python 3000 Wouters Open PEPs (under consideration) @@ -455,6 +456,7 @@ SA 3109 Raising Exceptions in Python 3000 Winter SA 3110 Catching Exceptions in Python 3000 Winter SA 3111 Simple input built-in in Python 3000 Roberge + SA 3112 Bytes literals in Python 3000 Wouters Key Modified: peps/trunk/pep-0358.txt ============================================================================== --- peps/trunk/pep-0358.txt (original) +++ peps/trunk/pep-0358.txt Sat Feb 24 06:42:52 2007 @@ -181,6 +181,9 @@ be added to language to allow objects to be converted into byte arrays. This decision is out of scope. + * A bytes literal of the form b"..." is also proposed. This is + the subject of PEP 3112. + Open Issues @@ -195,14 +198,7 @@ * Should all those list methods really be implemented? - * There is growing support for a b"..." literal. Here's a brief - spec. Each invocation of b"..." produces a new bytes object - (this is unlike "..." but similar to [...] and {...}). Inside - the literal, only ASCII characters and non-Unicode backslash - escapes are allowed; non-ASCII characters not specified as - escapes are rejected by the compiler regardless of the source - encoding. The resulting object's value is the same as if - bytes(map(ord, "...")) were called. + * Now that a b"..." literal exists, shouldn't repr() return one? * A case could be made for supporting .ljust(), .rjust(), .center() with a mandatory second argument. Added: peps/trunk/pep-3112.txt ============================================================================== --- (empty file) +++ peps/trunk/pep-3112.txt Sat Feb 24 06:42:52 2007 @@ -0,0 +1,159 @@ +PEP: +Title: Bytes literals in Python 3000 +Version: $Revision$ +Last-Modified: $Date$ +Author: Jason Orendorff +Status: Accepted +Type: +Content-Type: text/x-rst +Requires: 358 +Created: 23-Feb-2007 +Python-Version: 3.0 +Post-History: 23-Feb-2007 + + +Abstract +======== + +This PEP proposes a literal syntax for the ``bytes`` objects +introduced in PEP 358. The purpose is to provide a convenient way to +spell ASCII strings and arbitrary binary data. + + +Motivation +========== + +Existing spellings of an ASCII string in Python 3000 include: + + bytes('Hello world', 'ascii') + 'Hello world'.encode('ascii') + +The proposed syntax is: + + b'Hello world' + +Existing spellings of an 8-bit binary sequence in Python 3000 include: + + bytes([0x7f, 0x45, 0x4c, 0x46, 0x01, 0x01, 0x01, 0x00]) + bytes('\x7fELF\x01\x01\x01\0', 'latin-1') + '7f454c4601010100'.decode('hex') + +The proposed syntax is: + + b'\x7f\x45\x4c\x46\x01\x01\x01\x00' + b'\x7fELF\x01\x01\x01\0' + +In both cases, the advantages of the new syntax are brevity, some +small efficiency gain, and the detection of encoding errors at compile +time rather than at runtime. The brevity benefit is especially felt +when using the string-like methods of bytes objects: + + lines = bdata.split(bytes('\n', 'ascii')) # existing syntax + lines = bdata.split(b'\n') # proposed syntax + +And when converting code from Python 2.x to Python 3000: + + sok.send('EXIT\r\n') # Python 2.x + sok.send('EXIT\r\n'.encode('ascii')) # Python 3000 existing + sok.send(b'EXIT\r\n') # proposed + + +Grammar Changes +=============== + +The proposed syntax is an extension of the existing string +syntax. [#stringliterals]_ + +The new syntax for strings, including the new bytes literal, is: + + stringliteral: [stringprefix] (shortstring | longstring) + stringprefix: "b" | "r" | "br" | "B" | "R" | "BR" | "Br" | "bR" + shortstring: "'" shortstringitem* "'" | '"' shortstringitem* '"' + longstring: "'''" longstringitem* "'''" | '"""' longstringitem* '"""' + shortstringitem: shortstringchar | escapeseq + longstringitem: longstringchar | escapeseq + shortstringchar: + + longstringchar: + escapeseq: "\" NL + | "\\" | "\'" | '\"' + | "\a" | "\b" | "\f" | "\n" | "\r" | "\t" | "\v" + | "\ooo" | "\xhh" + | "\uxxxx" | "\Uxxxxxxxx" | "\N{name}" + +The following additional restrictions apply only to bytes literals +(``stringliteral`` tokens with ``b`` or ``B`` in the +``stringprefix``): + +- Each ``shortstringchar`` or ``longstringchar`` must be a character + between 1 and 127 inclusive, regardless of any encoding + declaration [#encodings]_ in the source file. + +- The Unicode-specific escape sequences ``\u``*xxxx*, + ``\U``*xxxxxxxx*, and ``\N{``*name*``}`` are unrecognized in + Python 2.x and forbidden in Python 3000. + +Adjacent bytes literals are subject to the same concatenation rules as +adjacent string literals. [#concat]_ A bytes literal adjacent to a +string literal is an error. + + +Semantics +========= + +Each evaluation of a bytes literal produces a new ``bytes`` object. +The bytes in the new object are the bytes represented by the +``shortstringitem``s or ``longstringitem``s in the literal, in the +same order. + + +Rationale +========= + +The proposed syntax provides a cleaner migration path from Python 2.x +to Python 3000 for most code involving 8-bit strings. Preserving the +old 8-bit meaning of a string literal is usually as simple as adding a +``b`` prefix. The one exception is Python 2.x strings containing +bytes >127, which must be rewritten using escape sequences. +Transcoding a source file from one encoding to another, and fixing up +the encoding declaration, should preserve the meaning of the program. +Python 2.x non-Unicode strings violate this principle; Python 3000 +bytes literals shouldn't. + +A string literal with a ``b`` in the prefix is always a syntax error +in Python 2.5, so this syntax can be introduced in Python 2.6, along +with the ``bytes`` type. + +A bytes literal produces a new object each time it is evaluated, like +list displays and unlike string literals. This is necessary because +bytes literals, like lists and unlike strings, are +mutable. [#eachnew]_ + + +Reference Implementation +======================== + +Thomas Wouters has checked an implementation into the Py3K branch, +r53872. + + +References +========== + +.. [#stringliterals] + http://www.python.org/doc/current/ref/strings.html + +.. [#encodings] + http://www.python.org/doc/current/ref/encodings.html + +.. [#concat] + http://www.python.org/doc/current/ref/string-catenation.html + +.. [#eachnew] + http://mail.python.org/pipermail/python-3000/2007-February/005779.html + + +Copyright +========= + +This document has been placed in the public domain. From python-checkins at python.org Sat Feb 24 16:28:06 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 24 Feb 2007 16:28:06 +0100 (CET) Subject: [Python-checkins] r53883 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070224152806.DBBCE1E4011@bag.python.org> Author: brett.cannon Date: Sat Feb 24 16:28:06 2007 New Revision: 53883 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Turn on Signature.bind tests and add a (failing) one for keyword-only arguments in Py3K. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sat Feb 24 16:28:06 2007 @@ -207,7 +207,9 @@ are present is to posssibly mutate an iterator then the method gives up and raises a BindError. This is to prevent something like a generator which is about to be used for an actual function call from being - exhausted by this method.""" + exhausted by this method. + + """ bindings = {} arg_names_seq = [param.name for param in self.parameters] arg_names_set = set(arg_names_seq) @@ -225,7 +227,7 @@ self.__positional_bind(arg_name, value, bindings) # Keyword arguments. var_kw_args = {} - for key, value in kwargs.items(): + for key, value in list(kwargs.items()): if key not in arg_names_set: if not self.var_kw_args: raise TypeError("unexpected keyword argument: %r" % key) @@ -250,7 +252,7 @@ bindings[param.name] = param.default_value # Make sure all required arguments are bound to. - for bound in bindings.iterkeys(): + for bound in bindings.keys(): try: required_args.remove(bound) except KeyError: Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sat Feb 24 16:28:06 2007 @@ -282,6 +282,13 @@ ('e', ('f',)):(4, (5,)), 'g':(6,), 'h':{'i':7}} self.failUnlessEqual(expected, binding) + @py3k_test + def test_keyword_only(self): + sig = pep362.Signature(pep362_py3k_fodder.keyword_only) + binding = sig.bind(a=42) + self.failUnlessEqual(binding, {'a':42}) + self.failUnlessRaises(pep362.BindError, sig.bind, 42) + def test_BindError(self): def gen(): yield 0 @@ -293,6 +300,7 @@ def test_main(): test_support.run_unittest(ParameterObjectTests, SignatureObjectTests, + SignatureBindTests, ) From python-checkins at python.org Sat Feb 24 17:32:07 2007 From: python-checkins at python.org (neal.norwitz) Date: Sat, 24 Feb 2007 17:32:07 +0100 (CET) Subject: [Python-checkins] r53884 - peps/trunk/pep-3100.txt Message-ID: <20070224163207.6C25F1E4011@bag.python.org> Author: neal.norwitz Date: Sat Feb 24 17:32:03 2007 New Revision: 53884 Modified: peps/trunk/pep-3100.txt Log: I assume this was from some mail msg, but I don't have the ref currently Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Sat Feb 24 17:32:03 2007 @@ -148,6 +148,9 @@ methods will be removed. Better: make keys(), etc. return views ala Java collections??? * Make ``string.join()`` stringify its arguments? [18]_ +* Fix file() so it returns a ValueError if the mode is bad rather than IOError. + (This probably affects lots of places, we should review the exceptions + and fix them if inappropriate.) To be removed: From python-checkins at python.org Sat Feb 24 17:36:18 2007 From: python-checkins at python.org (neal.norwitz) Date: Sat, 24 Feb 2007 17:36:18 +0100 (CET) Subject: [Python-checkins] r53885 - peps/trunk/pep-3100.txt Message-ID: <20070224163618.B27BA1E4011@bag.python.org> Author: neal.norwitz Date: Sat Feb 24 17:36:15 2007 New Revision: 53885 Modified: peps/trunk/pep-3100.txt Log: Add some ideas from Raymond Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Sat Feb 24 17:36:15 2007 @@ -234,6 +234,13 @@ in favor of always using threading.py.) * UserXyz classes, in favour of XyzMixins. +* Remove the unreliable empty() and full() methods from Queue.py? +* Remove jumpahead() from the random API? +* Make the primative for random be something generating random bytes + rather than random floats? +* Get rid of Cookie.SerialCookie and Cookie.SmartCookie? +* Modify the heapq.heapreplace() API to compare the new value to the top + of the heap? Outstanding Issues ================== @@ -321,6 +328,9 @@ .. [24] python-3000 email ("Pre-peps on raise and except changes") http://mail.python.org/pipermail/python-3000/2007-February/005672.html +.. [25] python-3000 email ("Py3.0 Library Ideas") + http://mail.python.org/pipermail/python-3000/2007-February/005726.html + .. [#sys-module] Python docs (sys -- System-specific parameters and functions) http://docs.python.org/lib/module-sys.html From python-checkins at python.org Sat Feb 24 18:00:18 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 24 Feb 2007 18:00:18 +0100 (CET) Subject: [Python-checkins] r53886 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070224170018.78E0D1E4011@bag.python.org> Author: brett.cannon Date: Sat Feb 24 18:00:16 2007 New Revision: 53886 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Rewrite Signature.bind. Missing tuple support along with properly dealing with multiple arguments for the same parameter. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sat Feb 24 18:00:16 2007 @@ -211,55 +211,82 @@ """ bindings = {} - arg_names_seq = [param.name for param in self.parameters] - arg_names_set = set(arg_names_seq) - arg_names_cnt = len(arg_names_set) - required_args = set(param.name for param in self.parameters - if not param.has_default) - required_args_cnt = len(required_args) - # *args. if self.var_args: - bindings[self.var_args] = args[arg_names_cnt:] - args = args[:arg_names_cnt] - if len(args) > arg_names_cnt: - raise TypeError("too many positional arguments provided") - for arg_name, value in zip(arg_names_seq, args): - self.__positional_bind(arg_name, value, bindings) - # Keyword arguments. - var_kw_args = {} - for key, value in list(kwargs.items()): - if key not in arg_names_set: - if not self.var_kw_args: - raise TypeError("unexpected keyword argument: %r" % key) - else: - var_kw_args[key] = value - else: - if key in bindings: - raise TypeError("got multiple values for argument %r" % - key) - else: - bindings[key] = value - del kwargs[key] - if kwargs: - raise TypeError("too many keyword arguments provided") - # **kwargs. + bindings[self.var_args] = tuple() if self.var_kw_args: - bindings[self.var_kw_args] = var_kw_args - # Default values. + bindings[self.var_kw_args] = dict() + positional = [] + keyword_only = {} + + # XXX Multiple arguments for same parameter. + # XXX Error-checking for every place where something could fail. + # XXX Tuple parameters. + + if not self.parameters and args and self.var_args: + bindings[self.var_args] = args + args = tuple() + + for param in self.parameters: - if param.has_default: - if param.name not in bindings: - bindings[param.name] = param.default_value + if not param.keyword_only: + positional.append(param) + else: + keyword_only[param.name] = param - # Make sure all required arguments are bound to. - for bound in bindings.keys(): + # Positional arguments. + for index, position_arg in enumerate(args): try: - required_args.remove(bound) - except KeyError: - pass + param = positional.pop(0) + except IndexError: + # *args. + if self.var_args: + bindings[self.var_args] = tuple(args[index-1:]) + break + else: + raise BindError("too many positional arguments") + bindings[param.name] = position_arg + # Keyword arguments & default values. else: - if required_args: - raise TypeError("too few arguments provided") + for positional_param in positional: + param_name = positional_param.name + if param_name in kwargs: + try: + bindings[param_name] = kwargs[param_name] + del kwargs[param_name] + except KeyError: + raise BindError("%r unbound" % param_name) + else: + if positional_param.has_default: + bindings[param_name] = positional_param.default_value + else: + raise BindError("%r parameter lacking default value" % + param_name) + + # Keyword arguments. + positional_dict = dict((param.name, param) for param in positional) + for key, value in kwargs.copy().items(): + if key in positional_dict: + del positional_dict[key] + elif key in keyword_only: + del keyword_only[key] + else: + # **kwargs. + if self.var_kw_args: + bindings[self.var_kw_args] = kwargs + break + else: + raise BindError("too many keyword arguments") + bindings[key] = value + del kwargs[key] + # Keyword-only default values. + else: + for name, param in keyword_only.items(): + if param.has_default: + bindings[name] = param.default_value + else: + raise BindError("%s parameter lacking a default value" % + name) + return bindings Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sat Feb 24 18:00:16 2007 @@ -257,7 +257,7 @@ self.failUnlessRaises(TypeError, sig.bind, a=0, b=1) self.failUnlessRaises(TypeError, sig.bind, b=1) - def test_tuple_parameter(self): + def XXX_test_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.tuple_args) binding = sig.bind((1, (2,))) self.failUnlessEqual({('a', ('b',)):(1, (2,))}, binding) @@ -267,7 +267,7 @@ self.failUnlessRaises(TypeError, sig.bind, (1,2,3)) self.failUnlessRaises(TypeError, sig.bind, (1, 2)) - def test_default_tuple_parameter(self): + def XXX_test_default_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.default_tuple_args) binding = sig.bind() self.failUnlessEqual({('a', ('b',)):(1, (2,))}, binding) @@ -275,7 +275,7 @@ binding = sig.bind(arg) self.failUnlessEqual({('a', ('b',)):arg}, binding) - def test_all_parameter_types(self): + def XXX_test_all_parameter_types(self): sig = pep362.Signature(pep362_fodder.all_args) binding = sig.bind(0, (1, (2,)), 3, (4, (5,)), 6, i=7) expected = {'a':0, ('b', ('c',)):(1, (2,)), 'd':3, @@ -289,7 +289,9 @@ self.failUnlessEqual(binding, {'a':42}) self.failUnlessRaises(pep362.BindError, sig.bind, 42) - def test_BindError(self): + # XXX Make sure all paths covered (especially error checking). + + def XXX_test_do_not_consume_iterators(self): def gen(): yield 0 yield (1,) From python-checkins at python.org Sat Feb 24 18:00:58 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 24 Feb 2007 18:00:58 +0100 (CET) Subject: [Python-checkins] r53887 - sandbox/trunk/pep362/pep362.py Message-ID: <20070224170058.702BC1E4011@bag.python.org> Author: brett.cannon Date: Sat Feb 24 18:00:57 2007 New Revision: 53887 Modified: sandbox/trunk/pep362/pep362.py Log: Slight code reordering. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sat Feb 24 18:00:57 2007 @@ -222,11 +222,6 @@ # XXX Error-checking for every place where something could fail. # XXX Tuple parameters. - if not self.parameters and args and self.var_args: - bindings[self.var_args] = args - args = tuple() - - for param in self.parameters: if not param.keyword_only: positional.append(param) @@ -234,6 +229,9 @@ keyword_only[param.name] = param # Positional arguments. + if not self.parameters and args and self.var_args: + bindings[self.var_args] = args + args = tuple() for index, position_arg in enumerate(args): try: param = positional.pop(0) From python-checkins at python.org Sat Feb 24 18:04:24 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 24 Feb 2007 18:04:24 +0100 (CET) Subject: [Python-checkins] r53888 - sandbox/trunk/pep362/test_pep362.py Message-ID: <20070224170424.417161E4011@bag.python.org> Author: brett.cannon Date: Sat Feb 24 18:04:22 2007 New Revision: 53888 Modified: sandbox/trunk/pep362/test_pep362.py Log: Tighten up Signature.bind tests and what exception is expected. Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sat Feb 24 18:04:22 2007 @@ -216,8 +216,8 @@ sig = pep362.Signature(pep362_fodder.no_args) binding = sig.bind() self.failUnlessEqual({}, binding) - self.failUnlessRaises(TypeError, sig.bind, 42) - self.failUnlessRaises(TypeError, sig.bind, a=0) + self.failUnlessRaises(pep362.BindError, sig.bind, 42) + self.failUnlessRaises(pep362.BindError, sig.bind, a=0) def test_var_parameters(self): sig = pep362.Signature(pep362_fodder.var_args) @@ -225,7 +225,7 @@ self.failUnlessEqual({'args':(0, 1, 2)}, binding) binding = sig.bind() self.failUnlessEqual({'args':tuple()}, binding) - self.failUnlessRaises(TypeError, sig.bind, a=0) + self.failUnlessRaises(pep362.BindError, sig.bind, a=0) def test_var_kw_parameters(self): sig = pep362.Signature(pep362_fodder.var_kw_args) @@ -233,7 +233,7 @@ self.failUnlessEqual({'kwargs':{'a':0}}, binding) binding = sig.bind() self.failUnlessEqual({'kwargs':{}}, binding) - self.failUnlessRaises(TypeError, sig.bind, 42) + self.failUnlessRaises(pep362.BindError, sig.bind, 42) def test_positional_parameters(self): sig = pep362.Signature(pep362_fodder.no_default_args) @@ -241,9 +241,9 @@ self.failUnlessEqual({'a':42}, binding) binding = sig.bind(a=42) self.failUnlessEqual({'a':42}, binding) - self.failUnlessRaises(TypeError, sig.bind) - self.failUnlessRaises(TypeError, sig.bind, 0, 1) - self.failUnlessRaises(TypeError, sig.bind, b=0) + self.failUnlessRaises(pep362.BindError, sig.bind) + self.failUnlessRaises(pep362.BindError, sig.bind, 0, 1) + self.failUnlessRaises(pep362.BindError, sig.bind, b=0) def test_keyword_parameters(self): sig = pep362.Signature(pep362_fodder.default_args) @@ -253,9 +253,9 @@ self.failUnlessEqual({'a':42}, binding) binding = sig.bind(a=0) self.failUnlessEqual({'a':0}, binding) - self.failUnlessRaises(TypeError, sig.bind, 0, 1) - self.failUnlessRaises(TypeError, sig.bind, a=0, b=1) - self.failUnlessRaises(TypeError, sig.bind, b=1) + self.failUnlessRaises(pep362.BindError, sig.bind, 0, 1) + self.failUnlessRaises(pep362.BindError, sig.bind, a=0, b=1) + self.failUnlessRaises(pep362.BindError, sig.bind, b=1) def XXX_test_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.tuple_args) @@ -264,8 +264,8 @@ arg = (1, ((2,),)) binding = sig.bind(arg) self.failUnlessEqual({('a', ('b',)):arg}, binding) - self.failUnlessRaises(TypeError, sig.bind, (1,2,3)) - self.failUnlessRaises(TypeError, sig.bind, (1, 2)) + self.failUnlessRaises(pep362.BindError, sig.bind, (1,2,3)) + self.failUnlessRaises(pep362.BindError, sig.bind, (1, 2)) def XXX_test_default_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.default_tuple_args) From python-checkins at python.org Sat Feb 24 18:13:34 2007 From: python-checkins at python.org (thomas.wouters) Date: Sat, 24 Feb 2007 18:13:34 +0100 (CET) Subject: [Python-checkins] r53889 - peps/trunk/pep-0000.txt Message-ID: <20070224171334.F31DE1E4011@bag.python.org> Author: thomas.wouters Date: Sat Feb 24 18:13:30 2007 New Revision: 53889 Modified: peps/trunk/pep-0000.txt Log: Credit where credit due. Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Sat Feb 24 18:13:30 2007 @@ -83,7 +83,7 @@ SA 3109 Raising Exceptions in Python 3000 Winter SA 3110 Catching Exceptions in Python 3000 Winter SA 3111 Simple input built-in in Python 3000 Roberge - SA 3112 Bytes literals in Python 3000 Wouters + SA 3112 Bytes literals in Python 3000 Orendorff Open PEPs (under consideration) @@ -456,7 +456,7 @@ SA 3109 Raising Exceptions in Python 3000 Winter SA 3110 Catching Exceptions in Python 3000 Winter SA 3111 Simple input built-in in Python 3000 Roberge - SA 3112 Bytes literals in Python 3000 Wouters + SA 3112 Bytes literals in Python 3000 Orendorff Key @@ -539,6 +539,7 @@ North, Ben ben at redfrontdoor.org Norwitz, Neal nnorwitz at gmail.com Oliphant, Travis oliphant at ee.byu.edu + Orendorff, Jason jason.orendorff at gmail.com Pedroni, Samuele pedronis at python.org Pelletier, Michel michel at users.sourceforge.net Peters, Tim tim at zope.com From python-checkins at python.org Sat Feb 24 18:16:27 2007 From: python-checkins at python.org (thomas.wouters) Date: Sat, 24 Feb 2007 18:16:27 +0100 (CET) Subject: [Python-checkins] r53890 - peps/trunk/pep-0000.txt peps/trunk/pep-0203.txt peps/trunk/pep-0204.txt peps/trunk/pep-0221.txt Message-ID: <20070224171627.187651E4011@bag.python.org> Author: thomas.wouters Date: Sat Feb 24 18:16:22 2007 New Revision: 53890 Modified: peps/trunk/pep-0000.txt peps/trunk/pep-0203.txt peps/trunk/pep-0204.txt peps/trunk/pep-0221.txt Log: Update my email address from the old work address (which still works, but not indefinitely.) Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Sat Feb 24 18:16:22 2007 @@ -568,7 +568,7 @@ Wells, Cliff LogiplexSoftware at earthlink.net Wilson, Greg gvwilson at ddj.com Winter, Collin collinw at gmail.com - Wouters, Thomas thomas at xs4all.net + Wouters, Thomas thomas at python.org Yee, Ka-Ping ping at zesty.ca Zadka, Moshe moshez at zadka.site.co.il Zhu, Huaiyu hzhu at users.sourceforge.net Modified: peps/trunk/pep-0203.txt ============================================================================== --- peps/trunk/pep-0203.txt (original) +++ peps/trunk/pep-0203.txt Sat Feb 24 18:16:22 2007 @@ -2,7 +2,7 @@ Title: Augmented Assignments Version: $Revision$ Last-Modified: $Date$ -Author: thomas at xs4all.net (Thomas Wouters) +Author: thomas at python.org (Thomas Wouters) Status: Final Type: Standards Track Python-Version: 2.0 Modified: peps/trunk/pep-0204.txt ============================================================================== --- peps/trunk/pep-0204.txt (original) +++ peps/trunk/pep-0204.txt Sat Feb 24 18:16:22 2007 @@ -2,7 +2,7 @@ Title: Range Literals Version: $Revision$ Last-Modified: $Date$ -Author: thomas at xs4all.net (Thomas Wouters) +Author: thomas at python.org (Thomas Wouters) Status: Rejected Type: Standards Track Python-Version: 2.0 Modified: peps/trunk/pep-0221.txt ============================================================================== --- peps/trunk/pep-0221.txt (original) +++ peps/trunk/pep-0221.txt Sat Feb 24 18:16:22 2007 @@ -2,7 +2,7 @@ Title: Import As Version: $Revision$ Last-Modified: $Date$ -Author: thomas at xs4all.net (Thomas Wouters) +Author: thomas at python.org (Thomas Wouters) Status: Final Type: Standards Track Python-Version: 2.0 From python-checkins at python.org Sat Feb 24 18:29:42 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 24 Feb 2007 18:29:42 +0100 (CET) Subject: [Python-checkins] r53891 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070224172942.8EAFD1E4011@bag.python.org> Author: brett.cannon Date: Sat Feb 24 18:29:37 2007 New Revision: 53891 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Raise BindError when a positional and keyword argument bind to the same parameter. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sat Feb 24 18:29:37 2007 @@ -203,12 +203,9 @@ """Return a dictionary mapping function arguments to their parameter variables, if possible. - If the only way to determine the proper binding when tuple parameters - are present is to posssibly mutate an iterator then the method gives up - and raises a BindError. This is to prevent something like a generator - which is about to be used for an actual function call from being - exhausted by this method. - + Multiple arguments for the same parameter using keyword arguments + cannot be detected. + """ bindings = {} if self.var_args: @@ -218,8 +215,6 @@ positional = [] keyword_only = {} - # XXX Multiple arguments for same parameter. - # XXX Error-checking for every place where something could fail. # XXX Tuple parameters. for param in self.parameters: @@ -263,6 +258,9 @@ # Keyword arguments. positional_dict = dict((param.name, param) for param in positional) for key, value in kwargs.copy().items(): + if key in bindings: + raise BindError("too many arguments for %r parameter" + % key) if key in positional_dict: del positional_dict[key] elif key in keyword_only: Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sat Feb 24 18:29:37 2007 @@ -247,10 +247,10 @@ def test_keyword_parameters(self): sig = pep362.Signature(pep362_fodder.default_args) - binding = sig.bind(0) - self.failUnlessEqual({'a':0}, binding) binding = sig.bind() self.failUnlessEqual({'a':42}, binding) + binding = sig.bind(0) + self.failUnlessEqual({'a':0}, binding) binding = sig.bind(a=0) self.failUnlessEqual({'a':0}, binding) self.failUnlessRaises(pep362.BindError, sig.bind, 0, 1) @@ -287,9 +287,24 @@ sig = pep362.Signature(pep362_py3k_fodder.keyword_only) binding = sig.bind(a=42) self.failUnlessEqual(binding, {'a':42}) + self.failUnlessRaises(pep362.BindError, sig.bind) self.failUnlessRaises(pep362.BindError, sig.bind, 42) - # XXX Make sure all paths covered (especially error checking). + @py3k_test + def test_keyword_only_default(self): + sig = pep362.Signature(pep362_py3k_fodder.keyword_only_default) + binding = sig.bind() + self.failUnlessEqual(binding, {'a':42}) + binding = sig.bind(a=1) + self.failUnlessEqual(binding, {'a':1}) + self.failUnlessRaises(pep362.BindError, sig.bind, 1) + + def test_too_many_arguments(self): + # Only one argument should pair up with a parameter. + sig = pep362.Signature(pep362_fodder.no_default_args) + self.failUnlessRaises(pep362.BindError, sig.bind, 1, a=1) + # Technically handled by Python itself. + self.failUnlessRaises(pep362.BindError, sig.bind, a=1, a=2) def XXX_test_do_not_consume_iterators(self): def gen(): From python-checkins at python.org Sat Feb 24 21:54:44 2007 From: python-checkins at python.org (collin.winter) Date: Sat, 24 Feb 2007 21:54:44 +0100 (CET) Subject: [Python-checkins] r53893 - in sandbox/trunk/2to3: fixer_tests.py fixes/fix_raise.py fixes/fix_throw.py Message-ID: <20070224205444.C899F1E4006@bag.python.org> Author: collin.winter Date: Sat Feb 24 21:54:41 2007 New Revision: 53893 Modified: sandbox/trunk/2to3/fixer_tests.py sandbox/trunk/2to3/fixes/fix_raise.py sandbox/trunk/2to3/fixes/fix_throw.py Log: Change fix_raise and fix_throw to use the with_traceback() method Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Sat Feb 24 21:54:41 2007 @@ -681,9 +681,7 @@ b = """def foo(): raise Exception, 5, 6""" a = """def foo(): - xxx_todo_changeme5 = Exception(5) - xxx_todo_changeme5.__traceback__ = 6 - raise xxx_todo_changeme5""" + raise Exception(5).with_traceback(6)""" self.check(b, a) def test_tb_2(self): @@ -693,9 +691,7 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme6 = Exception(5) - xxx_todo_changeme6.__traceback__ = 6 - raise xxx_todo_changeme6 + raise Exception(5).with_traceback(6) b = 6""" self.check(b, a) @@ -703,9 +699,7 @@ b = """def foo(): raise Exception,5,6""" a = """def foo(): - xxx_todo_changeme7 = Exception(5) - xxx_todo_changeme7.__traceback__ = 6 - raise xxx_todo_changeme7""" + raise Exception(5).with_traceback(6)""" self.check(b, a) def test_tb_4(self): @@ -715,9 +709,7 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme8 = Exception(5) - xxx_todo_changeme8.__traceback__ = 6 - raise xxx_todo_changeme8 + raise Exception(5).with_traceback(6) b = 6""" self.check(b, a) @@ -725,9 +717,7 @@ b = """def foo(): raise Exception, (5, 6, 7), 6""" a = """def foo(): - xxx_todo_changeme9 = Exception(5, 6, 7) - xxx_todo_changeme9.__traceback__ = 6 - raise xxx_todo_changeme9""" + raise Exception(5, 6, 7).with_traceback(6)""" self.check(b, a) def test_tb_6(self): @@ -737,9 +727,7 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme10 = Exception(5, 6, 7) - xxx_todo_changeme10.__traceback__ = 6 - raise xxx_todo_changeme10 + raise Exception(5, 6, 7).with_traceback(6) b = 6""" self.check(b, a) @@ -759,27 +747,41 @@ def test_3(self): b = """g.throw(Exception, (5, 6, 7))""" - a = """g.throw(Exception((5, 6, 7)))""" + a = """g.throw(Exception(5, 6, 7))""" self.check(b, a) def test_4(self): b = """5 + g.throw(Exception, 5)""" a = """5 + g.throw(Exception(5))""" self.check(b, a) + + # These should produce warnings + + def test_warn_1(self): + s = """g.throw("foo")""" + self.warns(s, s, "Python 3 does not support string exceptions") + + def test_warn_2(self): + s = """g.throw("foo", 5)""" + self.warns(s, s, "Python 3 does not support string exceptions") + + def test_warn_3(self): + s = """g.throw("foo", 5, 6)""" + self.warns(s, s, "Python 3 does not support string exceptions") # These should not be touched - def test_5(self): + def test_untouched_1(self): b = """g.throw(Exception)""" a = """g.throw(Exception)""" self.check(b, a) - def test_6(self): + def test_untouched_2(self): b = """g.throw(Exception(5, 6))""" a = """g.throw(Exception(5, 6))""" self.check(b, a) - def test_7(self): + def test_untouched_3(self): b = """5 + g.throw(Exception(5, 6))""" a = """5 + g.throw(Exception(5, 6))""" self.check(b, a) @@ -790,9 +792,7 @@ b = """def foo(): g.throw(Exception, 5, 6)""" a = """def foo(): - xxx_todo_changeme11 = Exception(5) - xxx_todo_changeme11.__traceback__ = 6 - g.throw(xxx_todo_changeme11)""" + g.throw(Exception(5).with_traceback(6))""" self.check(b, a) def test_tb_2(self): @@ -802,9 +802,7 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme12 = Exception(5) - xxx_todo_changeme12.__traceback__ = 6 - g.throw(xxx_todo_changeme12) + g.throw(Exception(5).with_traceback(6)) b = 6""" self.check(b, a) @@ -812,9 +810,7 @@ b = """def foo(): g.throw(Exception,5,6)""" a = """def foo(): - xxx_todo_changeme13 = Exception(5) - xxx_todo_changeme13.__traceback__ = 6 - g.throw(xxx_todo_changeme13)""" + g.throw(Exception(5).with_traceback(6))""" self.check(b, a) def test_tb_4(self): @@ -824,9 +820,7 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme14 = Exception(5) - xxx_todo_changeme14.__traceback__ = 6 - g.throw(xxx_todo_changeme14) + g.throw(Exception(5).with_traceback(6)) b = 6""" self.check(b, a) @@ -834,9 +828,7 @@ b = """def foo(): g.throw(Exception, (5, 6, 7), 6)""" a = """def foo(): - xxx_todo_changeme15 = Exception((5, 6, 7)) - xxx_todo_changeme15.__traceback__ = 6 - g.throw(xxx_todo_changeme15)""" + g.throw(Exception(5, 6, 7).with_traceback(6))""" self.check(b, a) def test_tb_6(self): @@ -846,9 +838,7 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme16 = Exception((5, 6, 7)) - xxx_todo_changeme16.__traceback__ = 6 - g.throw(xxx_todo_changeme16) + g.throw(Exception(5, 6, 7).with_traceback(6)) b = 6""" self.check(b, a) @@ -856,9 +846,7 @@ b = """def foo(): a + g.throw(Exception, 5, 6)""" a = """def foo(): - xxx_todo_changeme17 = Exception(5) - xxx_todo_changeme17.__traceback__ = 6 - a + g.throw(xxx_todo_changeme17)""" + a + g.throw(Exception(5).with_traceback(6))""" self.check(b, a) def test_tb_8(self): @@ -868,9 +856,7 @@ b = 6""" a = """def foo(): a = 5 - xxx_todo_changeme18 = Exception(5) - xxx_todo_changeme18.__traceback__ = 6 - a + g.throw(xxx_todo_changeme18) + a + g.throw(Exception(5).with_traceback(6)) b = 6""" self.check(b, a) Modified: sandbox/trunk/2to3/fixes/fix_raise.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_raise.py (original) +++ sandbox/trunk/2to3/fixes/fix_raise.py Sat Feb 24 21:54:41 2007 @@ -5,7 +5,7 @@ import pytree from pgen2 import token from fixes import basefix -from fixes.macros import Name, Call, Assign, Newline, Attr, is_tuple +from fixes.macros import Name, Call, Attr, ArgList, is_tuple class FixRaise(basefix.BaseFix): @@ -50,34 +50,14 @@ if "tb" in results: tb = results["tb"].clone() - name = Name(self.new_name()) - children = list(node.parent.parent.children) - i = children.index(node.parent) - indent = children[1].value - - # Instance the exception - build_e = pytree.Node(syms.simple_stmt, - [Assign(name.clone(), Call(exc, args)), - Newline()]) - build_e.parent = node.parent.parent - if node.get_prefix(): - # Over-indents otherwise - build_e.set_prefix(indent) - - # Assign the traceback - set_tb = pytree.Node(syms.simple_stmt, - [Assign(Attr(name.clone(), Name("__traceback__")), tb), - Newline()]) - set_tb.set_prefix(indent) - set_tb.parent = node.parent.parent - - # Insert into the suite - children[i:i] = [build_e, set_tb] - node.parent.parent.children = tuple(children) - - name.set_prefix(" ") - new = pytree.Node(syms.simple_stmt, [Name("raise"), name]) - new.set_prefix(indent) + tb.set_prefix("") + + e = Call(exc, args) + with_tb = Attr(e, Name('with_traceback')) + call_wtb = list(with_tb + (ArgList([tb]),)) + + new = pytree.Node(syms.simple_stmt, [Name("raise")] + call_wtb) + new.set_prefix(node.get_prefix()) return new else: new = pytree.Node(syms.raise_stmt, [Name("raise"), Call(exc, args)]) Modified: sandbox/trunk/2to3/fixes/fix_throw.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_throw.py (original) +++ sandbox/trunk/2to3/fixes/fix_throw.py Sat Feb 24 21:54:41 2007 @@ -5,7 +5,7 @@ import pytree from pgen2 import token from fixes import basefix -from fixes.macros import Name, Call, Assign, Newline, Attr +from fixes.macros import Name, Call, ArgList, Attr, is_tuple class FixThrow(basefix.BaseFix): @@ -13,6 +13,8 @@ power< any trailer< '.' 'throw' > trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' > > + | + power< any trailer< '.' 'throw' > trailer< '(' exc=any ')' > > """ def transform(self, node): @@ -20,59 +22,35 @@ results = self.match(node) assert results - throw_args = results["args"] exc = results["exc"].clone() - args = [results["val"].clone()] - args[0].set_prefix("") + if exc.type is token.STRING: + self.cannot_convert(node, "Python 3 does not support string exceptions") + return + + # Leave "g.throw(E)" alone + val = results.get("val") + if val is None: + return + + val = val.clone() + if is_tuple(val): + args = [c.clone() for c in val.children[1:-1]] + else: + val.set_prefix("") + args = [val] + + throw_args = results["args"] if "tb" in results: tb = results["tb"].clone() - name = Name(self.new_name()) - suite = find_parent_suite(node) - stmts = list(suite.children) - node_stmt = find_stmt(stmts, node) - i = stmts.index(node_stmt) - indent = stmts[1].value - - # Instance the exception - build_e = pytree.Node(syms.simple_stmt, - [Assign(name.clone(), Call(exc, args)), - Newline()]) - build_e.parent = node.parent.parent - if node_stmt.get_prefix(): - # Over-indents otherwise - build_e.set_prefix(indent) - - # Assign the traceback - tb.set_prefix(" ") - set_tb = pytree.Node(syms.simple_stmt, - [Assign(Attr(name.clone(), - Name("__traceback__")), tb), - Newline()]) - set_tb.set_prefix(indent) - set_tb.parent = node.parent.parent - - # Insert into the suite - stmts[i:i] = [build_e, set_tb] - suite.children = tuple(stmts) - - throw_args.replace(name) - if not node_stmt.get_prefix(): - node_stmt.set_prefix(indent) + tb.set_prefix("") + + e = Call(exc, args) + with_tb = Attr(e, Name('with_traceback')) + call_wtb = list(with_tb + (ArgList([tb]),)) + + throw_args.replace(pytree.Node(syms.power, call_wtb)) # No return else: throw_args.replace(Call(exc, args)) # No return - - -def find_parent_suite(node): - parent = node.parent - while parent: - if len(parent.children) > 2 and parent.children[0].value == "\n": - return parent - parent = parent.parent - -def find_stmt(stmts, node): - while node not in stmts: - node = node.parent - return node From python-checkins at python.org Sat Feb 24 22:52:28 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 24 Feb 2007 22:52:28 +0100 (CET) Subject: [Python-checkins] r53894 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070224215228.2F6661E4006@bag.python.org> Author: brett.cannon Date: Sat Feb 24 22:52:24 2007 New Revision: 53894 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Remove some dead code. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sat Feb 24 22:52:24 2007 @@ -166,39 +166,6 @@ result += ")" return result - @classmethod - def __tuple_bind_ok(cls, tuple_, arg): - """Verify that 'arg' will unpack properly to be used with 'tuple_'.""" - try: - if len(tuple_) != len(arg): - return False - except TypeError: - raise BindError("cannot determine the length of the argument") - if (hasattr(arg, '__iter__') and hasattr(arg, 'next') and - callable(arg.__iter__) and callable(arg.next)): - raise IndexError("do not want to mutate an iterator") - for tuple_item, arg_item in zip(tuple_, arg): - if isinstance(tuple_item, tuple): - if not cls.__tuple_bind_ok(tuple_item, arg_item): - return False - return True - - @classmethod - def __positional_bind(cls, parameter, arg, bindings): - """Bind 'argument' to 'parameter' in 'bindings' if it is a legitimate - binding. - - A binding can be illegitimate if the parameter is a tuple and the - argument will either unpack improperly or it cannot be determined if it - will without possibly mutating the object (e.g., if it is an - iterator). - - """ - if isinstance(parameter, tuple): - if not cls.__tuple_bind_ok(parameter, arg): - raise TypeError("cannot unpack argument for %s" % parameter) - bindings[parameter] = arg - def bind(self, *args, **kwargs): """Return a dictionary mapping function arguments to their parameter variables, if possible. Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sat Feb 24 22:52:24 2007 @@ -303,8 +303,6 @@ # Only one argument should pair up with a parameter. sig = pep362.Signature(pep362_fodder.no_default_args) self.failUnlessRaises(pep362.BindError, sig.bind, 1, a=1) - # Technically handled by Python itself. - self.failUnlessRaises(pep362.BindError, sig.bind, a=1, a=2) def XXX_test_do_not_consume_iterators(self): def gen(): From python-checkins at python.org Sat Feb 24 23:09:21 2007 From: python-checkins at python.org (phillip.eby) Date: Sat, 24 Feb 2007 23:09:21 +0100 (CET) Subject: [Python-checkins] r53895 - sandbox/trunk/setuptools/setuptools/command/test.py Message-ID: <20070224220921.D51F01E4006@bag.python.org> Author: phillip.eby Date: Sat Feb 24 23:09:20 2007 New Revision: 53895 Modified: sandbox/trunk/setuptools/setuptools/command/test.py Log: Fix "test" command possibly failing if an older version of the project being tested is installed on sys.path ahead of the test source directory. Modified: sandbox/trunk/setuptools/setuptools/command/test.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/test.py (original) +++ sandbox/trunk/setuptools/setuptools/command/test.py Sat Feb 24 23:09:20 2007 @@ -80,7 +80,7 @@ - def run(self): + def with_project_on_sys_path(self, func): # Ensure metadata is up-to-date self.run_command('egg_info') @@ -88,6 +88,24 @@ self.reinitialize_command('build_ext', inplace=1) self.run_command('build_ext') + ei_cmd = self.get_finalized_command("egg_info") + + old_path = sys.path[:] + old_modules = sys.modules.copy() + + try: + sys.path.insert(0, normalize_path(ei_cmd.egg_base)) + working_set.__init__() + require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version)) + func() + finally: + sys.path[:] = old_path + sys.modules.clear() + sys.modules.update(old_modules) + working_set.__init__() + + + def run(self): if self.distribution.tests_require: self.distribution.fetch_build_eggs(self.distribution.tests_require) @@ -97,23 +115,50 @@ self.announce('skipping "unittest %s" (dry run)' % cmd) else: self.announce('running "unittest %s"' % cmd) - self.run_tests() + self.with_project_on_sys_path(self.run_tests) + + + def run_tests(self): import unittest - old_path = sys.path[:] - ei_cmd = self.get_finalized_command("egg_info") - path_item = normalize_path(ei_cmd.egg_base) - metadata = PathMetadata( - path_item, normalize_path(ei_cmd.egg_info) - ) - dist = Distribution(path_item, metadata, project_name=ei_cmd.egg_name) - working_set.add(dist) - require(str(dist.as_requirement())) loader_ep = EntryPoint.parse("x="+self.test_loader) loader_class = loader_ep.load(require=False) unittest.main( None, None, [unittest.__file__]+self.test_args, testLoader = loader_class() ) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From python-checkins at python.org Sat Feb 24 23:11:50 2007 From: python-checkins at python.org (phillip.eby) Date: Sat, 24 Feb 2007 23:11:50 +0100 (CET) Subject: [Python-checkins] r53896 - in sandbox/branches/setuptools-0.6: setuptools.txt setuptools/command/test.py Message-ID: <20070224221150.963AE1E4006@bag.python.org> Author: phillip.eby Date: Sat Feb 24 23:11:47 2007 New Revision: 53896 Modified: sandbox/branches/setuptools-0.6/setuptools.txt sandbox/branches/setuptools-0.6/setuptools/command/test.py Log: Fix ``test`` command possibly failing if an older version of the project being tested was installed on ``sys.path`` ahead of the test source directory. (backport from trunk) Modified: sandbox/branches/setuptools-0.6/setuptools.txt ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools.txt (original) +++ sandbox/branches/setuptools-0.6/setuptools.txt Sat Feb 24 23:11:47 2007 @@ -2622,6 +2622,10 @@ * Fix ``#!`` parsing problems in Windows ``.exe`` script wrappers, when there was whitespace inside a quoted argument or at the end of the ``#!`` line (a regression introduced in 0.6c4). + + * Fix ``test`` command possibly failing if an older version of the project + being tested was installed on ``sys.path`` ahead of the test source + directory. 0.6c5 * Fix uploaded ``bdist_rpm`` packages being described as ``bdist_egg`` Modified: sandbox/branches/setuptools-0.6/setuptools/command/test.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/test.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/test.py Sat Feb 24 23:11:47 2007 @@ -80,7 +80,7 @@ - def run(self): + def with_project_on_sys_path(self, func): # Ensure metadata is up-to-date self.run_command('egg_info') @@ -88,7 +88,25 @@ self.reinitialize_command('build_ext', inplace=1) self.run_command('build_ext') - if self.distribution.tests_require: + ei_cmd = self.get_finalized_command("egg_info") + + old_path = sys.path[:] + old_modules = sys.modules.copy() + + try: + sys.path.insert(0, normalize_path(ei_cmd.egg_base)) + working_set.__init__() + require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version)) + func() + finally: + sys.path[:] = old_path + sys.modules.clear() + sys.modules.update(old_modules) + working_set.__init__() + + + def run(self): + if self.distribution.tests_require: self.distribution.fetch_build_eggs(self.distribution.tests_require) if self.test_suite: @@ -97,20 +115,14 @@ self.announce('skipping "unittest %s" (dry run)' % cmd) else: self.announce('running "unittest %s"' % cmd) - self.run_tests() + self.with_project_on_sys_path(self.run_tests) + + + def run_tests(self): import unittest - old_path = sys.path[:] - ei_cmd = self.get_finalized_command("egg_info") - path_item = normalize_path(ei_cmd.egg_base) - metadata = PathMetadata( - path_item, normalize_path(ei_cmd.egg_info) - ) - dist = Distribution(path_item, metadata, project_name=ei_cmd.egg_name) - working_set.add(dist) - require(str(dist.as_requirement())) loader_ep = EntryPoint.parse("x="+self.test_loader) loader_class = loader_ep.load(require=False) unittest.main( @@ -121,3 +133,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From python-checkins at python.org Sun Feb 25 16:52:32 2007 From: python-checkins at python.org (neal.norwitz) Date: Sun, 25 Feb 2007 16:52:32 +0100 (CET) Subject: [Python-checkins] r53899 - python/trunk/Objects/stringobject.c Message-ID: <20070225155232.8B1231E4007@bag.python.org> Author: neal.norwitz Date: Sun Feb 25 16:52:27 2007 New Revision: 53899 Modified: python/trunk/Objects/stringobject.c Log: Add more details when releasing interned strings Modified: python/trunk/Objects/stringobject.c ============================================================================== --- python/trunk/Objects/stringobject.c (original) +++ python/trunk/Objects/stringobject.c Sun Feb 25 16:52:27 2007 @@ -4969,6 +4969,7 @@ PyObject *keys; PyStringObject *s; Py_ssize_t i, n; + Py_ssize_t immortal_size = 0, mortal_size = 0; if (interned == NULL || !PyDict_Check(interned)) return; @@ -4983,8 +4984,9 @@ give them their stolen references back, and then clear and DECREF the interned dict. */ - fprintf(stderr, "releasing interned strings\n"); n = PyList_GET_SIZE(keys); + fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n", + n); for (i = 0; i < n; i++) { s = (PyStringObject *) PyList_GET_ITEM(keys, i); switch (s->ob_sstate) { @@ -4993,15 +4995,20 @@ break; case SSTATE_INTERNED_IMMORTAL: s->ob_refcnt += 1; + immortal_size += s->ob_size; break; case SSTATE_INTERNED_MORTAL: s->ob_refcnt += 2; + mortal_size += s->ob_size; break; default: Py_FatalError("Inconsistent interned string state."); } s->ob_sstate = SSTATE_NOT_INTERNED; } + fprintf(stderr, "total size of all interned strings: " + "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d " + "mortal/immortal\n", mortal_size, immortal_size); Py_DECREF(keys); PyDict_Clear(interned); Py_DECREF(interned); From python-checkins at python.org Sun Feb 25 16:53:37 2007 From: python-checkins at python.org (neal.norwitz) Date: Sun, 25 Feb 2007 16:53:37 +0100 (CET) Subject: [Python-checkins] r53900 - python/trunk/Objects/stringobject.c Message-ID: <20070225155337.ECE221E4007@bag.python.org> Author: neal.norwitz Date: Sun Feb 25 16:53:36 2007 New Revision: 53900 Modified: python/trunk/Objects/stringobject.c Log: Whitespace only changes Modified: python/trunk/Objects/stringobject.c ============================================================================== --- python/trunk/Objects/stringobject.c (original) +++ python/trunk/Objects/stringobject.c Sun Feb 25 16:53:36 2007 @@ -1131,8 +1131,7 @@ much time, since Py_NE is rarely used. */ if (a->ob_size == b->ob_size && (a->ob_sval[0] == b->ob_sval[0] - && memcmp(a->ob_sval, b->ob_sval, - a->ob_size) == 0)) { + && memcmp(a->ob_sval, b->ob_sval, a->ob_size) == 0)) { result = Py_True; } else { result = Py_False; @@ -1145,7 +1144,7 @@ c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval); if (c==0) c = memcmp(a->ob_sval, b->ob_sval, min_len); - }else + } else c = 0; if (c == 0) c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; From python-checkins at python.org Sun Feb 25 16:57:47 2007 From: python-checkins at python.org (jeremy.hylton) Date: Sun, 25 Feb 2007 16:57:47 +0100 (CET) Subject: [Python-checkins] r53901 - in python/trunk: Misc/NEWS Python/ceval.c Message-ID: <20070225155747.05E6D1E4007@bag.python.org> Author: jeremy.hylton Date: Sun Feb 25 16:57:45 2007 New Revision: 53901 Modified: python/trunk/Misc/NEWS python/trunk/Python/ceval.c Log: Fix crash in exec when unicode filename can't be decoded. I can't think of an easy way to test this behavior. It only occurs when the file system default encoding and the interpreter default encoding are different, such that you can open the file but not decode its name. Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun Feb 25 16:57:45 2007 @@ -121,6 +121,7 @@ - with and as are now keywords. +- Bug #1664966: Fix crash in exec if Unicode filename can't be decoded. Library ------- Modified: python/trunk/Python/ceval.c ============================================================================== --- python/trunk/Python/ceval.c (original) +++ python/trunk/Python/ceval.c Sun Feb 25 16:57:45 2007 @@ -4202,6 +4202,8 @@ else if (PyFile_Check(prog)) { FILE *fp = PyFile_AsFile(prog); char *name = PyString_AsString(PyFile_Name(prog)); + if (name == NULL) + return -1; PyCompilerFlags cf; cf.cf_flags = 0; if (PyEval_MergeCompilerFlags(&cf)) From python-checkins at python.org Sun Feb 25 17:02:02 2007 From: python-checkins at python.org (jeremy.hylton) Date: Sun, 25 Feb 2007 17:02:02 +0100 (CET) Subject: [Python-checkins] r53902 - python/trunk/Python/ceval.c Message-ID: <20070225160202.3E1631E4007@bag.python.org> Author: jeremy.hylton Date: Sun Feb 25 17:01:58 2007 New Revision: 53902 Modified: python/trunk/Python/ceval.c Log: Put declarations before code. Modified: python/trunk/Python/ceval.c ============================================================================== --- python/trunk/Python/ceval.c (original) +++ python/trunk/Python/ceval.c Sun Feb 25 17:01:58 2007 @@ -4202,9 +4202,9 @@ else if (PyFile_Check(prog)) { FILE *fp = PyFile_AsFile(prog); char *name = PyString_AsString(PyFile_Name(prog)); + PyCompilerFlags cf; if (name == NULL) return -1; - PyCompilerFlags cf; cf.cf_flags = 0; if (PyEval_MergeCompilerFlags(&cf)) v = PyRun_FileFlags(fp, name, Py_file_input, globals, From python-checkins at python.org Sun Feb 25 17:03:08 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 25 Feb 2007 17:03:08 +0100 (CET) Subject: [Python-checkins] r53903 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/pep362_fodder.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070225160308.2C6B21E4007@bag.python.org> Author: brett.cannon Date: Sun Feb 25 17:03:03 2007 New Revision: 53903 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/pep362_fodder.py sandbox/trunk/pep362/test_pep362.py Log: Handle tuple arguments (or at least enough to pass a test). Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sun Feb 25 17:03:03 2007 @@ -182,8 +182,6 @@ positional = [] keyword_only = {} - # XXX Tuple parameters. - for param in self.parameters: if not param.keyword_only: positional.append(param) @@ -204,7 +202,7 @@ break else: raise BindError("too many positional arguments") - bindings[param.name] = position_arg + self._tuple_bind(bindings, param.name, position_arg) # Keyword arguments & default values. else: for positional_param in positional: @@ -252,6 +250,31 @@ return bindings + def _tuple_bind(self, bindings, possible_tuple, value): + """Where a tuple could be a parameter, handle binding the values to the + tuple and storing into the bindings mapping.""" + if not isinstance(possible_tuple, tuple): + bindings[possible_tuple] = value + else: + # Need to make sure that value is as long as the parameter, but not + # vice-versa. + error_msg = "not enough values to unpack for %r" + tuple_iter = iter(possible_tuple) + try: + value_iter = iter(value) + except TypeError: + raise BindError(error_msg % possible_tuple) + while True: + try: + sub_param = tuple_iter.next() + except StopIteration: + break + try: + sub_value = value_iter.next() + except StopIteration: + raise BindError(error_msg % possible_tuple) + self._tuple_bind(bindings, sub_param, sub_value) + def signature(func): """Return a Signature object for the function or method. Modified: sandbox/trunk/pep362/pep362_fodder.py ============================================================================== --- sandbox/trunk/pep362/pep362_fodder.py (original) +++ sandbox/trunk/pep362/pep362_fodder.py Sun Feb 25 17:03:03 2007 @@ -14,7 +14,7 @@ pass def tuple_args((a, (b,))): - pass + return a, b def default_tuple_args((a, (b,))=(1, (2,))): pass Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sun Feb 25 17:03:03 2007 @@ -257,23 +257,22 @@ self.failUnlessRaises(pep362.BindError, sig.bind, a=0, b=1) self.failUnlessRaises(pep362.BindError, sig.bind, b=1) - def XXX_test_tuple_parameter(self): + def test_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.tuple_args) - binding = sig.bind((1, (2,))) - self.failUnlessEqual({('a', ('b',)):(1, (2,))}, binding) arg = (1, ((2,),)) binding = sig.bind(arg) - self.failUnlessEqual({('a', ('b',)):arg}, binding) + self.failUnlessEqual({'a':1, 'b':(2,)}, binding) self.failUnlessRaises(pep362.BindError, sig.bind, (1,2,3)) self.failUnlessRaises(pep362.BindError, sig.bind, (1, 2)) def XXX_test_default_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.default_tuple_args) binding = sig.bind() - self.failUnlessEqual({('a', ('b',)):(1, (2,))}, binding) + self.failUnlessEqual({'a':1, 'b':(2,)}, binding) arg = (0, (1,)) + a, b = arg binding = sig.bind(arg) - self.failUnlessEqual({('a', ('b',)):arg}, binding) + self.failUnlessEqual({'a':a, 'b':b}, binding) def XXX_test_all_parameter_types(self): sig = pep362.Signature(pep362_fodder.all_args) From buildbot at python.org Sun Feb 25 17:07:12 2007 From: buildbot at python.org (buildbot at python.org) Date: Sun, 25 Feb 2007 16:07:12 +0000 Subject: [Python-checkins] buildbot failure in x86 OpenBSD trunk Message-ID: <20070225160712.CD0381E4011@bag.python.org> The Buildbot has detected a new failure of x86 OpenBSD trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520OpenBSD%2520trunk/builds/1576 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton,neal.norwitz BUILD FAILED: failed svn sincerely, -The Buildbot From python-checkins at python.org Sun Feb 25 17:08:05 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 25 Feb 2007 17:08:05 +0100 (CET) Subject: [Python-checkins] r53904 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070225160805.2A7E61E4007@bag.python.org> Author: brett.cannon Date: Sun Feb 25 17:08:01 2007 New Revision: 53904 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Handle default values for tuples. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sun Feb 25 17:08:01 2007 @@ -215,7 +215,8 @@ raise BindError("%r unbound" % param_name) else: if positional_param.has_default: - bindings[param_name] = positional_param.default_value + self._tuple_bind(bindings, param_name, + positional_param.default_value) else: raise BindError("%r parameter lacking default value" % param_name) Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sun Feb 25 17:08:01 2007 @@ -265,14 +265,13 @@ self.failUnlessRaises(pep362.BindError, sig.bind, (1,2,3)) self.failUnlessRaises(pep362.BindError, sig.bind, (1, 2)) - def XXX_test_default_tuple_parameter(self): + def test_default_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.default_tuple_args) binding = sig.bind() - self.failUnlessEqual({'a':1, 'b':(2,)}, binding) + self.failUnlessEqual({'a':1, 'b':2}, binding) arg = (0, (1,)) - a, b = arg binding = sig.bind(arg) - self.failUnlessEqual({'a':a, 'b':b}, binding) + self.failUnlessEqual({'a':0, 'b':1}, binding) def XXX_test_all_parameter_types(self): sig = pep362.Signature(pep362_fodder.all_args) From python-checkins at python.org Sun Feb 25 17:17:13 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 25 Feb 2007 17:17:13 +0100 (CET) Subject: [Python-checkins] r53905 - sandbox/trunk/pep362/pep362_fodder.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070225161713.CCBD21E4007@bag.python.org> Author: brett.cannon Date: Sun Feb 25 17:17:13 2007 New Revision: 53905 Modified: sandbox/trunk/pep362/pep362_fodder.py sandbox/trunk/pep362/test_pep362.py Log: Be able to pass worst-case function for 2.x. Modified: sandbox/trunk/pep362/pep362_fodder.py ============================================================================== --- sandbox/trunk/pep362/pep362_fodder.py (original) +++ sandbox/trunk/pep362/pep362_fodder.py Sun Feb 25 17:17:13 2007 @@ -19,5 +19,5 @@ def default_tuple_args((a, (b,))=(1, (2,))): pass -def all_args(a, (b, (c,)), d=0, (e, (f,))=(1, (2,)), *g, **h): - pass +def all_args(a, (b, (c,)), d=0, (e, (f,))=(4, (5,)), *g, **h): + return a, b, c, d, e, f, g, h Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sun Feb 25 17:17:13 2007 @@ -273,11 +273,11 @@ binding = sig.bind(arg) self.failUnlessEqual({'a':0, 'b':1}, binding) - def XXX_test_all_parameter_types(self): + def test_all_parameter_types(self): sig = pep362.Signature(pep362_fodder.all_args) - binding = sig.bind(0, (1, (2,)), 3, (4, (5,)), 6, i=7) - expected = {'a':0, ('b', ('c',)):(1, (2,)), 'd':3, - ('e', ('f',)):(4, (5,)), 'g':(6,), 'h':{'i':7}} + binding = sig.bind(0, (1, (2,)), d=3, i=7) + expected = {'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':tuple(), + 'h':{'i':7}} self.failUnlessEqual(expected, binding) @py3k_test From python-checkins at python.org Sun Feb 25 17:19:24 2007 From: python-checkins at python.org (neal.norwitz) Date: Sun, 25 Feb 2007 17:19:24 +0100 (CET) Subject: [Python-checkins] r53907 - in python/branches/release25-maint: Misc/NEWS Python/ceval.c Message-ID: <20070225161924.8F67A1E400B@bag.python.org> Author: neal.norwitz Date: Sun Feb 25 17:19:21 2007 New Revision: 53907 Modified: python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Python/ceval.c Log: Backport 53901 and 53902 to prevent crash when there is an error decoding unicode filenames Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Sun Feb 25 17:19:21 2007 @@ -124,6 +124,8 @@ - The version number of the ctypes package was changed to "1.0.2". +- Bug #1664966: Fix crash in exec if Unicode filename can't be decoded. + - Patch #1544279: Improve thread-safety of the socket module by moving the sock_addr_t storage out of the socket object. Modified: python/branches/release25-maint/Python/ceval.c ============================================================================== --- python/branches/release25-maint/Python/ceval.c (original) +++ python/branches/release25-maint/Python/ceval.c Sun Feb 25 17:19:21 2007 @@ -4173,6 +4173,8 @@ FILE *fp = PyFile_AsFile(prog); char *name = PyString_AsString(PyFile_Name(prog)); PyCompilerFlags cf; + if (name == NULL) + return -1; cf.cf_flags = 0; if (PyEval_MergeCompilerFlags(&cf)) v = PyRun_FileFlags(fp, name, Py_file_input, globals, From python-checkins at python.org Sun Feb 25 17:30:45 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 25 Feb 2007 17:30:45 +0100 (CET) Subject: [Python-checkins] r53908 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/pep362_py3k_fodder.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070225163045.286931E4007@bag.python.org> Author: brett.cannon Date: Sun Feb 25 17:30:40 2007 New Revision: 53908 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/pep362_py3k_fodder.py sandbox/trunk/pep362/test_pep362.py Log: Add annotations for variable parameters. Also add a worse-case Py3K test. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sun Feb 25 17:30:40 2007 @@ -90,6 +90,10 @@ # Variable parameters. self.var_args = argspec[1] if (argspec[1] is not None) else '' self.var_kw_args = argspec[2] if (argspec[2] is not None) else '' + self.var_annotations = {} + for var_arg in (self.var_args, self.var_kw_args): + if var_arg in func.func_annotations: + self.var_annotations[var_arg] = func.func_annotations[var_arg] # Non-keyword-only arguments. arg_count = len(argspec[0]) Modified: sandbox/trunk/pep362/pep362_py3k_fodder.py ============================================================================== --- sandbox/trunk/pep362/pep362_py3k_fodder.py (original) +++ sandbox/trunk/pep362/pep362_py3k_fodder.py Sun Feb 25 17:30:40 2007 @@ -10,8 +10,14 @@ def arg_annotation_default(a:int=42): pass +def arg_annotation_var(*args:int, **kwargs:int): + pass + def arg_annotation_keyword_only(*, a:int): pass def return_annotation() -> int: pass + +def all_args(a:int, (b, (c,)), *args:int, d, e, **kwargs) -> int: + pass Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sun Feb 25 17:30:40 2007 @@ -189,10 +189,18 @@ @py3k_test def test_return_annotation(self): + # The return value annotation. sig = pep362.Signature(pep362_py3k_fodder.return_annotation) self.failUnless(sig.has_annotation) self.failUnlessEqual(sig.annotation, int) + @py3k_test + def test_var_annotations(self): + # Annotation on variable arguments (*args & **kwargs). + sig = pep362.Signature(pep362_py3k_fodder.arg_annotation_var) + self.failUnlessEqual(sig.var_annotations[sig.var_args], int) + self.failUnlessEqual(sig.var_annotations[sig.var_kw_args], int) + def test_signature(self): def fresh_func(): pass @@ -302,13 +310,6 @@ sig = pep362.Signature(pep362_fodder.no_default_args) self.failUnlessRaises(pep362.BindError, sig.bind, 1, a=1) - def XXX_test_do_not_consume_iterators(self): - def gen(): - yield 0 - yield (1,) - sig = pep362.Signature(pep362_fodder.tuple_args) - self.failUnlessRaises(pep362.BindError, sig.bind, gen()) - def test_main(): test_support.run_unittest(ParameterObjectTests, From python-checkins at python.org Sun Feb 25 17:47:19 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 25 Feb 2007 17:47:19 +0100 (CET) Subject: [Python-checkins] r53909 - sandbox/trunk/pep362/pep362_py3k_fodder.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070225164719.F24E91E4007@bag.python.org> Author: brett.cannon Date: Sun Feb 25 17:47:17 2007 New Revision: 53909 Modified: sandbox/trunk/pep362/pep362_py3k_fodder.py sandbox/trunk/pep362/test_pep362.py Log: Add a unit test for the worst-case Py3K signature (currently fails). Modified: sandbox/trunk/pep362/pep362_py3k_fodder.py ============================================================================== --- sandbox/trunk/pep362/pep362_py3k_fodder.py (original) +++ sandbox/trunk/pep362/pep362_py3k_fodder.py Sun Feb 25 17:47:17 2007 @@ -19,5 +19,6 @@ def return_annotation() -> int: pass -def all_args(a:int, (b, (c,)), *args:int, d, e, **kwargs) -> int: +def all_args(a:int, (b, (c,)), d=0, (e, (f,))=(0, (0,)), *args:int, + g:int, h:int=8, **kwargs:int) -> int: pass Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sun Feb 25 17:47:17 2007 @@ -305,6 +305,14 @@ self.failUnlessEqual(binding, {'a':1}) self.failUnlessRaises(pep362.BindError, sig.bind, 1) + @py3k_test + def test_all_args(self): + sig = pep362.Signature(pep362_py3k_fodder.all_args) + binding = sig.bind(0, (1, (2,)), 3, (4, (5,)), 6, g=7, i=9) + expected = {'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':7, 'h':8, + 'i':9, 'args':(6,)} + self.failUnlessEqual(binding, expected) + def test_too_many_arguments(self): # Only one argument should pair up with a parameter. sig = pep362.Signature(pep362_fodder.no_default_args) From python-checkins at python.org Sun Feb 25 18:56:31 2007 From: python-checkins at python.org (fred.drake) Date: Sun, 25 Feb 2007 18:56:31 +0100 (CET) Subject: [Python-checkins] r53910 - python/trunk/Doc/lib/libetree.tex Message-ID: <20070225175631.821721E4007@bag.python.org> Author: fred.drake Date: Sun Feb 25 18:56:27 2007 New Revision: 53910 Modified: python/trunk/Doc/lib/libetree.tex Log: - SF patch #1657613: add documentation for the Element interface - clean up bogus use of the {datadescni} environment everywhere Modified: python/trunk/Doc/lib/libetree.tex ============================================================================== --- python/trunk/Doc/lib/libetree.tex (original) +++ python/trunk/Doc/lib/libetree.tex Sun Feb 25 18:56:27 2007 @@ -38,10 +38,7 @@ The comment string can be either an 8-bit ASCII string or a Unicode string. \var{text} is a string containing the comment string. - -\begin{datadescni}{Returns:} -An element instance, representing a comment. -\end{datadescni} +Returns an element instance representing a comment. \end{funcdesc} \begin{funcdesc}{dump}{elem} @@ -65,28 +62,19 @@ \var{tag} is the element name. \var{attrib} is an optional dictionary, containing element attributes. \var{extra} contains additional attributes, given as keyword arguments. - -\begin{datadescni}{Returns:} -An element instance. -\end{datadescni} +Returns an element instance. \end{funcdesc} \begin{funcdesc}{fromstring}{text} Parses an XML section from a string constant. Same as XML. \var{text} is a string containing XML data. - -\begin{datadescni}{Returns:} -An Element instance. -\end{datadescni} +Returns an Element instance. \end{funcdesc} \begin{funcdesc}{iselement}{element} Checks if an object appears to be a valid element object. \var{element} is an element instance. - -\begin{datadescni}{Returns:} -A true value if this is an element object. -\end{datadescni} +Returns a true value if this is an element object. \end{funcdesc} \begin{funcdesc}{iterparse}{source\optional{, events}} @@ -95,10 +83,7 @@ \var{source} is a filename or file object containing XML data. \var{events} is a list of events to report back. If omitted, only ``end'' events are reported. - -\begin{datadescni}{Returns:} -A (event, elem) iterator. -\end{datadescni} +Returns an iterator providing \code{(\var{event}, \var{elem})} pairs. \end{funcdesc} \begin{funcdesc}{parse}{source\optional{, parser}} @@ -106,10 +91,7 @@ \var{source} is a filename or file object containing XML data. \var{parser} is an optional parser instance. If not given, the standard XMLTreeBuilder parser is used. - -\begin{datadescni}{Returns:} -An ElementTree instance -\end{datadescni} +Returns an ElementTree instance. \end{funcdesc} \begin{funcdesc}{ProcessingInstruction}{target\optional{, text}} @@ -117,13 +99,11 @@ that will be serialized as an XML processing instruction. \var{target} is a string containing the PI target. \var{text} is a string containing the PI contents, if given. - -\begin{datadescni}{Returns:} -An element instance, representing a PI. -\end{datadescni} +Returns an element instance, representing a processing instruction. \end{funcdesc} -\begin{funcdesc}{SubElement}{parent, tag\optional{, attrib} \optional{, **extra}} +\begin{funcdesc}{SubElement}{parent, tag\optional{, + attrib\optional{, **extra}}} Subelement factory. This function creates an element instance, and appends it to an existing element. @@ -133,10 +113,7 @@ \var{tag} is the subelement name. \var{attrib} is an optional dictionary, containing element attributes. \var{extra} contains additional attributes, given as keyword arguments. - -\begin{datadescni}{Returns:} -An element instance. -\end{datadescni} +Returns an element instance. \end{funcdesc} \begin{funcdesc}{tostring}{element\optional{, encoding}} @@ -144,33 +121,162 @@ subelements. \var{element} is an Element instance. \var{encoding} is the output encoding (default is US-ASCII). - -\begin{datadescni}{Returns:} -An encoded string containing the XML data. -\end{datadescni} +Returns an encoded string containing the XML data. \end{funcdesc} \begin{funcdesc}{XML}{text} Parses an XML section from a string constant. This function can be used to embed ``XML literals'' in Python code. \var{text} is a string containing XML data. - -\begin{datadescni}{Returns:} -An Element instance. -\end{datadescni} +Returns an Element instance. \end{funcdesc} \begin{funcdesc}{XMLID}{text} Parses an XML section from a string constant, and also returns a dictionary which maps from element id:s to elements. \var{text} is a string containing XML data. - -\begin{datadescni}{Returns:} -A tuple containing an Element instance and a dictionary. -\end{datadescni} +Returns a tuple containing an Element instance and a dictionary. \end{funcdesc} +\subsection{The Element Interface\label{elementtree-element-interface}} + +Element objects returned by Element or SubElement have the +following methods and attributes. + +\begin{memberdesc}{tag} +A string identifying what kind of data this element represents +(the element type, in other words). +\end{memberdesc} + +\begin{memberdesc}{text} +The \var{text} attribute can be used to hold additional data +associated with the element. +As the name implies this attribute is usually a string but may be any +application-specific object. +If the element is created from an XML file the attribute will contain +any text found between the element tags. +\end{memberdesc} + +\begin{memberdesc}{tail} +The \var{tail} attribute can be used to hold additional data +associated with the element. +This attribute is usually a string but may be any application-specific object. +If the element is created from an XML file the attribute will contain +any text found after the element's end tag and before the next tag. +\end{memberdesc} + +\begin{memberdesc}{attrib} +A dictionary containing the element's attributes. +Note that while the \var{attrib} value is always a real mutable Python +dictionary, an ElementTree implementation may choose to use another +internal representation, and create the dictionary only if someone +asks for it. To take advantage of such implementations, use the +dictionary methods below whenever possible. +\end{memberdesc} + +The following dictionary-like methods work on the element attributes. + +\begin{methoddesc}{clear}{} +Resets an element. This function removes all subelements, clears +all attributes, and sets the text and tail attributes to None. +\end{methoddesc} + +\begin{methoddesc}{get}{key\optional{, default=None}} +Gets the element attribute named \var{key}. + +Returns the attribute value, or \var{default} if the +attribute was not found. +\end{methoddesc} + +\begin{methoddesc}{items}{} +Returns the element attributes as a sequence of (name, value) pairs. +The attributes are returned in an arbitrary order. +\end{methoddesc} + +\begin{methoddesc}{keys}{} +Returns the elements attribute names as a list. +The names are returned in an arbitrary order. +\end{methoddesc} + +\begin{methoddesc}{set}{key, value} +Set the attribute \var{key} on the element to \var{value}. +\end{methoddesc} + +The following methods work on the element's children (subelements). + +\begin{methoddesc}{append}{subelement} +Adds the element \var{subelement} to the end of this elements internal list +of subelements. +\end{methoddesc} + +\begin{methoddesc}{find}{match} +Finds the first subelement matching \var{match}. +\var{match} may be a tag name or path. +Returns an element instance or \code{None}. +\end{methoddesc} + +\begin{methoddesc}{findall}{match} +Finds all subelements matching \var{match}. +\var{match} may be a tag name or path. +Returns an iterable yielding all matching elements in document order. +\end{methoddesc} + +\begin{methoddesc}{findtext}{condition\optional{, default=None}} +Finds text for the first subelement matching \var{condition}. +\var{condition} may be a tag name or path. +Returns the text content of the first matching element, or +\var{default} if no element was found. Note that if the +matching element has no text content an empty string is returned. +\end{methoddesc} + +\begin{methoddesc}{getchildren}{} +Returns all subelements. The elements are returned in document order. +\end{methoddesc} + +\begin{methoddesc}{getiterator}{\optional{tag=None}} +Creates a tree iterator with the current element as the root. +The iterator iterates over this element and all elements below it +that match the given tag. If tag +is \code{None} or \code{'*'} then all elements are iterated over. +Returns an iterable that provides element objects in document (depth first) +order. +\end{methoddesc} + +\begin{methoddesc}{insert}{index, element} +Inserts a subelement at the given position in this element. +\end{methoddesc} + +\begin{methoddesc}{makeelement}{tag, attrib} +Creates a new element object of the same type as this element. +Do not call this method, use the SubElement factory function instead. +\end{methoddesc} + +\begin{methoddesc}{remove}{subelement} +Removes \var{subelement} from the element. +Unlike the findXXX methods this method compares elements based on +the instance identity, not on tag value or contents. +\end{methoddesc} + +Element objects also support the following sequence type methods for +working with subelements: \method{__delitem__()}, +\method{__getitem__()}, \method{__setitem__()}, \method{__len__()}. + +Caution: Because Element objects do not define a +\method{__nonzero__()} method, elements with no subelements will test +as \code{False}. + +\begin{verbatim} +element = root.find('foo') + +if not element: # careful! + print "element not found, or element has no subelements" + +if element is None: + print "element not found" +\end{verbatim} + + \subsection{ElementTree Objects\label{elementtree-elementtree-objects}} \begin{classdesc}{ElementTree}{\optional{element,} \optional{file}} @@ -193,21 +299,15 @@ Finds the first toplevel element with given tag. Same as getroot().find(path). \var{path} is the element to look for. - -\begin{datadescni}{Returns:} -The first matching element, or None if no element was found. -\end{datadescni} +Returns the first matching element, or \code{None} if no element was found. \end{methoddesc} \begin{methoddesc}{findall}{path} Finds all toplevel elements with the given tag. Same as getroot().findall(path). \var{path} is the element to look for. - -\begin{datadescni}{Returns:} -A list or iterator containing all matching elements, -in section order. -\end{datadescni} +Returns a list or iterator containing all matching elements, +in document order. \end{methoddesc} \begin{methoddesc}{findtext}{path\optional{, default}} @@ -215,31 +315,20 @@ tag. Same as getroot().findtext(path). \var{path} is the toplevel element to look for. \var{default} is the value to return if the element was not found. - -\begin{datadescni}{Returns:} -The text content of the first matching element, or the +Returns the text content of the first matching element, or the default value no element was found. Note that if the element has is found, but has no text content, this method returns an empty string. -\end{datadescni} \end{methoddesc} \begin{methoddesc}{getiterator}{\optional{tag}} -Creates a tree iterator for the root element. The iterator loops +Creates and returns a tree iterator for the root element. The iterator loops over all elements in this tree, in section order. \var{tag} is the tag to look for (default is to return all elements) - -\begin{datadescni}{Returns:} -An iterator. -\end{datadescni} \end{methoddesc} \begin{methoddesc}{getroot}{} -Gets the root element for this tree. - -\begin{datadescni}{Returns:} -An element instance. -\end{datadescni} +Returns the root element for this tree. \end{methoddesc} \begin{methoddesc}{parse}{source\optional{, parser}} @@ -247,10 +336,7 @@ \var{source} is a file name or file object. \var{parser} is an optional parser instance. If not given, the standard XMLTreeBuilder parser is used. - -\begin{datadescni}{Returns:} -The section root element. -\end{datadescni} +Returns the section root element. \end{methoddesc} \begin{methoddesc}{write}{file\optional{, encoding}} @@ -270,10 +356,7 @@ the URI part of a QName. If \var{tag} is given, the first argument is interpreted as an URI, and this argument is interpreted as a local name. - -\begin{datadescni}{Returns:} -An opaque object, representing the QName. -\end{datadescni} +\class{QName} instances are opaque. \end{classdesc} @@ -291,10 +374,7 @@ \begin{methoddesc}{close}{} Flushes the parser buffers, and returns the toplevel documen element. - -\begin{datadescni}{Returns:} -An Element instance. -\end{datadescni} +Returns an Element instance. \end{methoddesc} \begin{methoddesc}{data}{data} @@ -306,20 +386,14 @@ \begin{methoddesc}{end}{tag} Closes the current element. \var{tag} is the element name. - -\begin{datadescni}{Returns:} -The closed element. -\end{datadescni} +Returns the closed element. \end{methoddesc} \begin{methoddesc}{start}{tag, attrs} Opens a new element. \var{tag} is the element name. \var{attrs} is a dictionary containing element attributes. - -\begin{datadescni}{Returns:} -The opened element. -\end{datadescni} +Returns the opened element. \end{methoddesc} @@ -336,10 +410,7 @@ \begin{methoddesc}{close}{} Finishes feeding data to the parser. - -\begin{datadescni}{Returns:} -An element structure. -\end{datadescni} +Returns an element structure. \end{methoddesc} \begin{methoddesc}{doctype}{name, pubid, system} @@ -351,6 +422,5 @@ \begin{methoddesc}{feed}{data} Feeds data to the parser. - \var{data} is encoded data. \end{methoddesc} From python-checkins at python.org Sun Feb 25 20:44:52 2007 From: python-checkins at python.org (neal.norwitz) Date: Sun, 25 Feb 2007 20:44:52 +0100 (CET) Subject: [Python-checkins] r53911 - in python/trunk: Include/dictobject.h Include/intobject.h Include/listobject.h Include/longobject.h Include/object.h Include/pyerrors.h Include/stringobject.h Include/tupleobject.h Include/unicodeobject.h Objects/dictobject.c Objects/exceptions.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/stringobject.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodeobject.c Message-ID: <20070225194452.B83E21E4007@bag.python.org> Author: neal.norwitz Date: Sun Feb 25 20:44:48 2007 New Revision: 53911 Modified: python/trunk/Include/dictobject.h python/trunk/Include/intobject.h python/trunk/Include/listobject.h python/trunk/Include/longobject.h python/trunk/Include/object.h python/trunk/Include/pyerrors.h python/trunk/Include/stringobject.h python/trunk/Include/tupleobject.h python/trunk/Include/unicodeobject.h python/trunk/Objects/dictobject.c python/trunk/Objects/exceptions.c python/trunk/Objects/intobject.c python/trunk/Objects/listobject.c python/trunk/Objects/longobject.c python/trunk/Objects/stringobject.c python/trunk/Objects/tupleobject.c python/trunk/Objects/typeobject.c python/trunk/Objects/unicodeobject.c Log: Variation of patch # 1624059 to speed up checking if an object is a subclass of some of the common builtin types. Use a bit in tp_flags for each common builtin type. Check the bit to determine if any instance is a subclass of these common types. The check avoids a function call and O(n) search of the base classes. The check is done in the various Py*_Check macros rather than calling PyType_IsSubtype(). All the bits are set in tp_flags when the type is declared in the Objects/*object.c files because PyType_Ready() is not called for all the types. Should PyType_Ready() be called for all types? If so and the change is made, the changes to the Objects/*object.c files can be reverted (remove setting the tp_flags). Objects/typeobject.c would also have to be modified to add conditions for Py*_CheckExact() in addition to each the PyType_IsSubtype check. Modified: python/trunk/Include/dictobject.h ============================================================================== --- python/trunk/Include/dictobject.h (original) +++ python/trunk/Include/dictobject.h Sun Feb 25 20:44:48 2007 @@ -90,7 +90,8 @@ PyAPI_DATA(PyTypeObject) PyDict_Type; -#define PyDict_Check(op) PyObject_TypeCheck(op, &PyDict_Type) +#define PyDict_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_DICT_SUBCLASS) #define PyDict_CheckExact(op) ((op)->ob_type == &PyDict_Type) PyAPI_FUNC(PyObject *) PyDict_New(void); Modified: python/trunk/Include/intobject.h ============================================================================== --- python/trunk/Include/intobject.h (original) +++ python/trunk/Include/intobject.h Sun Feb 25 20:44:48 2007 @@ -27,7 +27,8 @@ PyAPI_DATA(PyTypeObject) PyInt_Type; -#define PyInt_Check(op) PyObject_TypeCheck(op, &PyInt_Type) +#define PyInt_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_INT_SUBCLASS) #define PyInt_CheckExact(op) ((op)->ob_type == &PyInt_Type) PyAPI_FUNC(PyObject *) PyInt_FromString(char*, char**, int); Modified: python/trunk/Include/listobject.h ============================================================================== --- python/trunk/Include/listobject.h (original) +++ python/trunk/Include/listobject.h Sun Feb 25 20:44:48 2007 @@ -40,7 +40,8 @@ PyAPI_DATA(PyTypeObject) PyList_Type; -#define PyList_Check(op) PyObject_TypeCheck(op, &PyList_Type) +#define PyList_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_LIST_SUBCLASS) #define PyList_CheckExact(op) ((op)->ob_type == &PyList_Type) PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size); Modified: python/trunk/Include/longobject.h ============================================================================== --- python/trunk/Include/longobject.h (original) +++ python/trunk/Include/longobject.h Sun Feb 25 20:44:48 2007 @@ -11,7 +11,8 @@ PyAPI_DATA(PyTypeObject) PyLong_Type; -#define PyLong_Check(op) PyObject_TypeCheck(op, &PyLong_Type) +#define PyLong_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_LONG_SUBCLASS) #define PyLong_CheckExact(op) ((op)->ob_type == &PyLong_Type) PyAPI_FUNC(PyObject *) PyLong_FromLong(long); Modified: python/trunk/Include/object.h ============================================================================== --- python/trunk/Include/object.h (original) +++ python/trunk/Include/object.h Sun Feb 25 20:44:48 2007 @@ -376,7 +376,8 @@ PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */ PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */ -#define PyType_Check(op) PyObject_TypeCheck(op, &PyType_Type) +#define PyType_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_TYPE_SUBCLASS) #define PyType_CheckExact(op) ((op)->ob_type == &PyType_Type) PyAPI_FUNC(int) PyType_Ready(PyTypeObject *); @@ -517,6 +518,17 @@ /* Objects support nb_index in PyNumberMethods */ #define Py_TPFLAGS_HAVE_INDEX (1L<<17) +/* These flags are used to determine if a type is a subclass. */ +#define Py_TPFLAGS_INT_SUBCLASS (1L<<23) +#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) +#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25) +#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26) +#define Py_TPFLAGS_STRING_SUBCLASS (1L<<27) +#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28) +#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29) +#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30) +#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31) + #define Py_TPFLAGS_DEFAULT ( \ Py_TPFLAGS_HAVE_GETCHARBUFFER | \ Py_TPFLAGS_HAVE_SEQUENCE_IN | \ @@ -530,6 +542,7 @@ 0) #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) +#define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) /* Modified: python/trunk/Include/pyerrors.h ============================================================================== --- python/trunk/Include/pyerrors.h (original) +++ python/trunk/Include/pyerrors.h Sun Feb 25 20:44:48 2007 @@ -95,14 +95,12 @@ /* */ #define PyExceptionClass_Check(x) \ - (PyClass_Check((x)) \ - || (PyType_Check((x)) && PyType_IsSubtype( \ - (PyTypeObject*)(x), (PyTypeObject*)PyExc_BaseException))) - + (PyClass_Check((x)) || (PyType_Check((x)) && \ + PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))) #define PyExceptionInstance_Check(x) \ (PyInstance_Check((x)) || \ - (PyType_IsSubtype((x)->ob_type, (PyTypeObject*)PyExc_BaseException))) + PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS)) #define PyExceptionClass_Name(x) \ (PyClass_Check((x)) \ Modified: python/trunk/Include/stringobject.h ============================================================================== --- python/trunk/Include/stringobject.h (original) +++ python/trunk/Include/stringobject.h Sun Feb 25 20:44:48 2007 @@ -55,7 +55,8 @@ PyAPI_DATA(PyTypeObject) PyBaseString_Type; PyAPI_DATA(PyTypeObject) PyString_Type; -#define PyString_Check(op) PyObject_TypeCheck(op, &PyString_Type) +#define PyString_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_STRING_SUBCLASS) #define PyString_CheckExact(op) ((op)->ob_type == &PyString_Type) PyAPI_FUNC(PyObject *) PyString_FromStringAndSize(const char *, Py_ssize_t); Modified: python/trunk/Include/tupleobject.h ============================================================================== --- python/trunk/Include/tupleobject.h (original) +++ python/trunk/Include/tupleobject.h Sun Feb 25 20:44:48 2007 @@ -33,7 +33,8 @@ PyAPI_DATA(PyTypeObject) PyTuple_Type; -#define PyTuple_Check(op) PyObject_TypeCheck(op, &PyTuple_Type) +#define PyTuple_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_TUPLE_SUBCLASS) #define PyTuple_CheckExact(op) ((op)->ob_type == &PyTuple_Type) PyAPI_FUNC(PyObject *) PyTuple_New(Py_ssize_t size); Modified: python/trunk/Include/unicodeobject.h ============================================================================== --- python/trunk/Include/unicodeobject.h (original) +++ python/trunk/Include/unicodeobject.h Sun Feb 25 20:44:48 2007 @@ -392,7 +392,8 @@ PyAPI_DATA(PyTypeObject) PyUnicode_Type; -#define PyUnicode_Check(op) PyObject_TypeCheck(op, &PyUnicode_Type) +#define PyUnicode_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_UNICODE_SUBCLASS) #define PyUnicode_CheckExact(op) ((op)->ob_type == &PyUnicode_Type) /* Fast access macros */ Modified: python/trunk/Objects/dictobject.c ============================================================================== --- python/trunk/Objects/dictobject.c (original) +++ python/trunk/Objects/dictobject.c Sun Feb 25 20:44:48 2007 @@ -2112,7 +2112,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ dictionary_doc, /* tp_doc */ dict_traverse, /* tp_traverse */ dict_tp_clear, /* tp_clear */ Modified: python/trunk/Objects/exceptions.c ============================================================================== --- python/trunk/Objects/exceptions.c (original) +++ python/trunk/Objects/exceptions.c Sun Feb 25 20:44:48 2007 @@ -300,7 +300,8 @@ PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ PyDoc_STR("Common base class for all exceptions"), /* tp_doc */ (traverseproc)BaseException_traverse, /* tp_traverse */ (inquiry)BaseException_clear, /* tp_clear */ Modified: python/trunk/Objects/intobject.c ============================================================================== --- python/trunk/Objects/intobject.c (original) +++ python/trunk/Objects/intobject.c Sun Feb 25 20:44:48 2007 @@ -1138,7 +1138,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */ int_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ Modified: python/trunk/Objects/listobject.c ============================================================================== --- python/trunk/Objects/listobject.c (original) +++ python/trunk/Objects/listobject.c Sun Feb 25 20:44:48 2007 @@ -2672,7 +2672,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ list_doc, /* tp_doc */ (traverseproc)list_traverse, /* tp_traverse */ (inquiry)list_clear, /* tp_clear */ Modified: python/trunk/Objects/longobject.c ============================================================================== --- python/trunk/Objects/longobject.c (original) +++ python/trunk/Objects/longobject.c Sun Feb 25 20:44:48 2007 @@ -3418,7 +3418,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ long_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ Modified: python/trunk/Objects/stringobject.c ============================================================================== --- python/trunk/Objects/stringobject.c (original) +++ python/trunk/Objects/stringobject.c Sun Feb 25 20:44:48 2007 @@ -4017,7 +4017,7 @@ 0, /* tp_setattro */ &string_as_buffer, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_STRING_SUBCLASS, /* tp_flags */ string_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ Modified: python/trunk/Objects/tupleobject.c ============================================================================== --- python/trunk/Objects/tupleobject.c (original) +++ python/trunk/Objects/tupleobject.c Sun Feb 25 20:44:48 2007 @@ -669,7 +669,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ tuple_doc, /* tp_doc */ (traverseproc)tupletraverse, /* tp_traverse */ 0, /* tp_clear */ Modified: python/trunk/Objects/typeobject.c ============================================================================== --- python/trunk/Objects/typeobject.c (original) +++ python/trunk/Objects/typeobject.c Sun Feb 25 20:44:48 2007 @@ -2288,7 +2288,7 @@ (setattrofunc)type_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ type_doc, /* tp_doc */ (traverseproc)type_traverse, /* tp_traverse */ (inquiry)type_clear, /* tp_clear */ @@ -2967,6 +2967,26 @@ if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) { COPYVAL(tp_dictoffset); } + + /* Setup fast subclass flags */ + if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) + type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; + else if (PyType_IsSubtype(base, &PyType_Type)) + type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyInt_Type)) + type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS; + else if (PyType_IsSubtype(base, &PyLong_Type)) + type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; + else if (PyType_IsSubtype(base, &PyString_Type)) + type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS; + else if (PyType_IsSubtype(base, &PyUnicode_Type)) + type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyTuple_Type)) + type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyList_Type)) + type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; + else if (PyType_IsSubtype(base, &PyDict_Type)) + type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; } static void Modified: python/trunk/Objects/unicodeobject.c ============================================================================== --- python/trunk/Objects/unicodeobject.c (original) +++ python/trunk/Objects/unicodeobject.c Sun Feb 25 20:44:48 2007 @@ -7967,7 +7967,7 @@ 0, /* tp_setattro */ &unicode_as_buffer, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */ unicode_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ From python-checkins at python.org Sun Feb 25 21:39:15 2007 From: python-checkins at python.org (thomas.wouters) Date: Sun, 25 Feb 2007 21:39:15 +0100 (CET) Subject: [Python-checkins] r53912 - in python/branches/p3yk: Doc/lib/libetree.tex Include/dictobject.h Include/listobject.h Include/longobject.h Include/object.h Include/pyerrors.h Include/stringobject.h Include/tupleobject.h Include/unicodeobject.h Objects/dictobject.c Objects/exceptions.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/stringobject.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodeobject.c Message-ID: <20070225203915.1B7121E4007@bag.python.org> Author: thomas.wouters Date: Sun Feb 25 21:39:11 2007 New Revision: 53912 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/lib/libetree.tex python/branches/p3yk/Include/dictobject.h python/branches/p3yk/Include/listobject.h python/branches/p3yk/Include/longobject.h python/branches/p3yk/Include/object.h python/branches/p3yk/Include/pyerrors.h python/branches/p3yk/Include/stringobject.h python/branches/p3yk/Include/tupleobject.h python/branches/p3yk/Include/unicodeobject.h python/branches/p3yk/Objects/dictobject.c python/branches/p3yk/Objects/exceptions.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/tupleobject.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/Objects/unicodeobject.c Log: Merged revisions 53875-53911 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53899 | neal.norwitz | 2007-02-25 16:52:27 +0100 (Sun, 25 Feb 2007) | 1 line Add more details when releasing interned strings ........ r53900 | neal.norwitz | 2007-02-25 16:53:36 +0100 (Sun, 25 Feb 2007) | 1 line Whitespace only changes ........ r53901 | jeremy.hylton | 2007-02-25 16:57:45 +0100 (Sun, 25 Feb 2007) | 8 lines Fix crash in exec when unicode filename can't be decoded. I can't think of an easy way to test this behavior. It only occurs when the file system default encoding and the interpreter default encoding are different, such that you can open the file but not decode its name. ........ r53902 | jeremy.hylton | 2007-02-25 17:01:58 +0100 (Sun, 25 Feb 2007) | 2 lines Put declarations before code. ........ r53910 | fred.drake | 2007-02-25 18:56:27 +0100 (Sun, 25 Feb 2007) | 3 lines - SF patch #1657613: add documentation for the Element interface - clean up bogus use of the {datadescni} environment everywhere ........ r53911 | neal.norwitz | 2007-02-25 20:44:48 +0100 (Sun, 25 Feb 2007) | 17 lines Variation of patch # 1624059 to speed up checking if an object is a subclass of some of the common builtin types. Use a bit in tp_flags for each common builtin type. Check the bit to determine if any instance is a subclass of these common types. The check avoids a function call and O(n) search of the base classes. The check is done in the various Py*_Check macros rather than calling PyType_IsSubtype(). All the bits are set in tp_flags when the type is declared in the Objects/*object.c files because PyType_Ready() is not called for all the types. Should PyType_Ready() be called for all types? If so and the change is made, the changes to the Objects/*object.c files can be reverted (remove setting the tp_flags). Objects/typeobject.c would also have to be modified to add conditions for Py*_CheckExact() in addition to each the PyType_IsSubtype check. ........ Modified: python/branches/p3yk/Doc/lib/libetree.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libetree.tex (original) +++ python/branches/p3yk/Doc/lib/libetree.tex Sun Feb 25 21:39:11 2007 @@ -38,10 +38,7 @@ The comment string can be either an 8-bit ASCII string or a Unicode string. \var{text} is a string containing the comment string. - -\begin{datadescni}{Returns:} -An element instance, representing a comment. -\end{datadescni} +Returns an element instance representing a comment. \end{funcdesc} \begin{funcdesc}{dump}{elem} @@ -65,28 +62,19 @@ \var{tag} is the element name. \var{attrib} is an optional dictionary, containing element attributes. \var{extra} contains additional attributes, given as keyword arguments. - -\begin{datadescni}{Returns:} -An element instance. -\end{datadescni} +Returns an element instance. \end{funcdesc} \begin{funcdesc}{fromstring}{text} Parses an XML section from a string constant. Same as XML. \var{text} is a string containing XML data. - -\begin{datadescni}{Returns:} -An Element instance. -\end{datadescni} +Returns an Element instance. \end{funcdesc} \begin{funcdesc}{iselement}{element} Checks if an object appears to be a valid element object. \var{element} is an element instance. - -\begin{datadescni}{Returns:} -A true value if this is an element object. -\end{datadescni} +Returns a true value if this is an element object. \end{funcdesc} \begin{funcdesc}{iterparse}{source\optional{, events}} @@ -95,10 +83,7 @@ \var{source} is a filename or file object containing XML data. \var{events} is a list of events to report back. If omitted, only ``end'' events are reported. - -\begin{datadescni}{Returns:} -A (event, elem) iterator. -\end{datadescni} +Returns an iterator providing \code{(\var{event}, \var{elem})} pairs. \end{funcdesc} \begin{funcdesc}{parse}{source\optional{, parser}} @@ -106,10 +91,7 @@ \var{source} is a filename or file object containing XML data. \var{parser} is an optional parser instance. If not given, the standard XMLTreeBuilder parser is used. - -\begin{datadescni}{Returns:} -An ElementTree instance -\end{datadescni} +Returns an ElementTree instance. \end{funcdesc} \begin{funcdesc}{ProcessingInstruction}{target\optional{, text}} @@ -117,13 +99,11 @@ that will be serialized as an XML processing instruction. \var{target} is a string containing the PI target. \var{text} is a string containing the PI contents, if given. - -\begin{datadescni}{Returns:} -An element instance, representing a PI. -\end{datadescni} +Returns an element instance, representing a processing instruction. \end{funcdesc} -\begin{funcdesc}{SubElement}{parent, tag\optional{, attrib} \optional{, **extra}} +\begin{funcdesc}{SubElement}{parent, tag\optional{, + attrib\optional{, **extra}}} Subelement factory. This function creates an element instance, and appends it to an existing element. @@ -133,10 +113,7 @@ \var{tag} is the subelement name. \var{attrib} is an optional dictionary, containing element attributes. \var{extra} contains additional attributes, given as keyword arguments. - -\begin{datadescni}{Returns:} -An element instance. -\end{datadescni} +Returns an element instance. \end{funcdesc} \begin{funcdesc}{tostring}{element\optional{, encoding}} @@ -144,33 +121,162 @@ subelements. \var{element} is an Element instance. \var{encoding} is the output encoding (default is US-ASCII). - -\begin{datadescni}{Returns:} -An encoded string containing the XML data. -\end{datadescni} +Returns an encoded string containing the XML data. \end{funcdesc} \begin{funcdesc}{XML}{text} Parses an XML section from a string constant. This function can be used to embed ``XML literals'' in Python code. \var{text} is a string containing XML data. - -\begin{datadescni}{Returns:} -An Element instance. -\end{datadescni} +Returns an Element instance. \end{funcdesc} \begin{funcdesc}{XMLID}{text} Parses an XML section from a string constant, and also returns a dictionary which maps from element id:s to elements. \var{text} is a string containing XML data. - -\begin{datadescni}{Returns:} -A tuple containing an Element instance and a dictionary. -\end{datadescni} +Returns a tuple containing an Element instance and a dictionary. \end{funcdesc} +\subsection{The Element Interface\label{elementtree-element-interface}} + +Element objects returned by Element or SubElement have the +following methods and attributes. + +\begin{memberdesc}{tag} +A string identifying what kind of data this element represents +(the element type, in other words). +\end{memberdesc} + +\begin{memberdesc}{text} +The \var{text} attribute can be used to hold additional data +associated with the element. +As the name implies this attribute is usually a string but may be any +application-specific object. +If the element is created from an XML file the attribute will contain +any text found between the element tags. +\end{memberdesc} + +\begin{memberdesc}{tail} +The \var{tail} attribute can be used to hold additional data +associated with the element. +This attribute is usually a string but may be any application-specific object. +If the element is created from an XML file the attribute will contain +any text found after the element's end tag and before the next tag. +\end{memberdesc} + +\begin{memberdesc}{attrib} +A dictionary containing the element's attributes. +Note that while the \var{attrib} value is always a real mutable Python +dictionary, an ElementTree implementation may choose to use another +internal representation, and create the dictionary only if someone +asks for it. To take advantage of such implementations, use the +dictionary methods below whenever possible. +\end{memberdesc} + +The following dictionary-like methods work on the element attributes. + +\begin{methoddesc}{clear}{} +Resets an element. This function removes all subelements, clears +all attributes, and sets the text and tail attributes to None. +\end{methoddesc} + +\begin{methoddesc}{get}{key\optional{, default=None}} +Gets the element attribute named \var{key}. + +Returns the attribute value, or \var{default} if the +attribute was not found. +\end{methoddesc} + +\begin{methoddesc}{items}{} +Returns the element attributes as a sequence of (name, value) pairs. +The attributes are returned in an arbitrary order. +\end{methoddesc} + +\begin{methoddesc}{keys}{} +Returns the elements attribute names as a list. +The names are returned in an arbitrary order. +\end{methoddesc} + +\begin{methoddesc}{set}{key, value} +Set the attribute \var{key} on the element to \var{value}. +\end{methoddesc} + +The following methods work on the element's children (subelements). + +\begin{methoddesc}{append}{subelement} +Adds the element \var{subelement} to the end of this elements internal list +of subelements. +\end{methoddesc} + +\begin{methoddesc}{find}{match} +Finds the first subelement matching \var{match}. +\var{match} may be a tag name or path. +Returns an element instance or \code{None}. +\end{methoddesc} + +\begin{methoddesc}{findall}{match} +Finds all subelements matching \var{match}. +\var{match} may be a tag name or path. +Returns an iterable yielding all matching elements in document order. +\end{methoddesc} + +\begin{methoddesc}{findtext}{condition\optional{, default=None}} +Finds text for the first subelement matching \var{condition}. +\var{condition} may be a tag name or path. +Returns the text content of the first matching element, or +\var{default} if no element was found. Note that if the +matching element has no text content an empty string is returned. +\end{methoddesc} + +\begin{methoddesc}{getchildren}{} +Returns all subelements. The elements are returned in document order. +\end{methoddesc} + +\begin{methoddesc}{getiterator}{\optional{tag=None}} +Creates a tree iterator with the current element as the root. +The iterator iterates over this element and all elements below it +that match the given tag. If tag +is \code{None} or \code{'*'} then all elements are iterated over. +Returns an iterable that provides element objects in document (depth first) +order. +\end{methoddesc} + +\begin{methoddesc}{insert}{index, element} +Inserts a subelement at the given position in this element. +\end{methoddesc} + +\begin{methoddesc}{makeelement}{tag, attrib} +Creates a new element object of the same type as this element. +Do not call this method, use the SubElement factory function instead. +\end{methoddesc} + +\begin{methoddesc}{remove}{subelement} +Removes \var{subelement} from the element. +Unlike the findXXX methods this method compares elements based on +the instance identity, not on tag value or contents. +\end{methoddesc} + +Element objects also support the following sequence type methods for +working with subelements: \method{__delitem__()}, +\method{__getitem__()}, \method{__setitem__()}, \method{__len__()}. + +Caution: Because Element objects do not define a +\method{__nonzero__()} method, elements with no subelements will test +as \code{False}. + +\begin{verbatim} +element = root.find('foo') + +if not element: # careful! + print "element not found, or element has no subelements" + +if element is None: + print "element not found" +\end{verbatim} + + \subsection{ElementTree Objects\label{elementtree-elementtree-objects}} \begin{classdesc}{ElementTree}{\optional{element,} \optional{file}} @@ -193,21 +299,15 @@ Finds the first toplevel element with given tag. Same as getroot().find(path). \var{path} is the element to look for. - -\begin{datadescni}{Returns:} -The first matching element, or None if no element was found. -\end{datadescni} +Returns the first matching element, or \code{None} if no element was found. \end{methoddesc} \begin{methoddesc}{findall}{path} Finds all toplevel elements with the given tag. Same as getroot().findall(path). \var{path} is the element to look for. - -\begin{datadescni}{Returns:} -A list or iterator containing all matching elements, -in section order. -\end{datadescni} +Returns a list or iterator containing all matching elements, +in document order. \end{methoddesc} \begin{methoddesc}{findtext}{path\optional{, default}} @@ -215,31 +315,20 @@ tag. Same as getroot().findtext(path). \var{path} is the toplevel element to look for. \var{default} is the value to return if the element was not found. - -\begin{datadescni}{Returns:} -The text content of the first matching element, or the +Returns the text content of the first matching element, or the default value no element was found. Note that if the element has is found, but has no text content, this method returns an empty string. -\end{datadescni} \end{methoddesc} \begin{methoddesc}{getiterator}{\optional{tag}} -Creates a tree iterator for the root element. The iterator loops +Creates and returns a tree iterator for the root element. The iterator loops over all elements in this tree, in section order. \var{tag} is the tag to look for (default is to return all elements) - -\begin{datadescni}{Returns:} -An iterator. -\end{datadescni} \end{methoddesc} \begin{methoddesc}{getroot}{} -Gets the root element for this tree. - -\begin{datadescni}{Returns:} -An element instance. -\end{datadescni} +Returns the root element for this tree. \end{methoddesc} \begin{methoddesc}{parse}{source\optional{, parser}} @@ -247,10 +336,7 @@ \var{source} is a file name or file object. \var{parser} is an optional parser instance. If not given, the standard XMLTreeBuilder parser is used. - -\begin{datadescni}{Returns:} -The section root element. -\end{datadescni} +Returns the section root element. \end{methoddesc} \begin{methoddesc}{write}{file\optional{, encoding}} @@ -270,10 +356,7 @@ the URI part of a QName. If \var{tag} is given, the first argument is interpreted as an URI, and this argument is interpreted as a local name. - -\begin{datadescni}{Returns:} -An opaque object, representing the QName. -\end{datadescni} +\class{QName} instances are opaque. \end{classdesc} @@ -291,10 +374,7 @@ \begin{methoddesc}{close}{} Flushes the parser buffers, and returns the toplevel documen element. - -\begin{datadescni}{Returns:} -An Element instance. -\end{datadescni} +Returns an Element instance. \end{methoddesc} \begin{methoddesc}{data}{data} @@ -306,20 +386,14 @@ \begin{methoddesc}{end}{tag} Closes the current element. \var{tag} is the element name. - -\begin{datadescni}{Returns:} -The closed element. -\end{datadescni} +Returns the closed element. \end{methoddesc} \begin{methoddesc}{start}{tag, attrs} Opens a new element. \var{tag} is the element name. \var{attrs} is a dictionary containing element attributes. - -\begin{datadescni}{Returns:} -The opened element. -\end{datadescni} +Returns the opened element. \end{methoddesc} @@ -336,10 +410,7 @@ \begin{methoddesc}{close}{} Finishes feeding data to the parser. - -\begin{datadescni}{Returns:} -An element structure. -\end{datadescni} +Returns an element structure. \end{methoddesc} \begin{methoddesc}{doctype}{name, pubid, system} @@ -351,6 +422,5 @@ \begin{methoddesc}{feed}{data} Feeds data to the parser. - \var{data} is encoded data. \end{methoddesc} Modified: python/branches/p3yk/Include/dictobject.h ============================================================================== --- python/branches/p3yk/Include/dictobject.h (original) +++ python/branches/p3yk/Include/dictobject.h Sun Feb 25 21:39:11 2007 @@ -90,7 +90,8 @@ PyAPI_DATA(PyTypeObject) PyDict_Type; -#define PyDict_Check(op) PyObject_TypeCheck(op, &PyDict_Type) +#define PyDict_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_DICT_SUBCLASS) #define PyDict_CheckExact(op) ((op)->ob_type == &PyDict_Type) PyAPI_FUNC(PyObject *) PyDict_New(void); Modified: python/branches/p3yk/Include/listobject.h ============================================================================== --- python/branches/p3yk/Include/listobject.h (original) +++ python/branches/p3yk/Include/listobject.h Sun Feb 25 21:39:11 2007 @@ -40,7 +40,8 @@ PyAPI_DATA(PyTypeObject) PyList_Type; -#define PyList_Check(op) PyObject_TypeCheck(op, &PyList_Type) +#define PyList_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_LIST_SUBCLASS) #define PyList_CheckExact(op) ((op)->ob_type == &PyList_Type) PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size); Modified: python/branches/p3yk/Include/longobject.h ============================================================================== --- python/branches/p3yk/Include/longobject.h (original) +++ python/branches/p3yk/Include/longobject.h Sun Feb 25 21:39:11 2007 @@ -11,7 +11,8 @@ PyAPI_DATA(PyTypeObject) PyLong_Type; -#define PyLong_Check(op) PyObject_TypeCheck(op, &PyLong_Type) +#define PyLong_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_LONG_SUBCLASS) #define PyLong_CheckExact(op) ((op)->ob_type == &PyLong_Type) PyAPI_FUNC(PyObject *) PyLong_FromLong(long); Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Sun Feb 25 21:39:11 2007 @@ -357,7 +357,8 @@ PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */ PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */ -#define PyType_Check(op) PyObject_TypeCheck(op, &PyType_Type) +#define PyType_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_TYPE_SUBCLASS) #define PyType_CheckExact(op) ((op)->ob_type == &PyType_Type) PyAPI_FUNC(int) PyType_Ready(PyTypeObject *); @@ -469,11 +470,23 @@ #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0 #endif +/* These flags are used to determine if a type is a subclass. */ +#define Py_TPFLAGS_INT_SUBCLASS (1L<<23) +#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) +#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25) +#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26) +#define Py_TPFLAGS_STRING_SUBCLASS (1L<<27) +#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28) +#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29) +#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30) +#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31) + #define Py_TPFLAGS_DEFAULT ( \ Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ 0) #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) +#define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) /* Modified: python/branches/p3yk/Include/pyerrors.h ============================================================================== --- python/branches/p3yk/Include/pyerrors.h (original) +++ python/branches/p3yk/Include/pyerrors.h Sun Feb 25 21:39:11 2007 @@ -94,13 +94,12 @@ /* */ -#define PyExceptionClass_Check(x) \ - (PyType_Check((x)) && PyType_IsSubtype( \ - (PyTypeObject*)(x), (PyTypeObject*)PyExc_BaseException)) +#define PyExceptionClass_Check(x) \ + (PyType_Check((x)) && \ + PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) - -#define PyExceptionInstance_Check(x) \ - (PyType_IsSubtype((x)->ob_type, (PyTypeObject*)PyExc_BaseException)) +#define PyExceptionInstance_Check(x) \ + PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) #define PyExceptionClass_Name(x) \ ((char *)(((PyTypeObject*)(x))->tp_name)) Modified: python/branches/p3yk/Include/stringobject.h ============================================================================== --- python/branches/p3yk/Include/stringobject.h (original) +++ python/branches/p3yk/Include/stringobject.h Sun Feb 25 21:39:11 2007 @@ -55,7 +55,8 @@ PyAPI_DATA(PyTypeObject) PyBaseString_Type; PyAPI_DATA(PyTypeObject) PyString_Type; -#define PyString_Check(op) PyObject_TypeCheck(op, &PyString_Type) +#define PyString_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_STRING_SUBCLASS) #define PyString_CheckExact(op) ((op)->ob_type == &PyString_Type) PyAPI_FUNC(PyObject *) PyString_FromStringAndSize(const char *, Py_ssize_t); Modified: python/branches/p3yk/Include/tupleobject.h ============================================================================== --- python/branches/p3yk/Include/tupleobject.h (original) +++ python/branches/p3yk/Include/tupleobject.h Sun Feb 25 21:39:11 2007 @@ -33,7 +33,8 @@ PyAPI_DATA(PyTypeObject) PyTuple_Type; -#define PyTuple_Check(op) PyObject_TypeCheck(op, &PyTuple_Type) +#define PyTuple_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_TUPLE_SUBCLASS) #define PyTuple_CheckExact(op) ((op)->ob_type == &PyTuple_Type) PyAPI_FUNC(PyObject *) PyTuple_New(Py_ssize_t size); Modified: python/branches/p3yk/Include/unicodeobject.h ============================================================================== --- python/branches/p3yk/Include/unicodeobject.h (original) +++ python/branches/p3yk/Include/unicodeobject.h Sun Feb 25 21:39:11 2007 @@ -392,7 +392,8 @@ PyAPI_DATA(PyTypeObject) PyUnicode_Type; -#define PyUnicode_Check(op) PyObject_TypeCheck(op, &PyUnicode_Type) +#define PyUnicode_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_UNICODE_SUBCLASS) #define PyUnicode_CheckExact(op) ((op)->ob_type == &PyUnicode_Type) /* Fast access macros */ Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Sun Feb 25 21:39:11 2007 @@ -2027,7 +2027,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ dictionary_doc, /* tp_doc */ dict_traverse, /* tp_traverse */ dict_tp_clear, /* tp_clear */ Modified: python/branches/p3yk/Objects/exceptions.c ============================================================================== --- python/branches/p3yk/Objects/exceptions.c (original) +++ python/branches/p3yk/Objects/exceptions.c Sun Feb 25 21:39:11 2007 @@ -300,7 +300,8 @@ PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ PyDoc_STR("Common base class for all exceptions"), /* tp_doc */ (traverseproc)BaseException_traverse, /* tp_traverse */ (inquiry)BaseException_clear, /* tp_clear */ Modified: python/branches/p3yk/Objects/intobject.c ============================================================================== --- python/branches/p3yk/Objects/intobject.c (original) +++ python/branches/p3yk/Objects/intobject.c Sun Feb 25 21:39:11 2007 @@ -1115,7 +1115,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */ int_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ Modified: python/branches/p3yk/Objects/listobject.c ============================================================================== --- python/branches/p3yk/Objects/listobject.c (original) +++ python/branches/p3yk/Objects/listobject.c Sun Feb 25 21:39:11 2007 @@ -2683,7 +2683,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ list_doc, /* tp_doc */ (traverseproc)list_traverse, /* tp_traverse */ (inquiry)list_clear, /* tp_clear */ Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Sun Feb 25 21:39:11 2007 @@ -3643,7 +3643,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ long_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ Modified: python/branches/p3yk/Objects/stringobject.c ============================================================================== --- python/branches/p3yk/Objects/stringobject.c (original) +++ python/branches/p3yk/Objects/stringobject.c Sun Feb 25 21:39:11 2007 @@ -1131,8 +1131,7 @@ much time, since Py_NE is rarely used. */ if (a->ob_size == b->ob_size && (a->ob_sval[0] == b->ob_sval[0] - && memcmp(a->ob_sval, b->ob_sval, - a->ob_size) == 0)) { + && memcmp(a->ob_sval, b->ob_sval, a->ob_size) == 0)) { result = Py_True; } else { result = Py_False; @@ -1145,7 +1144,7 @@ c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval); if (c==0) c = memcmp(a->ob_sval, b->ob_sval, min_len); - }else + } else c = 0; if (c == 0) c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; @@ -4018,7 +4017,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &string_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_STRING_SUBCLASS, /* tp_flags */ string_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ @@ -4981,6 +4981,7 @@ PyObject *keys; PyStringObject *s; Py_ssize_t i, n; + Py_ssize_t immortal_size = 0, mortal_size = 0; if (interned == NULL || !PyDict_Check(interned)) return; @@ -4995,8 +4996,9 @@ give them their stolen references back, and then clear and DECREF the interned dict. */ - fprintf(stderr, "releasing interned strings\n"); n = PyList_GET_SIZE(keys); + fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n", + n); for (i = 0; i < n; i++) { s = (PyStringObject *) PyList_GET_ITEM(keys, i); switch (s->ob_sstate) { @@ -5005,15 +5007,20 @@ break; case SSTATE_INTERNED_IMMORTAL: s->ob_refcnt += 1; + immortal_size += s->ob_size; break; case SSTATE_INTERNED_MORTAL: s->ob_refcnt += 2; + mortal_size += s->ob_size; break; default: Py_FatalError("Inconsistent interned string state."); } s->ob_sstate = SSTATE_NOT_INTERNED; } + fprintf(stderr, "total size of all interned strings: " + "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d " + "mortal/immortal\n", mortal_size, immortal_size); Py_DECREF(keys); PyDict_Clear(interned); Py_DECREF(interned); Modified: python/branches/p3yk/Objects/tupleobject.c ============================================================================== --- python/branches/p3yk/Objects/tupleobject.c (original) +++ python/branches/p3yk/Objects/tupleobject.c Sun Feb 25 21:39:11 2007 @@ -669,7 +669,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ tuple_doc, /* tp_doc */ (traverseproc)tupletraverse, /* tp_traverse */ 0, /* tp_clear */ Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Sun Feb 25 21:39:11 2007 @@ -2205,7 +2205,7 @@ (setattrofunc)type_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ type_doc, /* tp_doc */ (traverseproc)type_traverse, /* tp_traverse */ (inquiry)type_clear, /* tp_clear */ @@ -2874,6 +2874,24 @@ COPYVAL(tp_itemsize); COPYVAL(tp_weaklistoffset); COPYVAL(tp_dictoffset); + + /* Setup fast subclass flags */ + if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) + type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; + else if (PyType_IsSubtype(base, &PyType_Type)) + type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyLong_Type)) + type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; + else if (PyType_IsSubtype(base, &PyString_Type)) + type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS; + else if (PyType_IsSubtype(base, &PyUnicode_Type)) + type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyTuple_Type)) + type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyList_Type)) + type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; + else if (PyType_IsSubtype(base, &PyDict_Type)) + type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; } /* Map rich comparison operators to their __xx__ namesakes */ Modified: python/branches/p3yk/Objects/unicodeobject.c ============================================================================== --- python/branches/p3yk/Objects/unicodeobject.c (original) +++ python/branches/p3yk/Objects/unicodeobject.c Sun Feb 25 21:39:11 2007 @@ -7971,7 +7971,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &unicode_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */ unicode_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ From python-checkins at python.org Sun Feb 25 22:45:06 2007 From: python-checkins at python.org (thomas.wouters) Date: Sun, 25 Feb 2007 22:45:06 +0100 (CET) Subject: [Python-checkins] r53916 - python/branches/twouters-dictviews-backport Message-ID: <20070225214506.B186A1E400C@bag.python.org> Author: thomas.wouters Date: Sun Feb 25 22:45:05 2007 New Revision: 53916 Added: python/branches/twouters-dictviews-backport/ - copied from r53915, python/trunk/ Log: Branch for backporting dictviews to 2.6 From python-checkins at python.org Sun Feb 25 22:56:39 2007 From: python-checkins at python.org (neal.norwitz) Date: Sun, 25 Feb 2007 22:56:39 +0100 (CET) Subject: [Python-checkins] r53917 - peps/trunk/pep-0361.txt Message-ID: <20070225215639.904D71E4009@bag.python.org> Author: neal.norwitz Date: Sun Feb 25 22:56:38 2007 New Revision: 53917 Modified: peps/trunk/pep-0361.txt Log: Another 3k warning Modified: peps/trunk/pep-0361.txt ============================================================================== --- peps/trunk/pep-0361.txt (original) +++ peps/trunk/pep-0361.txt Sun Feb 25 22:56:38 2007 @@ -110,6 +110,7 @@ * input() * apply() * xreadlines + * function attributes that start with func_* (should use __*__) - with/as will be keywords From python-checkins at python.org Sun Feb 25 22:58:14 2007 From: python-checkins at python.org (neal.norwitz) Date: Sun, 25 Feb 2007 22:58:14 +0100 (CET) Subject: [Python-checkins] r53918 - peps/trunk/pep-0361.txt Message-ID: <20070225215814.370F41E4007@bag.python.org> Author: neal.norwitz Date: Sun Feb 25 22:58:13 2007 New Revision: 53918 Modified: peps/trunk/pep-0361.txt Log: Some more 2.6 things to do Modified: peps/trunk/pep-0361.txt ============================================================================== --- peps/trunk/pep-0361.txt (original) +++ peps/trunk/pep-0361.txt Sun Feb 25 22:58:13 2007 @@ -94,6 +94,7 @@ http://mail.python.org/pipermail/python-dev/2006-April/064145.html - warnings module implemented in C + * Convert Parser/*.c to use warnings module rather than printf - Add warnings for Py3k features removed: * backticks and <> @@ -111,6 +112,7 @@ * apply() * xreadlines * function attributes that start with func_* (should use __*__) + * softspace removal for print() function - with/as will be keywords From python-checkins at python.org Sun Feb 25 23:12:33 2007 From: python-checkins at python.org (thomas.wouters) Date: Sun, 25 Feb 2007 23:12:33 +0100 (CET) Subject: [Python-checkins] r53919 - python/trunk/Lib/test/test_dbm.py python/trunk/Lib/test/test_gdbm.py Message-ID: <20070225221233.243081E4009@bag.python.org> Author: thomas.wouters Date: Sun Feb 25 23:12:31 2007 New Revision: 53919 Modified: python/trunk/Lib/test/test_dbm.py python/trunk/Lib/test/test_gdbm.py Log: Backported r51621 from p3yk: Don't use a fixed temporary name (gdbm). Don't use our own temp name creation (dbm). Should be backported to 2.5. Modified: python/trunk/Lib/test/test_dbm.py ============================================================================== --- python/trunk/Lib/test/test_dbm.py (original) +++ python/trunk/Lib/test/test_dbm.py Sun Feb 25 23:12:31 2007 @@ -6,11 +6,11 @@ import random import dbm from dbm import error -from test.test_support import verbose, verify, TestSkipped +from test.test_support import verbose, verify, TestSkipped, TESTFN # make filename unique to allow multiple concurrent tests # and to minimize the likelihood of a problem from an old file -filename = '/tmp/delete_me_' + str(random.random())[-6:] +filename = TESTFN def cleanup(): for suffix in ['', '.pag', '.dir', '.db']: Modified: python/trunk/Lib/test/test_gdbm.py ============================================================================== --- python/trunk/Lib/test/test_gdbm.py (original) +++ python/trunk/Lib/test/test_gdbm.py Sun Feb 25 23:12:31 2007 @@ -5,9 +5,9 @@ import gdbm from gdbm import error -from test.test_support import verbose, verify, TestFailed +from test.test_support import verbose, verify, TestFailed, TESTFN -filename= '/tmp/delete_me' +filename = TESTFN g = gdbm.open(filename, 'c') verify(g.keys() == []) From python-checkins at python.org Sun Feb 25 23:15:07 2007 From: python-checkins at python.org (thomas.wouters) Date: Sun, 25 Feb 2007 23:15:07 +0100 (CET) Subject: [Python-checkins] r53920 - python/branches/release25-maint/Lib/test/test_dbm.py python/branches/release25-maint/Lib/test/test_gdbm.py Message-ID: <20070225221507.95F231E4011@bag.python.org> Author: thomas.wouters Date: Sun Feb 25 23:15:04 2007 New Revision: 53920 Modified: python/branches/release25-maint/Lib/test/test_dbm.py python/branches/release25-maint/Lib/test/test_gdbm.py Log: Backported r51621 from p3yk: Don't use a fixed temporary name (gdbm). Don't use our own temp name creation (dbm). Modified: python/branches/release25-maint/Lib/test/test_dbm.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_dbm.py (original) +++ python/branches/release25-maint/Lib/test/test_dbm.py Sun Feb 25 23:15:04 2007 @@ -6,11 +6,11 @@ import random import dbm from dbm import error -from test.test_support import verbose, verify, TestSkipped +from test.test_support import verbose, verify, TestSkipped, TESTFN # make filename unique to allow multiple concurrent tests # and to minimize the likelihood of a problem from an old file -filename = '/tmp/delete_me_' + str(random.random())[-6:] +filename = TESTFN def cleanup(): for suffix in ['', '.pag', '.dir', '.db']: Modified: python/branches/release25-maint/Lib/test/test_gdbm.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_gdbm.py (original) +++ python/branches/release25-maint/Lib/test/test_gdbm.py Sun Feb 25 23:15:04 2007 @@ -5,9 +5,9 @@ import gdbm from gdbm import error -from test.test_support import verbose, verify, TestFailed +from test.test_support import verbose, verify, TestFailed, TESTFN -filename= '/tmp/delete_me' +filename = TESTFN g = gdbm.open(filename, 'c') verify(g.keys() == []) From python-checkins at python.org Sun Feb 25 23:15:56 2007 From: python-checkins at python.org (thomas.wouters) Date: Sun, 25 Feb 2007 23:15:56 +0100 (CET) Subject: [Python-checkins] r53921 - python/branches/release24-maint/Lib/test/test_dbm.py python/branches/release24-maint/Lib/test/test_gdbm.py Message-ID: <20070225221556.5E50F1E4009@bag.python.org> Author: thomas.wouters Date: Sun Feb 25 23:15:53 2007 New Revision: 53921 Modified: python/branches/release24-maint/Lib/test/test_dbm.py python/branches/release24-maint/Lib/test/test_gdbm.py Log: Backported r51621 from p3yk: Don't use a fixed temporary name (gdbm). Don't use our own temp name creation (dbm). Modified: python/branches/release24-maint/Lib/test/test_dbm.py ============================================================================== --- python/branches/release24-maint/Lib/test/test_dbm.py (original) +++ python/branches/release24-maint/Lib/test/test_dbm.py Sun Feb 25 23:15:53 2007 @@ -6,11 +6,11 @@ import random import dbm from dbm import error -from test.test_support import verbose, verify, TestSkipped +from test.test_support import verbose, verify, TestSkipped, TESTFN # make filename unique to allow multiple concurrent tests # and to minimize the likelihood of a problem from an old file -filename = '/tmp/delete_me_' + str(random.random())[-6:] +filename = TESTFN def cleanup(): for suffix in ['', '.pag', '.dir', '.db']: Modified: python/branches/release24-maint/Lib/test/test_gdbm.py ============================================================================== --- python/branches/release24-maint/Lib/test/test_gdbm.py (original) +++ python/branches/release24-maint/Lib/test/test_gdbm.py Sun Feb 25 23:15:53 2007 @@ -5,9 +5,9 @@ import gdbm from gdbm import error -from test.test_support import verbose, verify, TestFailed +from test.test_support import verbose, verify, TestFailed, TESTFN -filename= '/tmp/delete_me' +filename = TESTFN g = gdbm.open(filename, 'c') verify(g.keys() == []) From buildbot at python.org Sun Feb 25 23:45:03 2007 From: buildbot at python.org (buildbot at python.org) Date: Sun, 25 Feb 2007 22:45:03 +0000 Subject: [Python-checkins] buildbot warnings in x86 gentoo trunk Message-ID: <20070225224503.6351E1E4007@bag.python.org> The Buildbot has detected a new failure of x86 gentoo trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%2520trunk/builds/1942 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: thomas.wouters Build had warnings: warnings test Excerpt from the test logfile: Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30996, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30996, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30996, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30996, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30996, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 260, in writerThread self.assertEqual(data, self.makeData(key)) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/unittest.py", line 334, in failUnlessEqual (msg or '%r != %r' % (first, second)) AssertionError: None != '1000-1000-1000-1000-1000' Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 260, in writerThread self.assertEqual(data, self.makeData(key)) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/unittest.py", line 334, in failUnlessEqual (msg or '%r != %r' % (first, second)) AssertionError: None != '2001-2001-2001-2001-2001' Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/bsddb/test/test_thread.py", line 260, in writerThread self.assertEqual(data, self.makeData(key)) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/unittest.py", line 334, in failUnlessEqual (msg or '%r != %r' % (first, second)) AssertionError: None != '0003-0003-0003-0003-0003' 1 test failed: test_socketserver Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/test/test_socketserver.py", line 88, in run svr.serve_a_few() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/test/test_socketserver.py", line 35, in serve_a_few self.handle_request() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/SocketServer.py", line 224, in handle_request self.handle_error(request, client_address) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/SocketServer.py", line 222, in handle_request self.process_request(request, client_address) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/SocketServer.py", line 241, in process_request self.finish_request(request, client_address) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/SocketServer.py", line 521, in __init__ self.handle() File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/test/test_socketserver.py", line 21, in handle time.sleep(DELAY) AttributeError: 'NoneType' object has no attribute 'sleep' make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Sun Feb 25 23:55:01 2007 From: python-checkins at python.org (thomas.wouters) Date: Sun, 25 Feb 2007 23:55:01 +0100 (CET) Subject: [Python-checkins] r53923 - peps/trunk/pep-0361.txt Message-ID: <20070225225501.81FC01E4007@bag.python.org> Author: thomas.wouters Date: Sun Feb 25 23:54:58 2007 New Revision: 53923 Modified: peps/trunk/pep-0361.txt Log: Update warn-for-py3k list after review of py3k changelist. Modified: peps/trunk/pep-0361.txt ============================================================================== --- peps/trunk/pep-0361.txt (original) +++ peps/trunk/pep-0361.txt Sun Feb 25 23:54:58 2007 @@ -102,6 +102,7 @@ * float args to PyArgs_ParseTuple * float args to xrange * coerce and all its friends + * comparing by default comparison * __cmp__? * other comparison changes? * int division? @@ -110,9 +111,18 @@ * using zip() result as a list * input() * apply() - * xreadlines + * reduce() + * the exec statement (use function syntax) + * file.xreadlines * function attributes that start with func_* (should use __*__) * softspace removal for print() function + * the L prefix for long literals + * removal of the sets module + * renaming of __nonzero__ to __bool__ + * multiple inheritance with classic classes? (MRO might change) + * properties and classic classes? (instance attrs shadow property) + + - use __bool__ method if available and there's no __nonzero__ - with/as will be keywords From python-checkins at python.org Sun Feb 25 23:57:12 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 25 Feb 2007 23:57:12 +0100 (CET) Subject: [Python-checkins] r53924 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/pep362_py3k_fodder.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070225225712.90EFC1E4007@bag.python.org> Author: brett.cannon Date: Sun Feb 25 23:57:08 2007 New Revision: 53924 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/pep362_py3k_fodder.py sandbox/trunk/pep362/test_pep362.py Log: Rewrite Signature.__init__ since 'inspect' cannot handle keyword-only arguments. This means that tuples are once again not supported (at the moment). Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sun Feb 25 23:57:08 2007 @@ -1,5 +1,4 @@ -import inspect - +from inspect import getargspec class BindError(TypeError): """Represent a failure of inspect.Signature.bind() being able to to @@ -50,22 +49,21 @@ self.has_annotation = True self.annotation = annotation - @classmethod - def __tuple2param(self, tuple_): + def _tuple2param(self, tuple_): if not isinstance(tuple_, tuple): return str(tuple_) elif len(tuple_) == 1: return "(" + str(tuple_[0]) +",)" else: return ('(' + - ', '.join(self.__tuple2param(x) for x in tuple_) + + ', '.join(self._tuple2param(x) for x in tuple_) + ')') def __str__(self): """Return the string representation of the parameter as it would look in a function's signature.""" if isinstance(self.name, tuple): - result = self.__tuple2param(self.name) + result = self._tuple2param(self.name) else: result = self.name if self.has_default: @@ -85,58 +83,75 @@ self.name = func.__name__ - argspec = inspect.getargspec(func) - - # Variable parameters. - self.var_args = argspec[1] if (argspec[1] is not None) else '' - self.var_kw_args = argspec[2] if (argspec[2] is not None) else '' - self.var_annotations = {} - for var_arg in (self.var_args, self.var_kw_args): - if var_arg in func.func_annotations: - self.var_annotations[var_arg] = func.func_annotations[var_arg] - - # Non-keyword-only arguments. - arg_count = len(argspec[0]) - defaults_start = (arg_count - len(argspec[3]) - if argspec[3] else arg_count) + argspec = getargspec(func) parameters = [] - for index, arg_name in enumerate(argspec[0]): - kwargs = dict.fromkeys(('has_default', 'default_value', - 'has_annotation', 'annotation'), False) - if isinstance(arg_name, list): - arg_name = self.__list2tuple(arg_name) - - # Default values. - if index >= defaults_start: - kwargs['has_default'] = True - kwargs['default_value'] = argspec[3][index - defaults_start] - # Parameter annotations. - if hasattr(func, 'func_annotations'): - if arg_name in func.func_annotations: - kwargs['has_annotation'] = True - kwargs['annotation'] = func.func_annotations[arg_name] - param = Parameter(arg_name, index, **kwargs) - parameters.append(param) - # Keyword-only arguments. + # Parameter information. + pos_count = func_code.co_argcount if hasattr(func_code, 'co_kwonlyargcount'): - non_keyword_count = func_code.co_argcount - keyword_count = func_code.co_kwonlyargcount - keyword_only_params = func_code.co_varnames[non_keyword_count: - (non_keyword_count+keyword_count)] - for index, param_name in enumerate(keyword_only_params): - kwargs = dict.fromkeys(('has_default', 'default_value', - 'has_annotation', 'annotation'), False) - # Default values. - if func.func_kwdefaults and param_name in func.func_kwdefaults: - kwargs['has_default'] = True - kwargs['default_value'] = func.func_kwdefaults[param_name] - if param_name in func.func_annotations: - kwargs['has_annotation'] = True - kwargs['annotation'] = func.func_annotations[param_name] - parameters.append(Parameter(param_name, - index+non_keyword_count, - keyword_only=True, **kwargs)) + keyword_only_count = func_code.co_kwonlyargcount + else: + keyword_only_count = 0 + positional = func_code.co_varnames[:pos_count] + keyword_only = func_code.co_varnames[pos_count:keyword_only_count] + if func.func_defaults: + pos_default_count = len(func.func_defaults) + else: + pos_default_count = 0 + + # XXX Use inspect where tuple parameters are possible. + # Non-keyword-only parameters w/o defaults. + non_default_count = pos_count - pos_default_count + for index, name in enumerate(positional[:non_default_count]): + has_annotation, annotation = self._find_annotation(func, name) + param = Parameter(name, index, has_default=False, + has_annotation=has_annotation, annotation=annotation) + parameters.append(param) + # ... w/ defaults. + for offset, name in enumerate(positional[non_default_count:]): + has_annotation, annotation = self._find_annotation(func, name) + default_value = func.func_defaults[offset] + param = Parameter(name, offset+non_default_count, + has_default=True, default_value=default_value, + has_annotation=has_annotation, + annotation=annotation) + parameters.append(param) + # Keyword-only parameters. + for offset, name in enumerate(keyword_only): + has_annotation, annotation = self._find_annotation(func, name) + has_default, default_value = False, None + if func.func_kwdefaults and name in func.func_kwdefaults: + has_default = True + default_value = func.func_kwdefaults[name] + param = Parameter(name, offset+pos_count, keyword_only=True, + has_default=has_default, + default_value=default_value, + has_annotation=has_annotation, + annotation=annotation) + parameters.append(param) + # Variable parameters. + index = pos_count + keyword_only_count + self.var_annotations = dict() + if func_code.co_flags & 0x04: + self.var_args = func_code.co_varnames[index] + has_annotation, annotation = self._find_annotation(func, + self.var_args) + if has_annotation: + self.var_annotations[self.var_args] = ( + func.func_annotations[self.var_args]) + index += 1 + else: + self.var_args = '' + if func_code.co_flags & 0x08: + self.var_kw_args = func_code.co_varnames[index] + has_annotation, annotation = self._find_annotation(func, + self.var_args) + if has_annotation: + self.var_annotations[self.var_kw_args] = ( + func.func_annotations[self.var_kw_args]) + index += 1 + else: + self.var_kw_args = '' self.parameters = tuple(parameters) @@ -147,12 +162,21 @@ self.has_annotation = True self.annotation = func.func_annotations['return'] - @classmethod - def __list2tuple(cls, list_): + def _find_annotation(self, func, name): + """Return True if an annotation exists for the named parameter along + with its annotation, else return False and None.""" + has_annotation, annotation = False, None + if hasattr(func, 'func_annotations'): + if name in func.func_annotations: + has_annotation = True + annotation = func.func_annotations[name] + return has_annotation, annotation + + def _list2tuple(self, list_): if not isinstance(list_, list): return list_ else: - return tuple(cls.__list2tuple(x) for x in list_) + return tuple(cls._list2tuple(x) for x in list_) def __str__(self): """String representation of a signature as one might write it in source @@ -233,15 +257,15 @@ % key) if key in positional_dict: del positional_dict[key] + # Keyword-only. elif key in keyword_only: del keyword_only[key] + # **kwargs. + elif self.var_kw_args: + bindings[self.var_kw_args][key] = value + continue else: - # **kwargs. - if self.var_kw_args: - bindings[self.var_kw_args] = kwargs - break - else: - raise BindError("too many keyword arguments") + raise BindError("too many keyword arguments") bindings[key] = value del kwargs[key] # Keyword-only default values. Modified: sandbox/trunk/pep362/pep362_py3k_fodder.py ============================================================================== --- sandbox/trunk/pep362/pep362_py3k_fodder.py (original) +++ sandbox/trunk/pep362/pep362_py3k_fodder.py Sun Feb 25 23:57:08 2007 @@ -21,4 +21,4 @@ def all_args(a:int, (b, (c,)), d=0, (e, (f,))=(0, (0,)), *args:int, g:int, h:int=8, **kwargs:int) -> int: - pass + return a, b, c, d, e, f, g, h, args, kwargs Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Sun Feb 25 23:57:08 2007 @@ -110,7 +110,7 @@ self.failUnless(param.has_default) self.failUnlessEqual(42, param.default_value) - def test_parameter_tuple(self): + def XXX_test_parameter_tuple(self): # A function with a tuple as a parameter should work. sig = pep362.Signature(pep362_fodder.tuple_args) self.failUnlessEqual('tuple_args', sig.name) @@ -121,7 +121,7 @@ self.failUnless(not param.has_default) self.failUnless(not hasattr(param, 'default_value')) - def test_parameter_tuple_default(self): + def XXX_test_parameter_tuple_default(self): # A default argument for a tuple parameter needs to work. sig = pep362.Signature(pep362_fodder.default_tuple_args) self.failUnlessEqual('default_tuple_args', sig.name) @@ -265,7 +265,7 @@ self.failUnlessRaises(pep362.BindError, sig.bind, a=0, b=1) self.failUnlessRaises(pep362.BindError, sig.bind, b=1) - def test_tuple_parameter(self): + def XXX_test_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.tuple_args) arg = (1, ((2,),)) binding = sig.bind(arg) @@ -273,7 +273,7 @@ self.failUnlessRaises(pep362.BindError, sig.bind, (1,2,3)) self.failUnlessRaises(pep362.BindError, sig.bind, (1, 2)) - def test_default_tuple_parameter(self): + def XXX_test_default_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.default_tuple_args) binding = sig.bind() self.failUnlessEqual({'a':1, 'b':2}, binding) @@ -281,7 +281,7 @@ binding = sig.bind(arg) self.failUnlessEqual({'a':0, 'b':1}, binding) - def test_all_parameter_types(self): + def XXX_test_all_parameter_types(self): sig = pep362.Signature(pep362_fodder.all_args) binding = sig.bind(0, (1, (2,)), d=3, i=7) expected = {'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':tuple(), @@ -306,11 +306,11 @@ self.failUnlessRaises(pep362.BindError, sig.bind, 1) @py3k_test - def test_all_args(self): + def XXX_test_all_args(self): sig = pep362.Signature(pep362_py3k_fodder.all_args) binding = sig.bind(0, (1, (2,)), 3, (4, (5,)), 6, g=7, i=9) expected = {'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':7, 'h':8, - 'i':9, 'args':(6,)} + 'args':(6,), 'kwargs':{'i':9}} self.failUnlessEqual(binding, expected) def test_too_many_arguments(self): From python-checkins at python.org Sun Feb 25 23:59:40 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 25 Feb 2007 23:59:40 +0100 (CET) Subject: [Python-checkins] r53925 - sandbox/trunk/pep362/pep362.py Message-ID: <20070225225940.558E01E4007@bag.python.org> Author: brett.cannon Date: Sun Feb 25 23:59:37 2007 New Revision: 53925 Modified: sandbox/trunk/pep362/pep362.py Log: Remove __str__ support. Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Sun Feb 25 23:59:37 2007 @@ -49,27 +49,6 @@ self.has_annotation = True self.annotation = annotation - def _tuple2param(self, tuple_): - if not isinstance(tuple_, tuple): - return str(tuple_) - elif len(tuple_) == 1: - return "(" + str(tuple_[0]) +",)" - else: - return ('(' + - ', '.join(self._tuple2param(x) for x in tuple_) + - ')') - - def __str__(self): - """Return the string representation of the parameter as it would look - in a function's signature.""" - if isinstance(self.name, tuple): - result = self._tuple2param(self.name) - else: - result = self.name - if self.has_default: - result+= "=" + str(self.default_value) - return result - class Signature(object): @@ -92,7 +71,8 @@ keyword_only_count = func_code.co_kwonlyargcount else: keyword_only_count = 0 - positional = func_code.co_varnames[:pos_count] + #positional = func_code.co_varnames[:pos_count] + positional = argspec[0] keyword_only = func_code.co_varnames[pos_count:keyword_only_count] if func.func_defaults: pos_default_count = len(func.func_defaults) @@ -178,22 +158,6 @@ else: return tuple(cls._list2tuple(x) for x in list_) - def __str__(self): - """String representation of a signature as one might write it in source - code.""" - result = "%s(" % self.name - result += ", ".join(str(param) for param in self.parameters) - if self.var_args: - if self.parameters: - result +=", " - result += "*%s" % self.var_args - if self.var_kw_args: - if self.parameters or self.var_args: - result += ", " - result += "**%s" % self.var_kw_args - result += ")" - return result - def bind(self, *args, **kwargs): """Return a dictionary mapping function arguments to their parameter variables, if possible. From buildbot at python.org Mon Feb 26 00:04:38 2007 From: buildbot at python.org (buildbot at python.org) Date: Sun, 25 Feb 2007 23:04:38 +0000 Subject: [Python-checkins] buildbot warnings in x86 W2k 2.5 Message-ID: <20070225230438.957601E4007@bag.python.org> The Buildbot has detected a new failure of x86 W2k 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520W2k%25202.5/builds/47 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.wouters Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket_ssl sincerely, -The Buildbot From python-checkins at python.org Mon Feb 26 01:35:12 2007 From: python-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 01:35:12 +0100 (CET) Subject: [Python-checkins] r53927 - peps/trunk/pep-0000.txt peps/trunk/pep-3103.txt Message-ID: <20070226003512.711CA1E4011@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 01:35:06 2007 New Revision: 53927 Modified: peps/trunk/pep-0000.txt peps/trunk/pep-3103.txt Log: Reject PEP 3103 (switch/case statement). Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Mon Feb 26 01:35:06 2007 @@ -112,7 +112,6 @@ S 362 Function Signature Object Cannon, Seo S 754 IEEE 754 Floating Point Special Values Warnes S 3101 Advanced String Formatting Talin - S 3103 A Switch/Case Statement GvR S 3104 Access to Names in Outer Scopes Yee I 3108 Standard Library Reorganization Cannon @@ -248,6 +247,7 @@ SW 359 The "make" Statement Bethard SR 363 Syntax For Dynamic Attribute Access North SR 666 Reject Foolish Indentation Creighton + SR 3103 A Switch/Case Statement GvR Numerical Index @@ -447,7 +447,7 @@ I 3100 Python 3.0 Plans Kuchling, Cannon S 3101 Advanced String Formatting Talin SA 3102 Keyword-Only Arguments Talin - S 3103 A Switch/Case Statement GvR + SR 3103 A Switch/Case Statement GvR S 3104 Access to Names in Outer Scopes Yee SF 3105 Make print a function Brandl S 3106 Revamping dict.keys(), .values() and .items() GvR Modified: peps/trunk/pep-3103.txt ============================================================================== --- peps/trunk/pep-3103.txt (original) +++ peps/trunk/pep-3103.txt Mon Feb 26 01:35:06 2007 @@ -3,7 +3,7 @@ Version: $Revision$ Last-Modified: $Date$ Author: guido at python.org (Guido van Rossum) -Status: Draft +Status: Rejected Type: Standards Track Python-Version: 3.0 Content-Type: text/x-rst @@ -11,6 +11,13 @@ Post-History: 26-Jun-2006 +Rejection Notice +================ + +A quick poll during my keynote presentation at PyCon 2007 shows this +proposal has no popular support. I therefore reject it. + + Abstract ======== From python-checkins at python.org Mon Feb 26 14:51:31 2007 From: python-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 14:51:31 +0100 (CET) Subject: [Python-checkins] r53935 - python/trunk/Objects/stringobject.c Message-ID: <20070226135131.4D96A1E4006@bag.python.org> Author: georg.brandl Date: Mon Feb 26 14:51:29 2007 New Revision: 53935 Modified: python/trunk/Objects/stringobject.c Log: Backport from Py3k branch: fix refleak in PyString_Format. Modified: python/trunk/Objects/stringobject.c ============================================================================== --- python/trunk/Objects/stringobject.c (original) +++ python/trunk/Objects/stringobject.c Mon Feb 26 14:51:29 2007 @@ -4767,10 +4767,13 @@ reslen += rescnt; if (reslen < 0) { Py_DECREF(result); + Py_XDECREF(temp); return PyErr_NoMemory(); } - if (_PyString_Resize(&result, reslen) < 0) + if (_PyString_Resize(&result, reslen) < 0) { + Py_XDECREF(temp); return NULL; + } res = PyString_AS_STRING(result) + reslen - rescnt; } @@ -4821,6 +4824,7 @@ if (dict && (argidx < arglen) && c != '%') { PyErr_SetString(PyExc_TypeError, "not all arguments converted during string formatting"); + Py_XDECREF(temp); goto error; } Py_XDECREF(temp); From python-checkins at python.org Mon Feb 26 14:51:35 2007 From: python-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 14:51:35 +0100 (CET) Subject: [Python-checkins] r53936 - python/branches/release25-maint/Objects/stringobject.c Message-ID: <20070226135135.8431C1E4006@bag.python.org> Author: georg.brandl Date: Mon Feb 26 14:51:34 2007 New Revision: 53936 Modified: python/branches/release25-maint/Objects/stringobject.c Log: Backport from Py3k branch: fix refleak in PyString_Format. (backport from rev. 53935) Modified: python/branches/release25-maint/Objects/stringobject.c ============================================================================== --- python/branches/release25-maint/Objects/stringobject.c (original) +++ python/branches/release25-maint/Objects/stringobject.c Mon Feb 26 14:51:34 2007 @@ -4764,10 +4764,13 @@ reslen += rescnt; if (reslen < 0) { Py_DECREF(result); + Py_XDECREF(temp); return PyErr_NoMemory(); } - if (_PyString_Resize(&result, reslen) < 0) + if (_PyString_Resize(&result, reslen) < 0) { + Py_XDECREF(temp); return NULL; + } res = PyString_AS_STRING(result) + reslen - rescnt; } @@ -4818,6 +4821,7 @@ if (dict && (argidx < arglen) && c != '%') { PyErr_SetString(PyExc_TypeError, "not all arguments converted during string formatting"); + Py_XDECREF(temp); goto error; } Py_XDECREF(temp); From python-checkins at python.org Mon Feb 26 16:29:05 2007 From: python-checkins at python.org (brett.cannon) Date: Mon, 26 Feb 2007 16:29:05 +0100 (CET) Subject: [Python-checkins] r53940 - sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Message-ID: <20070226152905.728871E4006@bag.python.org> Author: brett.cannon Date: Mon Feb 26 16:29:03 2007 New Revision: 53940 Modified: sandbox/trunk/pep362/pep362.py sandbox/trunk/pep362/test_pep362.py Log: Expand worst-case tests to thoroughly check every parameter. Also fix a Signature.bind bug that was subsequently found. This means the code finally works (both in 2.6 and 3.0). Modified: sandbox/trunk/pep362/pep362.py ============================================================================== --- sandbox/trunk/pep362/pep362.py (original) +++ sandbox/trunk/pep362/pep362.py Mon Feb 26 16:29:03 2007 @@ -52,7 +52,23 @@ class Signature(object): - """Object to represent the signature of a function/method.""" + """Object to represent the signature of a function/method. + + Attributes: + * parameters + Sequence of Parameter objects. + * name + Name of the function/method. + * var_args + Name of the variable positional parameter, else ''. + * var_kw_wargs + Name of the variable keywrod parameter, else ''. + * var_annotations + Dict keyed on the variable parameter names with the values of the + annotation for the parameter. If an annotation does not exist for a + parameter, the key does not exist. + + """ def __init__(self, func): """Initialize from a function or method object.""" @@ -62,7 +78,7 @@ self.name = func.__name__ - argspec = getargspec(func) + argspec = getargspec(func) # Needed only for tuple parameters. parameters = [] # Parameter information. @@ -71,24 +87,25 @@ keyword_only_count = func_code.co_kwonlyargcount else: keyword_only_count = 0 - #positional = func_code.co_varnames[:pos_count] positional = argspec[0] - keyword_only = func_code.co_varnames[pos_count:keyword_only_count] + keyword_only = func_code.co_varnames[pos_count: + pos_count+keyword_only_count] if func.func_defaults: pos_default_count = len(func.func_defaults) else: pos_default_count = 0 - # XXX Use inspect where tuple parameters are possible. # Non-keyword-only parameters w/o defaults. non_default_count = pos_count - pos_default_count for index, name in enumerate(positional[:non_default_count]): + name = self._convert_name(name) has_annotation, annotation = self._find_annotation(func, name) param = Parameter(name, index, has_default=False, has_annotation=has_annotation, annotation=annotation) parameters.append(param) # ... w/ defaults. for offset, name in enumerate(positional[non_default_count:]): + name = self._convert_name(name) has_annotation, annotation = self._find_annotation(func, name) default_value = func.func_defaults[offset] param = Parameter(name, offset+non_default_count, @@ -152,11 +169,11 @@ annotation = func.func_annotations[name] return has_annotation, annotation - def _list2tuple(self, list_): - if not isinstance(list_, list): - return list_ + def _convert_name(self, name): + if not isinstance(name, list): + return name else: - return tuple(cls._list2tuple(x) for x in list_) + return tuple(self._convert_name(x) for x in name) def bind(self, *args, **kwargs): """Return a dictionary mapping function arguments to their parameter @@ -184,17 +201,18 @@ if not self.parameters and args and self.var_args: bindings[self.var_args] = args args = tuple() - for index, position_arg in enumerate(args): + for index, position_arg in enumerate(args[:]): try: param = positional.pop(0) except IndexError: # *args. if self.var_args: - bindings[self.var_args] = tuple(args[index-1:]) + bindings[self.var_args] = tuple(args) break else: raise BindError("too many positional arguments") self._tuple_bind(bindings, param.name, position_arg) + args = args[1:] # Keyword arguments & default values. else: for positional_param in positional: Modified: sandbox/trunk/pep362/test_pep362.py ============================================================================== --- sandbox/trunk/pep362/test_pep362.py (original) +++ sandbox/trunk/pep362/test_pep362.py Mon Feb 26 16:29:03 2007 @@ -44,6 +44,7 @@ self.failUnlessEqual(param.default_value, default_value) param = pep362.Parameter('_', 0, False) self.failUnlessEqual(param.has_default, False) + self.failUnless(not hasattr(param, 'default_value')) def test_keyword_only(self): # Setting the value for keyword_only should create an attribute. @@ -110,7 +111,7 @@ self.failUnless(param.has_default) self.failUnlessEqual(42, param.default_value) - def XXX_test_parameter_tuple(self): + def test_parameter_tuple(self): # A function with a tuple as a parameter should work. sig = pep362.Signature(pep362_fodder.tuple_args) self.failUnlessEqual('tuple_args', sig.name) @@ -121,7 +122,7 @@ self.failUnless(not param.has_default) self.failUnless(not hasattr(param, 'default_value')) - def XXX_test_parameter_tuple_default(self): + def test_parameter_tuple_default(self): # A default argument for a tuple parameter needs to work. sig = pep362.Signature(pep362_fodder.default_tuple_args) self.failUnlessEqual('default_tuple_args', sig.name) @@ -265,7 +266,7 @@ self.failUnlessRaises(pep362.BindError, sig.bind, a=0, b=1) self.failUnlessRaises(pep362.BindError, sig.bind, b=1) - def XXX_test_tuple_parameter(self): + def test_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.tuple_args) arg = (1, ((2,),)) binding = sig.bind(arg) @@ -273,7 +274,7 @@ self.failUnlessRaises(pep362.BindError, sig.bind, (1,2,3)) self.failUnlessRaises(pep362.BindError, sig.bind, (1, 2)) - def XXX_test_default_tuple_parameter(self): + def test_default_tuple_parameter(self): sig = pep362.Signature(pep362_fodder.default_tuple_args) binding = sig.bind() self.failUnlessEqual({'a':1, 'b':2}, binding) @@ -281,8 +282,31 @@ binding = sig.bind(arg) self.failUnlessEqual({'a':0, 'b':1}, binding) - def XXX_test_all_parameter_types(self): + def test_all_args(self): sig = pep362.Signature(pep362_fodder.all_args) + # a, (b, (c,)), d=0, (e, (f,))=(4, (5,)), *g, **h + # name, position, has_default, default value + expect = (('a', 0, False, None), + (('b', ('c',)), 1, False, None), + ('d', 2, True, 0), + (('e', ('f',)), 3, True, (4, (5,)))) + self.failUnlessEqual(len(sig.parameters), len(expect)) + for param, check in zip(sig.parameters, expect): + name, pos, has_default, default_value = check + self.failUnlessEqual(param.name, name) + self.failUnlessEqual(param.position, pos) + if has_default: + self.failUnless(param.has_default) + self.failUnlessEqual(param.default_value, default_value) + else: + self.failUnless(not param.has_default) + self.failUnless(not hasattr(param, 'default_value')) + self.failUnless(not param.keyword_only) + self.failUnless(not param.has_annotation) + self.failUnless(not hasattr(param, 'annotation')) + self.failUnlessEqual(sig.var_args, 'g') + self.failUnlessEqual(sig.var_kw_args, 'h') + self.failUnlessEqual(len(sig.var_annotations), 0) binding = sig.bind(0, (1, (2,)), d=3, i=7) expected = {'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':tuple(), 'h':{'i':7}} @@ -306,8 +330,46 @@ self.failUnlessRaises(pep362.BindError, sig.bind, 1) @py3k_test - def XXX_test_all_args(self): + def test_all_py3k_args(self): + # a, (b, (c,)), d=0, (e, (f,))=(0, (0,)), *args, g, h=8, **kwargs sig = pep362.Signature(pep362_py3k_fodder.all_args) + # name, position, kw only, has_default, default, has anno, anno + expected = (('a', 0, False, False, None, True, int), + (('b', ('c',)), 1, False, False, None, False, None), + ('d', 2, False, True, 0, False, None), + (('e', ('f',)), 3, False, True, (0, (0,)), False, None), + ('g', 4, True, False, None, True, int), + ('h', 5, True, True, 8, True, int)) + self.failUnlessEqual(len(sig.parameters), len(expected), + "len(%r) != len(%r)" % ([param.name + for param in sig.parameters], + [expect[0] for expect in expected])) + for param, check in zip(sig.parameters, expected): + name, pos, kw_only, has_default, default, has_anno, anno = check + self.failUnlessEqual(param.name, name) + self.failUnlessEqual(param.position, pos) + if kw_only: + self.failUnless(param.keyword_only) + else: + self.failUnless(not param.keyword_only) + if has_default: + self.failUnless(param.has_default) + self.failUnlessEqual(param.default_value, default) + else: + self.failUnless(not param.has_default) + self.failUnless(not hasattr(param, 'default_value')) + if has_anno: + self.failUnless(param.has_annotation) + self.failUnlessEqual(param.annotation, anno) + else: + self.failUnless(not param.has_annotation) + self.failUnless(not hasattr(param, 'annotation')) + self.failUnlessEqual(sig.var_args, 'args') + self.failUnless(sig.var_args in sig.var_annotations) + self.failUnlessEqual(sig.var_annotations[sig.var_args], int) + self.failUnlessEqual(sig.var_kw_args, 'kwargs') + self.failUnless(sig.var_kw_args in sig.var_annotations) + self.failUnlessEqual(sig.var_annotations[sig.var_kw_args], int) binding = sig.bind(0, (1, (2,)), 3, (4, (5,)), 6, g=7, i=9) expected = {'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':7, 'h':8, 'args':(6,), 'kwargs':{'i':9}} From python-checkins at python.org Mon Feb 26 16:30:54 2007 From: python-checkins at python.org (brett.cannon) Date: Mon, 26 Feb 2007 16:30:54 +0100 (CET) Subject: [Python-checkins] r53941 - peps/trunk/pep-0362.txt Message-ID: <20070226153054.78B641E4018@bag.python.org> Author: brett.cannon Date: Mon Feb 26 16:30:51 2007 New Revision: 53941 Modified: peps/trunk/pep-0362.txt Log: Update the PEP to be in line with the working implementation. Modified: peps/trunk/pep-0362.txt ============================================================================== --- peps/trunk/pep-0362.txt (original) +++ peps/trunk/pep-0362.txt Mon Feb 26 16:30:51 2007 @@ -17,49 +17,54 @@ Python has always supported powerful introspection capabilities, including that for functions and methods (for the rest of this PEP the word "function" refers to both functions and methods). Taking a -function object, you can fully reconstruct the function's signature -using ``func_defaults``, ``func_code.co_argcount``, -``func_code.co_flags``, and ``func_code.co_varnames``. Unfortunately -it is a little unruly having to look at four different attributes -to pull together complete information for a function's signature. +function object, you can fully reconstruct the function's signature. +Unfortunately it is a little unruly having to look at all the +different attributes to pull together complete information for a +function's signature. This PEP proposes an object representation for function signatures. -This should help facilitate introspection on functions. It also helps -for introspection for decorators that wrap the function they are -applied to by allowing the wrapped function's signature object be set -for the wrapping function. +This should help facilitate introspection on functions for various +usese (e.g., decorators). The introspection information contains all +possible information about the parameters in a signature (including +Python 3.0 features). Signature Object ================ The overall signature of an object is represented by the Signature -object. This object is to store a `Parameter Object`_ for each +object. This object is to store a `Parameter object`_ for each parameter in the signature. It is also to store any information about the function itself that is pertinent to the signature. A Signature object has the following structure attributes: -* name:str +* name : str Name of the function. This is not fully qualified because function objects for methods do not know the class they are contained within. This makes functions and methods indistinguishable from one another when passed to decorators, preventing proper creation of a fully qualified name. -* var_args:str - Name of the ``*args`` parameter, if present, or the empty - string. -* var_kw_args:str - Name of the ``**kwargs`` parameter, if present, or the empty - string. -* parameters:list(Parameter) +* var_args : str + Name of the variable positional parameter (i.e., ``*args``), if + present, or the empty string. +* var_kw_args : str + Name of the variable keyword parameter (i.e., ``**kwargs``), if + present, or the empty string. +* var_annotations: dict(str, object) + Dict that contains the annotations for the variable parameters. + The keys are of the variable parameter with values of the + annotation. If an annotation does not exist for a variable + parameter then the key does not exist in the dict. +* parameters : list(Parameter) List of the parameters of the function as represented by - Parameter objects (see `Parameter Object`_). -* __str__() -> str - Return the string representation of the signature as it might - appear in source code. -* bind(\*args, \*\*kwargs) -> dict - Create a mapping from parameter to argument for the signature. + Parameter objects in the order of its definition (keyword-only + arguments are in the order listed by ``code.co_varnames``). +* bind(\*args, \*\*kwargs) -> dict(str, Parameter) + Create a mapping from arguments to parameters. The keys are the + names of the parameter that an argument maps to with the value + being the value the parameter would have if this function was + called with the given arguments. The Signature object is stored in the ``__signature__`` attribute of the function. When it is to be created is discussed in @@ -69,167 +74,105 @@ Parameter Object ================ -A function's signature is partially made up of several parameters. -Python's different kinds of parameters is quite large and rich and -continues to grow. This means that Parameter objects require they -represent any possible parameter. +A function's signature is made up of several parameters. Python's +different kinds of parameters is quite large and rich and continues to +grow. Parameter objects represent any possible parameter. Originally the plan was to represent parameters using a list of parameter names on the Signature object along with various dicts keyed -on parameter names to disseminate the various possible pieces of -information one can know about a parameter. But the decision was made -to incorporate all information about a parameter in a single argument -so as to make extending the information easier. This was originally -put forth by Talin and the preferred form of Guido (as discussed at -the 2006 Google Sprint). +on parameter names to disseminate the various pieces of information +one can know about a parameter. But the decision was made to +incorporate all information about a parameter in a single object so +as to make extending the information easier. This was originally put +forth by Talin and the preferred form of Guido (as discussed at the +2006 Google Sprint). The structure of the Parameter object is: -* name:(str | tuple(str)) +* name : (str | tuple(str)) The name of the parameter as a string if it is not a tuple. If - the argument is a tuple, use a tuple of strings where each item is - the name of the parameter contained within the tuple. -* position:int + the argument is a tuple then a tuple of strings is used. +* position : int The position of the parameter within the signature of the - function (zero-indexed). -* has_default:bool + function (zero-indexed). For keyword-only parameters the position + value is arbitrary while not conflicting with positional + parameters. The suggestion of setting the attribute to None or -1 + to represent keyword-only parameters was rejected to prevent + variable type usage and as a possible point of errors, + respectively. +* has_default : bool True if the parameter has a default value, else False. -* default_value:object +* default_value : object The default value for the parameter, if present, else the attribute does not exist. This is done so that the attribute is not accidentally used if no default value is set as any default value could be a legitimate default value itself. -* __str__() -> str - Return the string representation of the parameter as it might - appear in source code in a function signature. +* keyword_only : bool + True if the parameter is keyword-only, else False. +* has_annotation : bool + True if the parameter has an annotation, else False. +* annotation + Set to the annotation for the parameter. If ``has_annotation`` is + False then the attribute does not exist to prevent accidental use. Implementation ============== -An implementation can be found in patch #1544909 [#impl]_. It -modifies the 'inspect' module [#inspect-module]_to include the -implementation. There is a function named ``getsignature()`` which -returns the value stored on the ``__signature__`` attribute (for -methods this is stored directly on the im_func function object since -that is what decorators will work with). - -For the `Open Issues`_ question of how to handle tuples, the current -implementation does the best it can to determine if the argument will -unpack properly, raising TypeError if it cannot reliably prove either -way if the argument can be unpacked. - - -Relation To Other PEPs -====================== - -Keyword-Only Arguments [#pep-3102]_ ------------------------------------- - -If keyword-only parameters come into existence, the Parameter object -will require modification. A ``keyword_only`` attribute will be added -that holds a boolean representing whether the parameter is -keyword-only or not. - -Nick Coghlan suggested to set 'position' to None to signal that the -argument is keyword-only and thus remove the need for the new -attribute. But that would cause different types to be used in the -attribute that are in no way compatible. It also removes the ability -to know the position number within the signature from the Paramter -object itself. Plus Guido preferred the original approach over this -alternative. This does mean, though, that how to set the position of -an argument when ``*args`` is not at the end of the parameter list. - - -Function Annotations [#pep-3107]_ ----------------------------------- - -Support needs to be added for function annotations. One option is to -have two new attributes for each Parameter object: ``has_annotation`` -and ``annotation``. This would remove any possible ambiguity in -terms of what an annotation could be. - -But one could argue that the chances of someone setting an annotation -to ``None`` is very low and thus allows it to be used as a value -for a single ``annotation`` attribute to signify that no annotation -was set. But there is the slight issue of breaking from consistency -compared to ``has_default``/``default_value``. - -Regardless of which approach is taken, Signature objects will also -need to gain support for annotations for ``*args`` and ``**kwargs``. +An implementation can be found in Python's sandbox [#impl]_. +There is a function named ``signature()`` which +returns the value stored on the ``__signature__`` attribute if it +exists, else it creates it bound to the Signature object for the +function. For methods this is stored directly on the im_func function +object since that is what decorators will work with. Open Issues =========== -When to construct the Parameter object? +When to construct the Signature object? --------------------------------------- -The Parameter object can either be created in an eager or lazy +The Signature object can either be created in an eager or lazy fashion. In the eager situation, the object can be created during creation of the function object. In the lazy situation, one would -pass a function object to ``inspect.getsignature()`` and that would -generate the Signature object and store it to ``__signature__`` if +pass a function object to a function and that would generate the +Signature object and store it to ``__signature__`` if needed, and then return the value of ``__signature__``. -How to handle tuples for ``Signature.bind()``? ----------------------------------------------- - -Tuples pose an interesting problem for generating the mapping from -arguments to parameters. If one wants ``Signature.bind()`` to do the -full mapping, then the unpacking of an argument tuple's values must be -done and then have those values bound to the proper parameter. This -could be a problem since this would require using the iterator to -verify the binding and thus could possibly make the iterator worthless -for actual use in a function call later. - -But if one wants parameters to be based on what is a single positional -argument, then the tuple should not be unpacked. This means that for -tuples one can do the best they can to verify that the argument will -unpack properly without running an iterator. But if an object is -passed in that does not define ``__len__()`` and ``__getitem__()`` for -verifying unpacking, then one can either just assume that if it -defines ``__iter__()`` it might be okay, or raise an exception stating -that the binding could not be calculated with full confidence. - - -How should ``Signature.bind`` handle ``*args`` and ``**kwargs``? ------------------------------------------------------------------- - -There are two possible approaches to how ``*args`` and ``**kwargs`` -should be returned by ``Signature.bind``. One is to have their -names as keys in the dictionary and their values be the list and -dictionary that would be created. Another is to have ``bind`` -return a three-item tuple of the parameters and their values, what -the ``*args`` value would be bound to, and a dict of what -``**kwargs`` would be set to. - - Should ``Signature.bind`` return Parameter objects as keys? ----------------------------------------------------------- Instead of returning a dict with keys consisting of the name of the -parameters, would it be more useful to instead return Parameter -objects? The name of the argument can easily be retrieved. It also -removes any need of having to map parameter name to the Parameter -object if that is desired. +parameters, would it be more useful to instead use Parameter +objects? The name of the argument can easily be retrieved from the +key (and the name would be used as the hash for a Parameter object). + + +Provide a mapping of parameter name to Parameter object? +-------------------------------------------------------- + +While providing access to the parameters in order is handy, it might +also be beneficial to provide a way to retrieve Parameter objects from +a Signature object based on the parameter's name. Which style of +access (sequential/iteration or mapping) will influence how the +parameters are stored internally and whether __getitem__ accepts +strings or integers. + +One possible compromise is to have ``__getitem__`` provide mapping +support and have ``__iter__`` return Parameter objects based on their +``position`` attribute. This allows for getting the sequence of +Parameter objects easily by using the ``__iter__`` method on Signature +object along with the sequence constructor (e.g., ``list`` or +``tuple``). References ========== -.. [#inspect-module] ``inspect`` -- Inspect live objects - (http://docs.python.org/lib/module-inspect.html) - -.. [#pep-3102] Keyword-Only Arguments - (http://www.python.org/dev/peps/pep-3102/) - -.. [#impl] Implementation of PEP 362 - (http://www.python.org/sf/1544909) - -.. [#pep-3107] Function Annotations - (http://www.python.org/dev/peps/pep-3107/) +.. [#impl] pep362 directory in Python's sandbox + (http://svn.python.org/view/sandbox/trunk/pep362/) Copyright From python-checkins at python.org Mon Feb 26 17:14:55 2007 From: python-checkins at python.org (jeremy.hylton) Date: Mon, 26 Feb 2007 17:14:55 +0100 (CET) Subject: [Python-checkins] r53943 - python/trunk/Python/ceval.c Message-ID: <20070226161455.9F6991E4006@bag.python.org> Author: jeremy.hylton Date: Mon Feb 26 17:14:51 2007 New Revision: 53943 Modified: python/trunk/Python/ceval.c Log: Reformat long lines. Modified: python/trunk/Python/ceval.c ============================================================================== --- python/trunk/Python/ceval.c (original) +++ python/trunk/Python/ceval.c Mon Feb 26 17:14:51 2007 @@ -4115,7 +4115,8 @@ metaclass = (PyObject *) &PyClass_Type; Py_INCREF(metaclass); } - result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, NULL); + result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, + NULL); Py_DECREF(metaclass); if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { /* A type error here likely means that the user passed @@ -4129,7 +4130,8 @@ if (PyString_Check(pvalue)) { PyObject *newmsg; newmsg = PyString_FromFormat( - "Error when calling the metaclass bases\n %s", + "Error when calling the metaclass bases\n" + " %s", PyString_AS_STRING(pvalue)); if (newmsg != NULL) { Py_DECREF(pvalue); From python-checkins at python.org Mon Feb 26 17:44:07 2007 From: python-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 17:44:07 +0100 (CET) Subject: [Python-checkins] r53944 - in sandbox/trunk/2to3: example.py fixer_tests.py fixes/fix_input.py fixes/fix_raw_input.py Message-ID: <20070226164407.28C1E1E4013@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 17:44:06 2007 New Revision: 53944 Added: sandbox/trunk/2to3/fixes/fix_input.py (contents, props changed) sandbox/trunk/2to3/fixes/fix_raw_input.py (contents, props changed) Modified: sandbox/trunk/2to3/example.py sandbox/trunk/2to3/fixer_tests.py Log: Fixers for input() and raw_input() by Andre Roberge, with unittests. Unittest for xrange() -> range() fixer, by Andre Roberge. Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Mon Feb 26 17:44:06 2007 @@ -319,4 +319,12 @@ for i in xrange(0, 100): print i for i in xrange(0, 100, 10): print i +def input_examples(): + a = input() + b = input(str(a)) + +def raw_input_examples(): + a = raw_input() + b = raw_input(a.rstrip()) + # This is the last line. Modified: sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/fixer_tests.py Mon Feb 26 17:44:06 2007 @@ -1057,6 +1057,66 @@ a = "for x in list(h.keys())[0]: print x" self.check(b, a) +class Test_xrange(FixerTestCase): + fixer = "xrange" + + def test_1(self): + b = """x = xrange(10)""" + a = """x = range(10)""" + self.check(b, a) + + def test_2(self): + b = """x = xrange(1, 10)""" + a = """x = range(1, 10)""" + self.check(b, a) + + def test_3(self): + b = """x = xrange(0, 10, 2)""" + a = """x = range(0, 10, 2)""" + self.check(b, a) + + def test_4(self): + b = """for i in xrange(10):\n j=i""" + a = """for i in range(10):\n j=i""" + self.check(b, a) + + +class Test_raw_input(FixerTestCase): + fixer = "raw_input" + + def test_1(self): + b = """x = raw_input()""" + a = """x = input()""" + self.check(b, a) + + def test_2(self): + b = """x = raw_input('')""" + a = """x = input('')""" + self.check(b, a) + + def test_3(self): + b = """x = raw_input('prompt')""" + a = """x = input('prompt')""" + self.check(b, a) + + +class Test_input(FixerTestCase): + fixer = "input" + + def test_1(self): + b = """x = input()""" + a = """x = eval(input())""" + self.check(b, a) + + def test_2(self): + b = """x = input('')""" + a = """x = eval(input(''))""" + self.check(b, a) + + def test_3(self): + b = """x = input('prompt')""" + a = """x = eval(input('prompt'))""" + self.check(b, a) if __name__ == "__main__": Added: sandbox/trunk/2to3/fixes/fix_input.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/fix_input.py Mon Feb 26 17:44:06 2007 @@ -0,0 +1,25 @@ +"""Fixer that changes input(...) into eval(input(...)).""" +# Author: Andre Roberge + +# Local imports +import pytree +import patcomp +from pgen2 import token +from fixes import basefix +from fixes import macros + +class FixInput(basefix.BaseFix): + + PATTERN = """ + power< + 'input' + args=trailer< '(' [any] ')' > + > + """ + + def transform(self, node): + new = node.clone() + new.set_prefix("") + new = macros.Call(macros.Name("eval"), [new]) + new.set_prefix(node.get_prefix()) + return new Added: sandbox/trunk/2to3/fixes/fix_raw_input.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/fix_raw_input.py Mon Feb 26 17:44:06 2007 @@ -0,0 +1,25 @@ +"""Fixer that changes raw_input(...) into input(...).""" +# Author: Andre Roberge + +# Local imports +import pytree +from pgen2 import token +from fixes import basefix +from fixes import macros + +class FixRawInput(basefix.BaseFix): + + PATTERN = """ + power< + 'raw_input' + args=trailer< '(' [any] ')' > + > + """ + + def transform(self, node): + results = self.match(node) + args = results["args"] + new = pytree.Node(self.syms.power, + [macros.Name("input"), args.clone()]) + new.set_prefix(node.get_prefix()) + return new From buildbot at python.org Mon Feb 26 17:47:45 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 16:47:45 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP trunk Message-ID: <20070226164745.3D2541E4012@bag.python.org> The Buildbot has detected a new failure of x86 XP trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%2520trunk/builds/216 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton Build had warnings: warnings failed slave lost sincerely, -The Buildbot From python-checkins at python.org Mon Feb 26 18:01:08 2007 From: python-checkins at python.org (neal.norwitz) Date: Mon, 26 Feb 2007 18:01:08 +0100 (CET) Subject: [Python-checkins] r53947 - python/trunk/Misc/developers.txt Message-ID: <20070226170108.C1F431E4006@bag.python.org> Author: neal.norwitz Date: Mon Feb 26 18:01:08 2007 New Revision: 53947 Modified: python/trunk/Misc/developers.txt Log: Add Steven Bethard to help out with patches. Modified: python/trunk/Misc/developers.txt ============================================================================== --- python/trunk/Misc/developers.txt (original) +++ python/trunk/Misc/developers.txt Mon Feb 26 18:01:08 2007 @@ -17,6 +17,9 @@ Permissions History ------------------- +- Steven Bethard (SF name "bevidiere") added to the SourceForge Python + project 26 Feb 2007, by NCN, as a tracker tech. + - Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python project 06 Jan 2007, by NCN, as a tracker tech. He will maintain asyncore. From python-checkins at python.org Mon Feb 26 18:04:05 2007 From: python-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 18:04:05 +0100 (CET) Subject: [Python-checkins] r53948 - peps/trunk/pep-3100.txt Message-ID: <20070226170405.111AF1E4006@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 18:04:01 2007 New Revision: 53948 Modified: peps/trunk/pep-3100.txt Log: Mark input() -> raw_input() as done (revising the plans). Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Mon Feb 26 18:04:01 2007 @@ -169,6 +169,8 @@ ``zip()``, etc.) [zip is done; Neal Norwitz has a patch for range()] * Relevant functions should consume iterators (e.g. ``min()``, ``max()``) [They already do, since 2.2.] +* Remove ``input()`` and rename ``raw_input()`` to ``input()``. + If you need the old input(), use eval(input()). [done] * Introduce ``trunc()``, which would call the ``__trunc__()`` method on its argument; suggested use is for objects like float where calling ``__int__()`` has data loss, but an integral representation is still desired? [8]_ @@ -182,12 +184,10 @@ * ``compile()``: put in ``sys`` (or perhaps in a module of its own) [2]_ * ``coerce()``: no longer needed [2]_ * ``execfile()``, ``reload()``: use ``exec()`` [2]_ -* ``input()``: use ``eval(sys.stdin.readline())`` [2]_ [done] * ``intern()``: put in ``sys`` [2]_, [22]_ [done] * ``map()``, ``filter()``: use list comprehensions instead??? [1]_, [9]_ (Actually these can stay.) * ``reduce()``: write a loop instead [2]_, [9]_ [done] -* ``raw_input()``: use ``sys.stdin.readline()`` ??? [2]_ [done] * ``xrange()``: use ``range()`` instead [1]_ [See range() above] From python-checkins at python.org Mon Feb 26 18:09:07 2007 From: python-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 18:09:07 +0100 (CET) Subject: [Python-checkins] r53949 - python/trunk/Misc/developers.txt Message-ID: <20070226170907.302B71E4006@bag.python.org> Author: georg.brandl Date: Mon Feb 26 18:09:03 2007 New Revision: 53949 Modified: python/trunk/Misc/developers.txt Log: Fix typo. Modified: python/trunk/Misc/developers.txt ============================================================================== --- python/trunk/Misc/developers.txt (original) +++ python/trunk/Misc/developers.txt Mon Feb 26 18:09:03 2007 @@ -17,7 +17,7 @@ Permissions History ------------------- -- Steven Bethard (SF name "bevidiere") added to the SourceForge Python +- Steven Bethard (SF name "bediviere") added to the SourceForge Python project 26 Feb 2007, by NCN, as a tracker tech. - Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python From python-checkins at python.org Mon Feb 26 18:33:18 2007 From: python-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 18:33:18 +0100 (CET) Subject: [Python-checkins] r53950 - peps/trunk/pep-0358.txt peps/trunk/pep-3100.txt Message-ID: <20070226173318.EEC501E4006@bag.python.org> Author: georg.brandl Date: Mon Feb 26 18:33:15 2007 New Revision: 53950 Modified: peps/trunk/pep-0358.txt peps/trunk/pep-3100.txt Log: Mark a few PEP 3100 items as done, update PEP 358 wrt. bytes literals. Modified: peps/trunk/pep-0358.txt ============================================================================== --- peps/trunk/pep-0358.txt (original) +++ peps/trunk/pep-0358.txt Mon Feb 26 18:33:15 2007 @@ -84,12 +84,10 @@ return new The .__repr__() method returns a string that can be evaluated to - generate a new bytes object containing the same sequence of - integers. The sequence is represented by a list of ints using - hexadecimal notation. For example: + generate a new bytes object containing a bytes literal: - >>> repr(bytes[10, 20, 30]) - 'bytes([0x0a, 0x14, 0x1e])' + >>> bytes([10, 20, 30]) + b'\n\x14\x1e' The object has a .decode() method equivalent to the .decode() method of the str object. The object has a classmethod .fromhex() @@ -98,14 +96,14 @@ example: >>> bytes.fromhex('5c5350ff') - bytes([92, 83, 80, 255]]) + b'\\SP\xff' >>> bytes.fromhex('5c 53 50 ff') - bytes([92, 83, 80, 255]]) + b'\\SP\xff' The object has a .hex() method that does the reverse conversion (similar to binascii.hexlify): - >> bytes([92, 83, 80, 255]]).hex() + >> bytes([92, 83, 80, 255]).hex() '5c5350ff' The bytes object has some methods similar to list method, and @@ -198,8 +196,6 @@ * Should all those list methods really be implemented? - * Now that a b"..." literal exists, shouldn't repr() return one? - * A case could be made for supporting .ljust(), .rjust(), .center() with a mandatory second argument. @@ -219,7 +215,7 @@ Frequently Asked Questions Q: Why have the optional encoding argument when the encode method of - Unicode objects does the same thing. + Unicode objects does the same thing? A: In the current version of Python, the encode method returns a str object and we cannot change that without breaking code. The Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Mon Feb 26 18:33:15 2007 @@ -103,7 +103,7 @@ with __builtin__. Keeping both with confusingly similar spellings and semantics is evil. * Attributes on functions of the form ``func_whatever`` will be renamed - ``__whatever__`` [17]_ + ``__whatever__`` [17]_ [done] * Set literals and comprehensions [19]_ [20]_ [done] {x} means set([x]); {x, y} means set([x, y]). {F(x) for x in S if P(x)} means set(F(x) for x in S if P(x)). @@ -143,10 +143,9 @@ literals with 'L' or 'l' suffix disappear [1]_ [done] * Make all strings be Unicode, and have a separate bytes() type [1]_ The new string type will be called 'str'. -* Return iterators instead of lists where appropriate for atomic type methods +* Return iterable views instead of lists where appropriate for atomic type methods (e.g. ``dict.keys()``, ``dict.values()``, ``dict.items()``, etc.); iter* - methods will be removed. - Better: make keys(), etc. return views ala Java collections??? + methods will be removed. [done] * Make ``string.join()`` stringify its arguments? [18]_ * Fix file() so it returns a ValueError if the mode is bad rather than IOError. (This probably affects lots of places, we should review the exceptions From python-checkins at python.org Mon Feb 26 19:10:49 2007 From: python-checkins at python.org (neal.norwitz) Date: Mon, 26 Feb 2007 19:10:49 +0100 (CET) Subject: [Python-checkins] r53951 - in python/trunk: Parser/asdl_c.py Python/Python-ast.c Message-ID: <20070226181049.A1A7C1E4006@bag.python.org> Author: neal.norwitz Date: Mon Feb 26 19:10:47 2007 New Revision: 53951 Modified: python/trunk/Parser/asdl_c.py python/trunk/Python/Python-ast.c Log: Fix a couple of problems in generating the AST code: * use %r instead of backticks since backticks are going away in Py3k * PyArena_Malloc() already sets PyErr_NoMemory so we don't need to do it again * the signature for ast2obj_int incorrectly used a bool, rather than a long Modified: python/trunk/Parser/asdl_c.py ============================================================================== --- python/trunk/Parser/asdl_c.py (original) +++ python/trunk/Parser/asdl_c.py Mon Feb 26 19:10:47 2007 @@ -47,7 +47,7 @@ # XXX this should be fixed for real if i == -1 and 'GeneratorExp' in cur: i = size + 3 - assert i != -1, "Impossible line %d to reflow: %s" % (size, `s`) + assert i != -1, "Impossible line %d to reflow: %r" % (size, s) lines.append(padding + cur[:i]) if len(lines) == 1: # find new size based on brace @@ -299,10 +299,8 @@ emit('}', 1) emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1); - emit("if (!p) {", 1) - emit("PyErr_NoMemory();", 2) + emit("if (!p)", 1) emit("return NULL;", 2) - emit("}", 1) if union: self.emit_body_union(name, args, attrs) else: @@ -474,7 +472,7 @@ return PyBool_FromLong(b); } -static PyObject* ast2obj_int(bool b) +static PyObject* ast2obj_int(long b) { return PyInt_FromLong(b); } Modified: python/trunk/Python/Python-ast.c ============================================================================== --- python/trunk/Python/Python-ast.c (original) +++ python/trunk/Python/Python-ast.c Mon Feb 26 19:10:47 2007 @@ -440,7 +440,7 @@ return PyBool_FromLong(b); } -static PyObject* ast2obj_int(bool b) +static PyObject* ast2obj_int(long b) { return PyInt_FromLong(b); } @@ -740,10 +740,8 @@ { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Module_kind; p->v.Module.body = body; return p; @@ -754,10 +752,8 @@ { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Interactive_kind; p->v.Interactive.body = body; return p; @@ -773,10 +769,8 @@ return NULL; } p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Expression_kind; p->v.Expression.body = body; return p; @@ -787,10 +781,8 @@ { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Suite_kind; p->v.Suite.body = body; return p; @@ -812,10 +804,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = FunctionDef_kind; p->v.FunctionDef.name = name; p->v.FunctionDef.args = args; @@ -837,10 +827,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ClassDef_kind; p->v.ClassDef.name = name; p->v.ClassDef.bases = bases; @@ -855,10 +843,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Return_kind; p->v.Return.value = value; p->lineno = lineno; @@ -871,10 +857,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Delete_kind; p->v.Delete.targets = targets; p->lineno = lineno; @@ -893,10 +877,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Assign_kind; p->v.Assign.targets = targets; p->v.Assign.value = value; @@ -926,10 +908,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = AugAssign_kind; p->v.AugAssign.target = target; p->v.AugAssign.op = op; @@ -945,10 +925,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Print_kind; p->v.Print.dest = dest; p->v.Print.values = values; @@ -974,10 +952,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = For_kind; p->v.For.target = target; p->v.For.iter = iter; @@ -999,10 +975,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = While_kind; p->v.While.test = test; p->v.While.body = body; @@ -1023,10 +997,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = If_kind; p->v.If.test = test; p->v.If.body = body; @@ -1047,10 +1019,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = With_kind; p->v.With.context_expr = context_expr; p->v.With.optional_vars = optional_vars; @@ -1066,10 +1036,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Raise_kind; p->v.Raise.type = type; p->v.Raise.inst = inst; @@ -1085,10 +1053,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = TryExcept_kind; p->v.TryExcept.body = body; p->v.TryExcept.handlers = handlers; @@ -1104,10 +1070,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = TryFinally_kind; p->v.TryFinally.body = body; p->v.TryFinally.finalbody = finalbody; @@ -1126,10 +1090,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Assert_kind; p->v.Assert.test = test; p->v.Assert.msg = msg; @@ -1143,10 +1105,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Import_kind; p->v.Import.names = names; p->lineno = lineno; @@ -1165,10 +1125,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ImportFrom_kind; p->v.ImportFrom.module = module; p->v.ImportFrom.names = names; @@ -1189,10 +1147,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Exec_kind; p->v.Exec.body = body; p->v.Exec.globals = globals; @@ -1207,10 +1163,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Global_kind; p->v.Global.names = names; p->lineno = lineno; @@ -1228,10 +1182,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Expr_kind; p->v.Expr.value = value; p->lineno = lineno; @@ -1244,10 +1196,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Pass_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1259,10 +1209,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Break_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1274,10 +1222,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Continue_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1295,10 +1241,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = BoolOp_kind; p->v.BoolOp.op = op; p->v.BoolOp.values = values; @@ -1328,10 +1272,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = BinOp_kind; p->v.BinOp.left = left; p->v.BinOp.op = op; @@ -1357,10 +1299,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = UnaryOp_kind; p->v.UnaryOp.op = op; p->v.UnaryOp.operand = operand; @@ -1385,10 +1325,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Lambda_kind; p->v.Lambda.args = args; p->v.Lambda.body = body; @@ -1418,10 +1356,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = IfExp_kind; p->v.IfExp.test = test; p->v.IfExp.body = body; @@ -1437,10 +1373,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Dict_kind; p->v.Dict.keys = keys; p->v.Dict.values = values; @@ -1460,10 +1394,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ListComp_kind; p->v.ListComp.elt = elt; p->v.ListComp.generators = generators; @@ -1483,10 +1415,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = GeneratorExp_kind; p->v.GeneratorExp.elt = elt; p->v.GeneratorExp.generators = generators; @@ -1500,10 +1430,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Yield_kind; p->v.Yield.value = value; p->lineno = lineno; @@ -1522,10 +1450,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Compare_kind; p->v.Compare.left = left; p->v.Compare.ops = ops; @@ -1546,10 +1472,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Call_kind; p->v.Call.func = func; p->v.Call.args = args; @@ -1571,10 +1495,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Repr_kind; p->v.Repr.value = value; p->lineno = lineno; @@ -1592,10 +1514,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Num_kind; p->v.Num.n = n; p->lineno = lineno; @@ -1613,10 +1533,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Str_kind; p->v.Str.s = s; p->lineno = lineno; @@ -1645,10 +1563,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Attribute_kind; p->v.Attribute.value = value; p->v.Attribute.attr = attr; @@ -1679,10 +1595,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Subscript_kind; p->v.Subscript.value = value; p->v.Subscript.slice = slice; @@ -1708,10 +1622,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Name_kind; p->v.Name.id = id; p->v.Name.ctx = ctx; @@ -1731,10 +1643,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = List_kind; p->v.List.elts = elts; p->v.List.ctx = ctx; @@ -1754,10 +1664,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Tuple_kind; p->v.Tuple.elts = elts; p->v.Tuple.ctx = ctx; @@ -1771,10 +1679,8 @@ { slice_ty p; p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Ellipsis_kind; return p; } @@ -1784,10 +1690,8 @@ { slice_ty p; p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Slice_kind; p->v.Slice.lower = lower; p->v.Slice.upper = upper; @@ -1800,10 +1704,8 @@ { slice_ty p; p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ExtSlice_kind; p->v.ExtSlice.dims = dims; return p; @@ -1819,10 +1721,8 @@ return NULL; } p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Index_kind; p->v.Index.value = value; return p; @@ -1843,10 +1743,8 @@ return NULL; } p = (comprehension_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->target = target; p->iter = iter; p->ifs = ifs; @@ -1859,10 +1757,8 @@ { excepthandler_ty p; p = (excepthandler_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->type = type; p->name = name; p->body = body; @@ -1877,10 +1773,8 @@ { arguments_ty p; p = (arguments_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->args = args; p->vararg = vararg; p->kwarg = kwarg; @@ -1903,10 +1797,8 @@ return NULL; } p = (keyword_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->arg = arg; p->value = value; return p; @@ -1922,10 +1814,8 @@ return NULL; } p = (alias_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->name = name; p->asname = asname; return p; From python-checkins at python.org Mon Feb 26 19:20:19 2007 From: python-checkins at python.org (thomas.wouters) Date: Mon, 26 Feb 2007 19:20:19 +0100 (CET) Subject: [Python-checkins] r53952 - in python/branches/p3yk: Misc/developers.txt Parser/asdl_c.py Python/Python-ast.c Python/ceval.c Message-ID: <20070226182019.7C8451E4017@bag.python.org> Author: thomas.wouters Date: Mon Feb 26 19:20:15 2007 New Revision: 53952 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Misc/developers.txt python/branches/p3yk/Parser/asdl_c.py python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/ceval.c Log: Merged revisions 53912-53951 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53919 | thomas.wouters | 2007-02-25 23:12:31 +0100 (Sun, 25 Feb 2007) | 8 lines Backported r51621 from p3yk: Don't use a fixed temporary name (gdbm). Don't use our own temp name creation (dbm). Should be backported to 2.5. ........ r53935 | georg.brandl | 2007-02-26 14:51:29 +0100 (Mon, 26 Feb 2007) | 2 lines Backport from Py3k branch: fix refleak in PyString_Format. ........ r53943 | jeremy.hylton | 2007-02-26 17:14:51 +0100 (Mon, 26 Feb 2007) | 2 lines Reformat long lines. ........ r53947 | neal.norwitz | 2007-02-26 18:01:08 +0100 (Mon, 26 Feb 2007) | 1 line Add Steven Bethard to help out with patches. ........ r53949 | georg.brandl | 2007-02-26 18:09:03 +0100 (Mon, 26 Feb 2007) | 3 lines Fix typo. ........ r53951 | neal.norwitz | 2007-02-26 19:10:47 +0100 (Mon, 26 Feb 2007) | 5 lines Fix a couple of problems in generating the AST code: * use %r instead of backticks since backticks are going away in Py3k * PyArena_Malloc() already sets PyErr_NoMemory so we don't need to do it again * the signature for ast2obj_int incorrectly used a bool, rather than a long ........ Modified: python/branches/p3yk/Misc/developers.txt ============================================================================== --- python/branches/p3yk/Misc/developers.txt (original) +++ python/branches/p3yk/Misc/developers.txt Mon Feb 26 19:20:15 2007 @@ -17,6 +17,9 @@ Permissions History ------------------- +- Steven Bethard (SF name "bediviere") added to the SourceForge Python + project 26 Feb 2007, by NCN, as a tracker tech. + - Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python project 06 Jan 2007, by NCN, as a tracker tech. He will maintain asyncore. Modified: python/branches/p3yk/Parser/asdl_c.py ============================================================================== --- python/branches/p3yk/Parser/asdl_c.py (original) +++ python/branches/p3yk/Parser/asdl_c.py Mon Feb 26 19:20:15 2007 @@ -299,10 +299,8 @@ emit('}', 1) emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1); - emit("if (!p) {", 1) - emit("PyErr_NoMemory();", 2) + emit("if (!p)", 1) emit("return NULL;", 2) - emit("}", 1) if union: self.emit_body_union(name, args, attrs) else: @@ -474,7 +472,7 @@ return PyBool_FromLong(b); } -static PyObject* ast2obj_int(bool b) +static PyObject* ast2obj_int(long b) { return PyInt_FromLong(b); } Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Mon Feb 26 19:20:15 2007 @@ -2,7 +2,7 @@ /* - __version__ 53872. + __version__ 53873. This module must be committed separately after each AST grammar change; The __version__ number is set to the revision number of the commit @@ -448,7 +448,7 @@ return PyBool_FromLong(b); } -static PyObject* ast2obj_int(bool b) +static PyObject* ast2obj_int(long b) { return PyInt_FromLong(b); } @@ -754,10 +754,8 @@ { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Module_kind; p->v.Module.body = body; return p; @@ -768,10 +766,8 @@ { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Interactive_kind; p->v.Interactive.body = body; return p; @@ -787,10 +783,8 @@ return NULL; } p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Expression_kind; p->v.Expression.body = body; return p; @@ -801,10 +795,8 @@ { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Suite_kind; p->v.Suite.body = body; return p; @@ -827,10 +819,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = FunctionDef_kind; p->v.FunctionDef.name = name; p->v.FunctionDef.args = args; @@ -853,10 +843,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ClassDef_kind; p->v.ClassDef.name = name; p->v.ClassDef.bases = bases; @@ -871,10 +859,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Return_kind; p->v.Return.value = value; p->lineno = lineno; @@ -887,10 +873,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Delete_kind; p->v.Delete.targets = targets; p->lineno = lineno; @@ -909,10 +893,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Assign_kind; p->v.Assign.targets = targets; p->v.Assign.value = value; @@ -942,10 +924,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = AugAssign_kind; p->v.AugAssign.target = target; p->v.AugAssign.op = op; @@ -971,10 +951,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = For_kind; p->v.For.target = target; p->v.For.iter = iter; @@ -996,10 +974,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = While_kind; p->v.While.test = test; p->v.While.body = body; @@ -1020,10 +996,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = If_kind; p->v.If.test = test; p->v.If.body = body; @@ -1044,10 +1018,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = With_kind; p->v.With.context_expr = context_expr; p->v.With.optional_vars = optional_vars; @@ -1063,10 +1035,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Raise_kind; p->v.Raise.type = type; p->v.Raise.inst = inst; @@ -1082,10 +1052,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = TryExcept_kind; p->v.TryExcept.body = body; p->v.TryExcept.handlers = handlers; @@ -1101,10 +1069,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = TryFinally_kind; p->v.TryFinally.body = body; p->v.TryFinally.finalbody = finalbody; @@ -1123,10 +1089,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Assert_kind; p->v.Assert.test = test; p->v.Assert.msg = msg; @@ -1140,10 +1104,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Import_kind; p->v.Import.names = names; p->lineno = lineno; @@ -1162,10 +1124,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ImportFrom_kind; p->v.ImportFrom.module = module; p->v.ImportFrom.names = names; @@ -1180,10 +1140,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Global_kind; p->v.Global.names = names; p->lineno = lineno; @@ -1201,10 +1159,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Expr_kind; p->v.Expr.value = value; p->lineno = lineno; @@ -1217,10 +1173,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Pass_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1232,10 +1186,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Break_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1247,10 +1199,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Continue_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1268,10 +1218,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = BoolOp_kind; p->v.BoolOp.op = op; p->v.BoolOp.values = values; @@ -1301,10 +1249,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = BinOp_kind; p->v.BinOp.left = left; p->v.BinOp.op = op; @@ -1330,10 +1276,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = UnaryOp_kind; p->v.UnaryOp.op = op; p->v.UnaryOp.operand = operand; @@ -1358,10 +1302,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Lambda_kind; p->v.Lambda.args = args; p->v.Lambda.body = body; @@ -1391,10 +1333,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = IfExp_kind; p->v.IfExp.test = test; p->v.IfExp.body = body; @@ -1410,10 +1350,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Dict_kind; p->v.Dict.keys = keys; p->v.Dict.values = values; @@ -1427,10 +1365,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Set_kind; p->v.Set.elts = elts; p->lineno = lineno; @@ -1449,10 +1385,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ListComp_kind; p->v.ListComp.elt = elt; p->v.ListComp.generators = generators; @@ -1472,10 +1406,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = GeneratorExp_kind; p->v.GeneratorExp.elt = elt; p->v.GeneratorExp.generators = generators; @@ -1489,10 +1421,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Yield_kind; p->v.Yield.value = value; p->lineno = lineno; @@ -1511,10 +1441,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Compare_kind; p->v.Compare.left = left; p->v.Compare.ops = ops; @@ -1535,10 +1463,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Call_kind; p->v.Call.func = func; p->v.Call.args = args; @@ -1560,10 +1486,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Num_kind; p->v.Num.n = n; p->lineno = lineno; @@ -1581,10 +1505,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Str_kind; p->v.Str.s = s; p->lineno = lineno; @@ -1602,10 +1524,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Bytes_kind; p->v.Bytes.s = s; p->lineno = lineno; @@ -1618,10 +1538,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Ellipsis_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1649,10 +1567,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Attribute_kind; p->v.Attribute.value = value; p->v.Attribute.attr = attr; @@ -1683,10 +1599,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Subscript_kind; p->v.Subscript.value = value; p->v.Subscript.slice = slice; @@ -1712,10 +1626,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Name_kind; p->v.Name.id = id; p->v.Name.ctx = ctx; @@ -1735,10 +1647,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = List_kind; p->v.List.elts = elts; p->v.List.ctx = ctx; @@ -1758,10 +1668,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Tuple_kind; p->v.Tuple.elts = elts; p->v.Tuple.ctx = ctx; @@ -1775,10 +1683,8 @@ { slice_ty p; p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Slice_kind; p->v.Slice.lower = lower; p->v.Slice.upper = upper; @@ -1791,10 +1697,8 @@ { slice_ty p; p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ExtSlice_kind; p->v.ExtSlice.dims = dims; return p; @@ -1810,10 +1714,8 @@ return NULL; } p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Index_kind; p->v.Index.value = value; return p; @@ -1834,10 +1736,8 @@ return NULL; } p = (comprehension_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->target = target; p->iter = iter; p->ifs = ifs; @@ -1850,10 +1750,8 @@ { excepthandler_ty p; p = (excepthandler_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->type = type; p->name = name; p->body = body; @@ -1869,10 +1767,8 @@ { arguments_ty p; p = (arguments_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->args = args; p->vararg = vararg; p->varargannotation = varargannotation; @@ -1894,10 +1790,8 @@ return NULL; } p = (arg_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = SimpleArg_kind; p->v.SimpleArg.arg = arg; p->v.SimpleArg.annotation = annotation; @@ -1909,10 +1803,8 @@ { arg_ty p; p = (arg_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = NestedArgs_kind; p->v.NestedArgs.args = args; return p; @@ -1933,10 +1825,8 @@ return NULL; } p = (keyword_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->arg = arg; p->value = value; return p; @@ -1952,10 +1842,8 @@ return NULL; } p = (alias_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->name = name; p->asname = asname; return p; @@ -3125,7 +3013,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__", "53872") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53873") < 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/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Mon Feb 26 19:20:15 2007 @@ -4077,7 +4077,8 @@ metaclass = (PyObject *) &PyType_Type; Py_INCREF(metaclass); } - result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, NULL); + result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, + NULL); Py_DECREF(metaclass); if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { /* A type error here likely means that the user passed @@ -4091,7 +4092,8 @@ if (PyString_Check(pvalue)) { PyObject *newmsg; newmsg = PyString_FromFormat( - "Error when calling the metaclass bases\n %s", + "Error when calling the metaclass bases\n" + " %s", PyString_AS_STRING(pvalue)); if (newmsg != NULL) { Py_DECREF(pvalue); From python-checkins at python.org Mon Feb 26 19:22:04 2007 From: python-checkins at python.org (thomas.wouters) Date: Mon, 26 Feb 2007 19:22:04 +0100 (CET) Subject: [Python-checkins] r53953 - in python/branches/twouters-dictviews-backport: Lib/test/test_dict.py Objects/dictobject.c Message-ID: <20070226182204.47B961E4006@bag.python.org> Author: thomas.wouters Date: Mon Feb 26 19:22:00 2007 New Revision: 53953 Modified: python/branches/twouters-dictviews-backport/Lib/test/test_dict.py python/branches/twouters-dictviews-backport/Objects/dictobject.c Log: Step one of backporting dict.key/items/values from Py3k: the actual backporting, and renaming to viewkeys/viewitems/viewvalues. Modified: python/branches/twouters-dictviews-backport/Lib/test/test_dict.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/test/test_dict.py (original) +++ python/branches/twouters-dictviews-backport/Lib/test/test_dict.py Mon Feb 26 19:22:00 2007 @@ -26,6 +26,18 @@ self.assertRaises(TypeError, d.keys, None) + def test_viewkeys(self): + d = {} + self.assertEqual(d.viewkeys(), set()) + d = {'a': 1, 'b': 2} + k = d.viewkeys() + self.assert_('a' in k) + self.assert_('b' in k) + self.assertFalse('c' in k) + self.assertEquals(k, set(['a', 'b'])) + + self.assertRaises(TypeError, d.viewkeys, None) + def test_values(self): d = {} self.assertEqual(d.values(), []) @@ -34,15 +46,32 @@ self.assertRaises(TypeError, d.values, None) + def test_viewvalues(self): + d = {} + self.assertEqual(list(d.viewvalues()), []) + d = {1:2} + self.assertEqual(list(d.viewvalues()), [2]) + + self.assertRaises(TypeError, d.viewvalues, None) + def test_items(self): d = {} - self.assertEqual(d.items(), []) + self.assertEqual(list(d.items(), []) d = {1:2} self.assertEqual(d.items(), [(1, 2)]) self.assertRaises(TypeError, d.items, None) + def test_viewitems(self): + d = {} + self.assertEqual(list(d.viewitems()), []) + + d = {1:2} + self.assertEqual(list(d.viewitems()), [(1, 2)]) + + self.assertRaises(TypeError, d.viewitems, None) + def test_has_key(self): d = {} self.assert_(not d.has_key('a')) Modified: python/branches/twouters-dictviews-backport/Objects/dictobject.c ============================================================================== --- python/branches/twouters-dictviews-backport/Objects/dictobject.c (original) +++ python/branches/twouters-dictviews-backport/Objects/dictobject.c Mon Feb 26 19:22:00 2007 @@ -1959,6 +1959,15 @@ PyDoc_STRVAR(iteritems__doc__, "D.iteritems() -> an iterator over the (key, value) items of D"); +/* Forward */ +static PyObject *dictkeys_new(PyObject *); +static PyObject *dictitems_new(PyObject *); +static PyObject *dictvalues_new(PyObject *); + +PyDoc_STRVAR(KEYS__doc__, "D.KEYS() -> a set-like object for D's keys"); +PyDoc_STRVAR(ITEMS__doc__, "D.ITEMS() -> a set-like object for D's items"); +PyDoc_STRVAR(VALUES__doc__, "D.VALUES() -> a set-like object for D's values"); + static PyMethodDef mapp_methods[] = { {"__contains__",(PyCFunction)dict_has_key, METH_O | METH_COEXIST, contains__doc__}, @@ -1980,6 +1989,12 @@ items__doc__}, {"values", (PyCFunction)dict_values, METH_NOARGS, values__doc__}, + {"viewkeys", (PyCFunction)dictkeys_new, METH_NOARGS, + KEYS__doc__}, + {"viewitems", (PyCFunction)dictitems_new, METH_NOARGS, + ITEMS__doc__}, + {"viewvalues", (PyCFunction)dictvalues_new, METH_NOARGS, + VALUES__doc__}, {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, update__doc__}, {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, @@ -2466,3 +2481,359 @@ dictiter_methods, /* tp_methods */ 0, }; + + +/***********************************************/ +/* View objects for keys(), items(), values(). */ +/***********************************************/ + +/* While this is incomplete, we use KEYS(), ITEMS(), VALUES(). */ + +/* The instance lay-out is the same for all three; but the type differs. */ + +typedef struct { + PyObject_HEAD + dictobject *dv_dict; +} dictviewobject; + + +static void +dictview_dealloc(dictviewobject *dv) +{ + Py_XDECREF(dv->dv_dict); + PyObject_Del(dv); +} + +static Py_ssize_t +dictview_len(dictviewobject *dv) +{ + Py_ssize_t len = 0; + if (dv->dv_dict != NULL) + len = dv->dv_dict->ma_used; + return len; +} + +static PyObject * +dictview_new(PyObject *dict, PyTypeObject *type) +{ + dictviewobject *dv; + if (dict == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyDict_Check(dict)) { + /* XXX Get rid of this restriction later */ + PyErr_Format(PyExc_TypeError, + "%s() requires a dict argument, not '%s'", + type->tp_name, dict->ob_type->tp_name); + return NULL; + } + dv = PyObject_New(dictviewobject, type); + if (dv == NULL) + return NULL; + Py_INCREF(dict); + dv->dv_dict = (dictobject *)dict; + return (PyObject *)dv; +} + +/* Forward */ +PyTypeObject PyDictKeys_Type; +PyTypeObject PyDictItems_Type; +PyTypeObject PyDictValues_Type; + +#define PyDictKeys_Check(obj) ((obj)->ob_type == &PyDictKeys_Type) +#define PyDictItems_Check(obj) ((obj)->ob_type == &PyDictItems_Type) +#define PyDictValues_Check(obj) ((obj)->ob_type == &PyDictValues_Type) + +/* This excludes Values, since they are not sets. */ +# define PyDictViewSet_Check(obj) \ + (PyDictKeys_Check(obj) || PyDictItems_Check(obj)) + +static int +all_contained_in(PyObject *self, PyObject *other) +{ + PyObject *iter = PyObject_GetIter(self); + int ok = 1; + + if (iter == NULL) + return -1; + for (;;) { + PyObject *next = PyIter_Next(iter); + if (next == NULL) { + if (PyErr_Occurred()) + ok = -1; + break; + } + ok = PySequence_Contains(other, next); + Py_DECREF(next); + if (ok <= 0) + break; + } + Py_DECREF(iter); + return ok; +} + +static PyObject * +dictview_richcompare(PyObject *self, PyObject *other, int op) +{ + assert(self != NULL); + assert(PyDictViewSet_Check(self)); + assert(other != NULL); + if ((op == Py_EQ || op == Py_NE) && + (PyAnySet_Check(other) || PyDictViewSet_Check(other))) + { + Py_ssize_t len_self, len_other; + int ok; + PyObject *result; + + len_self = PyObject_Size(self); + if (len_self < 0) + return NULL; + len_other = PyObject_Size(other); + if (len_other < 0) + return NULL; + if (len_self != len_other) + ok = 0; + else if (len_self == 0) + ok = 1; + else + ok = all_contained_in(self, other); + if (ok < 0) + return NULL; + if (ok == (op == Py_EQ)) + result = Py_True; + else + result = Py_False; + Py_INCREF(result); + return result; + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } +} + +/*** dict_keys ***/ + +static PyObject * +dictkeys_iter(dictviewobject *dv) +{ + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); +} + +static int +dictkeys_contains(dictviewobject *dv, PyObject *obj) +{ + if (dv->dv_dict == NULL) + return 0; + return PyDict_Contains((PyObject *)dv->dv_dict, obj); +} + +static PySequenceMethods dictkeys_as_sequence = { + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictkeys_contains, /* sq_contains */ +}; + +static PyMethodDef dictkeys_methods[] = { + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyDictKeys_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "dict_keys", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &dictkeys_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictkeys_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictkeys_methods, /* tp_methods */ + 0, +}; + +static PyObject * +dictkeys_new(PyObject *dict) +{ + return dictview_new(dict, &PyDictKeys_Type); +} + +/*** dict_items ***/ + +static PyObject * +dictitems_iter(dictviewobject *dv) +{ + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); +} + +static int +dictitems_contains(dictviewobject *dv, PyObject *obj) +{ + PyObject *key, *value, *found; + if (dv->dv_dict == NULL) + return 0; + if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) + return 0; + key = PyTuple_GET_ITEM(obj, 0); + value = PyTuple_GET_ITEM(obj, 1); + found = PyDict_GetItem((PyObject *)dv->dv_dict, key); + if (found == NULL) { + if (PyErr_Occurred()) + return -1; + return 0; + } + return PyObject_RichCompareBool(value, found, Py_EQ); +} + +static PySequenceMethods dictitems_as_sequence = { + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictitems_contains, /* sq_contains */ +}; + +static PyMethodDef dictitems_methods[] = { + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyDictItems_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "dict_items", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &dictitems_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictitems_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictitems_methods, /* tp_methods */ + 0, +}; + +static PyObject * +dictitems_new(PyObject *dict) +{ + return dictview_new(dict, &PyDictItems_Type); +} + +/*** dict_values ***/ + +static PyObject * +dictvalues_iter(dictviewobject *dv) +{ + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); +} + +static PySequenceMethods dictvalues_as_sequence = { + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)0, /* sq_contains */ +}; + +static PyMethodDef dictvalues_methods[] = { + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyDictValues_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "dict_values", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &dictvalues_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictvalues_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictvalues_methods, /* tp_methods */ + 0, +}; + +static PyObject * +dictvalues_new(PyObject *dict) +{ + return dictview_new(dict, &PyDictValues_Type); +} From jimjjewett at gmail.com Mon Feb 26 19:31:51 2007 From: jimjjewett at gmail.com (Jim Jewett) Date: Mon, 26 Feb 2007 13:31:51 -0500 Subject: [Python-checkins] Why? Re: r53925 - sandbox/trunk/pep362/pep362.py Message-ID: Why are you removing the __str__ function? For me, (1) one of the more frustrating parts of the introspection API is that you can't (easily) use it to create a new "similar" function. (2) one of the main uses of introspection is seeing what I have -- and "equivalent" source code is a useful output format. On 2/25/07, brett.cannon wrote: > Author: brett.cannon > Date: Sun Feb 25 23:59:37 2007 > New Revision: 53925 > > Modified: > sandbox/trunk/pep362/pep362.py > Log: > Remove __str__ support. > > > Modified: sandbox/trunk/pep362/pep362.py > ============================================================================== > --- sandbox/trunk/pep362/pep362.py (original) > +++ sandbox/trunk/pep362/pep362.py Sun Feb 25 23:59:37 2007 > @@ -49,27 +49,6 @@ > self.has_annotation = True > self.annotation = annotation > > - def _tuple2param(self, tuple_): > - if not isinstance(tuple_, tuple): > - return str(tuple_) > - elif len(tuple_) == 1: > - return "(" + str(tuple_[0]) +",)" > - else: > - return ('(' + > - ', '.join(self._tuple2param(x) for x in tuple_) + > - ')') > - > - def __str__(self): > - """Return the string representation of the parameter as it would look > - in a function's signature.""" > - if isinstance(self.name, tuple): > - result = self._tuple2param(self.name) > - else: > - result = self.name > - if self.has_default: > - result+= "=" + str(self.default_value) > - return result > - > > class Signature(object): > > @@ -92,7 +71,8 @@ > keyword_only_count = func_code.co_kwonlyargcount > else: > keyword_only_count = 0 > - positional = func_code.co_varnames[:pos_count] > + #positional = func_code.co_varnames[:pos_count] > + positional = argspec[0] > keyword_only = func_code.co_varnames[pos_count:keyword_only_count] > if func.func_defaults: > pos_default_count = len(func.func_defaults) > @@ -178,22 +158,6 @@ > else: > return tuple(cls._list2tuple(x) for x in list_) > > - def __str__(self): > - """String representation of a signature as one might write it in source > - code.""" > - result = "%s(" % self.name > - result += ", ".join(str(param) for param in self.parameters) > - if self.var_args: > - if self.parameters: > - result +=", " > - result += "*%s" % self.var_args > - if self.var_kw_args: > - if self.parameters or self.var_args: > - result += ", " > - result += "**%s" % self.var_kw_args > - result += ")" > - return result > - > def bind(self, *args, **kwargs): > """Return a dictionary mapping function arguments to their parameter > variables, if possible. > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From python-checkins at python.org Mon Feb 26 19:41:23 2007 From: python-checkins at python.org (jeremy.hylton) Date: Mon, 26 Feb 2007 19:41:23 +0100 (CET) Subject: [Python-checkins] r53954 - in python/trunk: Doc/lib/libfuncs.tex Lib/test/test_scope.py Objects/frameobject.c Message-ID: <20070226184123.54C351E4007@bag.python.org> Author: jeremy.hylton Date: Mon Feb 26 19:41:18 2007 New Revision: 53954 Modified: python/trunk/Doc/lib/libfuncs.tex python/trunk/Lib/test/test_scope.py python/trunk/Objects/frameobject.c Log: Do not copy free variables to locals in class namespaces. Fixes bug 1569356, but at the cost of a minor incompatibility in locals(). Add test that verifies that the class namespace is not polluted. Also clarify the behavior in the library docs. Along the way, cleaned up the dict_to_map and map_to_dict implementations and added some comments that explain what they do. Modified: python/trunk/Doc/lib/libfuncs.tex ============================================================================== --- python/trunk/Doc/lib/libfuncs.tex (original) +++ python/trunk/Doc/lib/libfuncs.tex Mon Feb 26 19:41:18 2007 @@ -607,6 +607,11 @@ \warning{The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter.} + + Free variables are returned by \var{locals} when it is called in + a function block. Modifications of free variables may not affect + the values used by the interpreter. Free variables are not + returned in class blocks. \end{funcdesc} \begin{funcdesc}{long}{\optional{x\optional{, radix}}} Modified: python/trunk/Lib/test/test_scope.py ============================================================================== --- python/trunk/Lib/test/test_scope.py (original) +++ python/trunk/Lib/test/test_scope.py Mon Feb 26 19:41:18 2007 @@ -486,6 +486,39 @@ del d['h'] self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) + def testLocalsClass(self): + # This test verifies that calling locals() does not pollute + # the local namespace of the class with free variables. Old + # versions of Python had a bug, where a free variable being + # passed through a class namespace would be inserted into + # locals() by locals() or exec or a trace function. + # + # The real bug lies in frame code that copies variables + # between fast locals and the locals dict, e.g. when executing + # a trace function. + + def f(x): + class C: + x = 12 + def m(self): + return x + locals() + return C + + self.assertEqual(f(1).x, 12) + + def f(x): + class C: + y = x + def m(self): + return x + z = list(locals()) + return C + + varnames = f(1).z + self.assert_("x" not in varnames) + self.assert_("y" in varnames) + def testBoundAndFree(self): # var is bound and free in class Modified: python/trunk/Objects/frameobject.c ============================================================================== --- python/trunk/Objects/frameobject.c (original) +++ python/trunk/Objects/frameobject.c Mon Feb 26 19:41:18 2007 @@ -701,18 +701,38 @@ return b; } -/* Convert between "fast" version of locals and dictionary version */ +/* Convert between "fast" version of locals and dictionary version. + + map and values are input arguments. map is a tuple of strings. + values is an array of PyObject*. At index i, map[i] is the name of + the variable with value values[i]. The function copies the first + nmap variable from map/values into dict. If values[i] is NULL, + the variable is deleted from dict. + + If deref is true, then the values being copied are cell variables + and the value is extracted from the cell variable before being put + in dict. + + Exceptions raised while modifying the dict are silently ignored, + because there is no good way to report them. + */ static void map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, - Py_ssize_t deref) + int deref) { Py_ssize_t j; + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) > nmap); for (j = nmap; --j >= 0; ) { PyObject *key = PyTuple_GET_ITEM(map, j); PyObject *value = values[j]; - if (deref) + assert(PyString_Check(key)); + if (deref) { + assert(PyCell_Check(value)); value = PyCell_GET(value); + } if (value == NULL) { if (PyObject_DelItem(dict, key) != 0) PyErr_Clear(); @@ -724,29 +744,55 @@ } } +/* Copy values from the "locals" dict into the fast locals. + + dict is an input argument containing string keys representing + variables names and arbitrary PyObject* as values. + + map and values are input arguments. map is a tuple of strings. + values is an array of PyObject*. At index i, map[i] is the name of + the variable with value values[i]. The function copies the first + nmap variable from map/values into dict. If values[i] is NULL, + the variable is deleted from dict. + + If deref is true, then the values being copied are cell variables + and the value is extracted from the cell variable before being put + in dict. If clear is true, then variables in map but not in dict + are set to NULL in map; if clear is false, variables missing in + dict are ignored. + + Exceptions raised while modifying the dict are silently ignored, + because there is no good way to report them. +*/ + static void dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, - Py_ssize_t deref, int clear) + int deref, int clear) { Py_ssize_t j; + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) > nmap); for (j = nmap; --j >= 0; ) { PyObject *key = PyTuple_GET_ITEM(map, j); PyObject *value = PyObject_GetItem(dict, key); - if (value == NULL) + assert(PyString_Check(key)); + /* We only care about NULLs if clear is true. */ + if (value == NULL) { PyErr_Clear(); + if (!clear) + continue; + } if (deref) { - if (value || clear) { - if (PyCell_GET(values[j]) != value) { - if (PyCell_Set(values[j], value) < 0) - PyErr_Clear(); - } - } - } else if (value != NULL || clear) { - if (values[j] != value) { - Py_XINCREF(value); - Py_XDECREF(values[j]); - values[j] = value; - } + assert(PyCell_Check(values[j])); + if (PyCell_GET(values[j]) != value) { + if (PyCell_Set(values[j], value) < 0) + PyErr_Clear(); + } + } else if (values[j] != value) { + Py_XINCREF(value); + Py_XDECREF(values[j]); + values[j] = value; } Py_XDECREF(value); } @@ -788,8 +834,18 @@ if (ncells || nfreevars) { map_to_dict(co->co_cellvars, ncells, locals, fast + co->co_nlocals, 1); - map_to_dict(co->co_freevars, nfreevars, - locals, fast + co->co_nlocals + ncells, 1); + /* If the namespace is unoptimized, then one of the + following cases applies: + 1. It does not contain free variables, because it + uses import * or is a top-level namespace. + 2. It is a class namespace. + We don't want to accidentally copy free variables + into the locals dict used by the class. + */ + if (co->co_flags & CO_OPTIMIZED) { + map_to_dict(co->co_freevars, nfreevars, + locals, fast + co->co_nlocals + ncells, 1); + } } PyErr_Restore(error_type, error_value, error_traceback); } From buildbot at python.org Mon Feb 26 19:47:21 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 18:47:21 +0000 Subject: [Python-checkins] buildbot failure in ppc Debian unstable trunk Message-ID: <20070226184721.A29521E4006@bag.python.org> The Buildbot has detected a new failure of ppc Debian unstable trunk. Full details are available at: http://www.python.org/dev/buildbot/all/ppc%2520Debian%2520unstable%2520trunk/builds/98 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 19:47:22 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 18:47:22 +0000 Subject: [Python-checkins] buildbot failure in amd64 gentoo trunk Message-ID: <20070226184723.069A01E400C@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo trunk. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%2520trunk/builds/1864 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 19:47:31 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 18:47:31 +0000 Subject: [Python-checkins] buildbot failure in x86 gentoo trunk Message-ID: <20070226184731.61F0E1E4006@bag.python.org> The Buildbot has detected a new failure of x86 gentoo trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520gentoo%2520trunk/builds/1946 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 19:47:45 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 18:47:45 +0000 Subject: [Python-checkins] buildbot failure in x86 mvlgcc trunk Message-ID: <20070226184745.758751E4006@bag.python.org> The Buildbot has detected a new failure of x86 mvlgcc trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520mvlgcc%2520trunk/builds/270 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 19:49:43 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 18:49:43 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian trunk Message-ID: <20070226184943.B24D51E4006@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%2520trunk/builds/96 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: georg.brandl,neal.norwitz Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socketserver make: *** [buildbottest] Error 1 sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 19:50:35 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 18:50:35 +0000 Subject: [Python-checkins] buildbot failure in PPC64 Debian trunk Message-ID: <20070226185035.42D781E401A@bag.python.org> The Buildbot has detected a new failure of PPC64 Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/PPC64%2520Debian%2520trunk/builds/97 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 19:50:49 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 18:50:49 +0000 Subject: [Python-checkins] buildbot failure in alpha Tru64 5.1 trunk Message-ID: <20070226185049.565581E4006@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%2520trunk/builds/1433 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 19:56:08 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 18:56:08 +0000 Subject: [Python-checkins] buildbot failure in sparc solaris10 gcc trunk Message-ID: <20070226185609.0B3301E4013@bag.python.org> The Buildbot has detected a new failure of sparc solaris10 gcc trunk. Full details are available at: http://www.python.org/dev/buildbot/all/sparc%2520solaris10%2520gcc%2520trunk/builds/1787 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 19:58:13 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 18:58:13 +0000 Subject: [Python-checkins] buildbot failure in g4 osx.4 trunk Message-ID: <20070226185813.D42F01E4006@bag.python.org> The Buildbot has detected a new failure of g4 osx.4 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/g4%2520osx.4%2520trunk/builds/1768 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From python-checkins at python.org Mon Feb 26 20:00:22 2007 From: python-checkins at python.org (jeremy.hylton) Date: Mon, 26 Feb 2007 20:00:22 +0100 (CET) Subject: [Python-checkins] r53955 - python/trunk/Objects/frameobject.c Message-ID: <20070226190022.4CB231E4009@bag.python.org> Author: jeremy.hylton Date: Mon Feb 26 20:00:20 2007 New Revision: 53955 Modified: python/trunk/Objects/frameobject.c Log: Fix assertion. Modified: python/trunk/Objects/frameobject.c ============================================================================== --- python/trunk/Objects/frameobject.c (original) +++ python/trunk/Objects/frameobject.c Mon Feb 26 20:00:20 2007 @@ -724,7 +724,7 @@ Py_ssize_t j; assert(PyTuple_Check(map)); assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) > nmap); + assert(PyTuple_Size(map) >= nmap); for (j = nmap; --j >= 0; ) { PyObject *key = PyTuple_GET_ITEM(map, j); PyObject *value = values[j]; @@ -772,7 +772,7 @@ Py_ssize_t j; assert(PyTuple_Check(map)); assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) > nmap); + assert(PyTuple_Size(map) >= nmap); for (j = nmap; --j >= 0; ) { PyObject *key = PyTuple_GET_ITEM(map, j); PyObject *value = PyObject_GetItem(dict, key); From buildbot at python.org Mon Feb 26 20:05:10 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 19:05:10 +0000 Subject: [Python-checkins] buildbot failure in ia64 Ubuntu trunk trunk Message-ID: <20070226190510.3DEC51E400A@bag.python.org> The Buildbot has detected a new failure of ia64 Ubuntu trunk trunk. Full details are available at: http://www.python.org/dev/buildbot/all/ia64%2520Ubuntu%2520trunk%2520trunk/builds/407 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 20:06:24 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 19:06:24 +0000 Subject: [Python-checkins] buildbot failure in x86 W2k trunk Message-ID: <20070226190624.A6FA81E4009@bag.python.org> The Buildbot has detected a new failure of x86 W2k trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520W2k%2520trunk/builds/116 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 20:06:35 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 19:06:35 +0000 Subject: [Python-checkins] buildbot failure in x86 XP trunk Message-ID: <20070226190635.381B01E400B@bag.python.org> The Buildbot has detected a new failure of x86 XP trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%2520trunk/builds/218 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton BUILD FAILED: failed compile sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 20:09:51 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 19:09:51 +0000 Subject: [Python-checkins] buildbot warnings in alpha Tru64 5.1 trunk Message-ID: <20070226190951.733B71E4006@bag.python.org> The Buildbot has detected a new failure of alpha Tru64 5.1 trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Tru64%25205.1%2520trunk/builds/1434 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Mon Feb 26 20:36:37 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 26 Feb 2007 19:36:37 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP trunk Message-ID: <20070226193637.D24771E4007@bag.python.org> The Buildbot has detected a new failure of x86 XP trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%2520trunk/builds/219 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton Build had warnings: warnings failed slave lost sincerely, -The Buildbot From bcannon at gmail.com Mon Feb 26 21:14:10 2007 From: bcannon at gmail.com (Brett Cannon) Date: Mon, 26 Feb 2007 14:14:10 -0600 Subject: [Python-checkins] Why? Re: r53925 - sandbox/trunk/pep362/pep362.py In-Reply-To: References: Message-ID: On 2/26/07, Jim Jewett wrote: > Why are you removing the __str__ function? > Because annotations prevent an accurate representation. How do you get int to display as 'int'? > For me, > > (1) one of the more frustrating parts of the introspection API is > that you can't (easily) use it to create a new "similar" function. > > (2) one of the main uses of introspection is seeing what I have -- > and "equivalent" source code is a useful output format. > I undderstand; I put in the method for a reason. But if I can't have it properly display all information then I don't want to have to support a partial implementation. -Brett > > > On 2/25/07, brett.cannon wrote: > > Author: brett.cannon > > Date: Sun Feb 25 23:59:37 2007 > > New Revision: 53925 > > > > Modified: > > sandbox/trunk/pep362/pep362.py > > Log: > > Remove __str__ support. > > > > > > Modified: sandbox/trunk/pep362/pep362.py > > ============================================================================== > > --- sandbox/trunk/pep362/pep362.py (original) > > +++ sandbox/trunk/pep362/pep362.py Sun Feb 25 23:59:37 2007 > > @@ -49,27 +49,6 @@ > > self.has_annotation = True > > self.annotation = annotation > > > > - def _tuple2param(self, tuple_): > > - if not isinstance(tuple_, tuple): > > - return str(tuple_) > > - elif len(tuple_) == 1: > > - return "(" + str(tuple_[0]) +",)" > > - else: > > - return ('(' + > > - ', '.join(self._tuple2param(x) for x in tuple_) + > > - ')') > > - > > - def __str__(self): > > - """Return the string representation of the parameter as it would look > > - in a function's signature.""" > > - if isinstance(self.name, tuple): > > - result = self._tuple2param(self.name) > > - else: > > - result = self.name > > - if self.has_default: > > - result+= "=" + str(self.default_value) > > - return result > > - > > > > class Signature(object): > > > > @@ -92,7 +71,8 @@ > > keyword_only_count = func_code.co_kwonlyargcount > > else: > > keyword_only_count = 0 > > - positional = func_code.co_varnames[:pos_count] > > + #positional = func_code.co_varnames[:pos_count] > > + positional = argspec[0] > > keyword_only = func_code.co_varnames[pos_count:keyword_only_count] > > if func.func_defaults: > > pos_default_count = len(func.func_defaults) > > @@ -178,22 +158,6 @@ > > else: > > return tuple(cls._list2tuple(x) for x in list_) > > > > - def __str__(self): > > - """String representation of a signature as one might write it in source > > - code.""" > > - result = "%s(" % self.name > > - result += ", ".join(str(param) for param in self.parameters) > > - if self.var_args: > > - if self.parameters: > > - result +=", " > > - result += "*%s" % self.var_args > > - if self.var_kw_args: > > - if self.parameters or self.var_args: > > - result += ", " > > - result += "**%s" % self.var_kw_args > > - result += ")" > > - return result > > - > > def bind(self, *args, **kwargs): > > """Return a dictionary mapping function arguments to their parameter > > variables, if possible. > > _______________________________________________ > > Python-checkins mailing list > > Python-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-checkins > > > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From guido at python.org Mon Feb 26 21:21:57 2007 From: guido at python.org (Guido van Rossum) Date: Mon, 26 Feb 2007 14:21:57 -0600 Subject: [Python-checkins] Why? Re: r53925 - sandbox/trunk/pep362/pep362.py In-Reply-To: References: Message-ID: On 2/26/07, Brett Cannon wrote: > On 2/26/07, Jim Jewett wrote: > > Why are you removing the __str__ function? > > > > Because annotations prevent an accurate representation. How do you > get int to display as 'int'? By changing type.__str__ to return self.__name__? I would be open to considering this. > > For me, > > > > (1) one of the more frustrating parts of the introspection API is > > that you can't (easily) use it to create a new "similar" function. > > > > (2) one of the main uses of introspection is seeing what I have -- > > and "equivalent" source code is a useful output format. > > > > I undderstand; I put in the method for a reason. But if I can't have > it properly display all information then I don't want to have to > support a partial implementation. > > -Brett > > > > > > > On 2/25/07, brett.cannon wrote: > > > Author: brett.cannon > > > Date: Sun Feb 25 23:59:37 2007 > > > New Revision: 53925 > > > > > > Modified: > > > sandbox/trunk/pep362/pep362.py > > > Log: > > > Remove __str__ support. > > > > > > > > > Modified: sandbox/trunk/pep362/pep362.py > > > ============================================================================== > > > --- sandbox/trunk/pep362/pep362.py (original) > > > +++ sandbox/trunk/pep362/pep362.py Sun Feb 25 23:59:37 2007 > > > @@ -49,27 +49,6 @@ > > > self.has_annotation = True > > > self.annotation = annotation > > > > > > - def _tuple2param(self, tuple_): > > > - if not isinstance(tuple_, tuple): > > > - return str(tuple_) > > > - elif len(tuple_) == 1: > > > - return "(" + str(tuple_[0]) +",)" > > > - else: > > > - return ('(' + > > > - ', '.join(self._tuple2param(x) for x in tuple_) + > > > - ')') > > > - > > > - def __str__(self): > > > - """Return the string representation of the parameter as it would look > > > - in a function's signature.""" > > > - if isinstance(self.name, tuple): > > > - result = self._tuple2param(self.name) > > > - else: > > > - result = self.name > > > - if self.has_default: > > > - result+= "=" + str(self.default_value) > > > - return result > > > - > > > > > > class Signature(object): > > > > > > @@ -92,7 +71,8 @@ > > > keyword_only_count = func_code.co_kwonlyargcount > > > else: > > > keyword_only_count = 0 > > > - positional = func_code.co_varnames[:pos_count] > > > + #positional = func_code.co_varnames[:pos_count] > > > + positional = argspec[0] > > > keyword_only = func_code.co_varnames[pos_count:keyword_only_count] > > > if func.func_defaults: > > > pos_default_count = len(func.func_defaults) > > > @@ -178,22 +158,6 @@ > > > else: > > > return tuple(cls._list2tuple(x) for x in list_) > > > > > > - def __str__(self): > > > - """String representation of a signature as one might write it in source > > > - code.""" > > > - result = "%s(" % self.name > > > - result += ", ".join(str(param) for param in self.parameters) > > > - if self.var_args: > > > - if self.parameters: > > > - result +=", " > > > - result += "*%s" % self.var_args > > > - if self.var_kw_args: > > > - if self.parameters or self.var_args: > > > - result += ", " > > > - result += "**%s" % self.var_kw_args > > > - result += ")" > > > - return result > > > - > > > def bind(self, *args, **kwargs): > > > """Return a dictionary mapping function arguments to their parameter > > > variables, if possible. > > > _______________________________________________ > > > Python-checkins mailing list > > > Python-checkins at python.org > > > http://mail.python.org/mailman/listinfo/python-checkins > > > > > _______________________________________________ > > Python-checkins mailing list > > Python-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-checkins > > > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From python-checkins at python.org Mon Feb 26 21:27:09 2007 From: python-checkins at python.org (thomas.wouters) Date: Mon, 26 Feb 2007 21:27:09 +0100 (CET) Subject: [Python-checkins] r53958 - in python/branches/twouters-dictviews-backport: Include/code.h Include/compile.h Include/object.h Include/opcode.h Include/pythonrun.h Lib/__future__.py Lib/opcode.py Objects/object.c Python/ceval.c Python/compile.c Python/future.c Message-ID: <20070226202709.939211E4007@bag.python.org> Author: thomas.wouters Date: Mon Feb 26 21:27:03 2007 New Revision: 53958 Modified: python/branches/twouters-dictviews-backport/Include/code.h python/branches/twouters-dictviews-backport/Include/compile.h python/branches/twouters-dictviews-backport/Include/object.h python/branches/twouters-dictviews-backport/Include/opcode.h python/branches/twouters-dictviews-backport/Include/pythonrun.h python/branches/twouters-dictviews-backport/Lib/__future__.py python/branches/twouters-dictviews-backport/Lib/opcode.py python/branches/twouters-dictviews-backport/Objects/object.c python/branches/twouters-dictviews-backport/Python/ceval.c python/branches/twouters-dictviews-backport/Python/compile.c python/branches/twouters-dictviews-backport/Python/future.c Log: Future statement for d.keys() to return a keys view (and similar for items and values.) Works by specialcasing dicts (and subclasses), but dict-alikes (even those with both 'keys' and 'viewkeys' attributes) won't feel the magic; they don't automatically get it in Python 3.0 either. Still to do: fixing getattr() to do the same thing. Modified: python/branches/twouters-dictviews-backport/Include/code.h ============================================================================== --- python/branches/twouters-dictviews-backport/Include/code.h (original) +++ python/branches/twouters-dictviews-backport/Include/code.h Mon Feb 26 21:27:03 2007 @@ -48,6 +48,7 @@ #define CO_FUTURE_DIVISION 0x2000 #define CO_FUTURE_ABSOLUTE_IMPORT 0x4000 /* do absolute imports by default */ #define CO_FUTURE_WITH_STATEMENT 0x8000 +#define CO_FUTURE_DICTVIEWS 0x10000 /* This should be defined if a future statement modifies the syntax. For example, when a keyword is added. Modified: python/branches/twouters-dictviews-backport/Include/compile.h ============================================================================== --- python/branches/twouters-dictviews-backport/Include/compile.h (original) +++ python/branches/twouters-dictviews-backport/Include/compile.h Mon Feb 26 21:27:03 2007 @@ -24,6 +24,7 @@ #define FUTURE_DIVISION "division" #define FUTURE_ABSOLUTE_IMPORT "absolute_import" #define FUTURE_WITH_STATEMENT "with_statement" +#define FUTURE_DICTVIEWS "dictviews" struct _mod; /* Declare the existence of this type */ PyAPI_FUNC(PyCodeObject *) PyAST_Compile(struct _mod *, const char *, Modified: python/branches/twouters-dictviews-backport/Include/object.h ============================================================================== --- python/branches/twouters-dictviews-backport/Include/object.h (original) +++ python/branches/twouters-dictviews-backport/Include/object.h Mon Feb 26 21:27:03 2007 @@ -402,7 +402,9 @@ PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *); PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *); PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *); +PyAPI_FUNC(PyObject *) _PyObject_GetViewAttr(PyObject *, PyObject *); PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *); +PyAPI_FUNC(int) _PyObject_SetViewAttr(PyObject *, PyObject *, PyObject *); PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *); PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *); PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *); Modified: python/branches/twouters-dictviews-backport/Include/opcode.h ============================================================================== --- python/branches/twouters-dictviews-backport/Include/opcode.h (original) +++ python/branches/twouters-dictviews-backport/Include/opcode.h Mon Feb 26 21:27:03 2007 @@ -103,12 +103,13 @@ #define COMPARE_OP 106 /* Comparison operator */ #define IMPORT_NAME 107 /* Index in name list */ #define IMPORT_FROM 108 /* Index in name list */ - +#define LOAD_VIEWATTR 109 /* Index in name list */ #define JUMP_FORWARD 110 /* Number of bytes to skip */ #define JUMP_IF_FALSE 111 /* "" */ #define JUMP_IF_TRUE 112 /* "" */ #define JUMP_ABSOLUTE 113 /* Target byte offset from beginning of code */ - +#define STORE_VIEWATTR 114 /* Index in name list */ +#define DELETE_VIEWATTR 115 /* Index in name list */ #define LOAD_GLOBAL 116 /* Index in name list */ #define CONTINUE_LOOP 119 /* Start of loop (absolute) */ Modified: python/branches/twouters-dictviews-backport/Include/pythonrun.h ============================================================================== --- python/branches/twouters-dictviews-backport/Include/pythonrun.h (original) +++ python/branches/twouters-dictviews-backport/Include/pythonrun.h Mon Feb 26 21:27:03 2007 @@ -8,7 +8,7 @@ #endif #define PyCF_MASK (CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | \ - CO_FUTURE_WITH_STATEMENT) + CO_FUTURE_WITH_STATEMENT | CO_FUTURE_DICTVIEWS) #define PyCF_MASK_OBSOLETE (CO_NESTED) #define PyCF_SOURCE_IS_UTF8 0x0100 #define PyCF_DONT_IMPLY_DEDENT 0x0200 Modified: python/branches/twouters-dictviews-backport/Lib/__future__.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/__future__.py (original) +++ python/branches/twouters-dictviews-backport/Lib/__future__.py Mon Feb 26 21:27:03 2007 @@ -66,6 +66,7 @@ CO_FUTURE_DIVISION = 0x2000 # division CO_FUTURE_ABSOLUTE_IMPORT = 0x4000 # perform absolute imports by default CO_FUTURE_WITH_STATEMENT = 0x8000 # with statement +CO_FUTURE_DICTVIEWS = 0x10000 class _Feature: def __init__(self, optionalRelease, mandatoryRelease, compiler_flag): @@ -114,3 +115,7 @@ with_statement = _Feature((2, 5, 0, "alpha", 1), (2, 6, 0, "alpha", 0), CO_FUTURE_WITH_STATEMENT) + +dictviews = _Feature((2, 6, 0, "alpha", 1), + (3, 0, 0, "alpha", 0), + CO_FUTURE_DICTVIEWS) Modified: python/branches/twouters-dictviews-backport/Lib/opcode.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/opcode.py (original) +++ python/branches/twouters-dictviews-backport/Lib/opcode.py Mon Feb 26 21:27:03 2007 @@ -144,12 +144,13 @@ hascompare.append(106) name_op('IMPORT_NAME', 107) # Index in name list name_op('IMPORT_FROM', 108) # Index in name list - +name_op('LOAD_VIEWATTR', 109) # Index in name list jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip jrel_op('JUMP_IF_FALSE', 111) # "" jrel_op('JUMP_IF_TRUE', 112) # "" jabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code - +name_op('STORE_VIEWATTR', 114) # Index in name list +name_op('DELETE_VIEWATTR', 115) # Index in name list name_op('LOAD_GLOBAL', 116) # Index in name list jabs_op('CONTINUE_LOOP', 119) # Target address Modified: python/branches/twouters-dictviews-backport/Objects/object.c ============================================================================== --- python/branches/twouters-dictviews-backport/Objects/object.c (original) +++ python/branches/twouters-dictviews-backport/Objects/object.c Mon Feb 26 21:27:03 2007 @@ -1100,6 +1100,33 @@ } PyObject * +_PyObject_GetViewAttr(PyObject *v, PyObject *name) +{ + /* Wrapper around PyObject_GetAttr that translates + dict.keys/items/values into dict.viewkeys/viewitems/viewvalues + for all subclasses of dict. It doesn't care about dict-like + objects even if they have view* attrs, and doesn't check + whether the attribute is actually one of keys/items/values */ + if (PyDict_Check(v)) { + static PyObject *viewstr; + PyObject *result; + + if (viewstr == NULL) { + viewstr = PyString_InternFromString("view"); + if (viewstr == NULL) + return NULL; + } + name = PyNumber_Add(viewstr, name); + if (name == NULL) + return NULL; + result = PyObject_GetAttr(v, name); + Py_DECREF(name); + return result; + } + return PyObject_GetAttr(v, name); +} + +PyObject * PyObject_GetAttr(PyObject *v, PyObject *name) { PyTypeObject *tp = v->ob_type; @@ -1146,6 +1173,29 @@ } int +_PyObject_SetViewAttr(PyObject *v, PyObject *name, PyObject *value) +{ + /* Like _PyObject_GetViewAttr(), but for setting/deleting */ + if (PyDict_Check(v)) { + static PyObject *viewstr; + int result; + + if (viewstr == NULL) { + viewstr = PyString_InternFromString("view"); + if (viewstr == NULL) + return -1; + } + name = PyNumber_Add(viewstr, name); + if (name == NULL) + return -1; + result = PyObject_SetAttr(v, name, value); + Py_DECREF(name); + return result; + } + return PyObject_SetAttr(v, name, value); +} + +int PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value) { PyTypeObject *tp = v->ob_type; Modified: python/branches/twouters-dictviews-backport/Python/ceval.c ============================================================================== --- python/branches/twouters-dictviews-backport/Python/ceval.c (original) +++ python/branches/twouters-dictviews-backport/Python/ceval.c Mon Feb 26 21:27:03 2007 @@ -1796,6 +1796,17 @@ if (err == 0) continue; break; + case STORE_VIEWATTR: + w = GETITEM(names, oparg); + v = TOP(); + u = SECOND(); + STACKADJ(-2); + err = _PyObject_SetViewAttr(v, w, u); /* v.w = u */ + Py_DECREF(v); + Py_DECREF(u); + if (err == 0) continue; + break; + case DELETE_ATTR: w = GETITEM(names, oparg); v = POP(); @@ -1804,6 +1815,13 @@ Py_DECREF(v); break; + case DELETE_VIEWATTR: + w = GETITEM(names, oparg); + v = POP(); + err = _PyObject_SetViewAttr(v, w, (PyObject *)NULL); + Py_DECREF(v); + break; + case STORE_GLOBAL: w = GETITEM(names, oparg); v = POP(); @@ -2003,6 +2021,16 @@ if (x != NULL) continue; break; + case LOAD_VIEWATTR: + w = GETITEM(names, oparg); + v = TOP(); + x = _PyObject_GetViewAttr(v, w); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) + continue; + break; + case COMPARE_OP: w = POP(); v = TOP(); Modified: python/branches/twouters-dictviews-backport/Python/compile.c ============================================================================== --- python/branches/twouters-dictviews-backport/Python/compile.c (original) +++ python/branches/twouters-dictviews-backport/Python/compile.c Mon Feb 26 21:27:03 2007 @@ -155,6 +155,7 @@ static basicblock *compiler_use_new_block(struct compiler *); static int compiler_error(struct compiler *, const char *); static int compiler_nameop(struct compiler *, identifier, expr_context_ty); +static int compiler_attrop(struct compiler *, expr_ty); static PyCodeObject *compiler_mod(struct compiler *, mod_ty); static int compiler_visit_stmt(struct compiler *, stmt_ty); @@ -781,8 +782,10 @@ return 1; case STORE_ATTR: + case STORE_VIEWATTR: return -2; case DELETE_ATTR: + case DELETE_VIEWATTR: return -1; case STORE_GLOBAL: return -1; @@ -800,6 +803,7 @@ case BUILD_MAP: return 1; case LOAD_ATTR: + case LOAD_VIEWATTR: return 0; case COMPARE_OP: return -1; @@ -2942,31 +2946,7 @@ break; /* The following exprs can be assignment targets. */ case Attribute_kind: - if (e->v.Attribute.ctx != AugStore) - VISIT(c, expr, e->v.Attribute.value); - switch (e->v.Attribute.ctx) { - case AugLoad: - ADDOP(c, DUP_TOP); - /* Fall through to load */ - case Load: - ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); - break; - case AugStore: - ADDOP(c, ROT_TWO); - /* Fall through to save */ - case Store: - ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); - break; - case Del: - ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names); - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid in attribute expression"); - return 0; - } - break; + return compiler_attrop(c, e); case Subscript_kind: switch (e->v.Subscript.ctx) { case AugLoad: @@ -3052,6 +3032,50 @@ return 1; } + /* Helper to handle dictviews future-import magic */ +static int +compiler_attrop(struct compiler *c, expr_ty e) +{ + int needviews = 0; + + if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_DICTVIEWS)) { + const char *attrstr = PyString_AS_STRING(e->v.Attribute.attr); + if (strcmp(attrstr, "keys") == 0 || + strcmp(attrstr, "items") == 0 || + strcmp(attrstr, "values") == 0) + needviews = 1; + } + + if (e->v.Attribute.ctx != AugStore) + VISIT(c, expr, e->v.Attribute.value); + switch (e->v.Attribute.ctx) { + case AugLoad: + ADDOP(c, DUP_TOP); + /* Fall through to load */ + case Load: + ADDOP_NAME(c, needviews ? LOAD_VIEWATTR : LOAD_ATTR, + e->v.Attribute.attr, names); + break; + case AugStore: + ADDOP(c, ROT_TWO); + /* Fall through to save */ + case Store: + ADDOP_NAME(c, needviews ? STORE_VIEWATTR : STORE_ATTR, + e->v.Attribute.attr, names); + break; + case Del: + ADDOP_NAME(c, needviews ? DELETE_VIEWATTR : DELETE_ATTR, + e->v.Attribute.attr, names); + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid in attribute expression"); + return 0; + } + return 1; +} + static int compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { Modified: python/branches/twouters-dictviews-backport/Python/future.c ============================================================================== --- python/branches/twouters-dictviews-backport/Python/future.c (original) +++ python/branches/twouters-dictviews-backport/Python/future.c Mon Feb 26 21:27:03 2007 @@ -33,6 +33,8 @@ ff->ff_features |= CO_FUTURE_ABSOLUTE_IMPORT; } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { ff->ff_features |= CO_FUTURE_WITH_STATEMENT; + } else if (strcmp(feature, FUTURE_DICTVIEWS) == 0) { + ff->ff_features |= CO_FUTURE_DICTVIEWS; } else if (strcmp(feature, "braces") == 0) { PyErr_SetString(PyExc_SyntaxError, "not a chance"); From bcannon at gmail.com Mon Feb 26 21:40:47 2007 From: bcannon at gmail.com (Brett Cannon) Date: Mon, 26 Feb 2007 14:40:47 -0600 Subject: [Python-checkins] Why? Re: r53925 - sandbox/trunk/pep362/pep362.py In-Reply-To: References: Message-ID: On 2/26/07, Guido van Rossum wrote: > On 2/26/07, Brett Cannon wrote: > > On 2/26/07, Jim Jewett wrote: > > > Why are you removing the __str__ function? > > > > > > > Because annotations prevent an accurate representation. How do you > > get int to display as 'int'? > > By changing type.__str__ to return self.__name__? I would be open to > considering this. > Guido said that we can do this if Anthony likes it for either __str__ or __repr__. What do you think, Anthony? -Brett > > > For me, > > > > > > (1) one of the more frustrating parts of the introspection API is > > > that you can't (easily) use it to create a new "similar" function. > > > > > > (2) one of the main uses of introspection is seeing what I have -- > > > and "equivalent" source code is a useful output format. > > > > > > > I undderstand; I put in the method for a reason. But if I can't have > > it properly display all information then I don't want to have to > > support a partial implementation. > > > > -Brett > > > > > > > > > > > On 2/25/07, brett.cannon wrote: > > > > Author: brett.cannon > > > > Date: Sun Feb 25 23:59:37 2007 > > > > New Revision: 53925 > > > > > > > > Modified: > > > > sandbox/trunk/pep362/pep362.py > > > > Log: > > > > Remove __str__ support. > > > > > > > > > > > > Modified: sandbox/trunk/pep362/pep362.py > > > > ============================================================================== > > > > --- sandbox/trunk/pep362/pep362.py (original) > > > > +++ sandbox/trunk/pep362/pep362.py Sun Feb 25 23:59:37 2007 > > > > @@ -49,27 +49,6 @@ > > > > self.has_annotation = True > > > > self.annotation = annotation > > > > > > > > - def _tuple2param(self, tuple_): > > > > - if not isinstance(tuple_, tuple): > > > > - return str(tuple_) > > > > - elif len(tuple_) == 1: > > > > - return "(" + str(tuple_[0]) +",)" > > > > - else: > > > > - return ('(' + > > > > - ', '.join(self._tuple2param(x) for x in tuple_) + > > > > - ')') > > > > - > > > > - def __str__(self): > > > > - """Return the string representation of the parameter as it would look > > > > - in a function's signature.""" > > > > - if isinstance(self.name, tuple): > > > > - result = self._tuple2param(self.name) > > > > - else: > > > > - result = self.name > > > > - if self.has_default: > > > > - result+= "=" + str(self.default_value) > > > > - return result > > > > - > > > > > > > > class Signature(object): > > > > > > > > @@ -92,7 +71,8 @@ > > > > keyword_only_count = func_code.co_kwonlyargcount > > > > else: > > > > keyword_only_count = 0 > > > > - positional = func_code.co_varnames[:pos_count] > > > > + #positional = func_code.co_varnames[:pos_count] > > > > + positional = argspec[0] > > > > keyword_only = func_code.co_varnames[pos_count:keyword_only_count] > > > > if func.func_defaults: > > > > pos_default_count = len(func.func_defaults) > > > > @@ -178,22 +158,6 @@ > > > > else: > > > > return tuple(cls._list2tuple(x) for x in list_) > > > > > > > > - def __str__(self): > > > > - """String representation of a signature as one might write it in source > > > > - code.""" > > > > - result = "%s(" % self.name > > > > - result += ", ".join(str(param) for param in self.parameters) > > > > - if self.var_args: > > > > - if self.parameters: > > > > - result +=", " > > > > - result += "*%s" % self.var_args > > > > - if self.var_kw_args: > > > > - if self.parameters or self.var_args: > > > > - result += ", " > > > > - result += "**%s" % self.var_kw_args > > > > - result += ")" > > > > - return result > > > > - > > > > def bind(self, *args, **kwargs): > > > > """Return a dictionary mapping function arguments to their parameter > > > > variables, if possible. > > > > _______________________________________________ > > > > Python-checkins mailing list > > > > Python-checkins at python.org > > > > http://mail.python.org/mailman/listinfo/python-checkins > > > > > > > _______________________________________________ > > > Python-checkins mailing list > > > Python-checkins at python.org > > > http://mail.python.org/mailman/listinfo/python-checkins > > > > > _______________________________________________ > > Python-checkins mailing list > > Python-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-checkins > > > > > -- > --Guido van Rossum (home page: http://www.python.org/~guido/) > From python-checkins at python.org Mon Feb 26 22:03:24 2007 From: python-checkins at python.org (thomas.wouters) Date: Mon, 26 Feb 2007 22:03:24 +0100 (CET) Subject: [Python-checkins] r53959 - python/branches/twouters-dictviews-backport/Python/bltinmodule.c Message-ID: <20070226210324.8212B1E4006@bag.python.org> Author: thomas.wouters Date: Mon Feb 26 22:03:20 2007 New Revision: 53959 Modified: python/branches/twouters-dictviews-backport/Python/bltinmodule.c Log: dictviews-future support for getattr/setattr/delattr. Modified: python/branches/twouters-dictviews-backport/Python/bltinmodule.c ============================================================================== --- python/branches/twouters-dictviews-backport/Python/bltinmodule.c (original) +++ python/branches/twouters-dictviews-backport/Python/bltinmodule.c Mon Feb 26 22:03:20 2007 @@ -5,6 +5,7 @@ #include "node.h" #include "code.h" #include "eval.h" +#include "frameobject.h" #include @@ -718,6 +719,7 @@ { PyObject *v, *result, *dflt = NULL; PyObject *name; + const char *sname; if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt)) return NULL; @@ -734,7 +736,16 @@ "getattr(): attribute name must be string"); return NULL; } - result = PyObject_GetAttr(v, name); + sname = PyString_AS_STRING(name); + /* Do some magic to see if the caller wanted dictviews or not */ + if ((strcmp(sname, "keys") == 0 || + strcmp(sname, "items") == 0 || + strcmp(sname, "values") == 0) && + (PyThreadState_GET()->frame->f_code->co_flags & + CO_FUTURE_DICTVIEWS)) { + result = _PyObject_GetViewAttr(v, name); + } else + result = PyObject_GetAttr(v, name); if (result == NULL && dflt != NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { @@ -994,10 +1005,35 @@ PyObject *v; PyObject *name; PyObject *value; + const char *sname; + int result; if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value)) return NULL; - if (PyObject_SetAttr(v, name, value) != 0) +#ifdef Py_USING_UNICODE + if (PyUnicode_Check(name)) { + name = _PyUnicode_AsDefaultEncodedString(name, NULL); + if (name == NULL) + return NULL; + } +#endif + + if (!PyString_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "setattr(): attribute name must be string"); + return NULL; + } + sname = PyString_AS_STRING(name); + /* Do some magic to see if the caller wanted dictviews or not */ + if ((strcmp(sname, "keys") == 0 || + strcmp(sname, "items") == 0 || + strcmp(sname, "values") == 0) && + (PyThreadState_GET()->frame->f_code->co_flags & + CO_FUTURE_DICTVIEWS)) { + result = _PyObject_SetViewAttr(v, name, value); + } else + result = PyObject_SetAttr(v, name, value); + if (result != 0) return NULL; Py_INCREF(Py_None); return Py_None; @@ -1015,11 +1051,34 @@ { PyObject *v; PyObject *name; + const char *sname; + int result; if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name)) return NULL; - if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) +#ifdef Py_USING_UNICODE + if (PyUnicode_Check(name)) { + name = _PyUnicode_AsDefaultEncodedString(name, NULL); + if (name == NULL) + return NULL; + } +#endif + + if (!PyString_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "delattr(): attribute name must be string"); return NULL; + } + sname = PyString_AS_STRING(name); + /* Do some magic to see if the caller wanted dictviews or not */ + if ((strcmp(sname, "keys") == 0 || + strcmp(sname, "items") == 0 || + strcmp(sname, "values") == 0) && + (PyThreadState_GET()->frame->f_code->co_flags & + CO_FUTURE_DICTVIEWS)) { + result = _PyObject_SetViewAttr(v, name, (PyObject *)NULL); + } else + result = PyObject_SetAttr(v, name, (PyObject *)NULL); Py_INCREF(Py_None); return Py_None; } From python-checkins at python.org Mon Feb 26 23:24:32 2007 From: python-checkins at python.org (thomas.wouters) Date: Mon, 26 Feb 2007 23:24:32 +0100 (CET) Subject: [Python-checkins] r53968 - in python/branches/twouters-dictviews-backport: Lib/__future__.py Lib/compiler/consts.py Lib/compiler/future.py Lib/compiler/pyassem.py Lib/compiler/pycodegen.py Lib/test/test_compiler.py Lib/test/test_dict.py Python/bltinmodule.c Message-ID: <20070226222432.8063B1E4006@bag.python.org> Author: thomas.wouters Date: Mon Feb 26 23:24:25 2007 New Revision: 53968 Modified: python/branches/twouters-dictviews-backport/Lib/__future__.py python/branches/twouters-dictviews-backport/Lib/compiler/consts.py python/branches/twouters-dictviews-backport/Lib/compiler/future.py python/branches/twouters-dictviews-backport/Lib/compiler/pyassem.py python/branches/twouters-dictviews-backport/Lib/compiler/pycodegen.py python/branches/twouters-dictviews-backport/Lib/test/test_compiler.py python/branches/twouters-dictviews-backport/Lib/test/test_dict.py python/branches/twouters-dictviews-backport/Python/bltinmodule.c Log: Add some dictview tests, and compiler support plus tests. Modified: python/branches/twouters-dictviews-backport/Lib/__future__.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/__future__.py (original) +++ python/branches/twouters-dictviews-backport/Lib/__future__.py Mon Feb 26 23:24:25 2007 @@ -53,6 +53,7 @@ "division", "absolute_import", "with_statement", + "dictviews", ] __all__ = ["all_feature_names"] + all_feature_names Modified: python/branches/twouters-dictviews-backport/Lib/compiler/consts.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/compiler/consts.py (original) +++ python/branches/twouters-dictviews-backport/Lib/compiler/consts.py Mon Feb 26 23:24:25 2007 @@ -19,3 +19,4 @@ CO_FUTURE_DIVISION = 0x2000 CO_FUTURE_ABSIMPORT = 0x4000 CO_FUTURE_WITH_STATEMENT = 0x8000 +CO_FUTURE_DICTVIEWS = 0x10000 Modified: python/branches/twouters-dictviews-backport/Lib/compiler/future.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/compiler/future.py (original) +++ python/branches/twouters-dictviews-backport/Lib/compiler/future.py Mon Feb 26 23:24:25 2007 @@ -16,7 +16,7 @@ class FutureParser: features = ("nested_scopes", "generators", "division", - "absolute_import", "with_statement") + "absolute_import", "with_statement", "dictviews") def __init__(self): self.found = {} # set Modified: python/branches/twouters-dictviews-backport/Lib/compiler/pyassem.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/compiler/pyassem.py (original) +++ python/branches/twouters-dictviews-backport/Lib/compiler/pyassem.py Mon Feb 26 23:24:25 2007 @@ -533,6 +533,9 @@ _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME + _convert_STORE_VIEWATTR = _convert_NAME + _convert_LOAD_VIEWATTR = _convert_NAME + _convert_DELETE_VIEWATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME @@ -766,7 +769,9 @@ 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, + 'STORE_VIEWATTR': -2, 'DELETE_ATTR': -1, + 'DELETE_VIEWATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, @@ -775,6 +780,7 @@ 'IMPORT_NAME': -1, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads + 'LOAD_VIEWATTR': 0, # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, Modified: python/branches/twouters-dictviews-backport/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/compiler/pycodegen.py (original) +++ python/branches/twouters-dictviews-backport/Lib/compiler/pycodegen.py Mon Feb 26 23:24:25 2007 @@ -10,7 +10,7 @@ from compiler.consts import SC_LOCAL, SC_GLOBAL, SC_FREE, SC_CELL from compiler.consts import (CO_VARARGS, CO_VARKEYWORDS, CO_NEWLOCALS, CO_NESTED, CO_GENERATOR, CO_FUTURE_DIVISION, - CO_FUTURE_ABSIMPORT, CO_FUTURE_WITH_STATEMENT) + CO_FUTURE_ABSIMPORT, CO_FUTURE_WITH_STATEMENT, CO_FUTURE_DICTVIEWS) from compiler.pyassem import TupleArg # XXX The version-specific code can go, since this code only works with 2.x. @@ -218,6 +218,8 @@ self.graph.setFlag(CO_FUTURE_ABSIMPORT) elif feature == "with_statement": self.graph.setFlag(CO_FUTURE_WITH_STATEMENT) + elif feature == "dictviews": + self.graph.setFlag(CO_FUTURE_DICTVIEWS) def initClass(self): """This method is called once for each class""" @@ -929,9 +931,18 @@ for elt in elts[1:]: self.emit('LOAD_ATTR', elt) + def _checkViewAttr(self, regop, viewop, attrname): + if (self.graph.checkFlag(CO_FUTURE_DICTVIEWS) and + attrname in ('keys', 'items', 'values')): + return viewop + else: + return regop + def visitGetattr(self, node): self.visit(node.expr) - self.emit('LOAD_ATTR', self.mangle(node.attrname)) + load_op = self._checkViewAttr('LOAD_ATTR', 'LOAD_VIEWATTR', + node.attrname) + self.emit(load_op, self.mangle(node.attrname)) # next five implement assignments @@ -958,9 +969,13 @@ def visitAssAttr(self, node): self.visit(node.expr) if node.flags == 'OP_ASSIGN': - self.emit('STORE_ATTR', self.mangle(node.attrname)) + op = self._checkViewAttr('STORE_ATTR', 'STORE_VIEWATTR', + node.attrname) + self.emit(op, self.mangle(node.attrname)) elif node.flags == 'OP_DELETE': - self.emit('DELETE_ATTR', self.mangle(node.attrname)) + op = self._checkViewAttr('DELETE_ATTR', 'DELETE_VIEWATTR', + node.attrname) + self.emit(op, self.mangle(node.attrname)) else: print "warning: unexpected flags:", node.flags print node @@ -1016,10 +1031,14 @@ if mode == "load": self.visit(node.expr) self.emit('DUP_TOP') - self.emit('LOAD_ATTR', self.mangle(node.attrname)) + op = self._checkViewAttr('LOAD_ATTR', 'LOAD_VIEWATTR', + node.attrname) + self.emit(op, self.mangle(node.attrname)) elif mode == "store": self.emit('ROT_TWO') - self.emit('STORE_ATTR', self.mangle(node.attrname)) + op = self._checkViewAttr('STORE_ATTR', 'STORE_VIEWATTR', + node.attrname) + self.emit(op, self.mangle(node.attrname)) def visitAugSlice(self, node, mode): if mode == "load": Modified: python/branches/twouters-dictviews-backport/Lib/test/test_compiler.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/test/test_compiler.py (original) +++ python/branches/twouters-dictviews-backport/Lib/test/test_compiler.py Mon Feb 26 23:24:25 2007 @@ -154,6 +154,40 @@ exec c in dct self.assertEquals(dct.get('result'), 1) + def testDictViews(self): + class Dict(dict): pass + class NonDict: + def keys(self): pass + def items(self): pass + def values(self): pass + def viewkeys(self): pass + def viewitems(self): pass + def viewvalues(self): pass + c = compiler.compile('from __future__ import dictviews\n' + 'keys, items, values = d.keys, d.items, d.values\n', + '', + 'exec') + obj = {} + dct = {'d': obj} + exec c in dct + self.assertEquals(dct['keys'].__name__, obj.viewkeys.__name__) + self.assertEquals(dct['items'].__name__, obj.viewitems.__name__) + self.assertEquals(dct['values'].__name__, obj.viewvalues.__name__) + + obj = Dict() + dct = {'d': obj} + exec c in dct + self.assertEquals(dct['keys'].__name__, obj.viewkeys.__name__) + self.assertEquals(dct['items'].__name__, obj.viewitems.__name__) + self.assertEquals(dct['values'].__name__, obj.viewvalues.__name__) + + obj = NonDict() + dct = {'d': obj} + exec c in dct + self.assertEquals(dct['keys'].__name__, obj.keys.__name__) + self.assertEquals(dct['items'].__name__, obj.items.__name__) + self.assertEquals(dct['values'].__name__, obj.values.__name__) + NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard) Modified: python/branches/twouters-dictviews-backport/Lib/test/test_dict.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/test/test_dict.py (original) +++ python/branches/twouters-dictviews-backport/Lib/test/test_dict.py Mon Feb 26 23:24:25 2007 @@ -56,7 +56,7 @@ def test_items(self): d = {} - self.assertEqual(list(d.items(), []) + self.assertEqual(list(d.items()), []) d = {1:2} self.assertEqual(d.items(), [(1, 2)]) @@ -491,6 +491,89 @@ else: self.fail("missing KeyError") + def test_dictviews_future(self): + import __future__ + + d = {'a': 1, 'b': 2, 'c': 3} + c = compile("d.keys", "d.keys", "eval", 0) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.keys.__name__) + c = compile("d.items", "d.items", "eval", 0) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.items.__name__) + c = compile("d.values", "d.values", "eval", 0) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.values.__name__) + c = compile("d.keys", "d.keys", "eval", + __future__.CO_FUTURE_DICTVIEWS) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.viewkeys.__name__) + c = compile("d.items", "d.items", "eval", + __future__.CO_FUTURE_DICTVIEWS) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.viewitems.__name__) + c = compile("d.values", "d.values", "eval", + __future__.CO_FUTURE_DICTVIEWS) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.viewvalues.__name__) + + d = Dict(a=1, b=2, c=3) + c = compile("d.keys", "d.keys", "eval", 0) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.keys.__name__) + c = compile("d.items", "d.items", "eval", 0) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.items.__name__) + c = compile("d.values", "d.values", "eval", 0) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.values.__name__) + c = compile("d.keys", "d.keys", "eval", + __future__.CO_FUTURE_DICTVIEWS) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.viewkeys.__name__) + c = compile("d.items", "d.items", "eval", + __future__.CO_FUTURE_DICTVIEWS) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.viewitems.__name__) + c = compile("d.values", "d.values", "eval", + __future__.CO_FUTURE_DICTVIEWS) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.viewvalues.__name__) + + class NonDict: + def __init__(self, *args, **kwargs): + self.d = dict(*args, **kwargs) + def keys(self): return self.d.keys() + def items(self): return self.d.items() + def values(self): return self.d.values() + # these should *not* end up being used + def viewkeys(self): pass + def viewitems(self): pass + def viewvalues(self): pass + + d = NonDict(a=1, b=2, c=3) + c = compile("d.keys", "d.keys", "eval", 0) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.keys.__name__) + c = compile("d.items", "d.items", "eval", 0) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.items.__name__) + c = compile("d.values", "d.values", "eval", 0) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.values.__name__) + c = compile("d.keys", "d.keys", "eval", + __future__.CO_FUTURE_DICTVIEWS) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.keys.__name__) + c = compile("d.items", "d.items", "eval", + __future__.CO_FUTURE_DICTVIEWS) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.items.__name__) + c = compile("d.values", "d.values", "eval", + __future__.CO_FUTURE_DICTVIEWS) + k = eval(c, locals()) + self.assertEquals(k.__name__, d.values.__name__) + from test import mapping_tests Modified: python/branches/twouters-dictviews-backport/Python/bltinmodule.c ============================================================================== --- python/branches/twouters-dictviews-backport/Python/bltinmodule.c (original) +++ python/branches/twouters-dictviews-backport/Python/bltinmodule.c Mon Feb 26 23:24:25 2007 @@ -1079,6 +1079,8 @@ result = _PyObject_SetViewAttr(v, name, (PyObject *)NULL); } else result = PyObject_SetAttr(v, name, (PyObject *)NULL); + if (result != 0) + return NULL; Py_INCREF(Py_None); return Py_None; } From python-checkins at python.org Mon Feb 26 23:41:54 2007 From: python-checkins at python.org (neal.norwitz) Date: Mon, 26 Feb 2007 23:41:54 +0100 (CET) Subject: [Python-checkins] r53969 - in python/trunk: Lib/test/test_generators.py Misc/NEWS Python/errors.c Message-ID: <20070226224154.A3C421E4006@bag.python.org> Author: neal.norwitz Date: Mon Feb 26 23:41:45 2007 New Revision: 53969 Modified: python/trunk/Lib/test/test_generators.py python/trunk/Misc/NEWS python/trunk/Python/errors.c Log: When printing an unraisable error, don't print exceptions. before the name. This duplicates the behavior whening normally printing exceptions. Modified: python/trunk/Lib/test/test_generators.py ============================================================================== --- python/trunk/Lib/test/test_generators.py (original) +++ python/trunk/Lib/test/test_generators.py Mon Feb 26 23:41:45 2007 @@ -1681,7 +1681,7 @@ >>> g.next() >>> del g >>> sys.stderr.getvalue().startswith( -... "Exception exceptions.RuntimeError: 'generator ignored GeneratorExit' in " +... "Exception RuntimeError: 'generator ignored GeneratorExit' in " ... ) True >>> sys.stderr = old @@ -1798,7 +1798,7 @@ ... del l ... err = sys.stderr.getvalue().strip() ... err.startswith( -... "Exception exceptions.RuntimeError: RuntimeError() in <" +... "Exception RuntimeError: RuntimeError() in <" ... ) ... err.endswith("> ignored") ... len(err.splitlines()) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon Feb 26 23:41:45 2007 @@ -12,6 +12,9 @@ Core and builtins ----------------- +- When printing an unraisable error, don't print exceptions. before the name. + This duplicates the behavior whening normally printing exceptions. + - Bug #1653736: Properly discard third argument to slot_nb_inplace_power. - PEP 352: Raising a string exception now triggers a TypeError. Attempting to Modified: python/trunk/Python/errors.c ============================================================================== --- python/trunk/Python/errors.c (original) +++ python/trunk/Python/errors.c Mon Feb 26 23:41:45 2007 @@ -603,7 +603,8 @@ PyFile_WriteString("", f); else { char* modstr = PyString_AsString(moduleName); - if (modstr) + if (modstr && + strcmp(modstr, "exceptions") != 0) { PyFile_WriteString(modstr, f); PyFile_WriteString(".", f); From python-checkins at python.org Tue Feb 27 00:02:50 2007 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 27 Feb 2007 00:02:50 +0100 (CET) Subject: [Python-checkins] r53970 - python/trunk/Doc/lib/libgettext.tex Message-ID: <20070226230250.254FF1E4006@bag.python.org> Author: andrew.kuchling Date: Tue Feb 27 00:02:47 2007 New Revision: 53970 Modified: python/trunk/Doc/lib/libgettext.tex Log: Markup fix Modified: python/trunk/Doc/lib/libgettext.tex ============================================================================== --- python/trunk/Doc/lib/libgettext.tex (original) +++ python/trunk/Doc/lib/libgettext.tex Tue Feb 27 00:02:47 2007 @@ -102,9 +102,9 @@ return \var{plural} otherwise. The Plural formula is taken from the catalog header. It is a C or -Python expression that has a free variable n; the expression evaluates +Python expression that has a free variable \var{n}; the expression evaluates to the index of the plural in the catalog. See the GNU gettext -documentation for the precise syntax to be used in .po files, and the +documentation for the precise syntax to be used in \file{.po} files and the formulas for a variety of languages. \versionadded{2.3} From python-checkins at python.org Tue Feb 27 00:03:08 2007 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 27 Feb 2007 00:03:08 +0100 (CET) Subject: [Python-checkins] r53971 - python/branches/release25-maint/Doc/lib/libgettext.tex Message-ID: <20070226230308.618031E4006@bag.python.org> Author: andrew.kuchling Date: Tue Feb 27 00:03:03 2007 New Revision: 53971 Modified: python/branches/release25-maint/Doc/lib/libgettext.tex Log: Markup fix Modified: python/branches/release25-maint/Doc/lib/libgettext.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libgettext.tex (original) +++ python/branches/release25-maint/Doc/lib/libgettext.tex Tue Feb 27 00:03:03 2007 @@ -102,9 +102,9 @@ return \var{plural} otherwise. The Plural formula is taken from the catalog header. It is a C or -Python expression that has a free variable n; the expression evaluates +Python expression that has a free variable \var{n}; the expression evaluates to the index of the plural in the catalog. See the GNU gettext -documentation for the precise syntax to be used in .po files, and the +documentation for the precise syntax to be used in \file{.po} files and the formulas for a variety of languages. \versionadded{2.3} From python-checkins at python.org Tue Feb 27 00:46:56 2007 From: python-checkins at python.org (neal.norwitz) Date: Tue, 27 Feb 2007 00:46:56 +0100 (CET) Subject: [Python-checkins] r53974 - in python/branches/release25-maint: Misc/NEWS Python/errors.c Message-ID: <20070226234656.608571E4013@bag.python.org> Author: neal.norwitz Date: Tue Feb 27 00:46:51 2007 New Revision: 53974 Modified: python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Python/errors.c Log: Fix SF bug #1669182. Handle string exceptions even if unraisable (ie in __del__). Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Tue Feb 27 00:46:51 2007 @@ -12,6 +12,9 @@ Core and builtins ----------------- +- Bug #1669182: prevent crash when trying to print an unraisable error + from a string exception. + - Bug #1653736: Properly discard third argument to slot_nb_inplace_power. - SF #151204: enumerate() now raises an Overflow error at sys.maxint items. Modified: python/branches/release25-maint/Python/errors.c ============================================================================== --- python/branches/release25-maint/Python/errors.c (original) +++ python/branches/release25-maint/Python/errors.c Tue Feb 27 00:46:51 2007 @@ -590,7 +590,11 @@ PyFile_WriteString("Exception ", f); if (t) { PyObject* moduleName; - char* className = PyExceptionClass_Name(t); + char* className = NULL; + if (PyExceptionClass_Check(t)) + className = PyExceptionClass_Name(t); + else if (PyString_Check(t)) + className = PyString_AS_STRING(t); if (className != NULL) { char *dot = strrchr(className, '.'); From python-checkins at python.org Tue Feb 27 00:48:30 2007 From: python-checkins at python.org (neal.norwitz) Date: Tue, 27 Feb 2007 00:48:30 +0100 (CET) Subject: [Python-checkins] r53975 - python/trunk/Python/errors.c Message-ID: <20070226234830.A09E61E4006@bag.python.org> Author: neal.norwitz Date: Tue Feb 27 00:48:27 2007 New Revision: 53975 Modified: python/trunk/Python/errors.c Log: SF #1669182, 2.5 was already fixed. Just assert in 2.6 since string exceptions are gone. Modified: python/trunk/Python/errors.c ============================================================================== --- python/trunk/Python/errors.c (original) +++ python/trunk/Python/errors.c Tue Feb 27 00:48:27 2007 @@ -590,8 +590,9 @@ PyFile_WriteString("Exception ", f); if (t) { PyObject* moduleName; - char* className = PyExceptionClass_Name(t); - + char* className; + assert(PyExceptionClass_Check(t)); + className = PyExceptionClass_Name(t); if (className != NULL) { char *dot = strrchr(className, '.'); if (dot != NULL) From python-checkins at python.org Tue Feb 27 00:54:21 2007 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 27 Feb 2007 00:54:21 +0100 (CET) Subject: [Python-checkins] r53976 - python/trunk/Doc/whatsnew/whatsnew26.tex Message-ID: <20070226235421.4915D1E4006@bag.python.org> Author: andrew.kuchling Date: Tue Feb 27 00:54:17 2007 New Revision: 53976 Modified: python/trunk/Doc/whatsnew/whatsnew26.tex Log: Add some items Modified: python/trunk/Doc/whatsnew/whatsnew26.tex ============================================================================== --- python/trunk/Doc/whatsnew/whatsnew26.tex (original) +++ python/trunk/Doc/whatsnew/whatsnew26.tex Tue Feb 27 00:54:17 2007 @@ -37,7 +37,13 @@ language. \begin{itemize} -\item TBD + +% Bug 1569356 +\item An obscure change: when you use the the \function{locals()} +function inside a \keyword{class} statement, the resulting dictionary +no longer returns free variables. (Free variables, in this case, are +variables referred to in the \keyword{class} statement +that aren't attributes of the class.) \end{itemize} @@ -47,7 +53,10 @@ \begin{itemize} -\item Optimizations should be described here. +% Patch 1624059 +\item Internally, a bit is now set in type objects to indicate some of +the standard built-in types. This speeds up checking if an object is +a subclass of one of these types. (Contributed by Neal Norwitz.) \end{itemize} @@ -67,6 +76,43 @@ \begin{itemize} +\item New function in the \module{heapq} module: +\function{merge(iter1, iter2, ...)} +takes any number of iterables that return data +\emph{in sorted order}, +and +returns a new iterator that returns the contents of +all the iterators, also in sorted order. For example: + +\begin{verbatim} +heapq.merge([1, 3, 5, 9], [2, 8, 16]) -> + [1, 2, 3, 5, 8, 9, 16] +\end{verbatim} + +(Contributed by Raymond Hettinger.) + +\item New function in the \module{itertools} module: +\function{izip_longest(iter1, iter2, ...\optional{, fillvalue})} +makes tuples from each of the elements; if some of the iterables +are shorter than others, the missing values +are set to \var{fillvalue}. For example: + +\begin{verbatim} +itertools.izip_longest([1,2,3], [1,2,3,4,5]) -> + [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)] +\end{verbatim} + +(Contributed by Raymond Hettinger.) + +% Patch #1490190 +\item New functions in the \module{posix} module: \function{chflags()} +and \function{lchflags()} are wrappers for the corresponding system +calls (where they're available). Constants for the flag values are +defined in the \module{stat} module; some possible values include +\constant{UF_IMMUTABLE} to signal the file may not be changed and +\constant{UF_APPEND} to indicate that data can only be appended to the +file. (Contributed by M. Levinson.) + \item The \module{smtplib} module now supports SMTP over SSL thanks to the addition of the \class{SMTP_SSL} class. This class supports an interface identical to the existing \class{SMTP} From python-checkins at python.org Tue Feb 27 01:10:28 2007 From: python-checkins at python.org (thomas.wouters) Date: Tue, 27 Feb 2007 01:10:28 +0100 (CET) Subject: [Python-checkins] r53977 - in python/branches/twouters-dictviews-backport: Include/code.h Include/compile.h Include/pythonrun.h Lib/__future__.py Lib/compiler/consts.py Lib/compiler/future.py Lib/compiler/pycodegen.py Lib/test/test_compiler.py Lib/test/test_dict.py Lib/test/test_dictviews.py Python/bltinmodule.c Python/compile.c Python/future.c Message-ID: <20070227001028.CC5011E4006@bag.python.org> Author: thomas.wouters Date: Tue Feb 27 01:10:25 2007 New Revision: 53977 Added: python/branches/twouters-dictviews-backport/Lib/test/test_dictviews.py - copied, changed from r53969, python/branches/p3yk/Lib/test/test_dictviews.py Modified: python/branches/twouters-dictviews-backport/Include/code.h python/branches/twouters-dictviews-backport/Include/compile.h python/branches/twouters-dictviews-backport/Include/pythonrun.h python/branches/twouters-dictviews-backport/Lib/__future__.py python/branches/twouters-dictviews-backport/Lib/compiler/consts.py python/branches/twouters-dictviews-backport/Lib/compiler/future.py python/branches/twouters-dictviews-backport/Lib/compiler/pycodegen.py python/branches/twouters-dictviews-backport/Lib/test/test_compiler.py python/branches/twouters-dictviews-backport/Lib/test/test_dict.py python/branches/twouters-dictviews-backport/Python/bltinmodule.c python/branches/twouters-dictviews-backport/Python/compile.c python/branches/twouters-dictviews-backport/Python/future.c Log: Rename the 'dictviews' future-import into 'dict_views' as Guido requested. Also copy test_dictviews from p3yk (but adjust for the lack of set literals.) Modified: python/branches/twouters-dictviews-backport/Include/code.h ============================================================================== --- python/branches/twouters-dictviews-backport/Include/code.h (original) +++ python/branches/twouters-dictviews-backport/Include/code.h Tue Feb 27 01:10:25 2007 @@ -48,7 +48,7 @@ #define CO_FUTURE_DIVISION 0x2000 #define CO_FUTURE_ABSOLUTE_IMPORT 0x4000 /* do absolute imports by default */ #define CO_FUTURE_WITH_STATEMENT 0x8000 -#define CO_FUTURE_DICTVIEWS 0x10000 +#define CO_FUTURE_DICT_VIEWS 0x10000 /* This should be defined if a future statement modifies the syntax. For example, when a keyword is added. Modified: python/branches/twouters-dictviews-backport/Include/compile.h ============================================================================== --- python/branches/twouters-dictviews-backport/Include/compile.h (original) +++ python/branches/twouters-dictviews-backport/Include/compile.h Tue Feb 27 01:10:25 2007 @@ -24,7 +24,7 @@ #define FUTURE_DIVISION "division" #define FUTURE_ABSOLUTE_IMPORT "absolute_import" #define FUTURE_WITH_STATEMENT "with_statement" -#define FUTURE_DICTVIEWS "dictviews" +#define FUTURE_DICT_VIEWS "dict_views" struct _mod; /* Declare the existence of this type */ PyAPI_FUNC(PyCodeObject *) PyAST_Compile(struct _mod *, const char *, Modified: python/branches/twouters-dictviews-backport/Include/pythonrun.h ============================================================================== --- python/branches/twouters-dictviews-backport/Include/pythonrun.h (original) +++ python/branches/twouters-dictviews-backport/Include/pythonrun.h Tue Feb 27 01:10:25 2007 @@ -8,7 +8,7 @@ #endif #define PyCF_MASK (CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | \ - CO_FUTURE_WITH_STATEMENT | CO_FUTURE_DICTVIEWS) + CO_FUTURE_WITH_STATEMENT | CO_FUTURE_DICT_VIEWS) #define PyCF_MASK_OBSOLETE (CO_NESTED) #define PyCF_SOURCE_IS_UTF8 0x0100 #define PyCF_DONT_IMPLY_DEDENT 0x0200 Modified: python/branches/twouters-dictviews-backport/Lib/__future__.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/__future__.py (original) +++ python/branches/twouters-dictviews-backport/Lib/__future__.py Tue Feb 27 01:10:25 2007 @@ -53,7 +53,7 @@ "division", "absolute_import", "with_statement", - "dictviews", + "dict_views", ] __all__ = ["all_feature_names"] + all_feature_names @@ -67,7 +67,7 @@ CO_FUTURE_DIVISION = 0x2000 # division CO_FUTURE_ABSOLUTE_IMPORT = 0x4000 # perform absolute imports by default CO_FUTURE_WITH_STATEMENT = 0x8000 # with statement -CO_FUTURE_DICTVIEWS = 0x10000 +CO_FUTURE_DICT_VIEWS = 0x10000 class _Feature: def __init__(self, optionalRelease, mandatoryRelease, compiler_flag): @@ -117,6 +117,6 @@ (2, 6, 0, "alpha", 0), CO_FUTURE_WITH_STATEMENT) -dictviews = _Feature((2, 6, 0, "alpha", 1), - (3, 0, 0, "alpha", 0), - CO_FUTURE_DICTVIEWS) +dict_views = _Feature((2, 6, 0, "alpha", 1), + (3, 0, 0, "alpha", 0), + CO_FUTURE_DICT_VIEWS) Modified: python/branches/twouters-dictviews-backport/Lib/compiler/consts.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/compiler/consts.py (original) +++ python/branches/twouters-dictviews-backport/Lib/compiler/consts.py Tue Feb 27 01:10:25 2007 @@ -19,4 +19,4 @@ CO_FUTURE_DIVISION = 0x2000 CO_FUTURE_ABSIMPORT = 0x4000 CO_FUTURE_WITH_STATEMENT = 0x8000 -CO_FUTURE_DICTVIEWS = 0x10000 +CO_FUTURE_DICT_VIEWS = 0x10000 Modified: python/branches/twouters-dictviews-backport/Lib/compiler/future.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/compiler/future.py (original) +++ python/branches/twouters-dictviews-backport/Lib/compiler/future.py Tue Feb 27 01:10:25 2007 @@ -16,7 +16,7 @@ class FutureParser: features = ("nested_scopes", "generators", "division", - "absolute_import", "with_statement", "dictviews") + "absolute_import", "with_statement", "dict_views") def __init__(self): self.found = {} # set Modified: python/branches/twouters-dictviews-backport/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/compiler/pycodegen.py (original) +++ python/branches/twouters-dictviews-backport/Lib/compiler/pycodegen.py Tue Feb 27 01:10:25 2007 @@ -10,7 +10,7 @@ from compiler.consts import SC_LOCAL, SC_GLOBAL, SC_FREE, SC_CELL from compiler.consts import (CO_VARARGS, CO_VARKEYWORDS, CO_NEWLOCALS, CO_NESTED, CO_GENERATOR, CO_FUTURE_DIVISION, - CO_FUTURE_ABSIMPORT, CO_FUTURE_WITH_STATEMENT, CO_FUTURE_DICTVIEWS) + CO_FUTURE_ABSIMPORT, CO_FUTURE_WITH_STATEMENT, CO_FUTURE_DICT_VIEWS) from compiler.pyassem import TupleArg # XXX The version-specific code can go, since this code only works with 2.x. @@ -218,8 +218,8 @@ self.graph.setFlag(CO_FUTURE_ABSIMPORT) elif feature == "with_statement": self.graph.setFlag(CO_FUTURE_WITH_STATEMENT) - elif feature == "dictviews": - self.graph.setFlag(CO_FUTURE_DICTVIEWS) + elif feature == "dict_views": + self.graph.setFlag(CO_FUTURE_DICT_VIEWS) def initClass(self): """This method is called once for each class""" @@ -932,7 +932,7 @@ self.emit('LOAD_ATTR', elt) def _checkViewAttr(self, regop, viewop, attrname): - if (self.graph.checkFlag(CO_FUTURE_DICTVIEWS) and + if (self.graph.checkFlag(CO_FUTURE_DICT_VIEWS) and attrname in ('keys', 'items', 'values')): return viewop else: Modified: python/branches/twouters-dictviews-backport/Lib/test/test_compiler.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/test/test_compiler.py (original) +++ python/branches/twouters-dictviews-backport/Lib/test/test_compiler.py Tue Feb 27 01:10:25 2007 @@ -163,7 +163,7 @@ def viewkeys(self): pass def viewitems(self): pass def viewvalues(self): pass - c = compiler.compile('from __future__ import dictviews\n' + c = compiler.compile('from __future__ import dict_views\n' 'keys, items, values = d.keys, d.items, d.values\n', '', 'exec') Modified: python/branches/twouters-dictviews-backport/Lib/test/test_dict.py ============================================================================== --- python/branches/twouters-dictviews-backport/Lib/test/test_dict.py (original) +++ python/branches/twouters-dictviews-backport/Lib/test/test_dict.py Tue Feb 27 01:10:25 2007 @@ -491,7 +491,7 @@ else: self.fail("missing KeyError") - def test_dictviews_future(self): + def test_dict_views_future(self): import __future__ d = {'a': 1, 'b': 2, 'c': 3} @@ -505,15 +505,15 @@ k = eval(c, locals()) self.assertEquals(k.__name__, d.values.__name__) c = compile("d.keys", "d.keys", "eval", - __future__.CO_FUTURE_DICTVIEWS) + __future__.CO_FUTURE_DICT_VIEWS) k = eval(c, locals()) self.assertEquals(k.__name__, d.viewkeys.__name__) c = compile("d.items", "d.items", "eval", - __future__.CO_FUTURE_DICTVIEWS) + __future__.CO_FUTURE_DICT_VIEWS) k = eval(c, locals()) self.assertEquals(k.__name__, d.viewitems.__name__) c = compile("d.values", "d.values", "eval", - __future__.CO_FUTURE_DICTVIEWS) + __future__.CO_FUTURE_DICT_VIEWS) k = eval(c, locals()) self.assertEquals(k.__name__, d.viewvalues.__name__) @@ -528,15 +528,15 @@ k = eval(c, locals()) self.assertEquals(k.__name__, d.values.__name__) c = compile("d.keys", "d.keys", "eval", - __future__.CO_FUTURE_DICTVIEWS) + __future__.CO_FUTURE_DICT_VIEWS) k = eval(c, locals()) self.assertEquals(k.__name__, d.viewkeys.__name__) c = compile("d.items", "d.items", "eval", - __future__.CO_FUTURE_DICTVIEWS) + __future__.CO_FUTURE_DICT_VIEWS) k = eval(c, locals()) self.assertEquals(k.__name__, d.viewitems.__name__) c = compile("d.values", "d.values", "eval", - __future__.CO_FUTURE_DICTVIEWS) + __future__.CO_FUTURE_DICT_VIEWS) k = eval(c, locals()) self.assertEquals(k.__name__, d.viewvalues.__name__) @@ -562,15 +562,15 @@ k = eval(c, locals()) self.assertEquals(k.__name__, d.values.__name__) c = compile("d.keys", "d.keys", "eval", - __future__.CO_FUTURE_DICTVIEWS) + __future__.CO_FUTURE_DICT_VIEWS) k = eval(c, locals()) self.assertEquals(k.__name__, d.keys.__name__) c = compile("d.items", "d.items", "eval", - __future__.CO_FUTURE_DICTVIEWS) + __future__.CO_FUTURE_DICT_VIEWS) k = eval(c, locals()) self.assertEquals(k.__name__, d.items.__name__) c = compile("d.values", "d.values", "eval", - __future__.CO_FUTURE_DICTVIEWS) + __future__.CO_FUTURE_DICT_VIEWS) k = eval(c, locals()) self.assertEquals(k.__name__, d.values.__name__) Copied: python/branches/twouters-dictviews-backport/Lib/test/test_dictviews.py (from r53969, python/branches/p3yk/Lib/test/test_dictviews.py) ============================================================================== --- python/branches/p3yk/Lib/test/test_dictviews.py (original) +++ python/branches/twouters-dictviews-backport/Lib/test/test_dictviews.py Tue Feb 27 01:10:25 2007 @@ -1,3 +1,4 @@ +from __future__ import dict_views import unittest from test import test_support @@ -18,11 +19,11 @@ d = {1: 10, "a": "ABC"} keys = d.keys() self.assertEqual(len(keys), 2) - self.assertEqual(set(keys), {1, "a"}) - self.assertEqual(keys, {1, "a"}) - self.assertNotEqual(keys, {1, "a", "b"}) - self.assertNotEqual(keys, {1, "b"}) - self.assertNotEqual(keys, {1}) + self.assertEqual(set(keys), set([1, "a"])) + self.assertEqual(keys, set([1, "a"])) + self.assertNotEqual(keys, set([1, "a", "b"])) + self.assertNotEqual(keys, set([1, "b"])) + self.assertNotEqual(keys, set([1])) self.assertNotEqual(keys, 42) self.assert_(1 in keys) self.assert_("a" in keys) @@ -38,11 +39,11 @@ d = {1: 10, "a": "ABC"} items = d.items() self.assertEqual(len(items), 2) - self.assertEqual(set(items), {(1, 10), ("a", "ABC")}) - self.assertEqual(items, {(1, 10), ("a", "ABC")}) - self.assertNotEqual(items, {(1, 10), ("a", "ABC"), "junk"}) - self.assertNotEqual(items, {(1, 10), ("a", "def")}) - self.assertNotEqual(items, {(1, 10)}) + self.assertEqual(set(items), set([(1, 10), ("a", "ABC")])) + self.assertEqual(items, set([(1, 10), ("a", "ABC")])) + self.assertNotEqual(items, set([(1, 10), ("a", "ABC"), "junk"])) + self.assertNotEqual(items, set([(1, 10), ("a", "def")])) + self.assertNotEqual(items, set([(1, 10)])) self.assertNotEqual(items, 42) self.assert_((1, 10) in items) self.assert_(("a", "ABC") in items) @@ -66,7 +67,7 @@ def test_dict_values(self): d = {1: 10, "a": "ABC"} values = d.values() - self.assertEqual(set(values), {10, "ABC"}) + self.assertEqual(set(values), set([10, "ABC"])) self.assertEqual(len(values), 2) def test_main(): Modified: python/branches/twouters-dictviews-backport/Python/bltinmodule.c ============================================================================== --- python/branches/twouters-dictviews-backport/Python/bltinmodule.c (original) +++ python/branches/twouters-dictviews-backport/Python/bltinmodule.c Tue Feb 27 01:10:25 2007 @@ -742,7 +742,7 @@ strcmp(sname, "items") == 0 || strcmp(sname, "values") == 0) && (PyThreadState_GET()->frame->f_code->co_flags & - CO_FUTURE_DICTVIEWS)) { + CO_FUTURE_DICT_VIEWS)) { result = _PyObject_GetViewAttr(v, name); } else result = PyObject_GetAttr(v, name); @@ -1029,7 +1029,7 @@ strcmp(sname, "items") == 0 || strcmp(sname, "values") == 0) && (PyThreadState_GET()->frame->f_code->co_flags & - CO_FUTURE_DICTVIEWS)) { + CO_FUTURE_DICT_VIEWS)) { result = _PyObject_SetViewAttr(v, name, value); } else result = PyObject_SetAttr(v, name, value); @@ -1075,7 +1075,7 @@ strcmp(sname, "items") == 0 || strcmp(sname, "values") == 0) && (PyThreadState_GET()->frame->f_code->co_flags & - CO_FUTURE_DICTVIEWS)) { + CO_FUTURE_DICT_VIEWS)) { result = _PyObject_SetViewAttr(v, name, (PyObject *)NULL); } else result = PyObject_SetAttr(v, name, (PyObject *)NULL); Modified: python/branches/twouters-dictviews-backport/Python/compile.c ============================================================================== --- python/branches/twouters-dictviews-backport/Python/compile.c (original) +++ python/branches/twouters-dictviews-backport/Python/compile.c Tue Feb 27 01:10:25 2007 @@ -3032,13 +3032,13 @@ return 1; } - /* Helper to handle dictviews future-import magic */ + /* Helper to handle dict views future-import magic */ static int compiler_attrop(struct compiler *c, expr_ty e) { int needviews = 0; - if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_DICTVIEWS)) { + if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_DICT_VIEWS)) { const char *attrstr = PyString_AS_STRING(e->v.Attribute.attr); if (strcmp(attrstr, "keys") == 0 || strcmp(attrstr, "items") == 0 || Modified: python/branches/twouters-dictviews-backport/Python/future.c ============================================================================== --- python/branches/twouters-dictviews-backport/Python/future.c (original) +++ python/branches/twouters-dictviews-backport/Python/future.c Tue Feb 27 01:10:25 2007 @@ -33,8 +33,8 @@ ff->ff_features |= CO_FUTURE_ABSOLUTE_IMPORT; } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { ff->ff_features |= CO_FUTURE_WITH_STATEMENT; - } else if (strcmp(feature, FUTURE_DICTVIEWS) == 0) { - ff->ff_features |= CO_FUTURE_DICTVIEWS; + } else if (strcmp(feature, FUTURE_DICT_VIEWS) == 0) { + ff->ff_features |= CO_FUTURE_DICT_VIEWS; } else if (strcmp(feature, "braces") == 0) { PyErr_SetString(PyExc_SyntaxError, "not a chance"); From python-checkins at python.org Tue Feb 27 01:28:30 2007 From: python-checkins at python.org (guido.van.rossum) Date: Tue, 27 Feb 2007 01:28:30 +0100 (CET) Subject: [Python-checkins] r53980 - peps/trunk/pep-3111.txt Message-ID: <20070227002830.5F57B1E4006@bag.python.org> Author: guido.van.rossum Date: Tue Feb 27 01:28:24 2007 New Revision: 53980 Modified: peps/trunk/pep-3111.txt Log: This pep was accepted but the status was never updated. Modified: peps/trunk/pep-3111.txt ============================================================================== --- peps/trunk/pep-3111.txt (original) +++ peps/trunk/pep-3111.txt Tue Feb 27 01:28:24 2007 @@ -2,8 +2,8 @@ Title: Simple input built-in in Python 3000 Version: $Revision$ Last-Modified: $Date$ -Author: Andr? Roberge -Status: Draft +Author: Andre Roberge +Status: Accepted Type: Standards Track Content-Type: text/x-rst Created: 13-Sep-2006 From python-checkins at python.org Tue Feb 27 02:02:00 2007 From: python-checkins at python.org (jeremy.hylton) Date: Tue, 27 Feb 2007 02:02:00 +0100 (CET) Subject: [Python-checkins] r53981 - in python/trunk: Lib/test/test_compile.py Python/compile.c Message-ID: <20070227010200.DC6491E4019@bag.python.org> Author: jeremy.hylton Date: Tue Feb 27 02:01:59 2007 New Revision: 53981 Modified: python/trunk/Lib/test/test_compile.py python/trunk/Python/compile.c Log: Fix long-standing bug in name mangling for package imports Reported by Mike Verdone. Modified: python/trunk/Lib/test/test_compile.py ============================================================================== --- python/trunk/Lib/test/test_compile.py (original) +++ python/trunk/Lib/test/test_compile.py Tue Feb 27 02:01:59 2007 @@ -394,6 +394,19 @@ del d[..., ...] self.assertEqual((Ellipsis, Ellipsis) in d, False) + def test_mangling(self): + class A: + def f(): + __mangled = 1 + __not_mangled__ = 2 + import __mangled_mod + import __package__.module + + self.assert_("_A__mangled" in A.f.func_code.co_varnames) + self.assert_("__not_mangled__" in A.f.func_code.co_varnames) + self.assert_("_A__mangled_mod" in A.f.func_code.co_varnames) + self.assert_("__package__" in A.f.func_code.co_varnames) + def test_main(): test_support.run_unittest(TestSpecifics) Modified: python/trunk/Python/compile.c ============================================================================== --- python/trunk/Python/compile.c (original) +++ python/trunk/Python/compile.c Tue Feb 27 02:01:59 2007 @@ -194,7 +194,17 @@ } p = PyString_AsString(privateobj); nlen = strlen(name); - if (name[nlen-1] == '_' && name[nlen-2] == '_') { + /* Don't mangle __id__ or names with dots. + + The only time a name with a dot can occur is when + we are compiling an import statement that has a + package name. + + TODO(jhylton): Decide whether we want to support + mangling of the module name, e.g. __M.X. + */ + if ((name[nlen-1] == '_' && name[nlen-2] == '_') + || strchr(name, '.')) { Py_INCREF(ident); return ident; /* Don't mangle __whatever__ */ } @@ -2243,7 +2253,7 @@ return compiler_error(c, "can not assign to __debug__"); } - mangled = _Py_Mangle(c->u->u_private, name); +mangled = _Py_Mangle(c->u->u_private, name); if (!mangled) return 0; From python-checkins at python.org Tue Feb 27 09:39:10 2007 From: python-checkins at python.org (georg.brandl) Date: Tue, 27 Feb 2007 09:39:10 +0100 (CET) Subject: [Python-checkins] r53988 - peps/trunk/pep-0358.txt Message-ID: <20070227083910.04E441E4007@bag.python.org> Author: georg.brandl Date: Tue Feb 27 09:39:07 2007 New Revision: 53988 Modified: peps/trunk/pep-0358.txt Log: Correctly specify the set of hexadecimal characters. Modified: peps/trunk/pep-0358.txt ============================================================================== --- peps/trunk/pep-0358.txt (original) +++ peps/trunk/pep-0358.txt Tue Feb 27 09:39:07 2007 @@ -91,7 +91,7 @@ The object has a .decode() method equivalent to the .decode() method of the str object. The object has a classmethod .fromhex() - that takes a string of characters from the set [0-9a-zA-Z ] and + that takes a string of characters from the set [0-9a-fA-F ] and returns a bytes object (similar to binascii.unhexlify). For example: From python-checkins at python.org Tue Feb 27 17:00:08 2007 From: python-checkins at python.org (jeremy.hylton) Date: Tue, 27 Feb 2007 17:00:08 +0100 (CET) Subject: [Python-checkins] r53993 - python/trunk/Objects/frameobject.c Message-ID: <20070227160008.D8DB21E4019@bag.python.org> Author: jeremy.hylton Date: Tue Feb 27 17:00:06 2007 New Revision: 53993 Modified: python/trunk/Objects/frameobject.c Log: tabify Modified: python/trunk/Objects/frameobject.c ============================================================================== --- python/trunk/Objects/frameobject.c (original) +++ python/trunk/Objects/frameobject.c Tue Feb 27 17:00:06 2007 @@ -48,7 +48,7 @@ } /* Setter for f_lineno - you can set f_lineno from within a trace function in - * order to jump to a given line of code, subject to some restrictions. Most + * order to jump to a given line of code, subject to some restrictions. Most * lines are OK to jump to because they don't make any assumptions about the * state of the stack (obvious because you could remove the line and the code * would still work without any stack errors), but there are some constructs @@ -85,7 +85,7 @@ int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */ int in_finally[CO_MAXBLOCKS]; /* (ditto) */ int blockstack_top = 0; /* (ditto) */ - int setup_op = 0; /* (ditto) */ + int setup_op = 0; /* (ditto) */ /* f_lineno must be an integer. */ if (!PyInt_Check(p_new_lineno)) { @@ -159,7 +159,7 @@ /* You can't jump into or out of a 'finally' block because the 'try' * block leaves something on the stack for the END_FINALLY to clean - * up. So we walk the bytecode, maintaining a simulated blockstack. + * up. So we walk the bytecode, maintaining a simulated blockstack. * When we reach the old or new address and it's in a 'finally' block * we note the address of the corresponding SETUP_FINALLY. The jump * is only legal if neither address is in a 'finally' block or @@ -383,7 +383,7 @@ ob_type == &Frametype f_back next item on free list, or NULL f_stacksize size of value stack - ob_size size of localsplus + ob_size size of localsplus Note that the value and block stacks are preserved -- this can save another malloc() call or two (and two free() calls as well!). Also note that, unlike for integers, each frame object is a @@ -408,12 +408,12 @@ PyObject **p, **valuestack; PyCodeObject *co; - PyObject_GC_UnTrack(f); + PyObject_GC_UnTrack(f); Py_TRASHCAN_SAFE_BEGIN(f) /* Kill all local variables */ - valuestack = f->f_valuestack; - for (p = f->f_localsplus; p < valuestack; p++) - Py_CLEAR(*p); + valuestack = f->f_valuestack; + for (p = f->f_localsplus; p < valuestack; p++) + Py_CLEAR(*p); /* Free stack */ if (f->f_stacktop != NULL) { @@ -430,18 +430,18 @@ Py_CLEAR(f->f_exc_value); Py_CLEAR(f->f_exc_traceback); - co = f->f_code; - if (co->co_zombieframe == NULL) - co->co_zombieframe = f; + co = f->f_code; + if (co->co_zombieframe == NULL) + co->co_zombieframe = f; else if (numfree < MAXFREELIST) { ++numfree; f->f_back = free_list; free_list = f; - } + } else PyObject_GC_Del(f); - Py_DECREF(co); + Py_DECREF(co); Py_TRASHCAN_SAFE_END(f) } @@ -482,12 +482,12 @@ int i, slots; /* Before anything else, make sure that this frame is clearly marked - * as being defunct! Else, e.g., a generator reachable from this - * frame may also point to this frame, believe itself to still be - * active, and try cleaning up this frame again. - */ + * as being defunct! Else, e.g., a generator reachable from this + * frame may also point to this frame, believe itself to still be + * active, and try cleaning up this frame again. + */ oldtop = f->f_stacktop; - f->f_stacktop = NULL; + f->f_stacktop = NULL; Py_CLEAR(f->f_exc_type); Py_CLEAR(f->f_exc_value); @@ -514,10 +514,10 @@ "frame", sizeof(PyFrameObject), sizeof(PyObject *), - (destructor)frame_dealloc, /* tp_dealloc */ + (destructor)frame_dealloc, /* tp_dealloc */ 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ @@ -530,8 +530,8 @@ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ - 0, /* tp_doc */ - (traverseproc)frame_traverse, /* tp_traverse */ + 0, /* tp_doc */ + (traverseproc)frame_traverse, /* tp_traverse */ (inquiry)frame_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ @@ -579,7 +579,7 @@ builtins = NULL; } if (builtins == NULL) { - /* No builtins! Make up a minimal one + /* No builtins! Make up a minimal one Give them 'None', at least. */ builtins = PyDict_New(); if (builtins == NULL || @@ -599,39 +599,39 @@ Py_INCREF(builtins); } if (code->co_zombieframe != NULL) { - f = code->co_zombieframe; - code->co_zombieframe = NULL; - _Py_NewReference((PyObject *)f); - assert(f->f_code == code); - } - else { - Py_ssize_t extras, ncells, nfrees; - ncells = PyTuple_GET_SIZE(code->co_cellvars); - nfrees = PyTuple_GET_SIZE(code->co_freevars); - extras = code->co_stacksize + code->co_nlocals + ncells + - nfrees; - if (free_list == NULL) { - f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, - extras); - if (f == NULL) { - Py_DECREF(builtins); - return NULL; - } - } - else { - assert(numfree > 0); - --numfree; - f = free_list; - free_list = free_list->f_back; - if (f->ob_size < extras) { - f = PyObject_GC_Resize(PyFrameObject, f, extras); - if (f == NULL) { - Py_DECREF(builtins); - return NULL; - } - } - _Py_NewReference((PyObject *)f); - } + f = code->co_zombieframe; + code->co_zombieframe = NULL; + _Py_NewReference((PyObject *)f); + assert(f->f_code == code); + } + else { + Py_ssize_t extras, ncells, nfrees; + ncells = PyTuple_GET_SIZE(code->co_cellvars); + nfrees = PyTuple_GET_SIZE(code->co_freevars); + extras = code->co_stacksize + code->co_nlocals + ncells + + nfrees; + if (free_list == NULL) { + f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, + extras); + if (f == NULL) { + Py_DECREF(builtins); + return NULL; + } + } + else { + assert(numfree > 0); + --numfree; + f = free_list; + free_list = free_list->f_back; + if (f->ob_size < extras) { + f = PyObject_GC_Resize(PyFrameObject, f, extras); + if (f == NULL) { + Py_DECREF(builtins); + return NULL; + } + } + _Py_NewReference((PyObject *)f); + } f->f_code = code; extras = code->co_nlocals + ncells + nfrees; @@ -640,7 +640,7 @@ f->f_localsplus[i] = NULL; f->f_locals = NULL; f->f_trace = NULL; - f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; + f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; } f->f_stacktop = f->f_valuestack; f->f_builtins = builtins; @@ -659,13 +659,13 @@ Py_DECREF(f); return NULL; } - f->f_locals = locals; + f->f_locals = locals; } else { if (locals == NULL) locals = globals; Py_INCREF(locals); - f->f_locals = locals; + f->f_locals = locals; } f->f_tstate = tstate; @@ -703,7 +703,7 @@ /* Convert between "fast" version of locals and dictionary version. - map and values are input arguments. map is a tuple of strings. + map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, @@ -722,17 +722,17 @@ int deref) { Py_ssize_t j; - assert(PyTuple_Check(map)); - assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) >= nmap); + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) >= nmap); for (j = nmap; --j >= 0; ) { PyObject *key = PyTuple_GET_ITEM(map, j); PyObject *value = values[j]; - assert(PyString_Check(key)); + assert(PyString_Check(key)); if (deref) { - assert(PyCell_Check(value)); + assert(PyCell_Check(value)); value = PyCell_GET(value); - } + } if (value == NULL) { if (PyObject_DelItem(dict, key) != 0) PyErr_Clear(); @@ -749,7 +749,7 @@ dict is an input argument containing string keys representing variables names and arbitrary PyObject* as values. - map and values are input arguments. map is a tuple of strings. + map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, @@ -770,29 +770,29 @@ int deref, int clear) { Py_ssize_t j; - assert(PyTuple_Check(map)); - assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) >= nmap); + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) >= nmap); for (j = nmap; --j >= 0; ) { PyObject *key = PyTuple_GET_ITEM(map, j); PyObject *value = PyObject_GetItem(dict, key); - assert(PyString_Check(key)); - /* We only care about NULLs if clear is true. */ + assert(PyString_Check(key)); + /* We only care about NULLs if clear is true. */ if (value == NULL) { PyErr_Clear(); - if (!clear) - continue; - } + if (!clear) + continue; + } if (deref) { - assert(PyCell_Check(values[j])); - if (PyCell_GET(values[j]) != value) { - if (PyCell_Set(values[j], value) < 0) - PyErr_Clear(); - } + assert(PyCell_Check(values[j])); + if (PyCell_GET(values[j]) != value) { + if (PyCell_Set(values[j], value) < 0) + PyErr_Clear(); + } } else if (values[j] != value) { - Py_XINCREF(value); - Py_XDECREF(values[j]); - values[j] = value; + Py_XINCREF(value); + Py_XDECREF(values[j]); + values[j] = value; } Py_XDECREF(value); } @@ -807,7 +807,7 @@ PyObject *error_type, *error_value, *error_traceback; PyCodeObject *co; Py_ssize_t j; - int ncells, nfreevars; + int ncells, nfreevars; if (f == NULL) return; locals = f->f_locals; @@ -834,18 +834,18 @@ if (ncells || nfreevars) { map_to_dict(co->co_cellvars, ncells, locals, fast + co->co_nlocals, 1); - /* If the namespace is unoptimized, then one of the - following cases applies: - 1. It does not contain free variables, because it - uses import * or is a top-level namespace. - 2. It is a class namespace. - We don't want to accidentally copy free variables - into the locals dict used by the class. - */ - if (co->co_flags & CO_OPTIMIZED) { - map_to_dict(co->co_freevars, nfreevars, - locals, fast + co->co_nlocals + ncells, 1); - } + /* If the namespace is unoptimized, then one of the + following cases applies: + 1. It does not contain free variables, because it + uses import * or is a top-level namespace. + 2. It is a class namespace. + We don't want to accidentally copy free variables + into the locals dict used by the class. + */ + if (co->co_flags & CO_OPTIMIZED) { + map_to_dict(co->co_freevars, nfreevars, + locals, fast + co->co_nlocals + ncells, 1); + } } PyErr_Restore(error_type, error_value, error_traceback); } @@ -883,7 +883,7 @@ locals, fast + co->co_nlocals, 1, clear); dict_to_map(co->co_freevars, nfreevars, locals, fast + co->co_nlocals + ncells, 1, - clear); + clear); } PyErr_Restore(error_type, error_value, error_traceback); } From python-checkins at python.org Tue Feb 27 17:13:25 2007 From: python-checkins at python.org (jeremy.hylton) Date: Tue, 27 Feb 2007 17:13:25 +0100 (CET) Subject: [Python-checkins] r53994 - python/trunk/Python/ast.c python/trunk/Python/compile.c Message-ID: <20070227161325.7E2511E4015@bag.python.org> Author: jeremy.hylton Date: Tue Feb 27 17:13:23 2007 New Revision: 53994 Modified: python/trunk/Python/ast.c python/trunk/Python/compile.c Log: tabify Note that ast.c still has a mix of tabs and spaces, because it attempts to use four-space indents for more of the new code. Modified: python/trunk/Python/ast.c ============================================================================== --- python/trunk/Python/ast.c (original) +++ python/trunk/Python/ast.c Tue Feb 27 17:13:23 2007 @@ -37,7 +37,7 @@ static PyObject *parsestrplus(struct compiling *, const node *n); #ifndef LINENO -#define LINENO(n) ((n)->n_lineno) +#define LINENO(n) ((n)->n_lineno) #endif static identifier @@ -62,7 +62,7 @@ { PyObject *u = Py_BuildValue("zi", errstr, LINENO(n)); if (!u) - return 0; + return 0; PyErr_SetObject(PyExc_SyntaxError, u); Py_DECREF(u); return 0; @@ -76,36 +76,36 @@ assert(PyErr_Occurred()); if (!PyErr_ExceptionMatches(PyExc_SyntaxError)) - return; + return; PyErr_Fetch(&type, &value, &tback); errstr = PyTuple_GetItem(value, 0); if (!errstr) - return; + return; Py_INCREF(errstr); lineno = PyInt_AsLong(PyTuple_GetItem(value, 1)); if (lineno == -1) { - Py_DECREF(errstr); - return; + Py_DECREF(errstr); + return; } Py_DECREF(value); loc = PyErr_ProgramText(filename, lineno); if (!loc) { - Py_INCREF(Py_None); - loc = Py_None; + Py_INCREF(Py_None); + loc = Py_None; } tmp = Py_BuildValue("(zlOO)", filename, lineno, Py_None, loc); Py_DECREF(loc); if (!tmp) { - Py_DECREF(errstr); - return; + Py_DECREF(errstr); + return; } value = PyTuple_Pack(2, errstr, tmp); Py_DECREF(errstr); Py_DECREF(tmp); if (!value) - return; + return; PyErr_Restore(type, value, tback); } @@ -130,41 +130,41 @@ node *ch; switch (TYPE(n)) { - case single_input: - if (TYPE(CHILD(n, 0)) == NEWLINE) - return 0; - else - return num_stmts(CHILD(n, 0)); - case file_input: - l = 0; - for (i = 0; i < NCH(n); i++) { - ch = CHILD(n, i); - if (TYPE(ch) == stmt) - l += num_stmts(ch); - } - return l; - case stmt: - return num_stmts(CHILD(n, 0)); - case compound_stmt: - return 1; - case simple_stmt: - return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */ - case suite: - if (NCH(n) == 1) - return num_stmts(CHILD(n, 0)); - else { - l = 0; - for (i = 2; i < (NCH(n) - 1); i++) - l += num_stmts(CHILD(n, i)); - return l; - } - default: { - char buf[128]; - - sprintf(buf, "Non-statement found: %d %d\n", - TYPE(n), NCH(n)); - Py_FatalError(buf); - } + case single_input: + if (TYPE(CHILD(n, 0)) == NEWLINE) + return 0; + else + return num_stmts(CHILD(n, 0)); + case file_input: + l = 0; + for (i = 0; i < NCH(n); i++) { + ch = CHILD(n, i); + if (TYPE(ch) == stmt) + l += num_stmts(ch); + } + return l; + case stmt: + return num_stmts(CHILD(n, 0)); + case compound_stmt: + return 1; + case simple_stmt: + return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */ + case suite: + if (NCH(n) == 1) + return num_stmts(CHILD(n, 0)); + else { + l = 0; + for (i = 2; i < (NCH(n) - 1); i++) + l += num_stmts(CHILD(n, i)); + return l; + } + default: { + char buf[128]; + + sprintf(buf, "Non-statement found: %d %d\n", + TYPE(n), NCH(n)); + Py_FatalError(buf); + } } assert(0); return 0; @@ -175,7 +175,7 @@ mod_ty PyAST_FromNode(const node *n, PyCompilerFlags *flags, const char *filename, - PyArena *arena) + PyArena *arena) { int i, j, k, num; asdl_seq *stmts = NULL; @@ -184,96 +184,96 @@ struct compiling c; if (flags && flags->cf_flags & PyCF_SOURCE_IS_UTF8) { - c.c_encoding = "utf-8"; - if (TYPE(n) == encoding_decl) { - ast_error(n, "encoding declaration in Unicode string"); - goto error; - } + c.c_encoding = "utf-8"; + if (TYPE(n) == encoding_decl) { + ast_error(n, "encoding declaration in Unicode string"); + goto error; + } } else if (TYPE(n) == encoding_decl) { - c.c_encoding = STR(n); - n = CHILD(n, 0); + c.c_encoding = STR(n); + n = CHILD(n, 0); } else { - c.c_encoding = NULL; + c.c_encoding = NULL; } c.c_arena = arena; k = 0; switch (TYPE(n)) { - case file_input: - stmts = asdl_seq_new(num_stmts(n), arena); - if (!stmts) - return NULL; - for (i = 0; i < NCH(n) - 1; i++) { - ch = CHILD(n, i); - if (TYPE(ch) == NEWLINE) - continue; - REQ(ch, stmt); - num = num_stmts(ch); - if (num == 1) { - s = ast_for_stmt(&c, ch); - if (!s) - goto error; - asdl_seq_SET(stmts, k++, s); - } - else { - ch = CHILD(ch, 0); - REQ(ch, simple_stmt); - for (j = 0; j < num; j++) { - s = ast_for_stmt(&c, CHILD(ch, j * 2)); - if (!s) - goto error; - asdl_seq_SET(stmts, k++, s); - } - } - } - return Module(stmts, arena); - case eval_input: { - expr_ty testlist_ast; - - /* XXX Why not gen_for here? */ - testlist_ast = ast_for_testlist(&c, CHILD(n, 0)); - if (!testlist_ast) - goto error; - return Expression(testlist_ast, arena); - } - case single_input: - if (TYPE(CHILD(n, 0)) == NEWLINE) { - stmts = asdl_seq_new(1, arena); - if (!stmts) - goto error; - asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset, - arena)); - return Interactive(stmts, arena); - } - else { - n = CHILD(n, 0); - num = num_stmts(n); - stmts = asdl_seq_new(num, arena); - if (!stmts) - goto error; - if (num == 1) { - s = ast_for_stmt(&c, n); - if (!s) - goto error; - asdl_seq_SET(stmts, 0, s); - } - else { - /* Only a simple_stmt can contain multiple statements. */ - REQ(n, simple_stmt); - for (i = 0; i < NCH(n); i += 2) { - if (TYPE(CHILD(n, i)) == NEWLINE) - break; - s = ast_for_stmt(&c, CHILD(n, i)); - if (!s) - goto error; - asdl_seq_SET(stmts, i / 2, s); - } - } - - return Interactive(stmts, arena); - } - default: - goto error; + case file_input: + stmts = asdl_seq_new(num_stmts(n), arena); + if (!stmts) + return NULL; + for (i = 0; i < NCH(n) - 1; i++) { + ch = CHILD(n, i); + if (TYPE(ch) == NEWLINE) + continue; + REQ(ch, stmt); + num = num_stmts(ch); + if (num == 1) { + s = ast_for_stmt(&c, ch); + if (!s) + goto error; + asdl_seq_SET(stmts, k++, s); + } + else { + ch = CHILD(ch, 0); + REQ(ch, simple_stmt); + for (j = 0; j < num; j++) { + s = ast_for_stmt(&c, CHILD(ch, j * 2)); + if (!s) + goto error; + asdl_seq_SET(stmts, k++, s); + } + } + } + return Module(stmts, arena); + case eval_input: { + expr_ty testlist_ast; + + /* XXX Why not gen_for here? */ + testlist_ast = ast_for_testlist(&c, CHILD(n, 0)); + if (!testlist_ast) + goto error; + return Expression(testlist_ast, arena); + } + case single_input: + if (TYPE(CHILD(n, 0)) == NEWLINE) { + stmts = asdl_seq_new(1, arena); + if (!stmts) + goto error; + asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset, + arena)); + return Interactive(stmts, arena); + } + else { + n = CHILD(n, 0); + num = num_stmts(n); + stmts = asdl_seq_new(num, arena); + if (!stmts) + goto error; + if (num == 1) { + s = ast_for_stmt(&c, n); + if (!s) + goto error; + asdl_seq_SET(stmts, 0, s); + } + else { + /* Only a simple_stmt can contain multiple statements. */ + REQ(n, simple_stmt); + for (i = 0; i < NCH(n); i += 2) { + if (TYPE(CHILD(n, i)) == NEWLINE) + break; + s = ast_for_stmt(&c, CHILD(n, i)); + if (!s) + goto error; + asdl_seq_SET(stmts, i / 2, s); + } + } + + return Interactive(stmts, arena); + } + default: + goto error; } error: ast_error_finish(filename); @@ -287,30 +287,30 @@ get_operator(const node *n) { switch (TYPE(n)) { - case VBAR: - return BitOr; - case CIRCUMFLEX: - return BitXor; - case AMPER: - return BitAnd; - case LEFTSHIFT: - return LShift; - case RIGHTSHIFT: - return RShift; - case PLUS: - return Add; - case MINUS: - return Sub; - case STAR: - return Mult; - case SLASH: - return Div; - case DOUBLESLASH: - return FloorDiv; - case PERCENT: - return Mod; - default: - return (operator_ty)0; + case VBAR: + return BitOr; + case CIRCUMFLEX: + return BitXor; + case AMPER: + return BitAnd; + case LEFTSHIFT: + return LShift; + case RIGHTSHIFT: + return RShift; + case PLUS: + return Add; + case MINUS: + return Sub; + case STAR: + return Mult; + case SLASH: + return Div; + case DOUBLESLASH: + return FloorDiv; + case PERCENT: + return Mod; + default: + return (operator_ty)0; } } @@ -340,93 +340,93 @@ assert(ctx != AugStore && ctx != AugLoad); switch (e->kind) { - case Attribute_kind: - if (ctx == Store && - !strcmp(PyString_AS_STRING(e->v.Attribute.attr), "None")) { - return ast_error(n, "assignment to None"); - } - e->v.Attribute.ctx = ctx; - break; - case Subscript_kind: - e->v.Subscript.ctx = ctx; - break; - case Name_kind: - if (ctx == Store && - !strcmp(PyString_AS_STRING(e->v.Name.id), "None")) { - return ast_error(n, "assignment to None"); - } - e->v.Name.ctx = ctx; - break; - case List_kind: - e->v.List.ctx = ctx; - s = e->v.List.elts; - break; - case Tuple_kind: - if (asdl_seq_LEN(e->v.Tuple.elts) == 0) - return ast_error(n, "can't assign to ()"); - e->v.Tuple.ctx = ctx; - s = e->v.Tuple.elts; - break; - case Lambda_kind: - expr_name = "lambda"; - break; - case Call_kind: - expr_name = "function call"; - break; - case BoolOp_kind: - case BinOp_kind: - case UnaryOp_kind: - expr_name = "operator"; - break; - case GeneratorExp_kind: - expr_name = "generator expression"; - break; - case Yield_kind: - expr_name = "yield expression"; - break; - case ListComp_kind: - expr_name = "list comprehension"; - break; - case Dict_kind: - case Num_kind: - case Str_kind: - expr_name = "literal"; - break; - case Compare_kind: - expr_name = "comparison"; - break; - case Repr_kind: - expr_name = "repr"; - break; - case IfExp_kind: - expr_name = "conditional expression"; - break; - default: - PyErr_Format(PyExc_SystemError, - "unexpected expression in assignment %d (line %d)", - e->kind, e->lineno); - return 0; + case Attribute_kind: + if (ctx == Store && + !strcmp(PyString_AS_STRING(e->v.Attribute.attr), "None")) { + return ast_error(n, "assignment to None"); + } + e->v.Attribute.ctx = ctx; + break; + case Subscript_kind: + e->v.Subscript.ctx = ctx; + break; + case Name_kind: + if (ctx == Store && + !strcmp(PyString_AS_STRING(e->v.Name.id), "None")) { + return ast_error(n, "assignment to None"); + } + e->v.Name.ctx = ctx; + break; + case List_kind: + e->v.List.ctx = ctx; + s = e->v.List.elts; + break; + case Tuple_kind: + if (asdl_seq_LEN(e->v.Tuple.elts) == 0) + return ast_error(n, "can't assign to ()"); + e->v.Tuple.ctx = ctx; + s = e->v.Tuple.elts; + break; + case Lambda_kind: + expr_name = "lambda"; + break; + case Call_kind: + expr_name = "function call"; + break; + case BoolOp_kind: + case BinOp_kind: + case UnaryOp_kind: + expr_name = "operator"; + break; + case GeneratorExp_kind: + expr_name = "generator expression"; + break; + case Yield_kind: + expr_name = "yield expression"; + break; + case ListComp_kind: + expr_name = "list comprehension"; + break; + case Dict_kind: + case Num_kind: + case Str_kind: + expr_name = "literal"; + break; + case Compare_kind: + expr_name = "comparison"; + break; + case Repr_kind: + expr_name = "repr"; + break; + case IfExp_kind: + expr_name = "conditional expression"; + break; + default: + PyErr_Format(PyExc_SystemError, + "unexpected expression in assignment %d (line %d)", + e->kind, e->lineno); + return 0; } /* Check for error string set by switch */ if (expr_name) { - char buf[300]; - PyOS_snprintf(buf, sizeof(buf), - "can't %s %s", - ctx == Store ? "assign to" : "delete", - expr_name); - return ast_error(n, buf); + char buf[300]; + PyOS_snprintf(buf, sizeof(buf), + "can't %s %s", + ctx == Store ? "assign to" : "delete", + expr_name); + return ast_error(n, buf); } /* If the LHS is a list or tuple, we need to set the assignment - context for all the contained elements. + context for all the contained elements. */ if (s) { - int i; + int i; - for (i = 0; i < asdl_seq_LEN(s); i++) { - if (!set_context((expr_ty)asdl_seq_GET(s, i), ctx, n)) - return 0; - } + for (i = 0; i < asdl_seq_LEN(s); i++) { + if (!set_context((expr_ty)asdl_seq_GET(s, i), ctx, n)) + return 0; + } } return 1; } @@ -437,35 +437,35 @@ REQ(n, augassign); n = CHILD(n, 0); switch (STR(n)[0]) { - case '+': - return Add; - case '-': - return Sub; - case '/': - if (STR(n)[1] == '/') - return FloorDiv; - else - return Div; - case '%': - return Mod; - case '<': - return LShift; - case '>': - return RShift; - case '&': - return BitAnd; - case '^': - return BitXor; - case '|': - return BitOr; - case '*': - if (STR(n)[1] == '*') - return Pow; - else - return Mult; - default: - PyErr_Format(PyExc_SystemError, "invalid augassign: %s", STR(n)); - return (operator_ty)0; + case '+': + return Add; + case '-': + return Sub; + case '/': + if (STR(n)[1] == '/') + return FloorDiv; + else + return Div; + case '%': + return Mod; + case '<': + return LShift; + case '>': + return RShift; + case '&': + return BitAnd; + case '^': + return BitXor; + case '|': + return BitOr; + case '*': + if (STR(n)[1] == '*') + return Pow; + else + return Mult; + default: + PyErr_Format(PyExc_SystemError, "invalid augassign: %s", STR(n)); + return (operator_ty)0; } } @@ -473,51 +473,51 @@ ast_for_comp_op(const node *n) { /* comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is' - |'is' 'not' + |'is' 'not' */ REQ(n, comp_op); if (NCH(n) == 1) { - n = CHILD(n, 0); - switch (TYPE(n)) { - case LESS: - return Lt; - case GREATER: - return Gt; - case EQEQUAL: /* == */ - return Eq; - case LESSEQUAL: - return LtE; - case GREATEREQUAL: - return GtE; - case NOTEQUAL: - return NotEq; - case NAME: - if (strcmp(STR(n), "in") == 0) - return In; - if (strcmp(STR(n), "is") == 0) - return Is; - default: - PyErr_Format(PyExc_SystemError, "invalid comp_op: %s", - STR(n)); - return (cmpop_ty)0; - } + n = CHILD(n, 0); + switch (TYPE(n)) { + case LESS: + return Lt; + case GREATER: + return Gt; + case EQEQUAL: /* == */ + return Eq; + case LESSEQUAL: + return LtE; + case GREATEREQUAL: + return GtE; + case NOTEQUAL: + return NotEq; + case NAME: + if (strcmp(STR(n), "in") == 0) + return In; + if (strcmp(STR(n), "is") == 0) + return Is; + default: + PyErr_Format(PyExc_SystemError, "invalid comp_op: %s", + STR(n)); + return (cmpop_ty)0; + } } else if (NCH(n) == 2) { - /* handle "not in" and "is not" */ - switch (TYPE(CHILD(n, 0))) { - case NAME: - if (strcmp(STR(CHILD(n, 1)), "in") == 0) - return NotIn; - if (strcmp(STR(CHILD(n, 0)), "is") == 0) - return IsNot; - default: - PyErr_Format(PyExc_SystemError, "invalid comp_op: %s %s", - STR(CHILD(n, 0)), STR(CHILD(n, 1))); - return (cmpop_ty)0; - } + /* handle "not in" and "is not" */ + switch (TYPE(CHILD(n, 0))) { + case NAME: + if (strcmp(STR(CHILD(n, 1)), "in") == 0) + return NotIn; + if (strcmp(STR(CHILD(n, 0)), "is") == 0) + return IsNot; + default: + PyErr_Format(PyExc_SystemError, "invalid comp_op: %s %s", + STR(CHILD(n, 0)), STR(CHILD(n, 1))); + return (cmpop_ty)0; + } } PyErr_Format(PyExc_SystemError, "invalid comp_op: has %d children", - NCH(n)); + NCH(n)); return (cmpop_ty)0; } @@ -529,25 +529,25 @@ expr_ty expression; int i; assert(TYPE(n) == testlist - || TYPE(n) == listmaker - || TYPE(n) == testlist_gexp - || TYPE(n) == testlist_safe - || TYPE(n) == testlist1 - ); + || TYPE(n) == listmaker + || TYPE(n) == testlist_gexp + || TYPE(n) == testlist_safe + || TYPE(n) == testlist1 + ); seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!seq) - return NULL; + return NULL; for (i = 0; i < NCH(n); i += 2) { - assert(TYPE(CHILD(n, i)) == test || TYPE(CHILD(n, i)) == old_test); + assert(TYPE(CHILD(n, i)) == test || TYPE(CHILD(n, i)) == old_test); - expression = ast_for_expr(c, CHILD(n, i)); - if (!expression) - return NULL; + expression = ast_for_expr(c, CHILD(n, i)); + if (!expression) + return NULL; - assert(i / 2 < seq->size); - asdl_seq_SET(seq, i / 2, expression); + assert(i / 2 < seq->size); + asdl_seq_SET(seq, i / 2, expression); } return seq; } @@ -559,46 +559,46 @@ expr_ty result; asdl_seq *args = asdl_seq_new(len, c->c_arena); if (!args) - return NULL; + return NULL; /* fpdef: NAME | '(' fplist ')' fplist: fpdef (',' fpdef)* [','] */ REQ(n, fplist); for (i = 0; i < len; i++) { - const node *fpdef_node = CHILD(n, 2*i); - const node *child; - expr_ty arg; + const node *fpdef_node = CHILD(n, 2*i); + const node *child; + expr_ty arg; set_name: - /* fpdef_node is either a NAME or an fplist */ - child = CHILD(fpdef_node, 0); - if (TYPE(child) == NAME) { - if (!strcmp(STR(child), "None")) { - ast_error(child, "assignment to None"); - return NULL; - } - arg = Name(NEW_IDENTIFIER(child), Store, LINENO(child), - child->n_col_offset, c->c_arena); - } - else { - assert(TYPE(fpdef_node) == fpdef); - /* fpdef_node[0] is not a name, so it must be a '(', get CHILD[1] */ - child = CHILD(fpdef_node, 1); - assert(TYPE(child) == fplist); - /* NCH == 1 means we have (x), we need to elide the extra parens */ - if (NCH(child) == 1) { - fpdef_node = CHILD(child, 0); - assert(TYPE(fpdef_node) == fpdef); - goto set_name; - } - arg = compiler_complex_args(c, child); - } - asdl_seq_SET(args, i, arg); + /* fpdef_node is either a NAME or an fplist */ + child = CHILD(fpdef_node, 0); + if (TYPE(child) == NAME) { + if (!strcmp(STR(child), "None")) { + ast_error(child, "assignment to None"); + return NULL; + } + arg = Name(NEW_IDENTIFIER(child), Store, LINENO(child), + child->n_col_offset, c->c_arena); + } + else { + assert(TYPE(fpdef_node) == fpdef); + /* fpdef_node[0] is not a name, so it must be a '(', get CHILD[1] */ + child = CHILD(fpdef_node, 1); + assert(TYPE(child) == fplist); + /* NCH == 1 means we have (x), we need to elide the extra parens */ + if (NCH(child) == 1) { + fpdef_node = CHILD(child, 0); + assert(TYPE(fpdef_node) == fpdef); + goto set_name; + } + arg = compiler_complex_args(c, child); + } + asdl_seq_SET(args, i, arg); } result = Tuple(args, Store, LINENO(n), n->n_col_offset, c->c_arena); if (!set_context(result, Store, n)) - return NULL; + return NULL; return result; } @@ -610,7 +610,7 @@ { /* parameters: '(' [varargslist] ')' varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] - | '**' NAME) | fpdef ['=' test] (',' fpdef ['=' test])* [','] + | '**' NAME) | fpdef ['=' test] (',' fpdef ['=' test])* [','] */ int i, j, k, n_args = 0, n_defaults = 0, found_default = 0; asdl_seq *args, *defaults; @@ -618,26 +618,26 @@ node *ch; if (TYPE(n) == parameters) { - if (NCH(n) == 2) /* () as argument list */ - return arguments(NULL, NULL, NULL, NULL, c->c_arena); - n = CHILD(n, 1); + if (NCH(n) == 2) /* () as argument list */ + return arguments(NULL, NULL, NULL, NULL, c->c_arena); + n = CHILD(n, 1); } REQ(n, varargslist); /* first count the number of normal args & defaults */ for (i = 0; i < NCH(n); i++) { - ch = CHILD(n, i); - if (TYPE(ch) == fpdef) - n_args++; - if (TYPE(ch) == EQUAL) - n_defaults++; + ch = CHILD(n, i); + if (TYPE(ch) == fpdef) + n_args++; + if (TYPE(ch) == EQUAL) + n_defaults++; } args = (n_args ? asdl_seq_new(n_args, c->c_arena) : NULL); if (!args && n_args) - return NULL; /* Don't need to goto error; no objects allocated */ + return NULL; /* Don't need to goto error; no objects allocated */ defaults = (n_defaults ? asdl_seq_new(n_defaults, c->c_arena) : NULL); if (!defaults && n_defaults) - return NULL; /* Don't need to goto error; no objects allocated */ + return NULL; /* Don't need to goto error; no objects allocated */ /* fpdef: NAME | '(' fplist ')' fplist: fpdef (',' fpdef)* [','] @@ -646,80 +646,80 @@ j = 0; /* index for defaults */ k = 0; /* index for args */ while (i < NCH(n)) { - ch = CHILD(n, i); - switch (TYPE(ch)) { - case fpdef: - handle_fpdef: - /* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is - anything other than EQUAL or a comma? */ - /* XXX Should NCH(n) check be made a separate check? */ - if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { - expr_ty expression = ast_for_expr(c, CHILD(n, i + 2)); - if (!expression) - goto error; - assert(defaults != NULL); - asdl_seq_SET(defaults, j++, expression); - i += 2; - found_default = 1; - } - else if (found_default) { - ast_error(n, - "non-default argument follows default argument"); - goto error; - } - if (NCH(ch) == 3) { - ch = CHILD(ch, 1); - /* def foo((x)): is not complex, special case. */ - if (NCH(ch) != 1) { - /* We have complex arguments, setup for unpacking. */ - asdl_seq_SET(args, k++, compiler_complex_args(c, ch)); - } else { - /* def foo((x)): setup for checking NAME below. */ - /* Loop because there can be many parens and tuple - unpacking mixed in. */ - ch = CHILD(ch, 0); - assert(TYPE(ch) == fpdef); - goto handle_fpdef; - } - } - if (TYPE(CHILD(ch, 0)) == NAME) { - expr_ty name; - if (!strcmp(STR(CHILD(ch, 0)), "None")) { - ast_error(CHILD(ch, 0), "assignment to None"); - goto error; - } - name = Name(NEW_IDENTIFIER(CHILD(ch, 0)), - Param, LINENO(ch), ch->n_col_offset, - c->c_arena); - if (!name) - goto error; - asdl_seq_SET(args, k++, name); - - } - i += 2; /* the name and the comma */ - break; - case STAR: - if (!strcmp(STR(CHILD(n, i+1)), "None")) { - ast_error(CHILD(n, i+1), "assignment to None"); - goto error; - } - vararg = NEW_IDENTIFIER(CHILD(n, i+1)); - i += 3; - break; - case DOUBLESTAR: - if (!strcmp(STR(CHILD(n, i+1)), "None")) { - ast_error(CHILD(n, i+1), "assignment to None"); - goto error; - } - kwarg = NEW_IDENTIFIER(CHILD(n, i+1)); - i += 3; - break; - default: - PyErr_Format(PyExc_SystemError, - "unexpected node in varargslist: %d @ %d", - TYPE(ch), i); - goto error; - } + ch = CHILD(n, i); + switch (TYPE(ch)) { + case fpdef: + handle_fpdef: + /* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is + anything other than EQUAL or a comma? */ + /* XXX Should NCH(n) check be made a separate check? */ + if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { + expr_ty expression = ast_for_expr(c, CHILD(n, i + 2)); + if (!expression) + goto error; + assert(defaults != NULL); + asdl_seq_SET(defaults, j++, expression); + i += 2; + found_default = 1; + } + else if (found_default) { + ast_error(n, + "non-default argument follows default argument"); + goto error; + } + if (NCH(ch) == 3) { + ch = CHILD(ch, 1); + /* def foo((x)): is not complex, special case. */ + if (NCH(ch) != 1) { + /* We have complex arguments, setup for unpacking. */ + asdl_seq_SET(args, k++, compiler_complex_args(c, ch)); + } else { + /* def foo((x)): setup for checking NAME below. */ + /* Loop because there can be many parens and tuple + unpacking mixed in. */ + ch = CHILD(ch, 0); + assert(TYPE(ch) == fpdef); + goto handle_fpdef; + } + } + if (TYPE(CHILD(ch, 0)) == NAME) { + expr_ty name; + if (!strcmp(STR(CHILD(ch, 0)), "None")) { + ast_error(CHILD(ch, 0), "assignment to None"); + goto error; + } + name = Name(NEW_IDENTIFIER(CHILD(ch, 0)), + Param, LINENO(ch), ch->n_col_offset, + c->c_arena); + if (!name) + goto error; + asdl_seq_SET(args, k++, name); + + } + i += 2; /* the name and the comma */ + break; + case STAR: + if (!strcmp(STR(CHILD(n, i+1)), "None")) { + ast_error(CHILD(n, i+1), "assignment to None"); + goto error; + } + vararg = NEW_IDENTIFIER(CHILD(n, i+1)); + i += 3; + break; + case DOUBLESTAR: + if (!strcmp(STR(CHILD(n, i+1)), "None")) { + ast_error(CHILD(n, i+1), "assignment to None"); + goto error; + } + kwarg = NEW_IDENTIFIER(CHILD(n, i+1)); + i += 3; + break; + default: + PyErr_Format(PyExc_SystemError, + "unexpected node in varargslist: %d @ %d", + TYPE(ch), i); + goto error; + } } return arguments(args, vararg, kwarg, defaults, c->c_arena); @@ -745,18 +745,18 @@ id = NEW_IDENTIFIER(CHILD(n, 0)); if (!id) - return NULL; + return NULL; e = Name(id, Load, lineno, col_offset, c->c_arena); if (!e) - return NULL; + return NULL; for (i = 2; i < NCH(n); i+=2) { - id = NEW_IDENTIFIER(CHILD(n, i)); - if (!id) - return NULL; - e = Attribute(e, id, Load, lineno, col_offset, c->c_arena); - if (!e) - return NULL; + id = NEW_IDENTIFIER(CHILD(n, i)); + if (!id) + return NULL; + e = Attribute(e, id, Load, lineno, col_offset, c->c_arena); + if (!e) + return NULL; } return e; @@ -775,24 +775,24 @@ name_expr = ast_for_dotted_name(c, CHILD(n, 1)); if (!name_expr) - return NULL; - + return NULL; + if (NCH(n) == 3) { /* No arguments */ - d = name_expr; - name_expr = NULL; + d = name_expr; + name_expr = NULL; } else if (NCH(n) == 5) { /* Call with no arguments */ - d = Call(name_expr, NULL, NULL, NULL, NULL, LINENO(n), - n->n_col_offset, c->c_arena); - if (!d) - return NULL; - name_expr = NULL; + d = Call(name_expr, NULL, NULL, NULL, NULL, LINENO(n), + n->n_col_offset, c->c_arena); + if (!d) + return NULL; + name_expr = NULL; } else { - d = ast_for_call(c, CHILD(n, 3), name_expr); - if (!d) - return NULL; - name_expr = NULL; + d = ast_for_call(c, CHILD(n, 3), name_expr); + if (!d) + return NULL; + name_expr = NULL; } return d; @@ -808,13 +808,13 @@ REQ(n, decorators); decorator_seq = asdl_seq_new(NCH(n), c->c_arena); if (!decorator_seq) - return NULL; - + return NULL; + for (i = 0; i < NCH(n); i++) { - d = ast_for_decorator(c, CHILD(n, i)); - if (!d) - return NULL; - asdl_seq_SET(decorator_seq, i, d); + d = ast_for_decorator(c, CHILD(n, i)); + if (!d) + return NULL; + asdl_seq_SET(decorator_seq, i, d); } return decorator_seq; } @@ -832,31 +832,31 @@ REQ(n, funcdef); if (NCH(n) == 6) { /* decorators are present */ - decorator_seq = ast_for_decorators(c, CHILD(n, 0)); - if (!decorator_seq) - return NULL; - name_i = 2; + decorator_seq = ast_for_decorators(c, CHILD(n, 0)); + if (!decorator_seq) + return NULL; + name_i = 2; } else { - name_i = 1; + name_i = 1; } name = NEW_IDENTIFIER(CHILD(n, name_i)); if (!name) - return NULL; + return NULL; else if (!strcmp(STR(CHILD(n, name_i)), "None")) { - ast_error(CHILD(n, name_i), "assignment to None"); - return NULL; + ast_error(CHILD(n, name_i), "assignment to None"); + return NULL; } args = ast_for_arguments(c, CHILD(n, name_i + 1)); if (!args) - return NULL; + return NULL; body = ast_for_suite(c, CHILD(n, name_i + 3)); if (!body) - return NULL; + return NULL; return FunctionDef(name, args, body, decorator_seq, LINENO(n), - n->n_col_offset, c->c_arena); + n->n_col_offset, c->c_arena); } static expr_ty @@ -867,20 +867,20 @@ expr_ty expression; if (NCH(n) == 3) { - args = arguments(NULL, NULL, NULL, NULL, c->c_arena); - if (!args) - return NULL; - expression = ast_for_expr(c, CHILD(n, 2)); - if (!expression) - return NULL; + args = arguments(NULL, NULL, NULL, NULL, c->c_arena); + if (!args) + return NULL; + expression = ast_for_expr(c, CHILD(n, 2)); + if (!expression) + return NULL; } else { - args = ast_for_arguments(c, CHILD(n, 1)); - if (!args) - return NULL; - expression = ast_for_expr(c, CHILD(n, 3)); - if (!expression) - return NULL; + args = ast_for_arguments(c, CHILD(n, 1)); + if (!args) + return NULL; + expression = ast_for_expr(c, CHILD(n, 3)); + if (!expression) + return NULL; } return Lambda(args, expression, LINENO(n), n->n_col_offset, c->c_arena); @@ -895,15 +895,15 @@ assert(NCH(n) == 5); body = ast_for_expr(c, CHILD(n, 0)); if (!body) - return NULL; + return NULL; expression = ast_for_expr(c, CHILD(n, 2)); if (!expression) - return NULL; + return NULL; orelse = ast_for_expr(c, CHILD(n, 4)); if (!orelse) - return NULL; + return NULL; return IfExp(expression, body, orelse, LINENO(n), n->n_col_offset, - c->c_arena); + c->c_arena); } /* XXX(nnorwitz): the listcomp and genexpr code should be refactored @@ -926,21 +926,21 @@ n_fors++; REQ(ch, list_for); if (NCH(ch) == 5) - ch = CHILD(ch, 4); + ch = CHILD(ch, 4); else - return n_fors; + return n_fors; count_list_iter: REQ(ch, list_iter); ch = CHILD(ch, 0); if (TYPE(ch) == list_for) - goto count_list_for; + goto count_list_for; else if (TYPE(ch) == list_if) { - if (NCH(ch) == 3) { - ch = CHILD(ch, 2); - goto count_list_iter; - } - else - return n_fors; + if (NCH(ch) == 3) { + ch = CHILD(ch, 2); + goto count_list_iter; + } + else + return n_fors; } /* Should never be reached */ @@ -961,12 +961,12 @@ count_list_iter: REQ(n, list_iter); if (TYPE(CHILD(n, 0)) == list_for) - return n_ifs; + return n_ifs; n = CHILD(n, 0); REQ(n, list_if); n_ifs++; if (NCH(n) == 2) - return n_ifs; + return n_ifs; n = CHILD(n, 2); goto count_list_iter; } @@ -990,73 +990,73 @@ elt = ast_for_expr(c, CHILD(n, 0)); if (!elt) - return NULL; + return NULL; n_fors = count_list_fors(n); if (n_fors == -1) - return NULL; + return NULL; listcomps = asdl_seq_new(n_fors, c->c_arena); if (!listcomps) - return NULL; + return NULL; ch = CHILD(n, 1); for (i = 0; i < n_fors; i++) { - comprehension_ty lc; - asdl_seq *t; - expr_ty expression; - node *for_ch; - - REQ(ch, list_for); - - for_ch = CHILD(ch, 1); - t = ast_for_exprlist(c, for_ch, Store); - if (!t) - return NULL; - expression = ast_for_testlist(c, CHILD(ch, 3)); - if (!expression) - return NULL; - - /* Check the # of children rather than the length of t, since - [x for x, in ... ] has 1 element in t, but still requires a Tuple. */ - if (NCH(for_ch) == 1) - lc = comprehension((expr_ty)asdl_seq_GET(t, 0), expression, NULL, - c->c_arena); - else - lc = comprehension(Tuple(t, Store, LINENO(ch), ch->n_col_offset, - c->c_arena), - expression, NULL, c->c_arena); - if (!lc) - return NULL; - - if (NCH(ch) == 5) { - int j, n_ifs; - asdl_seq *ifs; - - ch = CHILD(ch, 4); - n_ifs = count_list_ifs(ch); - if (n_ifs == -1) - return NULL; - - ifs = asdl_seq_new(n_ifs, c->c_arena); - if (!ifs) - return NULL; - - for (j = 0; j < n_ifs; j++) { - REQ(ch, list_iter); - ch = CHILD(ch, 0); - REQ(ch, list_if); - - asdl_seq_SET(ifs, j, ast_for_expr(c, CHILD(ch, 1))); - if (NCH(ch) == 3) - ch = CHILD(ch, 2); - } - /* on exit, must guarantee that ch is a list_for */ - if (TYPE(ch) == list_iter) - ch = CHILD(ch, 0); - lc->ifs = ifs; - } - asdl_seq_SET(listcomps, i, lc); + comprehension_ty lc; + asdl_seq *t; + expr_ty expression; + node *for_ch; + + REQ(ch, list_for); + + for_ch = CHILD(ch, 1); + t = ast_for_exprlist(c, for_ch, Store); + if (!t) + return NULL; + expression = ast_for_testlist(c, CHILD(ch, 3)); + if (!expression) + return NULL; + + /* Check the # of children rather than the length of t, since + [x for x, in ... ] has 1 element in t, but still requires a Tuple. */ + if (NCH(for_ch) == 1) + lc = comprehension((expr_ty)asdl_seq_GET(t, 0), expression, NULL, + c->c_arena); + else + lc = comprehension(Tuple(t, Store, LINENO(ch), ch->n_col_offset, + c->c_arena), + expression, NULL, c->c_arena); + if (!lc) + return NULL; + + if (NCH(ch) == 5) { + int j, n_ifs; + asdl_seq *ifs; + + ch = CHILD(ch, 4); + n_ifs = count_list_ifs(ch); + if (n_ifs == -1) + return NULL; + + ifs = asdl_seq_new(n_ifs, c->c_arena); + if (!ifs) + return NULL; + + for (j = 0; j < n_ifs; j++) { + REQ(ch, list_iter); + ch = CHILD(ch, 0); + REQ(ch, list_if); + + asdl_seq_SET(ifs, j, ast_for_expr(c, CHILD(ch, 1))); + if (NCH(ch) == 3) + ch = CHILD(ch, 2); + } + /* on exit, must guarantee that ch is a list_for */ + if (TYPE(ch) == list_iter) + ch = CHILD(ch, 0); + lc->ifs = ifs; + } + asdl_seq_SET(listcomps, i, lc); } return ListComp(elt, listcomps, LINENO(n), n->n_col_offset, c->c_arena); @@ -1071,34 +1071,34 @@ static int count_gen_fors(const node *n) { - int n_fors = 0; - node *ch = CHILD(n, 1); + int n_fors = 0; + node *ch = CHILD(n, 1); count_gen_for: - n_fors++; - REQ(ch, gen_for); - if (NCH(ch) == 5) - ch = CHILD(ch, 4); - else - return n_fors; + n_fors++; + REQ(ch, gen_for); + if (NCH(ch) == 5) + ch = CHILD(ch, 4); + else + return n_fors; count_gen_iter: - REQ(ch, gen_iter); - ch = CHILD(ch, 0); - if (TYPE(ch) == gen_for) - goto count_gen_for; - else if (TYPE(ch) == gen_if) { - if (NCH(ch) == 3) { - ch = CHILD(ch, 2); - goto count_gen_iter; - } - else - return n_fors; - } - - /* Should never be reached */ - PyErr_SetString(PyExc_SystemError, - "logic error in count_gen_fors"); - return -1; + REQ(ch, gen_iter); + ch = CHILD(ch, 0); + if (TYPE(ch) == gen_for) + goto count_gen_for; + else if (TYPE(ch) == gen_if) { + if (NCH(ch) == 3) { + ch = CHILD(ch, 2); + goto count_gen_iter; + } + else + return n_fors; + } + + /* Should never be reached */ + PyErr_SetString(PyExc_SystemError, + "logic error in count_gen_fors"); + return -1; } /* Count the number of 'if' statements in a generator expression. @@ -1109,19 +1109,19 @@ static int count_gen_ifs(const node *n) { - int n_ifs = 0; + int n_ifs = 0; - while (1) { - REQ(n, gen_iter); - if (TYPE(CHILD(n, 0)) == gen_for) - return n_ifs; - n = CHILD(n, 0); - REQ(n, gen_if); - n_ifs++; - if (NCH(n) == 2) - return n_ifs; - n = CHILD(n, 2); - } + while (1) { + REQ(n, gen_iter); + if (TYPE(CHILD(n, 0)) == gen_for) + return n_ifs; + n = CHILD(n, 0); + REQ(n, gen_if); + n_ifs++; + if (NCH(n) == 2) + return n_ifs; + n = CHILD(n, 2); + } } /* TODO(jhylton): Combine with list comprehension code? */ @@ -1129,7 +1129,7 @@ ast_for_genexp(struct compiling *c, const node *n) { /* testlist_gexp: test ( gen_for | (',' test)* [','] ) - argument: [test '='] test [gen_for] # Really [keyword '='] test */ + argument: [test '='] test [gen_for] # Really [keyword '='] test */ expr_ty elt; asdl_seq *genexps; int i, n_fors; @@ -1140,77 +1140,77 @@ elt = ast_for_expr(c, CHILD(n, 0)); if (!elt) - return NULL; + return NULL; n_fors = count_gen_fors(n); if (n_fors == -1) - return NULL; + return NULL; genexps = asdl_seq_new(n_fors, c->c_arena); if (!genexps) - return NULL; + return NULL; ch = CHILD(n, 1); for (i = 0; i < n_fors; i++) { - comprehension_ty ge; - asdl_seq *t; - expr_ty expression; - node *for_ch; - - REQ(ch, gen_for); - - for_ch = CHILD(ch, 1); - t = ast_for_exprlist(c, for_ch, Store); - if (!t) - return NULL; - expression = ast_for_expr(c, CHILD(ch, 3)); - if (!expression) - return NULL; - - /* Check the # of children rather than the length of t, since - (x for x, in ...) has 1 element in t, but still requires a Tuple. */ - if (NCH(for_ch) == 1) - ge = comprehension((expr_ty)asdl_seq_GET(t, 0), expression, - NULL, c->c_arena); - else - ge = comprehension(Tuple(t, Store, LINENO(ch), ch->n_col_offset, - c->c_arena), - expression, NULL, c->c_arena); - - if (!ge) - return NULL; - - if (NCH(ch) == 5) { - int j, n_ifs; - asdl_seq *ifs; - - ch = CHILD(ch, 4); - n_ifs = count_gen_ifs(ch); - if (n_ifs == -1) - return NULL; - - ifs = asdl_seq_new(n_ifs, c->c_arena); - if (!ifs) - return NULL; - - for (j = 0; j < n_ifs; j++) { - REQ(ch, gen_iter); - ch = CHILD(ch, 0); - REQ(ch, gen_if); - - expression = ast_for_expr(c, CHILD(ch, 1)); - if (!expression) - return NULL; - asdl_seq_SET(ifs, j, expression); - if (NCH(ch) == 3) - ch = CHILD(ch, 2); - } - /* on exit, must guarantee that ch is a gen_for */ - if (TYPE(ch) == gen_iter) - ch = CHILD(ch, 0); - ge->ifs = ifs; - } - asdl_seq_SET(genexps, i, ge); + comprehension_ty ge; + asdl_seq *t; + expr_ty expression; + node *for_ch; + + REQ(ch, gen_for); + + for_ch = CHILD(ch, 1); + t = ast_for_exprlist(c, for_ch, Store); + if (!t) + return NULL; + expression = ast_for_expr(c, CHILD(ch, 3)); + if (!expression) + return NULL; + + /* Check the # of children rather than the length of t, since + (x for x, in ...) has 1 element in t, but still requires a Tuple. */ + if (NCH(for_ch) == 1) + ge = comprehension((expr_ty)asdl_seq_GET(t, 0), expression, + NULL, c->c_arena); + else + ge = comprehension(Tuple(t, Store, LINENO(ch), ch->n_col_offset, + c->c_arena), + expression, NULL, c->c_arena); + + if (!ge) + return NULL; + + if (NCH(ch) == 5) { + int j, n_ifs; + asdl_seq *ifs; + + ch = CHILD(ch, 4); + n_ifs = count_gen_ifs(ch); + if (n_ifs == -1) + return NULL; + + ifs = asdl_seq_new(n_ifs, c->c_arena); + if (!ifs) + return NULL; + + for (j = 0; j < n_ifs; j++) { + REQ(ch, gen_iter); + ch = CHILD(ch, 0); + REQ(ch, gen_if); + + expression = ast_for_expr(c, CHILD(ch, 1)); + if (!expression) + return NULL; + asdl_seq_SET(ifs, j, expression); + if (NCH(ch) == 3) + ch = CHILD(ch, 2); + } + /* on exit, must guarantee that ch is a gen_for */ + if (TYPE(ch) == gen_iter) + ch = CHILD(ch, 0); + ge->ifs = ifs; + } + asdl_seq_SET(genexps, i, ge); } return GeneratorExp(elt, genexps, LINENO(n), n->n_col_offset, c->c_arena); @@ -1226,96 +1226,96 @@ switch (TYPE(ch)) { case NAME: - /* All names start in Load context, but may later be - changed. */ - return Name(NEW_IDENTIFIER(ch), Load, LINENO(n), n->n_col_offset, c->c_arena); + /* All names start in Load context, but may later be + changed. */ + return Name(NEW_IDENTIFIER(ch), Load, LINENO(n), n->n_col_offset, c->c_arena); case STRING: { - PyObject *str = parsestrplus(c, n); - if (!str) - return NULL; + PyObject *str = parsestrplus(c, n); + if (!str) + return NULL; - PyArena_AddPyObject(c->c_arena, str); - return Str(str, LINENO(n), n->n_col_offset, c->c_arena); + PyArena_AddPyObject(c->c_arena, str); + return Str(str, LINENO(n), n->n_col_offset, c->c_arena); } case NUMBER: { - PyObject *pynum = parsenumber(STR(ch)); - if (!pynum) - return NULL; + PyObject *pynum = parsenumber(STR(ch)); + if (!pynum) + return NULL; - PyArena_AddPyObject(c->c_arena, pynum); - return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena); + PyArena_AddPyObject(c->c_arena, pynum); + return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena); } case LPAR: /* some parenthesized expressions */ - ch = CHILD(n, 1); - - if (TYPE(ch) == RPAR) - return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - - if (TYPE(ch) == yield_expr) - return ast_for_expr(c, ch); - - if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == gen_for)) - return ast_for_genexp(c, ch); - - return ast_for_testlist_gexp(c, ch); + ch = CHILD(n, 1); + + if (TYPE(ch) == RPAR) + return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); + + if (TYPE(ch) == yield_expr) + return ast_for_expr(c, ch); + + if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == gen_for)) + return ast_for_genexp(c, ch); + + return ast_for_testlist_gexp(c, ch); case LSQB: /* list (or list comprehension) */ - ch = CHILD(n, 1); - - if (TYPE(ch) == RSQB) - return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - - REQ(ch, listmaker); - if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { - asdl_seq *elts = seq_for_testlist(c, ch); - if (!elts) - return NULL; - - return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena); - } - else - return ast_for_listcomp(c, ch); + ch = CHILD(n, 1); + + if (TYPE(ch) == RSQB) + return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); + + REQ(ch, listmaker); + if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { + asdl_seq *elts = seq_for_testlist(c, ch); + if (!elts) + return NULL; + + return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena); + } + else + return ast_for_listcomp(c, ch); case LBRACE: { - /* dictmaker: test ':' test (',' test ':' test)* [','] */ - int i, size; - asdl_seq *keys, *values; - - ch = CHILD(n, 1); - size = (NCH(ch) + 1) / 4; /* +1 in case no trailing comma */ - keys = asdl_seq_new(size, c->c_arena); - if (!keys) - return NULL; - - values = asdl_seq_new(size, c->c_arena); - if (!values) - return NULL; - - for (i = 0; i < NCH(ch); i += 4) { - expr_ty expression; - - expression = ast_for_expr(c, CHILD(ch, i)); - if (!expression) - return NULL; - - asdl_seq_SET(keys, i / 4, expression); - - expression = ast_for_expr(c, CHILD(ch, i + 2)); - if (!expression) - return NULL; - - asdl_seq_SET(values, i / 4, expression); - } - return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena); + /* dictmaker: test ':' test (',' test ':' test)* [','] */ + int i, size; + asdl_seq *keys, *values; + + ch = CHILD(n, 1); + size = (NCH(ch) + 1) / 4; /* +1 in case no trailing comma */ + keys = asdl_seq_new(size, c->c_arena); + if (!keys) + return NULL; + + values = asdl_seq_new(size, c->c_arena); + if (!values) + return NULL; + + for (i = 0; i < NCH(ch); i += 4) { + expr_ty expression; + + expression = ast_for_expr(c, CHILD(ch, i)); + if (!expression) + return NULL; + + asdl_seq_SET(keys, i / 4, expression); + + expression = ast_for_expr(c, CHILD(ch, i + 2)); + if (!expression) + return NULL; + + asdl_seq_SET(values, i / 4, expression); + } + return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena); } case BACKQUOTE: { /* repr */ - expr_ty expression = ast_for_testlist(c, CHILD(n, 1)); - if (!expression) - return NULL; + expr_ty expression = ast_for_testlist(c, CHILD(n, 1)); + if (!expression) + return NULL; - return Repr(expression, LINENO(n), n->n_col_offset, c->c_arena); + return Repr(expression, LINENO(n), n->n_col_offset, c->c_arena); } default: - PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch)); - return NULL; + PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch)); + return NULL; } } @@ -1333,62 +1333,62 @@ */ ch = CHILD(n, 0); if (TYPE(ch) == DOT) - return Ellipsis(c->c_arena); + return Ellipsis(c->c_arena); if (NCH(n) == 1 && TYPE(ch) == test) { - /* 'step' variable hold no significance in terms of being used over - other vars */ - step = ast_for_expr(c, ch); - if (!step) - return NULL; - - return Index(step, c->c_arena); + /* 'step' variable hold no significance in terms of being used over + other vars */ + step = ast_for_expr(c, ch); + if (!step) + return NULL; + + return Index(step, c->c_arena); } if (TYPE(ch) == test) { - lower = ast_for_expr(c, ch); - if (!lower) - return NULL; + lower = ast_for_expr(c, ch); + if (!lower) + return NULL; } /* If there's an upper bound it's in the second or third position. */ if (TYPE(ch) == COLON) { - if (NCH(n) > 1) { - node *n2 = CHILD(n, 1); + if (NCH(n) > 1) { + node *n2 = CHILD(n, 1); - if (TYPE(n2) == test) { - upper = ast_for_expr(c, n2); - if (!upper) - return NULL; - } - } + if (TYPE(n2) == test) { + upper = ast_for_expr(c, n2); + if (!upper) + return NULL; + } + } } else if (NCH(n) > 2) { - node *n2 = CHILD(n, 2); + node *n2 = CHILD(n, 2); - if (TYPE(n2) == test) { - upper = ast_for_expr(c, n2); - if (!upper) - return NULL; - } + if (TYPE(n2) == test) { + upper = ast_for_expr(c, n2); + if (!upper) + return NULL; + } } ch = CHILD(n, NCH(n) - 1); if (TYPE(ch) == sliceop) { - if (NCH(ch) == 1) { - /* No expression, so step is None */ - ch = CHILD(ch, 0); - step = Name(new_identifier("None", c->c_arena), Load, - LINENO(ch), ch->n_col_offset, c->c_arena); - if (!step) - return NULL; - } else { - ch = CHILD(ch, 1); - if (TYPE(ch) == test) { - step = ast_for_expr(c, ch); - if (!step) - return NULL; - } - } + if (NCH(ch) == 1) { + /* No expression, so step is None */ + ch = CHILD(ch, 0); + step = Name(new_identifier("None", c->c_arena), Load, + LINENO(ch), ch->n_col_offset, c->c_arena); + if (!step) + return NULL; + } else { + ch = CHILD(ch, 1); + if (TYPE(ch) == test) { + step = ast_for_expr(c, ch); + if (!step) + return NULL; + } + } } return Slice(lower, upper, step, c->c_arena); @@ -1397,53 +1397,53 @@ static expr_ty ast_for_binop(struct compiling *c, const node *n) { - /* Must account for a sequence of expressions. - How should A op B op C by represented? - BinOp(BinOp(A, op, B), op, C). - */ - - int i, nops; - expr_ty expr1, expr2, result; - operator_ty newoperator; - - expr1 = ast_for_expr(c, CHILD(n, 0)); - if (!expr1) - return NULL; - - expr2 = ast_for_expr(c, CHILD(n, 2)); - if (!expr2) - return NULL; - - newoperator = get_operator(CHILD(n, 1)); - if (!newoperator) - return NULL; - - result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, - c->c_arena); - if (!result) - return NULL; - - nops = (NCH(n) - 1) / 2; - for (i = 1; i < nops; i++) { - expr_ty tmp_result, tmp; - const node* next_oper = CHILD(n, i * 2 + 1); - - newoperator = get_operator(next_oper); - if (!newoperator) - return NULL; - - tmp = ast_for_expr(c, CHILD(n, i * 2 + 2)); - if (!tmp) - return NULL; - - tmp_result = BinOp(result, newoperator, tmp, - LINENO(next_oper), next_oper->n_col_offset, - c->c_arena); - if (!tmp) - return NULL; - result = tmp_result; - } - return result; + /* Must account for a sequence of expressions. + How should A op B op C by represented? + BinOp(BinOp(A, op, B), op, C). + */ + + int i, nops; + expr_ty expr1, expr2, result; + operator_ty newoperator; + + expr1 = ast_for_expr(c, CHILD(n, 0)); + if (!expr1) + return NULL; + + expr2 = ast_for_expr(c, CHILD(n, 2)); + if (!expr2) + return NULL; + + newoperator = get_operator(CHILD(n, 1)); + if (!newoperator) + return NULL; + + result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, + c->c_arena); + if (!result) + return NULL; + + nops = (NCH(n) - 1) / 2; + for (i = 1; i < nops; i++) { + expr_ty tmp_result, tmp; + const node* next_oper = CHILD(n, i * 2 + 1); + + newoperator = get_operator(next_oper); + if (!newoperator) + return NULL; + + tmp = ast_for_expr(c, CHILD(n, i * 2 + 2)); + if (!tmp) + return NULL; + + tmp_result = BinOp(result, newoperator, tmp, + LINENO(next_oper), next_oper->n_col_offset, + c->c_arena); + if (!tmp) + return NULL; + result = tmp_result; + } + return result; } static expr_ty @@ -1455,67 +1455,67 @@ */ REQ(n, trailer); if (TYPE(CHILD(n, 0)) == LPAR) { - if (NCH(n) == 2) - return Call(left_expr, NULL, NULL, NULL, NULL, LINENO(n), - n->n_col_offset, c->c_arena); - else - return ast_for_call(c, CHILD(n, 1), left_expr); + if (NCH(n) == 2) + return Call(left_expr, NULL, NULL, NULL, NULL, LINENO(n), + n->n_col_offset, c->c_arena); + else + return ast_for_call(c, CHILD(n, 1), left_expr); } else if (TYPE(CHILD(n, 0)) == DOT ) { - return Attribute(left_expr, NEW_IDENTIFIER(CHILD(n, 1)), Load, - LINENO(n), n->n_col_offset, c->c_arena); + return Attribute(left_expr, NEW_IDENTIFIER(CHILD(n, 1)), Load, + LINENO(n), n->n_col_offset, c->c_arena); } else { - REQ(CHILD(n, 0), LSQB); - REQ(CHILD(n, 2), RSQB); - n = CHILD(n, 1); - if (NCH(n) == 1) { - slice_ty slc = ast_for_slice(c, CHILD(n, 0)); - if (!slc) - return NULL; - return Subscript(left_expr, slc, Load, LINENO(n), n->n_col_offset, - c->c_arena); - } - else { - /* The grammar is ambiguous here. The ambiguity is resolved - by treating the sequence as a tuple literal if there are - no slice features. - */ - int j; - slice_ty slc; - expr_ty e; - bool simple = true; - asdl_seq *slices, *elts; - slices = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); - if (!slices) - return NULL; - for (j = 0; j < NCH(n); j += 2) { - slc = ast_for_slice(c, CHILD(n, j)); - if (!slc) - return NULL; - if (slc->kind != Index_kind) - simple = false; - asdl_seq_SET(slices, j / 2, slc); - } - if (!simple) { - return Subscript(left_expr, ExtSlice(slices, c->c_arena), - Load, LINENO(n), n->n_col_offset, c->c_arena); - } - /* extract Index values and put them in a Tuple */ - elts = asdl_seq_new(asdl_seq_LEN(slices), c->c_arena); - if (!elts) - return NULL; - for (j = 0; j < asdl_seq_LEN(slices); ++j) { - slc = (slice_ty)asdl_seq_GET(slices, j); - assert(slc->kind == Index_kind && slc->v.Index.value); - asdl_seq_SET(elts, j, slc->v.Index.value); - } - e = Tuple(elts, Load, LINENO(n), n->n_col_offset, c->c_arena); - if (!e) - return NULL; - return Subscript(left_expr, Index(e, c->c_arena), - Load, LINENO(n), n->n_col_offset, c->c_arena); - } + REQ(CHILD(n, 0), LSQB); + REQ(CHILD(n, 2), RSQB); + n = CHILD(n, 1); + if (NCH(n) == 1) { + slice_ty slc = ast_for_slice(c, CHILD(n, 0)); + if (!slc) + return NULL; + return Subscript(left_expr, slc, Load, LINENO(n), n->n_col_offset, + c->c_arena); + } + else { + /* The grammar is ambiguous here. The ambiguity is resolved + by treating the sequence as a tuple literal if there are + no slice features. + */ + int j; + slice_ty slc; + expr_ty e; + bool simple = true; + asdl_seq *slices, *elts; + slices = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); + if (!slices) + return NULL; + for (j = 0; j < NCH(n); j += 2) { + slc = ast_for_slice(c, CHILD(n, j)); + if (!slc) + return NULL; + if (slc->kind != Index_kind) + simple = false; + asdl_seq_SET(slices, j / 2, slc); + } + if (!simple) { + return Subscript(left_expr, ExtSlice(slices, c->c_arena), + Load, LINENO(n), n->n_col_offset, c->c_arena); + } + /* extract Index values and put them in a Tuple */ + elts = asdl_seq_new(asdl_seq_LEN(slices), c->c_arena); + if (!elts) + return NULL; + for (j = 0; j < asdl_seq_LEN(slices); ++j) { + slc = (slice_ty)asdl_seq_GET(slices, j); + assert(slc->kind == Index_kind && slc->v.Index.value); + asdl_seq_SET(elts, j, slc->v.Index.value); + } + e = Tuple(elts, Load, LINENO(n), n->n_col_offset, c->c_arena); + if (!e) + return NULL; + return Subscript(left_expr, Index(e, c->c_arena), + Load, LINENO(n), n->n_col_offset, c->c_arena); + } } } @@ -1526,47 +1526,47 @@ expr_ty expression; /* If the unary - operator is applied to a constant, don't generate - a UNARY_NEGATIVE opcode. Just store the approriate value as a + a UNARY_NEGATIVE opcode. Just store the approriate value as a constant. The peephole optimizer already does something like this but it doesn't handle the case where the constant is (sys.maxint - 1). In that case, we want a PyIntObject, not a PyLongObject. */ if (TYPE(CHILD(n, 0)) == MINUS - && NCH(n) == 2 - && TYPE((pfactor = CHILD(n, 1))) == factor - && NCH(pfactor) == 1 - && TYPE((ppower = CHILD(pfactor, 0))) == power - && NCH(ppower) == 1 - && TYPE((patom = CHILD(ppower, 0))) == atom - && TYPE((pnum = CHILD(patom, 0))) == NUMBER) { - char *s = PyObject_MALLOC(strlen(STR(pnum)) + 2); - if (s == NULL) - return NULL; - s[0] = '-'; - strcpy(s + 1, STR(pnum)); - PyObject_FREE(STR(pnum)); - STR(pnum) = s; - return ast_for_atom(c, patom); + && NCH(n) == 2 + && TYPE((pfactor = CHILD(n, 1))) == factor + && NCH(pfactor) == 1 + && TYPE((ppower = CHILD(pfactor, 0))) == power + && NCH(ppower) == 1 + && TYPE((patom = CHILD(ppower, 0))) == atom + && TYPE((pnum = CHILD(patom, 0))) == NUMBER) { + char *s = PyObject_MALLOC(strlen(STR(pnum)) + 2); + if (s == NULL) + return NULL; + s[0] = '-'; + strcpy(s + 1, STR(pnum)); + PyObject_FREE(STR(pnum)); + STR(pnum) = s; + return ast_for_atom(c, patom); } expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) - return NULL; + return NULL; switch (TYPE(CHILD(n, 0))) { - case PLUS: - return UnaryOp(UAdd, expression, LINENO(n), n->n_col_offset, - c->c_arena); - case MINUS: - return UnaryOp(USub, expression, LINENO(n), n->n_col_offset, - c->c_arena); - case TILDE: - return UnaryOp(Invert, expression, LINENO(n), - n->n_col_offset, c->c_arena); + case PLUS: + return UnaryOp(UAdd, expression, LINENO(n), n->n_col_offset, + c->c_arena); + case MINUS: + return UnaryOp(USub, expression, LINENO(n), n->n_col_offset, + c->c_arena); + case TILDE: + return UnaryOp(Invert, expression, LINENO(n), + n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "unhandled factor: %d", - TYPE(CHILD(n, 0))); + TYPE(CHILD(n, 0))); return NULL; } @@ -1580,28 +1580,28 @@ REQ(n, power); e = ast_for_atom(c, CHILD(n, 0)); if (!e) - return NULL; + return NULL; if (NCH(n) == 1) - return e; + return e; for (i = 1; i < NCH(n); i++) { - node *ch = CHILD(n, i); - if (TYPE(ch) != trailer) - break; - tmp = ast_for_trailer(c, ch, e); - if (!tmp) - return NULL; - tmp->lineno = e->lineno; - tmp->col_offset = e->col_offset; - e = tmp; + node *ch = CHILD(n, i); + if (TYPE(ch) != trailer) + break; + tmp = ast_for_trailer(c, ch, e); + if (!tmp) + return NULL; + tmp->lineno = e->lineno; + tmp->col_offset = e->col_offset; + e = tmp; } if (TYPE(CHILD(n, NCH(n) - 1)) == factor) { - expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1)); - if (!f) - return NULL; - tmp = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, c->c_arena); - if (!tmp) - return NULL; - e = tmp; + expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1)); + if (!f) + return NULL; + tmp = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, c->c_arena); + if (!tmp) + return NULL; + e = tmp; } return e; } @@ -1642,124 +1642,124 @@ loop: switch (TYPE(n)) { - case test: - case old_test: - if (TYPE(CHILD(n, 0)) == lambdef || - TYPE(CHILD(n, 0)) == old_lambdef) - return ast_for_lambdef(c, CHILD(n, 0)); - else if (NCH(n) > 1) - return ast_for_ifexpr(c, n); - /* Fallthrough */ - case or_test: - case and_test: - if (NCH(n) == 1) { - n = CHILD(n, 0); - goto loop; - } - seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); - if (!seq) - return NULL; - for (i = 0; i < NCH(n); i += 2) { - expr_ty e = ast_for_expr(c, CHILD(n, i)); - if (!e) - return NULL; - asdl_seq_SET(seq, i / 2, e); - } - if (!strcmp(STR(CHILD(n, 1)), "and")) - return BoolOp(And, seq, LINENO(n), n->n_col_offset, - c->c_arena); - assert(!strcmp(STR(CHILD(n, 1)), "or")); - return BoolOp(Or, seq, LINENO(n), n->n_col_offset, c->c_arena); - case not_test: - if (NCH(n) == 1) { - n = CHILD(n, 0); - goto loop; - } - else { - expr_ty expression = ast_for_expr(c, CHILD(n, 1)); - if (!expression) - return NULL; - - return UnaryOp(Not, expression, LINENO(n), n->n_col_offset, - c->c_arena); - } - case comparison: - if (NCH(n) == 1) { - n = CHILD(n, 0); - goto loop; - } - else { - expr_ty expression; - asdl_int_seq *ops; - asdl_seq *cmps; - ops = asdl_int_seq_new(NCH(n) / 2, c->c_arena); - if (!ops) - return NULL; - cmps = asdl_seq_new(NCH(n) / 2, c->c_arena); - if (!cmps) { - return NULL; - } - for (i = 1; i < NCH(n); i += 2) { - cmpop_ty newoperator; - - newoperator = ast_for_comp_op(CHILD(n, i)); - if (!newoperator) { - return NULL; - } - - expression = ast_for_expr(c, CHILD(n, i + 1)); - if (!expression) { - return NULL; - } - - asdl_seq_SET(ops, i / 2, newoperator); - asdl_seq_SET(cmps, i / 2, expression); - } - expression = ast_for_expr(c, CHILD(n, 0)); - if (!expression) { - return NULL; - } - - return Compare(expression, ops, cmps, LINENO(n), - n->n_col_offset, c->c_arena); - } - break; - - /* The next five cases all handle BinOps. The main body of code - is the same in each case, but the switch turned inside out to - reuse the code for each type of operator. - */ - case expr: - case xor_expr: - case and_expr: - case shift_expr: - case arith_expr: - case term: - if (NCH(n) == 1) { - n = CHILD(n, 0); - goto loop; - } - return ast_for_binop(c, n); - case yield_expr: { - expr_ty exp = NULL; - if (NCH(n) == 2) { - exp = ast_for_testlist(c, CHILD(n, 1)); - if (!exp) - return NULL; - } - return Yield(exp, LINENO(n), n->n_col_offset, c->c_arena); - } - case factor: - if (NCH(n) == 1) { - n = CHILD(n, 0); - goto loop; - } - return ast_for_factor(c, n); - case power: - return ast_for_power(c, n); - default: - PyErr_Format(PyExc_SystemError, "unhandled expr: %d", TYPE(n)); - return NULL; + case test: + case old_test: + if (TYPE(CHILD(n, 0)) == lambdef || + TYPE(CHILD(n, 0)) == old_lambdef) + return ast_for_lambdef(c, CHILD(n, 0)); + else if (NCH(n) > 1) + return ast_for_ifexpr(c, n); + /* Fallthrough */ + case or_test: + case and_test: + if (NCH(n) == 1) { + n = CHILD(n, 0); + goto loop; + } + seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); + if (!seq) + return NULL; + for (i = 0; i < NCH(n); i += 2) { + expr_ty e = ast_for_expr(c, CHILD(n, i)); + if (!e) + return NULL; + asdl_seq_SET(seq, i / 2, e); + } + if (!strcmp(STR(CHILD(n, 1)), "and")) + return BoolOp(And, seq, LINENO(n), n->n_col_offset, + c->c_arena); + assert(!strcmp(STR(CHILD(n, 1)), "or")); + return BoolOp(Or, seq, LINENO(n), n->n_col_offset, c->c_arena); + case not_test: + if (NCH(n) == 1) { + n = CHILD(n, 0); + goto loop; + } + else { + expr_ty expression = ast_for_expr(c, CHILD(n, 1)); + if (!expression) + return NULL; + + return UnaryOp(Not, expression, LINENO(n), n->n_col_offset, + c->c_arena); + } + case comparison: + if (NCH(n) == 1) { + n = CHILD(n, 0); + goto loop; + } + else { + expr_ty expression; + asdl_int_seq *ops; + asdl_seq *cmps; + ops = asdl_int_seq_new(NCH(n) / 2, c->c_arena); + if (!ops) + return NULL; + cmps = asdl_seq_new(NCH(n) / 2, c->c_arena); + if (!cmps) { + return NULL; + } + for (i = 1; i < NCH(n); i += 2) { + cmpop_ty newoperator; + + newoperator = ast_for_comp_op(CHILD(n, i)); + if (!newoperator) { + return NULL; + } + + expression = ast_for_expr(c, CHILD(n, i + 1)); + if (!expression) { + return NULL; + } + + asdl_seq_SET(ops, i / 2, newoperator); + asdl_seq_SET(cmps, i / 2, expression); + } + expression = ast_for_expr(c, CHILD(n, 0)); + if (!expression) { + return NULL; + } + + return Compare(expression, ops, cmps, LINENO(n), + n->n_col_offset, c->c_arena); + } + break; + + /* The next five cases all handle BinOps. The main body of code + is the same in each case, but the switch turned inside out to + reuse the code for each type of operator. + */ + case expr: + case xor_expr: + case and_expr: + case shift_expr: + case arith_expr: + case term: + if (NCH(n) == 1) { + n = CHILD(n, 0); + goto loop; + } + return ast_for_binop(c, n); + case yield_expr: { + expr_ty exp = NULL; + if (NCH(n) == 2) { + exp = ast_for_testlist(c, CHILD(n, 1)); + if (!exp) + return NULL; + } + return Yield(exp, LINENO(n), n->n_col_offset, c->c_arena); + } + case factor: + if (NCH(n) == 1) { + n = CHILD(n, 0); + goto loop; + } + return ast_for_factor(c, n); + case power: + return ast_for_power(c, n); + default: + PyErr_Format(PyExc_SystemError, "unhandled expr: %d", TYPE(n)); + return NULL; } /* should never get here unless if error is set */ return NULL; @@ -1770,8 +1770,8 @@ { /* arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] - | '**' test) - argument: [test '='] test [gen_for] # Really [keyword '='] test + | '**' test) + argument: [test '='] test [gen_for] # Really [keyword '='] test */ int i, nargs, nkeywords, ngens; @@ -1785,20 +1785,20 @@ nkeywords = 0; ngens = 0; for (i = 0; i < NCH(n); i++) { - node *ch = CHILD(n, i); - if (TYPE(ch) == argument) { - if (NCH(ch) == 1) - nargs++; - else if (TYPE(CHILD(ch, 1)) == gen_for) - ngens++; - else - nkeywords++; - } + node *ch = CHILD(n, i); + if (TYPE(ch) == argument) { + if (NCH(ch) == 1) + nargs++; + else if (TYPE(CHILD(ch, 1)) == gen_for) + ngens++; + else + nkeywords++; + } } if (ngens > 1 || (ngens && (nargs || nkeywords))) { - ast_error(n, "Generator expression must be parenthesized " - "if not sole argument"); - return NULL; + ast_error(n, "Generator expression must be parenthesized " + "if not sole argument"); + return NULL; } if (nargs + nkeywords + ngens > 255) { @@ -1808,71 +1808,71 @@ args = asdl_seq_new(nargs + ngens, c->c_arena); if (!args) - return NULL; + return NULL; keywords = asdl_seq_new(nkeywords, c->c_arena); if (!keywords) - return NULL; + return NULL; nargs = 0; nkeywords = 0; for (i = 0; i < NCH(n); i++) { - node *ch = CHILD(n, i); - if (TYPE(ch) == argument) { - expr_ty e; - if (NCH(ch) == 1) { - if (nkeywords) { - ast_error(CHILD(ch, 0), - "non-keyword arg after keyword arg"); - return NULL; - } - e = ast_for_expr(c, CHILD(ch, 0)); - if (!e) - return NULL; - asdl_seq_SET(args, nargs++, e); - } - else if (TYPE(CHILD(ch, 1)) == gen_for) { - e = ast_for_genexp(c, ch); - if (!e) - return NULL; - asdl_seq_SET(args, nargs++, e); - } - else { - keyword_ty kw; - identifier key; - - /* CHILD(ch, 0) is test, but must be an identifier? */ - e = ast_for_expr(c, CHILD(ch, 0)); - if (!e) - return NULL; - /* f(lambda x: x[0] = 3) ends up getting parsed with - * LHS test = lambda x: x[0], and RHS test = 3. - * SF bug 132313 points out that complaining about a keyword - * then is very confusing. - */ - if (e->kind == Lambda_kind) { - ast_error(CHILD(ch, 0), "lambda cannot contain assignment"); - return NULL; - } else if (e->kind != Name_kind) { - ast_error(CHILD(ch, 0), "keyword can't be an expression"); - return NULL; - } - key = e->v.Name.id; - e = ast_for_expr(c, CHILD(ch, 2)); - if (!e) - return NULL; - kw = keyword(key, e, c->c_arena); - if (!kw) - return NULL; - asdl_seq_SET(keywords, nkeywords++, kw); - } - } - else if (TYPE(ch) == STAR) { - vararg = ast_for_expr(c, CHILD(n, i+1)); - i++; - } - else if (TYPE(ch) == DOUBLESTAR) { - kwarg = ast_for_expr(c, CHILD(n, i+1)); - i++; - } + node *ch = CHILD(n, i); + if (TYPE(ch) == argument) { + expr_ty e; + if (NCH(ch) == 1) { + if (nkeywords) { + ast_error(CHILD(ch, 0), + "non-keyword arg after keyword arg"); + return NULL; + } + e = ast_for_expr(c, CHILD(ch, 0)); + if (!e) + return NULL; + asdl_seq_SET(args, nargs++, e); + } + else if (TYPE(CHILD(ch, 1)) == gen_for) { + e = ast_for_genexp(c, ch); + if (!e) + return NULL; + asdl_seq_SET(args, nargs++, e); + } + else { + keyword_ty kw; + identifier key; + + /* CHILD(ch, 0) is test, but must be an identifier? */ + e = ast_for_expr(c, CHILD(ch, 0)); + if (!e) + return NULL; + /* f(lambda x: x[0] = 3) ends up getting parsed with + * LHS test = lambda x: x[0], and RHS test = 3. + * SF bug 132313 points out that complaining about a keyword + * then is very confusing. + */ + if (e->kind == Lambda_kind) { + ast_error(CHILD(ch, 0), "lambda cannot contain assignment"); + return NULL; + } else if (e->kind != Name_kind) { + ast_error(CHILD(ch, 0), "keyword can't be an expression"); + return NULL; + } + key = e->v.Name.id; + e = ast_for_expr(c, CHILD(ch, 2)); + if (!e) + return NULL; + kw = keyword(key, e, c->c_arena); + if (!kw) + return NULL; + asdl_seq_SET(keywords, nkeywords++, kw); + } + } + else if (TYPE(ch) == STAR) { + vararg = ast_for_expr(c, CHILD(n, i+1)); + i++; + } + else if (TYPE(ch) == DOUBLESTAR) { + kwarg = ast_for_expr(c, CHILD(n, i+1)); + i++; + } } return Call(func, args, keywords, vararg, kwarg, func->lineno, func->col_offset, c->c_arena); @@ -1887,21 +1887,21 @@ /* testlist1: test (',' test)* */ assert(NCH(n) > 0); if (TYPE(n) == testlist_gexp) { - if (NCH(n) > 1) - assert(TYPE(CHILD(n, 1)) != gen_for); + if (NCH(n) > 1) + assert(TYPE(CHILD(n, 1)) != gen_for); } else { - assert(TYPE(n) == testlist || - TYPE(n) == testlist_safe || - TYPE(n) == testlist1); + assert(TYPE(n) == testlist || + TYPE(n) == testlist_safe || + TYPE(n) == testlist1); } if (NCH(n) == 1) - return ast_for_expr(c, CHILD(n, 0)); + return ast_for_expr(c, CHILD(n, 0)); else { - asdl_seq *tmp = seq_for_testlist(c, n); - if (!tmp) - return NULL; - return Tuple(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena); + asdl_seq *tmp = seq_for_testlist(c, n); + if (!tmp) + return NULL; + return Tuple(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena); } } @@ -1912,7 +1912,7 @@ /* argument: test [ gen_for ] */ assert(TYPE(n) == testlist_gexp || TYPE(n) == argument); if (NCH(n) > 1 && TYPE(CHILD(n, 1)) == gen_for) - return ast_for_genexp(c, n); + return ast_for_genexp(c, n); return ast_for_testlist(c, n); } @@ -1924,15 +1924,15 @@ assert(NCH(n) > 0); REQ(n, testlist); if (NCH(n) == 1) { - expr_ty base; - asdl_seq *bases = asdl_seq_new(1, c->c_arena); - if (!bases) - return NULL; - base = ast_for_expr(c, CHILD(n, 0)); - if (!base) - return NULL; - asdl_seq_SET(bases, 0, base); - return bases; + expr_ty base; + asdl_seq *bases = asdl_seq_new(1, c->c_arena); + if (!bases) + return NULL; + base = ast_for_expr(c, CHILD(n, 0)); + if (!base) + return NULL; + asdl_seq_SET(bases, 0, base); + return bases; } return seq_for_testlist(c, n); @@ -1943,107 +1943,107 @@ { REQ(n, expr_stmt); /* expr_stmt: testlist (augassign (yield_expr|testlist) - | ('=' (yield_expr|testlist))*) + | ('=' (yield_expr|testlist))*) testlist: test (',' test)* [','] augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' - | '<<=' | '>>=' | '**=' | '//=' + | '<<=' | '>>=' | '**=' | '//=' test: ... here starts the operator precendence dance */ if (NCH(n) == 1) { - expr_ty e = ast_for_testlist(c, CHILD(n, 0)); - if (!e) - return NULL; + expr_ty e = ast_for_testlist(c, CHILD(n, 0)); + if (!e) + return NULL; - return Expr(e, LINENO(n), n->n_col_offset, c->c_arena); + return Expr(e, LINENO(n), n->n_col_offset, c->c_arena); } else if (TYPE(CHILD(n, 1)) == augassign) { - expr_ty expr1, expr2; - operator_ty newoperator; - node *ch = CHILD(n, 0); - - expr1 = ast_for_testlist(c, ch); - if (!expr1) - return NULL; - /* TODO(nas): Remove duplicated error checks (set_context does it) */ - switch (expr1->kind) { - case GeneratorExp_kind: - ast_error(ch, "augmented assignment to generator " - "expression not possible"); - return NULL; - case Yield_kind: - ast_error(ch, "augmented assignment to yield " - "expression not possible"); - return NULL; - case Name_kind: { - const char *var_name = PyString_AS_STRING(expr1->v.Name.id); - if (var_name[0] == 'N' && !strcmp(var_name, "None")) { - ast_error(ch, "assignment to None"); - return NULL; - } - break; - } - case Attribute_kind: - case Subscript_kind: - break; - default: - ast_error(ch, "illegal expression for augmented " - "assignment"); - return NULL; - } - set_context(expr1, Store, ch); - - ch = CHILD(n, 2); - if (TYPE(ch) == testlist) - expr2 = ast_for_testlist(c, ch); - else - expr2 = ast_for_expr(c, ch); - if (!expr2) - return NULL; - - newoperator = ast_for_augassign(CHILD(n, 1)); - if (!newoperator) - return NULL; + expr_ty expr1, expr2; + operator_ty newoperator; + node *ch = CHILD(n, 0); + + expr1 = ast_for_testlist(c, ch); + if (!expr1) + return NULL; + /* TODO(nas): Remove duplicated error checks (set_context does it) */ + switch (expr1->kind) { + case GeneratorExp_kind: + ast_error(ch, "augmented assignment to generator " + "expression not possible"); + return NULL; + case Yield_kind: + ast_error(ch, "augmented assignment to yield " + "expression not possible"); + return NULL; + case Name_kind: { + const char *var_name = PyString_AS_STRING(expr1->v.Name.id); + if (var_name[0] == 'N' && !strcmp(var_name, "None")) { + ast_error(ch, "assignment to None"); + return NULL; + } + break; + } + case Attribute_kind: + case Subscript_kind: + break; + default: + ast_error(ch, "illegal expression for augmented " + "assignment"); + return NULL; + } + set_context(expr1, Store, ch); + + ch = CHILD(n, 2); + if (TYPE(ch) == testlist) + expr2 = ast_for_testlist(c, ch); + else + expr2 = ast_for_expr(c, ch); + if (!expr2) + return NULL; + + newoperator = ast_for_augassign(CHILD(n, 1)); + if (!newoperator) + return NULL; - return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, c->c_arena); + return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, c->c_arena); } else { - int i; - asdl_seq *targets; - node *value; - expr_ty expression; - - /* a normal assignment */ - REQ(CHILD(n, 1), EQUAL); - targets = asdl_seq_new(NCH(n) / 2, c->c_arena); - if (!targets) - return NULL; - for (i = 0; i < NCH(n) - 2; i += 2) { - expr_ty e; - node *ch = CHILD(n, i); - if (TYPE(ch) == yield_expr) { - ast_error(ch, "assignment to yield expression not possible"); - return NULL; - } - e = ast_for_testlist(c, ch); - - /* set context to assign */ - if (!e) - return NULL; - - if (!set_context(e, Store, CHILD(n, i))) - return NULL; - - asdl_seq_SET(targets, i / 2, e); - } - value = CHILD(n, NCH(n) - 1); - if (TYPE(value) == testlist) - expression = ast_for_testlist(c, value); - else - expression = ast_for_expr(c, value); - if (!expression) - return NULL; - return Assign(targets, expression, LINENO(n), n->n_col_offset, c->c_arena); + int i; + asdl_seq *targets; + node *value; + expr_ty expression; + + /* a normal assignment */ + REQ(CHILD(n, 1), EQUAL); + targets = asdl_seq_new(NCH(n) / 2, c->c_arena); + if (!targets) + return NULL; + for (i = 0; i < NCH(n) - 2; i += 2) { + expr_ty e; + node *ch = CHILD(n, i); + if (TYPE(ch) == yield_expr) { + ast_error(ch, "assignment to yield expression not possible"); + return NULL; + } + e = ast_for_testlist(c, ch); + + /* set context to assign */ + if (!e) + return NULL; + + if (!set_context(e, Store, CHILD(n, i))) + return NULL; + + asdl_seq_SET(targets, i / 2, e); + } + value = CHILD(n, NCH(n) - 1); + if (TYPE(value) == testlist) + expression = ast_for_testlist(c, value); + else + expression = ast_for_expr(c, value); + if (!expression) + return NULL; + return Assign(targets, expression, LINENO(n), n->n_col_offset, c->c_arena); } } @@ -2051,7 +2051,7 @@ ast_for_print_stmt(struct compiling *c, const node *n) { /* print_stmt: 'print' ( [ test (',' test)* [','] ] - | '>>' test [ (',' test)+ [','] ] ) + | '>>' test [ (',' test)+ [','] ] ) */ expr_ty dest = NULL, expression; asdl_seq *seq; @@ -2060,19 +2060,19 @@ REQ(n, print_stmt); if (NCH(n) >= 2 && TYPE(CHILD(n, 1)) == RIGHTSHIFT) { - dest = ast_for_expr(c, CHILD(n, 2)); - if (!dest) - return NULL; - start = 4; + dest = ast_for_expr(c, CHILD(n, 2)); + if (!dest) + return NULL; + start = 4; } seq = asdl_seq_new((NCH(n) + 1 - start) / 2, c->c_arena); if (!seq) - return NULL; + return NULL; for (i = start, j = 0; i < NCH(n); i += 2, ++j) { - expression = ast_for_expr(c, CHILD(n, i)); - if (!expression) - return NULL; - asdl_seq_SET(seq, j, expression); + expression = ast_for_expr(c, CHILD(n, i)); + if (!expression) + return NULL; + asdl_seq_SET(seq, j, expression); } nl = (TYPE(CHILD(n, NCH(n) - 1)) == COMMA) ? false : true; return Print(dest, seq, nl, LINENO(n), n->n_col_offset, c->c_arena); @@ -2089,14 +2089,14 @@ seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!seq) - return NULL; + return NULL; for (i = 0; i < NCH(n); i += 2) { - e = ast_for_expr(c, CHILD(n, i)); - if (!e) - return NULL; - asdl_seq_SET(seq, i / 2, e); - if (context && !set_context(e, context, CHILD(n, i))) - return NULL; + e = ast_for_expr(c, CHILD(n, i)); + if (!e) + return NULL; + asdl_seq_SET(seq, i / 2, e); + if (context && !set_context(e, context, CHILD(n, i))) + return NULL; } return seq; } @@ -2111,7 +2111,7 @@ expr_list = ast_for_exprlist(c, CHILD(n, 1), Del); if (!expr_list) - return NULL; + return NULL; return Delete(expr_list, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2120,7 +2120,7 @@ { /* flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt - | yield_stmt + | yield_stmt break_stmt: 'break' continue_stmt: 'continue' return_stmt: 'return' [testlist] @@ -2133,65 +2133,65 @@ REQ(n, flow_stmt); ch = CHILD(n, 0); switch (TYPE(ch)) { - case break_stmt: - return Break(LINENO(n), n->n_col_offset, c->c_arena); - case continue_stmt: - return Continue(LINENO(n), n->n_col_offset, c->c_arena); - case yield_stmt: { /* will reduce to yield_expr */ - expr_ty exp = ast_for_expr(c, CHILD(ch, 0)); - if (!exp) - return NULL; - return Expr(exp, LINENO(n), n->n_col_offset, c->c_arena); - } - case return_stmt: - if (NCH(ch) == 1) - return Return(NULL, LINENO(n), n->n_col_offset, c->c_arena); - else { - expr_ty expression = ast_for_testlist(c, CHILD(ch, 1)); - if (!expression) - return NULL; - return Return(expression, LINENO(n), n->n_col_offset, c->c_arena); - } - case raise_stmt: - if (NCH(ch) == 1) - return Raise(NULL, NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena); - else if (NCH(ch) == 2) { - expr_ty expression = ast_for_expr(c, CHILD(ch, 1)); - if (!expression) - return NULL; - return Raise(expression, NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena); - } - else if (NCH(ch) == 4) { - expr_ty expr1, expr2; - - expr1 = ast_for_expr(c, CHILD(ch, 1)); - if (!expr1) - return NULL; - expr2 = ast_for_expr(c, CHILD(ch, 3)); - if (!expr2) - return NULL; - - return Raise(expr1, expr2, NULL, LINENO(n), n->n_col_offset, c->c_arena); - } - else if (NCH(ch) == 6) { - expr_ty expr1, expr2, expr3; - - expr1 = ast_for_expr(c, CHILD(ch, 1)); - if (!expr1) - return NULL; - expr2 = ast_for_expr(c, CHILD(ch, 3)); - if (!expr2) - return NULL; - expr3 = ast_for_expr(c, CHILD(ch, 5)); - if (!expr3) - return NULL; - - return Raise(expr1, expr2, expr3, LINENO(n), n->n_col_offset, c->c_arena); - } - default: - PyErr_Format(PyExc_SystemError, - "unexpected flow_stmt: %d", TYPE(ch)); - return NULL; + case break_stmt: + return Break(LINENO(n), n->n_col_offset, c->c_arena); + case continue_stmt: + return Continue(LINENO(n), n->n_col_offset, c->c_arena); + case yield_stmt: { /* will reduce to yield_expr */ + expr_ty exp = ast_for_expr(c, CHILD(ch, 0)); + if (!exp) + return NULL; + return Expr(exp, LINENO(n), n->n_col_offset, c->c_arena); + } + case return_stmt: + if (NCH(ch) == 1) + return Return(NULL, LINENO(n), n->n_col_offset, c->c_arena); + else { + expr_ty expression = ast_for_testlist(c, CHILD(ch, 1)); + if (!expression) + return NULL; + return Return(expression, LINENO(n), n->n_col_offset, c->c_arena); + } + case raise_stmt: + if (NCH(ch) == 1) + return Raise(NULL, NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena); + else if (NCH(ch) == 2) { + expr_ty expression = ast_for_expr(c, CHILD(ch, 1)); + if (!expression) + return NULL; + return Raise(expression, NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena); + } + else if (NCH(ch) == 4) { + expr_ty expr1, expr2; + + expr1 = ast_for_expr(c, CHILD(ch, 1)); + if (!expr1) + return NULL; + expr2 = ast_for_expr(c, CHILD(ch, 3)); + if (!expr2) + return NULL; + + return Raise(expr1, expr2, NULL, LINENO(n), n->n_col_offset, c->c_arena); + } + else if (NCH(ch) == 6) { + expr_ty expr1, expr2, expr3; + + expr1 = ast_for_expr(c, CHILD(ch, 1)); + if (!expr1) + return NULL; + expr2 = ast_for_expr(c, CHILD(ch, 3)); + if (!expr2) + return NULL; + expr3 = ast_for_expr(c, CHILD(ch, 5)); + if (!expr3) + return NULL; + + return Raise(expr1, expr2, expr3, LINENO(n), n->n_col_offset, c->c_arena); + } + default: + PyErr_Format(PyExc_SystemError, + "unexpected flow_stmt: %d", TYPE(ch)); + return NULL; } PyErr_SetString(PyExc_SystemError, "unhandled flow statement"); @@ -2210,67 +2210,67 @@ loop: switch (TYPE(n)) { - case import_as_name: - str = NULL; - if (NCH(n) == 3) { - str = NEW_IDENTIFIER(CHILD(n, 2)); - } - return alias(NEW_IDENTIFIER(CHILD(n, 0)), str, c->c_arena); - case dotted_as_name: - if (NCH(n) == 1) { - n = CHILD(n, 0); - goto loop; - } - else { - alias_ty a = alias_for_import_name(c, CHILD(n, 0)); - if (!a) - return NULL; - assert(!a->asname); - a->asname = NEW_IDENTIFIER(CHILD(n, 2)); - return a; - } - break; - case dotted_name: - if (NCH(n) == 1) - return alias(NEW_IDENTIFIER(CHILD(n, 0)), NULL, c->c_arena); - else { - /* Create a string of the form "a.b.c" */ - int i; - size_t len; - char *s; - - len = 0; - for (i = 0; i < NCH(n); i += 2) - /* length of string plus one for the dot */ - len += strlen(STR(CHILD(n, i))) + 1; - len--; /* the last name doesn't have a dot */ - str = PyString_FromStringAndSize(NULL, len); - if (!str) - return NULL; - s = PyString_AS_STRING(str); - if (!s) - return NULL; - for (i = 0; i < NCH(n); i += 2) { - char *sch = STR(CHILD(n, i)); - strcpy(s, STR(CHILD(n, i))); - s += strlen(sch); - *s++ = '.'; - } - --s; - *s = '\0'; - PyString_InternInPlace(&str); - PyArena_AddPyObject(c->c_arena, str); - return alias(str, NULL, c->c_arena); - } - break; - case STAR: - str = PyString_InternFromString("*"); - PyArena_AddPyObject(c->c_arena, str); - return alias(str, NULL, c->c_arena); - default: - PyErr_Format(PyExc_SystemError, - "unexpected import name: %d", TYPE(n)); - return NULL; + case import_as_name: + str = NULL; + if (NCH(n) == 3) { + str = NEW_IDENTIFIER(CHILD(n, 2)); + } + return alias(NEW_IDENTIFIER(CHILD(n, 0)), str, c->c_arena); + case dotted_as_name: + if (NCH(n) == 1) { + n = CHILD(n, 0); + goto loop; + } + else { + alias_ty a = alias_for_import_name(c, CHILD(n, 0)); + if (!a) + return NULL; + assert(!a->asname); + a->asname = NEW_IDENTIFIER(CHILD(n, 2)); + return a; + } + break; + case dotted_name: + if (NCH(n) == 1) + return alias(NEW_IDENTIFIER(CHILD(n, 0)), NULL, c->c_arena); + else { + /* Create a string of the form "a.b.c" */ + int i; + size_t len; + char *s; + + len = 0; + for (i = 0; i < NCH(n); i += 2) + /* length of string plus one for the dot */ + len += strlen(STR(CHILD(n, i))) + 1; + len--; /* the last name doesn't have a dot */ + str = PyString_FromStringAndSize(NULL, len); + if (!str) + return NULL; + s = PyString_AS_STRING(str); + if (!s) + return NULL; + for (i = 0; i < NCH(n); i += 2) { + char *sch = STR(CHILD(n, i)); + strcpy(s, STR(CHILD(n, i))); + s += strlen(sch); + *s++ = '.'; + } + --s; + *s = '\0'; + PyString_InternInPlace(&str); + PyArena_AddPyObject(c->c_arena, str); + return alias(str, NULL, c->c_arena); + } + break; + case STAR: + str = PyString_InternFromString("*"); + PyArena_AddPyObject(c->c_arena, str); + return alias(str, NULL, c->c_arena); + default: + PyErr_Format(PyExc_SystemError, + "unexpected import name: %d", TYPE(n)); + return NULL; } PyErr_SetString(PyExc_SystemError, "unhandled import name condition"); @@ -2284,7 +2284,7 @@ import_stmt: import_name | import_from import_name: 'import' dotted_as_names import_from: 'from' ('.'* dotted_name | '.') 'import' - ('*' | '(' import_as_names ')' | import_as_names) + ('*' | '(' import_as_names ')' | import_as_names) */ int lineno; int col_offset; @@ -2296,97 +2296,97 @@ col_offset = n->n_col_offset; n = CHILD(n, 0); if (TYPE(n) == import_name) { - n = CHILD(n, 1); - REQ(n, dotted_as_names); - aliases = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); - if (!aliases) - return NULL; - for (i = 0; i < NCH(n); i += 2) { - alias_ty import_alias = alias_for_import_name(c, CHILD(n, i)); - if (!import_alias) - return NULL; - asdl_seq_SET(aliases, i / 2, import_alias); - } - return Import(aliases, lineno, col_offset, c->c_arena); + n = CHILD(n, 1); + REQ(n, dotted_as_names); + aliases = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); + if (!aliases) + return NULL; + for (i = 0; i < NCH(n); i += 2) { + alias_ty import_alias = alias_for_import_name(c, CHILD(n, i)); + if (!import_alias) + return NULL; + asdl_seq_SET(aliases, i / 2, import_alias); + } + return Import(aliases, lineno, col_offset, c->c_arena); } else if (TYPE(n) == import_from) { - int n_children; - int idx, ndots = 0; - alias_ty mod = NULL; - identifier modname; - + int n_children; + int idx, ndots = 0; + alias_ty mod = NULL; + identifier modname; + /* Count the number of dots (for relative imports) and check for the - optional module name */ - for (idx = 1; idx < NCH(n); idx++) { - if (TYPE(CHILD(n, idx)) == dotted_name) { - mod = alias_for_import_name(c, CHILD(n, idx)); - idx++; - break; - } else if (TYPE(CHILD(n, idx)) != DOT) { - break; - } - ndots++; - } - idx++; /* skip over the 'import' keyword */ - switch (TYPE(CHILD(n, idx))) { - case STAR: - /* from ... import * */ - n = CHILD(n, idx); - n_children = 1; - if (ndots) { - ast_error(n, "'import *' not allowed with 'from .'"); - return NULL; - } - break; - case LPAR: - /* from ... import (x, y, z) */ - n = CHILD(n, idx + 1); - n_children = NCH(n); - break; - case import_as_names: - /* from ... import x, y, z */ - n = CHILD(n, idx); - n_children = NCH(n); - if (n_children % 2 == 0) { - ast_error(n, "trailing comma not allowed without" - " surrounding parentheses"); - return NULL; - } - break; - default: - ast_error(n, "Unexpected node-type in from-import"); - return NULL; - } - - aliases = asdl_seq_new((n_children + 1) / 2, c->c_arena); - if (!aliases) - return NULL; - - /* handle "from ... import *" special b/c there's no children */ - if (TYPE(n) == STAR) { - alias_ty import_alias = alias_for_import_name(c, n); - if (!import_alias) - return NULL; - asdl_seq_SET(aliases, 0, import_alias); - } - else { - for (i = 0; i < NCH(n); i += 2) { - alias_ty import_alias = alias_for_import_name(c, CHILD(n, i)); - if (!import_alias) - return NULL; - asdl_seq_SET(aliases, i / 2, import_alias); - } - } - if (mod != NULL) - modname = mod->name; - else - modname = new_identifier("", c->c_arena); - return ImportFrom(modname, aliases, ndots, lineno, col_offset, - c->c_arena); + optional module name */ + for (idx = 1; idx < NCH(n); idx++) { + if (TYPE(CHILD(n, idx)) == dotted_name) { + mod = alias_for_import_name(c, CHILD(n, idx)); + idx++; + break; + } else if (TYPE(CHILD(n, idx)) != DOT) { + break; + } + ndots++; + } + idx++; /* skip over the 'import' keyword */ + switch (TYPE(CHILD(n, idx))) { + case STAR: + /* from ... import * */ + n = CHILD(n, idx); + n_children = 1; + if (ndots) { + ast_error(n, "'import *' not allowed with 'from .'"); + return NULL; + } + break; + case LPAR: + /* from ... import (x, y, z) */ + n = CHILD(n, idx + 1); + n_children = NCH(n); + break; + case import_as_names: + /* from ... import x, y, z */ + n = CHILD(n, idx); + n_children = NCH(n); + if (n_children % 2 == 0) { + ast_error(n, "trailing comma not allowed without" + " surrounding parentheses"); + return NULL; + } + break; + default: + ast_error(n, "Unexpected node-type in from-import"); + return NULL; + } + + aliases = asdl_seq_new((n_children + 1) / 2, c->c_arena); + if (!aliases) + return NULL; + + /* handle "from ... import *" special b/c there's no children */ + if (TYPE(n) == STAR) { + alias_ty import_alias = alias_for_import_name(c, n); + if (!import_alias) + return NULL; + asdl_seq_SET(aliases, 0, import_alias); + } + else { + for (i = 0; i < NCH(n); i += 2) { + alias_ty import_alias = alias_for_import_name(c, CHILD(n, i)); + if (!import_alias) + return NULL; + asdl_seq_SET(aliases, i / 2, import_alias); + } + } + if (mod != NULL) + modname = mod->name; + else + modname = new_identifier("", c->c_arena); + return ImportFrom(modname, aliases, ndots, lineno, col_offset, + c->c_arena); } PyErr_Format(PyExc_SystemError, - "unknown import statement: starts with command '%s'", - STR(CHILD(n, 0))); + "unknown import statement: starts with command '%s'", + STR(CHILD(n, 0))); return NULL; } @@ -2401,12 +2401,12 @@ REQ(n, global_stmt); s = asdl_seq_new(NCH(n) / 2, c->c_arena); if (!s) - return NULL; + return NULL; for (i = 1; i < NCH(n); i += 2) { - name = NEW_IDENTIFIER(CHILD(n, i)); - if (!name) - return NULL; - asdl_seq_SET(s, i / 2, name); + name = NEW_IDENTIFIER(CHILD(n, i)); + if (!name) + return NULL; + asdl_seq_SET(s, i / 2, name); } return Global(s, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2417,26 +2417,26 @@ expr_ty expr1, globals = NULL, locals = NULL; int n_children = NCH(n); if (n_children != 2 && n_children != 4 && n_children != 6) { - PyErr_Format(PyExc_SystemError, - "poorly formed 'exec' statement: %d parts to statement", - n_children); - return NULL; + PyErr_Format(PyExc_SystemError, + "poorly formed 'exec' statement: %d parts to statement", + n_children); + return NULL; } /* exec_stmt: 'exec' expr ['in' test [',' test]] */ REQ(n, exec_stmt); expr1 = ast_for_expr(c, CHILD(n, 1)); if (!expr1) - return NULL; + return NULL; if (n_children >= 4) { - globals = ast_for_expr(c, CHILD(n, 3)); - if (!globals) - return NULL; + globals = ast_for_expr(c, CHILD(n, 3)); + if (!globals) + return NULL; } if (n_children == 6) { - locals = ast_for_expr(c, CHILD(n, 5)); - if (!locals) - return NULL; + locals = ast_for_expr(c, CHILD(n, 5)); + if (!locals) + return NULL; } return Exec(expr1, globals, locals, LINENO(n), n->n_col_offset, c->c_arena); @@ -2448,26 +2448,26 @@ /* assert_stmt: 'assert' test [',' test] */ REQ(n, assert_stmt); if (NCH(n) == 2) { - expr_ty expression = ast_for_expr(c, CHILD(n, 1)); - if (!expression) - return NULL; - return Assert(expression, NULL, LINENO(n), n->n_col_offset, c->c_arena); + expr_ty expression = ast_for_expr(c, CHILD(n, 1)); + if (!expression) + return NULL; + return Assert(expression, NULL, LINENO(n), n->n_col_offset, c->c_arena); } else if (NCH(n) == 4) { - expr_ty expr1, expr2; + expr_ty expr1, expr2; - expr1 = ast_for_expr(c, CHILD(n, 1)); - if (!expr1) - return NULL; - expr2 = ast_for_expr(c, CHILD(n, 3)); - if (!expr2) - return NULL; - - return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena); + expr1 = ast_for_expr(c, CHILD(n, 1)); + if (!expr1) + return NULL; + expr2 = ast_for_expr(c, CHILD(n, 3)); + if (!expr2) + return NULL; + + return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, - "improper number of parts to 'assert' statement: %d", - NCH(n)); + "improper number of parts to 'assert' statement: %d", + NCH(n)); return NULL; } @@ -2485,53 +2485,53 @@ total = num_stmts(n); seq = asdl_seq_new(total, c->c_arena); if (!seq) - return NULL; + return NULL; if (TYPE(CHILD(n, 0)) == simple_stmt) { - n = CHILD(n, 0); - /* simple_stmt always ends with a NEWLINE, - and may have a trailing SEMI - */ - end = NCH(n) - 1; - if (TYPE(CHILD(n, end - 1)) == SEMI) - end--; - /* loop by 2 to skip semi-colons */ - for (i = 0; i < end; i += 2) { - ch = CHILD(n, i); - s = ast_for_stmt(c, ch); - if (!s) - return NULL; - asdl_seq_SET(seq, pos++, s); - } + n = CHILD(n, 0); + /* simple_stmt always ends with a NEWLINE, + and may have a trailing SEMI + */ + end = NCH(n) - 1; + if (TYPE(CHILD(n, end - 1)) == SEMI) + end--; + /* loop by 2 to skip semi-colons */ + for (i = 0; i < end; i += 2) { + ch = CHILD(n, i); + s = ast_for_stmt(c, ch); + if (!s) + return NULL; + asdl_seq_SET(seq, pos++, s); + } } else { - for (i = 2; i < (NCH(n) - 1); i++) { - ch = CHILD(n, i); - REQ(ch, stmt); - num = num_stmts(ch); - if (num == 1) { - /* small_stmt or compound_stmt with only one child */ - s = ast_for_stmt(c, ch); - if (!s) - return NULL; - asdl_seq_SET(seq, pos++, s); - } - else { - int j; - ch = CHILD(ch, 0); - REQ(ch, simple_stmt); - for (j = 0; j < NCH(ch); j += 2) { - /* statement terminates with a semi-colon ';' */ - if (NCH(CHILD(ch, j)) == 0) { - assert((j + 1) == NCH(ch)); - break; - } - s = ast_for_stmt(c, CHILD(ch, j)); - if (!s) - return NULL; - asdl_seq_SET(seq, pos++, s); - } - } - } + for (i = 2; i < (NCH(n) - 1); i++) { + ch = CHILD(n, i); + REQ(ch, stmt); + num = num_stmts(ch); + if (num == 1) { + /* small_stmt or compound_stmt with only one child */ + s = ast_for_stmt(c, ch); + if (!s) + return NULL; + asdl_seq_SET(seq, pos++, s); + } + else { + int j; + ch = CHILD(ch, 0); + REQ(ch, simple_stmt); + for (j = 0; j < NCH(ch); j += 2) { + /* statement terminates with a semi-colon ';' */ + if (NCH(CHILD(ch, j)) == 0) { + assert((j + 1) == NCH(ch)); + break; + } + s = ast_for_stmt(c, CHILD(ch, j)); + if (!s) + return NULL; + asdl_seq_SET(seq, pos++, s); + } + } + } } assert(pos == seq->size); return seq; @@ -2548,17 +2548,17 @@ REQ(n, if_stmt); if (NCH(n) == 4) { - expr_ty expression; - asdl_seq *suite_seq; + expr_ty expression; + asdl_seq *suite_seq; - expression = ast_for_expr(c, CHILD(n, 1)); - if (!expression) - return NULL; - suite_seq = ast_for_suite(c, CHILD(n, 3)); - if (!suite_seq) - return NULL; - - return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); + expression = ast_for_expr(c, CHILD(n, 1)); + if (!expression) + return NULL; + suite_seq = ast_for_suite(c, CHILD(n, 3)); + if (!suite_seq) + return NULL; + + return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } s = STR(CHILD(n, 4)); @@ -2567,84 +2567,84 @@ 'i' for el_i_f */ if (s[2] == 's') { - expr_ty expression; - asdl_seq *seq1, *seq2; + expr_ty expression; + asdl_seq *seq1, *seq2; - expression = ast_for_expr(c, CHILD(n, 1)); - if (!expression) - return NULL; - seq1 = ast_for_suite(c, CHILD(n, 3)); - if (!seq1) - return NULL; - seq2 = ast_for_suite(c, CHILD(n, 6)); - if (!seq2) - return NULL; + expression = ast_for_expr(c, CHILD(n, 1)); + if (!expression) + return NULL; + seq1 = ast_for_suite(c, CHILD(n, 3)); + if (!seq1) + return NULL; + seq2 = ast_for_suite(c, CHILD(n, 6)); + if (!seq2) + return NULL; - return If(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena); + return If(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena); } else if (s[2] == 'i') { - int i, n_elif, has_else = 0; - asdl_seq *orelse = NULL; - n_elif = NCH(n) - 4; - /* must reference the child n_elif+1 since 'else' token is third, - not fourth, child from the end. */ - if (TYPE(CHILD(n, (n_elif + 1))) == NAME - && STR(CHILD(n, (n_elif + 1)))[2] == 's') { - has_else = 1; - n_elif -= 3; - } - n_elif /= 4; - - if (has_else) { - expr_ty expression; - asdl_seq *seq1, *seq2; - - orelse = asdl_seq_new(1, c->c_arena); - if (!orelse) - return NULL; - expression = ast_for_expr(c, CHILD(n, NCH(n) - 6)); - if (!expression) - return NULL; - seq1 = ast_for_suite(c, CHILD(n, NCH(n) - 4)); - if (!seq1) - return NULL; - seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1)); - if (!seq2) - return NULL; - - asdl_seq_SET(orelse, 0, If(expression, seq1, seq2, - LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, - c->c_arena)); - /* the just-created orelse handled the last elif */ - n_elif--; - } - - for (i = 0; i < n_elif; i++) { - int off = 5 + (n_elif - i - 1) * 4; - expr_ty expression; - asdl_seq *suite_seq; - asdl_seq *newobj = asdl_seq_new(1, c->c_arena); - if (!newobj) - return NULL; - expression = ast_for_expr(c, CHILD(n, off)); - if (!expression) - return NULL; - suite_seq = ast_for_suite(c, CHILD(n, off + 2)); - if (!suite_seq) - return NULL; - - asdl_seq_SET(newobj, 0, - If(expression, suite_seq, orelse, - LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena)); - orelse = newobj; - } - return If(ast_for_expr(c, CHILD(n, 1)), - ast_for_suite(c, CHILD(n, 3)), - orelse, LINENO(n), n->n_col_offset, c->c_arena); + int i, n_elif, has_else = 0; + asdl_seq *orelse = NULL; + n_elif = NCH(n) - 4; + /* must reference the child n_elif+1 since 'else' token is third, + not fourth, child from the end. */ + if (TYPE(CHILD(n, (n_elif + 1))) == NAME + && STR(CHILD(n, (n_elif + 1)))[2] == 's') { + has_else = 1; + n_elif -= 3; + } + n_elif /= 4; + + if (has_else) { + expr_ty expression; + asdl_seq *seq1, *seq2; + + orelse = asdl_seq_new(1, c->c_arena); + if (!orelse) + return NULL; + expression = ast_for_expr(c, CHILD(n, NCH(n) - 6)); + if (!expression) + return NULL; + seq1 = ast_for_suite(c, CHILD(n, NCH(n) - 4)); + if (!seq1) + return NULL; + seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1)); + if (!seq2) + return NULL; + + asdl_seq_SET(orelse, 0, If(expression, seq1, seq2, + LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, + c->c_arena)); + /* the just-created orelse handled the last elif */ + n_elif--; + } + + for (i = 0; i < n_elif; i++) { + int off = 5 + (n_elif - i - 1) * 4; + expr_ty expression; + asdl_seq *suite_seq; + asdl_seq *newobj = asdl_seq_new(1, c->c_arena); + if (!newobj) + return NULL; + expression = ast_for_expr(c, CHILD(n, off)); + if (!expression) + return NULL; + suite_seq = ast_for_suite(c, CHILD(n, off + 2)); + if (!suite_seq) + return NULL; + + asdl_seq_SET(newobj, 0, + If(expression, suite_seq, orelse, + LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena)); + orelse = newobj; + } + return If(ast_for_expr(c, CHILD(n, 1)), + ast_for_suite(c, CHILD(n, 3)), + orelse, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, - "unexpected token in 'if' statement: %s", s); + "unexpected token in 'if' statement: %s", s); return NULL; } @@ -2655,37 +2655,37 @@ REQ(n, while_stmt); if (NCH(n) == 4) { - expr_ty expression; - asdl_seq *suite_seq; + expr_ty expression; + asdl_seq *suite_seq; - expression = ast_for_expr(c, CHILD(n, 1)); - if (!expression) - return NULL; - suite_seq = ast_for_suite(c, CHILD(n, 3)); - if (!suite_seq) - return NULL; - return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); + expression = ast_for_expr(c, CHILD(n, 1)); + if (!expression) + return NULL; + suite_seq = ast_for_suite(c, CHILD(n, 3)); + if (!suite_seq) + return NULL; + return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } else if (NCH(n) == 7) { - expr_ty expression; - asdl_seq *seq1, *seq2; + expr_ty expression; + asdl_seq *seq1, *seq2; - expression = ast_for_expr(c, CHILD(n, 1)); - if (!expression) - return NULL; - seq1 = ast_for_suite(c, CHILD(n, 3)); - if (!seq1) - return NULL; - seq2 = ast_for_suite(c, CHILD(n, 6)); - if (!seq2) - return NULL; + expression = ast_for_expr(c, CHILD(n, 1)); + if (!expression) + return NULL; + seq1 = ast_for_suite(c, CHILD(n, 3)); + if (!seq1) + return NULL; + seq2 = ast_for_suite(c, CHILD(n, 6)); + if (!seq2) + return NULL; - return While(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena); + return While(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, - "wrong number of tokens for 'while' statement: %d", - NCH(n)); + "wrong number of tokens for 'while' statement: %d", + NCH(n)); return NULL; } @@ -2700,31 +2700,31 @@ REQ(n, for_stmt); if (NCH(n) == 9) { - seq = ast_for_suite(c, CHILD(n, 8)); - if (!seq) - return NULL; + seq = ast_for_suite(c, CHILD(n, 8)); + if (!seq) + return NULL; } node_target = CHILD(n, 1); _target = ast_for_exprlist(c, node_target, Store); if (!_target) - return NULL; + return NULL; /* Check the # of children rather than the length of _target, since for x, in ... has 1 element in _target, but still requires a Tuple. */ if (NCH(node_target) == 1) - target = (expr_ty)asdl_seq_GET(_target, 0); + target = (expr_ty)asdl_seq_GET(_target, 0); else - target = Tuple(_target, Store, LINENO(n), n->n_col_offset, c->c_arena); + target = Tuple(_target, Store, LINENO(n), n->n_col_offset, c->c_arena); expression = ast_for_testlist(c, CHILD(n, 3)); if (!expression) - return NULL; + return NULL; suite_seq = ast_for_suite(c, CHILD(n, 5)); if (!suite_seq) - return NULL; + return NULL; return For(target, expression, suite_seq, seq, LINENO(n), n->n_col_offset, - c->c_arena); + c->c_arena); } static excepthandler_ty @@ -2735,49 +2735,49 @@ REQ(body, suite); if (NCH(exc) == 1) { - asdl_seq *suite_seq = ast_for_suite(c, body); - if (!suite_seq) - return NULL; + asdl_seq *suite_seq = ast_for_suite(c, body); + if (!suite_seq) + return NULL; - return excepthandler(NULL, NULL, suite_seq, LINENO(exc), - exc->n_col_offset, c->c_arena); + return excepthandler(NULL, NULL, suite_seq, LINENO(exc), + exc->n_col_offset, c->c_arena); } else if (NCH(exc) == 2) { - expr_ty expression; - asdl_seq *suite_seq; + expr_ty expression; + asdl_seq *suite_seq; - expression = ast_for_expr(c, CHILD(exc, 1)); - if (!expression) - return NULL; - suite_seq = ast_for_suite(c, body); - if (!suite_seq) - return NULL; + expression = ast_for_expr(c, CHILD(exc, 1)); + if (!expression) + return NULL; + suite_seq = ast_for_suite(c, body); + if (!suite_seq) + return NULL; - return excepthandler(expression, NULL, suite_seq, LINENO(exc), - exc->n_col_offset, c->c_arena); + return excepthandler(expression, NULL, suite_seq, LINENO(exc), + exc->n_col_offset, c->c_arena); } else if (NCH(exc) == 4) { - asdl_seq *suite_seq; - expr_ty expression; - expr_ty e = ast_for_expr(c, 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; - suite_seq = ast_for_suite(c, body); - if (!suite_seq) - return NULL; + asdl_seq *suite_seq; + expr_ty expression; + expr_ty e = ast_for_expr(c, 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; + suite_seq = ast_for_suite(c, body); + if (!suite_seq) + return NULL; - return excepthandler(expression, e, suite_seq, LINENO(exc), - exc->n_col_offset, c->c_arena); + return excepthandler(expression, e, suite_seq, LINENO(exc), + exc->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, - "wrong number of children for 'except' clause: %d", - NCH(exc)); + "wrong number of children for 'except' clause: %d", + NCH(exc)); return NULL; } @@ -2792,66 +2792,66 @@ body = ast_for_suite(c, CHILD(n, 2)); if (body == NULL) - return NULL; + return NULL; if (TYPE(CHILD(n, nch - 3)) == NAME) { - if (strcmp(STR(CHILD(n, nch - 3)), "finally") == 0) { - if (nch >= 9 && TYPE(CHILD(n, nch - 6)) == NAME) { - /* we can assume it's an "else", - because nch >= 9 for try-else-finally and - it would otherwise have a type of except_clause */ - orelse = ast_for_suite(c, CHILD(n, nch - 4)); - if (orelse == NULL) - return NULL; - n_except--; - } - - finally = ast_for_suite(c, CHILD(n, nch - 1)); - if (finally == NULL) - return NULL; - n_except--; - } - else { - /* we can assume it's an "else", - otherwise it would have a type of except_clause */ - orelse = ast_for_suite(c, CHILD(n, nch - 1)); - if (orelse == NULL) - return NULL; - n_except--; - } + if (strcmp(STR(CHILD(n, nch - 3)), "finally") == 0) { + if (nch >= 9 && TYPE(CHILD(n, nch - 6)) == NAME) { + /* we can assume it's an "else", + because nch >= 9 for try-else-finally and + it would otherwise have a type of except_clause */ + orelse = ast_for_suite(c, CHILD(n, nch - 4)); + if (orelse == NULL) + return NULL; + n_except--; + } + + finally = ast_for_suite(c, CHILD(n, nch - 1)); + if (finally == NULL) + return NULL; + n_except--; + } + else { + /* we can assume it's an "else", + otherwise it would have a type of except_clause */ + orelse = ast_for_suite(c, CHILD(n, nch - 1)); + if (orelse == NULL) + return NULL; + n_except--; + } } else if (TYPE(CHILD(n, nch - 3)) != except_clause) { - ast_error(n, "malformed 'try' statement"); - return NULL; + ast_error(n, "malformed 'try' statement"); + return NULL; } if (n_except > 0) { - int i; - stmt_ty except_st; - /* process except statements to create a try ... except */ - asdl_seq *handlers = asdl_seq_new(n_except, c->c_arena); - if (handlers == NULL) - return NULL; - - for (i = 0; i < n_except; i++) { - excepthandler_ty e = ast_for_except_clause(c, CHILD(n, 3 + i * 3), - CHILD(n, 5 + i * 3)); - if (!e) - return NULL; - asdl_seq_SET(handlers, i, e); - } - - except_st = TryExcept(body, handlers, orelse, LINENO(n), - n->n_col_offset, c->c_arena); - if (!finally) - return except_st; - - /* if a 'finally' is present too, we nest the TryExcept within a - TryFinally to emulate try ... except ... finally */ - body = asdl_seq_new(1, c->c_arena); - if (body == NULL) - return NULL; - asdl_seq_SET(body, 0, except_st); + int i; + stmt_ty except_st; + /* process except statements to create a try ... except */ + asdl_seq *handlers = asdl_seq_new(n_except, c->c_arena); + if (handlers == NULL) + return NULL; + + for (i = 0; i < n_except; i++) { + excepthandler_ty e = ast_for_except_clause(c, CHILD(n, 3 + i * 3), + CHILD(n, 5 + i * 3)); + if (!e) + return NULL; + asdl_seq_SET(handlers, i, e); + } + + except_st = TryExcept(body, handlers, orelse, LINENO(n), + n->n_col_offset, c->c_arena); + if (!finally) + return except_st; + + /* if a 'finally' is present too, we nest the TryExcept within a + TryFinally to emulate try ... except ... finally */ + body = asdl_seq_new(1, c->c_arena); + if (body == NULL) + return NULL; + asdl_seq_SET(body, 0, except_st); } /* must be a try ... finally (except clauses are in body, if any exist) */ @@ -2877,23 +2877,23 @@ assert(TYPE(n) == with_stmt); context_expr = ast_for_expr(c, CHILD(n, 1)); if (TYPE(CHILD(n, 2)) == with_var) { - optional_vars = ast_for_with_var(c, CHILD(n, 2)); + optional_vars = ast_for_with_var(c, CHILD(n, 2)); - if (!optional_vars) { - return NULL; - } - if (!set_context(optional_vars, Store, n)) { - return NULL; - } - suite_index = 4; + if (!optional_vars) { + return NULL; + } + if (!set_context(optional_vars, Store, n)) { + return NULL; + } + suite_index = 4; } suite_seq = ast_for_suite(c, CHILD(n, suite_index)); if (!suite_seq) { - return NULL; + return NULL; } return With(context_expr, optional_vars, suite_seq, LINENO(n), - n->n_col_offset, c->c_arena); + n->n_col_offset, c->c_arena); } static stmt_ty @@ -2905,246 +2905,246 @@ REQ(n, classdef); if (!strcmp(STR(CHILD(n, 1)), "None")) { - ast_error(n, "assignment to None"); - return NULL; + ast_error(n, "assignment to None"); + return NULL; } if (NCH(n) == 4) { - s = ast_for_suite(c, CHILD(n, 3)); - if (!s) - return NULL; - return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, s, LINENO(n), - n->n_col_offset, c->c_arena); + s = ast_for_suite(c, CHILD(n, 3)); + if (!s) + return NULL; + return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, s, LINENO(n), + n->n_col_offset, c->c_arena); } /* check for empty base list */ if (TYPE(CHILD(n,3)) == RPAR) { - s = ast_for_suite(c, CHILD(n,5)); - if (!s) - return NULL; - return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, s, LINENO(n), - n->n_col_offset, c->c_arena); + s = ast_for_suite(c, CHILD(n,5)); + if (!s) + return NULL; + return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, s, LINENO(n), + n->n_col_offset, c->c_arena); } /* else handle the base class list */ bases = ast_for_class_bases(c, CHILD(n, 3)); if (!bases) - return NULL; + return NULL; s = ast_for_suite(c, CHILD(n, 6)); if (!s) - return NULL; + return NULL; return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), bases, s, LINENO(n), - n->n_col_offset, c->c_arena); + n->n_col_offset, c->c_arena); } static stmt_ty ast_for_stmt(struct compiling *c, const node *n) { if (TYPE(n) == stmt) { - assert(NCH(n) == 1); - n = CHILD(n, 0); + assert(NCH(n) == 1); + n = CHILD(n, 0); } if (TYPE(n) == simple_stmt) { - assert(num_stmts(n) == 1); - n = CHILD(n, 0); + assert(num_stmts(n) == 1); + n = CHILD(n, 0); } if (TYPE(n) == small_stmt) { - REQ(n, small_stmt); - n = CHILD(n, 0); - /* small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt - | flow_stmt | import_stmt | global_stmt | exec_stmt - | assert_stmt - */ - switch (TYPE(n)) { - case expr_stmt: - return ast_for_expr_stmt(c, n); - case print_stmt: - return ast_for_print_stmt(c, n); - case del_stmt: - return ast_for_del_stmt(c, n); - case pass_stmt: - return Pass(LINENO(n), n->n_col_offset, c->c_arena); - case flow_stmt: - return ast_for_flow_stmt(c, n); - case import_stmt: - return ast_for_import_stmt(c, n); - case global_stmt: - return ast_for_global_stmt(c, n); - case exec_stmt: - return ast_for_exec_stmt(c, n); - case assert_stmt: - return ast_for_assert_stmt(c, n); - default: - PyErr_Format(PyExc_SystemError, - "unhandled small_stmt: TYPE=%d NCH=%d\n", - TYPE(n), NCH(n)); - return NULL; - } + REQ(n, small_stmt); + n = CHILD(n, 0); + /* small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt + | flow_stmt | import_stmt | global_stmt | exec_stmt + | assert_stmt + */ + switch (TYPE(n)) { + case expr_stmt: + return ast_for_expr_stmt(c, n); + case print_stmt: + return ast_for_print_stmt(c, n); + case del_stmt: + return ast_for_del_stmt(c, n); + case pass_stmt: + return Pass(LINENO(n), n->n_col_offset, c->c_arena); + case flow_stmt: + return ast_for_flow_stmt(c, n); + case import_stmt: + return ast_for_import_stmt(c, n); + case global_stmt: + return ast_for_global_stmt(c, n); + case exec_stmt: + return ast_for_exec_stmt(c, n); + case assert_stmt: + return ast_for_assert_stmt(c, n); + default: + PyErr_Format(PyExc_SystemError, + "unhandled small_stmt: TYPE=%d NCH=%d\n", + TYPE(n), NCH(n)); + return NULL; + } } else { - /* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt - | funcdef | classdef - */ - node *ch = CHILD(n, 0); - REQ(n, compound_stmt); - switch (TYPE(ch)) { - case if_stmt: - return ast_for_if_stmt(c, ch); - case while_stmt: - return ast_for_while_stmt(c, ch); - case for_stmt: - return ast_for_for_stmt(c, ch); - case try_stmt: - return ast_for_try_stmt(c, ch); - case with_stmt: - return ast_for_with_stmt(c, ch); - case funcdef: - return ast_for_funcdef(c, ch); - case classdef: - return ast_for_classdef(c, ch); - default: - PyErr_Format(PyExc_SystemError, - "unhandled small_stmt: TYPE=%d NCH=%d\n", - TYPE(n), NCH(n)); - return NULL; - } + /* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt + | funcdef | classdef + */ + node *ch = CHILD(n, 0); + REQ(n, compound_stmt); + switch (TYPE(ch)) { + case if_stmt: + return ast_for_if_stmt(c, ch); + case while_stmt: + return ast_for_while_stmt(c, ch); + case for_stmt: + return ast_for_for_stmt(c, ch); + case try_stmt: + return ast_for_try_stmt(c, ch); + case with_stmt: + return ast_for_with_stmt(c, ch); + case funcdef: + return ast_for_funcdef(c, ch); + case classdef: + return ast_for_classdef(c, ch); + default: + PyErr_Format(PyExc_SystemError, + "unhandled small_stmt: TYPE=%d NCH=%d\n", + TYPE(n), NCH(n)); + return NULL; + } } } static PyObject * parsenumber(const char *s) { - const char *end; - long x; - double dx; + const char *end; + long x; + double dx; #ifndef WITHOUT_COMPLEX - Py_complex c; - int imflag; + Py_complex c; + int imflag; #endif - errno = 0; - end = s + strlen(s) - 1; + errno = 0; + end = s + strlen(s) - 1; #ifndef WITHOUT_COMPLEX - imflag = *end == 'j' || *end == 'J'; + imflag = *end == 'j' || *end == 'J'; #endif - if (*end == 'l' || *end == 'L') - return PyLong_FromString((char *)s, (char **)0, 0); - if (s[0] == '0') { - x = (long) PyOS_strtoul((char *)s, (char **)&end, 0); - if (x < 0 && errno == 0) { - return PyLong_FromString((char *)s, - (char **)0, - 0); - } - } - else - x = PyOS_strtol((char *)s, (char **)&end, 0); - if (*end == '\0') { - if (errno != 0) - return PyLong_FromString((char *)s, (char **)0, 0); - return PyInt_FromLong(x); - } - /* XXX Huge floats may silently fail */ + if (*end == 'l' || *end == 'L') + return PyLong_FromString((char *)s, (char **)0, 0); + if (s[0] == '0') { + x = (long) PyOS_strtoul((char *)s, (char **)&end, 0); + if (x < 0 && errno == 0) { + return PyLong_FromString((char *)s, + (char **)0, + 0); + } + } + else + x = PyOS_strtol((char *)s, (char **)&end, 0); + if (*end == '\0') { + if (errno != 0) + return PyLong_FromString((char *)s, (char **)0, 0); + return PyInt_FromLong(x); + } + /* XXX Huge floats may silently fail */ #ifndef WITHOUT_COMPLEX - if (imflag) { - c.real = 0.; - PyFPE_START_PROTECT("atof", return 0) - c.imag = PyOS_ascii_atof(s); - PyFPE_END_PROTECT(c) - return PyComplex_FromCComplex(c); - } - else + if (imflag) { + c.real = 0.; + PyFPE_START_PROTECT("atof", return 0) + c.imag = PyOS_ascii_atof(s); + PyFPE_END_PROTECT(c) + return PyComplex_FromCComplex(c); + } + else #endif - { - PyFPE_START_PROTECT("atof", return 0) - dx = PyOS_ascii_atof(s); - PyFPE_END_PROTECT(dx) - return PyFloat_FromDouble(dx); - } + { + PyFPE_START_PROTECT("atof", return 0) + dx = PyOS_ascii_atof(s); + PyFPE_END_PROTECT(dx) + return PyFloat_FromDouble(dx); + } } static PyObject * decode_utf8(const char **sPtr, const char *end, char* encoding) { #ifndef Py_USING_UNICODE - Py_FatalError("decode_utf8 should not be called in this build."); - return NULL; + Py_FatalError("decode_utf8 should not be called in this build."); + return NULL; #else - PyObject *u, *v; - char *s, *t; - t = s = (char *)*sPtr; - /* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */ - while (s < end && (*s & 0x80)) s++; - *sPtr = s; - u = PyUnicode_DecodeUTF8(t, s - t, NULL); - if (u == NULL) - return NULL; - v = PyUnicode_AsEncodedString(u, encoding, NULL); - Py_DECREF(u); - return v; + PyObject *u, *v; + char *s, *t; + t = s = (char *)*sPtr; + /* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */ + while (s < end && (*s & 0x80)) s++; + *sPtr = s; + u = PyUnicode_DecodeUTF8(t, s - t, NULL); + if (u == NULL) + return NULL; + v = PyUnicode_AsEncodedString(u, encoding, NULL); + Py_DECREF(u); + return v; #endif } static PyObject * decode_unicode(const char *s, size_t len, int rawmode, const char *encoding) { - PyObject *v, *u; - char *buf; - char *p; - const char *end; - if (encoding == NULL) { - buf = (char *)s; - u = NULL; - } else if (strcmp(encoding, "iso-8859-1") == 0) { - buf = (char *)s; - u = NULL; - } else { - /* "\XX" may become "\u005c\uHHLL" (12 bytes) */ - u = PyString_FromStringAndSize((char *)NULL, len * 4); - if (u == NULL) - return NULL; - p = buf = PyString_AsString(u); - end = s + len; - while (s < end) { - if (*s == '\\') { - *p++ = *s++; - if (*s & 0x80) { - strcpy(p, "u005c"); - p += 5; - } - } - if (*s & 0x80) { /* XXX inefficient */ - PyObject *w; - char *r; - Py_ssize_t rn, i; - w = decode_utf8(&s, end, "utf-16-be"); - if (w == NULL) { - Py_DECREF(u); - return NULL; - } - r = PyString_AsString(w); - rn = PyString_Size(w); - assert(rn % 2 == 0); - for (i = 0; i < rn; i += 2) { - sprintf(p, "\\u%02x%02x", - r[i + 0] & 0xFF, - r[i + 1] & 0xFF); - p += 6; - } - Py_DECREF(w); - } else { - *p++ = *s++; - } - } - len = p - buf; - s = buf; - } - if (rawmode) - v = PyUnicode_DecodeRawUnicodeEscape(s, len, NULL); - else - v = PyUnicode_DecodeUnicodeEscape(s, len, NULL); - Py_XDECREF(u); - return v; + PyObject *v, *u; + char *buf; + char *p; + const char *end; + if (encoding == NULL) { + buf = (char *)s; + u = NULL; + } else if (strcmp(encoding, "iso-8859-1") == 0) { + buf = (char *)s; + u = NULL; + } else { + /* "\XX" may become "\u005c\uHHLL" (12 bytes) */ + u = PyString_FromStringAndSize((char *)NULL, len * 4); + if (u == NULL) + return NULL; + p = buf = PyString_AsString(u); + end = s + len; + while (s < end) { + if (*s == '\\') { + *p++ = *s++; + if (*s & 0x80) { + strcpy(p, "u005c"); + p += 5; + } + } + if (*s & 0x80) { /* XXX inefficient */ + PyObject *w; + char *r; + Py_ssize_t rn, i; + w = decode_utf8(&s, end, "utf-16-be"); + if (w == NULL) { + Py_DECREF(u); + return NULL; + } + r = PyString_AsString(w); + rn = PyString_Size(w); + assert(rn % 2 == 0); + for (i = 0; i < rn; i += 2) { + sprintf(p, "\\u%02x%02x", + r[i + 0] & 0xFF, + r[i + 1] & 0xFF); + p += 6; + } + Py_DECREF(w); + } else { + *p++ = *s++; + } + } + len = p - buf; + s = buf; + } + if (rawmode) + v = PyUnicode_DecodeRawUnicodeEscape(s, len, NULL); + else + v = PyUnicode_DecodeUnicodeEscape(s, len, NULL); + Py_XDECREF(u); + return v; } /* s is a Python string literal, including the bracketing quote characters, @@ -3154,75 +3154,75 @@ static PyObject * parsestr(const char *s, const char *encoding) { - size_t len; - int quote = Py_CHARMASK(*s); - int rawmode = 0; - int need_encoding; - int unicode = 0; - - if (isalpha(quote) || quote == '_') { - if (quote == 'u' || quote == 'U') { - quote = *++s; - unicode = 1; - } - if (quote == 'r' || quote == 'R') { - quote = *++s; - rawmode = 1; - } - } - if (quote != '\'' && quote != '\"') { - PyErr_BadInternalCall(); - return NULL; - } - s++; - len = strlen(s); - if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string to parse is too long"); - return NULL; - } - if (s[--len] != quote) { - PyErr_BadInternalCall(); - return NULL; - } - if (len >= 4 && s[0] == quote && s[1] == quote) { - s += 2; - len -= 2; - if (s[--len] != quote || s[--len] != quote) { - PyErr_BadInternalCall(); - return NULL; - } - } + size_t len; + int quote = Py_CHARMASK(*s); + int rawmode = 0; + int need_encoding; + int unicode = 0; + + if (isalpha(quote) || quote == '_') { + if (quote == 'u' || quote == 'U') { + quote = *++s; + unicode = 1; + } + if (quote == 'r' || quote == 'R') { + quote = *++s; + rawmode = 1; + } + } + if (quote != '\'' && quote != '\"') { + PyErr_BadInternalCall(); + return NULL; + } + s++; + len = strlen(s); + if (len > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string to parse is too long"); + return NULL; + } + if (s[--len] != quote) { + PyErr_BadInternalCall(); + return NULL; + } + if (len >= 4 && s[0] == quote && s[1] == quote) { + s += 2; + len -= 2; + if (s[--len] != quote || s[--len] != quote) { + PyErr_BadInternalCall(); + return NULL; + } + } #ifdef Py_USING_UNICODE - if (unicode || Py_UnicodeFlag) { - return decode_unicode(s, len, rawmode, encoding); - } + if (unicode || Py_UnicodeFlag) { + return decode_unicode(s, len, rawmode, encoding); + } #endif - need_encoding = (encoding != NULL && - strcmp(encoding, "utf-8") != 0 && - strcmp(encoding, "iso-8859-1") != 0); - if (rawmode || strchr(s, '\\') == NULL) { - if (need_encoding) { + need_encoding = (encoding != NULL && + strcmp(encoding, "utf-8") != 0 && + strcmp(encoding, "iso-8859-1") != 0); + if (rawmode || strchr(s, '\\') == NULL) { + if (need_encoding) { #ifndef Py_USING_UNICODE - /* This should not happen - we never see any other - encoding. */ - Py_FatalError( - "cannot deal with encodings in this build."); + /* This should not happen - we never see any other + encoding. */ + Py_FatalError( + "cannot deal with encodings in this build."); #else - PyObject *v, *u = PyUnicode_DecodeUTF8(s, len, NULL); - if (u == NULL) - return NULL; - v = PyUnicode_AsEncodedString(u, encoding, NULL); - Py_DECREF(u); - return v; + PyObject *v, *u = PyUnicode_DecodeUTF8(s, len, NULL); + if (u == NULL) + return NULL; + v = PyUnicode_AsEncodedString(u, encoding, NULL); + Py_DECREF(u); + return v; #endif - } else { - return PyString_FromStringAndSize(s, len); - } - } + } else { + return PyString_FromStringAndSize(s, len); + } + } - return PyString_DecodeEscape(s, len, NULL, unicode, - need_encoding ? encoding : NULL); + return PyString_DecodeEscape(s, len, NULL, unicode, + need_encoding ? encoding : NULL); } /* Build a Python string object out of a STRING atom. This takes care of @@ -3232,36 +3232,36 @@ static PyObject * parsestrplus(struct compiling *c, const node *n) { - PyObject *v; - int i; - REQ(CHILD(n, 0), STRING); - if ((v = parsestr(STR(CHILD(n, 0)), c->c_encoding)) != NULL) { - /* String literal concatenation */ - for (i = 1; i < NCH(n); i++) { - PyObject *s; - s = parsestr(STR(CHILD(n, i)), c->c_encoding); - if (s == NULL) - goto onError; - if (PyString_Check(v) && PyString_Check(s)) { - PyString_ConcatAndDel(&v, s); - if (v == NULL) - goto onError; - } + PyObject *v; + int i; + REQ(CHILD(n, 0), STRING); + if ((v = parsestr(STR(CHILD(n, 0)), c->c_encoding)) != NULL) { + /* String literal concatenation */ + for (i = 1; i < NCH(n); i++) { + PyObject *s; + s = parsestr(STR(CHILD(n, i)), c->c_encoding); + if (s == NULL) + goto onError; + if (PyString_Check(v) && PyString_Check(s)) { + PyString_ConcatAndDel(&v, s); + if (v == NULL) + goto onError; + } #ifdef Py_USING_UNICODE - else { - PyObject *temp = PyUnicode_Concat(v, s); - Py_DECREF(s); - Py_DECREF(v); - v = temp; - if (v == NULL) - goto onError; - } + else { + PyObject *temp = PyUnicode_Concat(v, s); + Py_DECREF(s); + Py_DECREF(v); + v = temp; + if (v == NULL) + goto onError; + } #endif - } - } - return v; + } + } + return v; onError: - Py_XDECREF(v); - return NULL; + Py_XDECREF(v); + return NULL; } Modified: python/trunk/Python/compile.c ============================================================================== --- python/trunk/Python/compile.c (original) +++ python/trunk/Python/compile.c Tue Feb 27 17:13:23 2007 @@ -8,7 +8,7 @@ * 2. Builds a symbol table. See symtable.c. * 3. Generate code for basic blocks. See compiler_mod() in this file. * 4. Assemble the basic blocks into final code. See assemble() in - * this file. + * this file. * 5. Optimize the byte code (peephole optimizations). See peephole.c * * Note that compiler_mod() suggests module, but the module ast type @@ -194,17 +194,17 @@ } p = PyString_AsString(privateobj); nlen = strlen(name); - /* Don't mangle __id__ or names with dots. + /* Don't mangle __id__ or names with dots. - The only time a name with a dot can occur is when - we are compiling an import statement that has a - package name. - - TODO(jhylton): Decide whether we want to support - mangling of the module name, e.g. __M.X. - */ + The only time a name with a dot can occur is when + we are compiling an import statement that has a + package name. + + TODO(jhylton): Decide whether we want to support + mangling of the module name, e.g. __M.X. + */ if ((name[nlen-1] == '_' && name[nlen-2] == '_') - || strchr(name, '.')) { + || strchr(name, '.')) { Py_INCREF(ident); return ident; /* Don't mangle __whatever__ */ } @@ -439,7 +439,7 @@ struct compiler_unit *u; u = (struct compiler_unit *)PyObject_Malloc(sizeof( - struct compiler_unit)); + struct compiler_unit)); if (!u) { PyErr_NoMemory(); return 0; @@ -607,7 +607,7 @@ assert(b != NULL); if (b->b_instr == NULL) { b->b_instr = (struct instr *)PyObject_Malloc( - sizeof(struct instr) * DEFAULT_BLOCK_SIZE); + sizeof(struct instr) * DEFAULT_BLOCK_SIZE); if (b->b_instr == NULL) { PyErr_NoMemory(); return -1; @@ -627,7 +627,7 @@ } b->b_ialloc <<= 1; tmp = (struct instr *)PyObject_Realloc( - (void *)b->b_instr, newsize); + (void *)b->b_instr, newsize); if (tmp == NULL) { PyErr_NoMemory(); return -1; @@ -1154,7 +1154,7 @@ case Interactive_kind: c->c_interactive = 1; VISIT_SEQ_IN_SCOPE(c, stmt, - mod->v.Interactive.body); + mod->v.Interactive.body); break; case Expression_kind: VISIT_IN_SCOPE(c, expr, mod->v.Expression.body); @@ -1538,7 +1538,7 @@ compiler_use_next_block(c, next); ADDOP(c, POP_TOP); if (s->v.If.orelse) - VISIT_SEQ(c, stmt, s->v.If.orelse); + VISIT_SEQ(c, stmt, s->v.If.orelse); } compiler_use_next_block(c, end); return 1; @@ -1786,8 +1786,8 @@ s->v.TryExcept.handlers, i); if (!handler->type && i < n-1) return compiler_error(c, "default 'except:' must be last"); - c->u->u_lineno_set = false; - c->u->u_lineno = handler->lineno; + c->u->u_lineno_set = false; + c->u->u_lineno = handler->lineno; except = compiler_new_block(c); if (except == NULL) return 0; @@ -2109,7 +2109,7 @@ case Pass_kind: break; case Break_kind: - if (!compiler_in_loop(c)) + if (!compiler_in_loop(c)) return compiler_error(c, "'break' outside loop"); ADDOP(c, BREAK_LOOP); break; @@ -2439,20 +2439,20 @@ if (cleanup == NULL) return 0; VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); + (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); } for (i = 1; i < n; i++) { ADDOP(c, DUP_TOP); ADDOP(c, ROT_THREE); ADDOP_I(c, COMPARE_OP, cmpop((cmpop_ty)(asdl_seq_GET( - e->v.Compare.ops, i - 1)))); + e->v.Compare.ops, i - 1)))); ADDOP_JREL(c, JUMP_IF_FALSE, cleanup); NEXT_BLOCK(c); ADDOP(c, POP_TOP); if (i < (n - 1)) VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); + (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); } VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1)); ADDOP_I(c, COMPARE_OP, @@ -2736,7 +2736,7 @@ /* __debug__ is not assignable, so we can optimize * it away in if and while statements */ if (strcmp(PyString_AS_STRING(e->v.Name.id), - "__debug__") == 0) + "__debug__") == 0) return ! Py_OptimizeFlag; /* fall through */ default: @@ -2883,8 +2883,8 @@ int i, n; /* If expr e has a different line number than the last expr/stmt, - set a new line number for the next instruction. - */ + set a new line number for the next instruction. + */ if (e->lineno > c->u->u_lineno) { c->u->u_lineno = e->lineno; c->u->u_lineno_set = false; @@ -2914,10 +2914,10 @@ for (i = 0; i < n; i++) { ADDOP(c, DUP_TOP); VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); + (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); ADDOP(c, ROT_TWO); VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); + (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); ADDOP(c, STORE_SUBSCR); } break; @@ -3089,13 +3089,13 @@ static int compiler_in_loop(struct compiler *c) { - int i; - struct compiler_unit *u = c->u; - for (i = 0; i < u->u_nfblocks; ++i) { - if (u->u_fblock[i].fb_type == LOOP) - return 1; - } - return 0; + int i; + struct compiler_unit *u = c->u; + for (i = 0; i < u->u_nfblocks; ++i) { + if (u->u_fblock[i].fb_type == LOOP) + return 1; + } + return 0; } /* Raises a SyntaxError and returns 0. If something goes wrong, a different exception may be raised. @@ -3290,7 +3290,7 @@ int i, n = asdl_seq_LEN(s->v.ExtSlice.dims); for (i = 0; i < n; i++) { slice_ty sub = (slice_ty)asdl_seq_GET( - s->v.ExtSlice.dims, i); + s->v.ExtSlice.dims, i); if (!compiler_visit_nested_slice(c, sub, ctx)) return 0; } @@ -3488,7 +3488,7 @@ increment is < 256. So, in the example above, assemble_lnotab (it used to be called com_set_lineno) should not (as was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, - but to 255, 0, 45, 255, 0, 45. + but to 255, 0, 45, 255, 0, 45. */ static int From buildbot at python.org Tue Feb 27 17:42:42 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 27 Feb 2007 16:42:42 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP trunk Message-ID: <20070227164242.2DFC81E4002@bag.python.org> The Buildbot has detected a new failure of x86 XP trunk. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP%2520trunk/builds/223 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_profile sincerely, -The Buildbot From buildbot at python.org Tue Feb 27 17:43:33 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 27 Feb 2007 16:43:33 +0000 Subject: [Python-checkins] buildbot warnings in amd64 gentoo trunk Message-ID: <20070227164333.E02DF1E4002@bag.python.org> The Buildbot has detected a new failure of amd64 gentoo trunk. Full details are available at: http://www.python.org/dev/buildbot/all/amd64%2520gentoo%2520trunk/builds/1869 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: jeremy.hylton Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_urllib2net ====================================================================== ERROR: testURLread (test.test_urllib2net.URLTimeoutTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/test/test_urllib2net.py", line 24, in testURLread f = urllib2.urlopen("http://www.python.org/") File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/urllib2.py", line 121, in urlopen return _opener.open(url, data) File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/urllib2.py", line 374, in open response = self._open(req, data) File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/urllib2.py", line 392, in _open '_open', req) File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/urllib2.py", line 353, in _call_chain result = func(*args) File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/urllib2.py", line 1101, in http_open return self.do_open(httplib.HTTPConnection, req) File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/urllib2.py", line 1076, in do_open raise URLError(err) URLError: make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Tue Feb 27 18:24:52 2007 From: python-checkins at python.org (jeremy.hylton) Date: Tue, 27 Feb 2007 18:24:52 +0100 (CET) Subject: [Python-checkins] r53996 - python/trunk/Objects/typeobject.c Message-ID: <20070227172452.829B71E4002@bag.python.org> Author: jeremy.hylton Date: Tue Feb 27 18:24:48 2007 New Revision: 53996 Modified: python/trunk/Objects/typeobject.c Log: whitespace normalization Modified: python/trunk/Objects/typeobject.c ============================================================================== --- python/trunk/Objects/typeobject.c (original) +++ python/trunk/Objects/typeobject.c Tue Feb 27 18:24:48 2007 @@ -531,7 +531,7 @@ if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) /* For a heaptype, the instances count as references - to the type. Traverse the type so the collector + to the type. Traverse the type so the collector can find cycles involving this link. */ Py_VISIT(type); @@ -651,7 +651,7 @@ assert(base); } - /* If we added a weaklist, we clear it. Do this *before* calling + /* If we added a weaklist, we clear it. Do this *before* calling the finalizer (__del__), clearing slots, or clearing the instance dict. */ @@ -722,7 +722,7 @@ A. Read the comment titled "Trashcan mechanism" in object.h. For one, this explains why there must be a call to GC-untrack - before the trashcan begin macro. Without understanding the + before the trashcan begin macro. Without understanding the trashcan code, the answers to the following questions don't make sense. @@ -730,7 +730,7 @@ GC-track again afterward? A. In the case that the base class is GC-aware, the base class - probably GC-untracks the object. If it does that using the + probably GC-untracks the object. If it does that using the UNTRACK macro, this will crash when the object is already untracked. Because we don't know what the base class does, the only safe thing is to make sure the object is tracked when we @@ -738,19 +738,19 @@ requires that the object is *untracked* before it is called. So the dance becomes: - GC untrack + GC untrack trashcan begin GC track - Q. Why did the last question say "immediately GC-track again"? - It's nowhere near immediately. + Q. Why did the last question say "immediately GC-track again"? + It's nowhere near immediately. - A. Because the code *used* to re-track immediately. Bad Idea. - self has a refcount of 0, and if gc ever gets its hands on it - (which can happen if any weakref callback gets invoked), it - looks like trash to gc too, and gc also tries to delete self - then. But we're already deleting self. Double dealloction is - a subtle disaster. + A. Because the code *used* to re-track immediately. Bad Idea. + self has a refcount of 0, and if gc ever gets its hands on it + (which can happen if any weakref callback gets invoked), it + looks like trash to gc too, and gc also tries to delete self + then. But we're already deleting self. Double dealloction is + a subtle disaster. Q. Why the bizarre (net-zero) manipulation of _PyTrash_delete_nesting around the trashcan macros? @@ -763,17 +763,17 @@ - subtype_dealloc() is called - the trashcan limit is not yet reached, so the trashcan level - is incremented and the code between trashcan begin and end is - executed + is incremented and the code between trashcan begin and end is + executed - this destroys much of the object's contents, including its - slots and __dict__ + slots and __dict__ - basedealloc() is called; this is really list_dealloc(), or - some other type which also uses the trashcan macros + some other type which also uses the trashcan macros - the trashcan limit is now reached, so the object is put on the - trashcan's to-be-deleted-later list + trashcan's to-be-deleted-later list - basedealloc() returns @@ -782,13 +782,13 @@ - subtype_dealloc() returns - later, the trashcan code starts deleting the objects from its - to-be-deleted-later list + to-be-deleted-later list - subtype_dealloc() is called *AGAIN* for the same object - at the very least (if the destroyed slots and __dict__ don't - cause problems) the object's type gets decref'ed a second - time, which is *BAD*!!! + cause problems) the object's type gets decref'ed a second + time, which is *BAD*!!! The remedy is to make sure that if the code between trashcan begin and end in subtype_dealloc() is called, the code between @@ -800,7 +800,7 @@ But now it's possible that a chain of objects consisting solely of objects whose deallocator is subtype_dealloc() will defeat the trashcan mechanism completely: the decremented level means - that the effective level never reaches the limit. Therefore, we + that the effective level never reaches the limit. Therefore, we *increment* the level *before* entering the trashcan block, and matchingly decrement it after leaving. This means the trashcan code will trigger a little early, but that's no big deal. @@ -854,7 +854,7 @@ /* Internal routines to do a method lookup in the type without looking in the instance dictionary (so we can't use PyObject_GetAttr) but still binding - it to the instance. The arguments are the object, + it to the instance. The arguments are the object, the method name as a C string, and the address of a static variable used to cache the interned Python string. @@ -897,7 +897,7 @@ } /* A variation of PyObject_CallMethod that uses lookup_method() - instead of PyObject_GetAttrString(). This uses the same convention + instead of PyObject_GetAttrString(). This uses the same convention as lookup_method to cache the interned name string object. */ static PyObject * @@ -1099,7 +1099,7 @@ It's hard to produce a good error message. In the absence of better insight into error reporting, report the classes that were candidates - to be put next into the MRO. There is some conflict between the + to be put next into the MRO. There is some conflict between the order in which they should be put in the MRO, but it's hard to diagnose what constraint can't be satisfied. */ @@ -1171,7 +1171,7 @@ if (remain[i] >= PyList_GET_SIZE(cur_list)) { empty_cnt++; continue; - } + } /* Choose next candidate for MRO. @@ -1252,7 +1252,7 @@ if (parentMRO == NULL) { Py_DECREF(to_merge); return NULL; - } + } PyList_SET_ITEM(to_merge, i, parentMRO); } @@ -1790,8 +1790,8 @@ (add_weak && strcmp(s, "__weakref__") == 0)) continue; tmp =_Py_Mangle(name, tmp); - if (!tmp) - goto bad_slots; + if (!tmp) + goto bad_slots; PyTuple_SET_ITEM(newslots, j, tmp); j++; } @@ -1903,13 +1903,13 @@ PyObject *doc = PyDict_GetItemString(dict, "__doc__"); if (doc != NULL && PyString_Check(doc)) { const size_t n = (size_t)PyString_GET_SIZE(doc); - char *tp_doc = (char *)PyObject_MALLOC(n+1); + char *tp_doc = (char *)PyObject_MALLOC(n+1); if (tp_doc == NULL) { Py_DECREF(type); return NULL; } memcpy(tp_doc, PyString_AS_STRING(doc), n+1); - type->tp_doc = tp_doc; + type->tp_doc = tp_doc; } } @@ -2153,9 +2153,9 @@ Py_XDECREF(type->tp_mro); Py_XDECREF(type->tp_cache); Py_XDECREF(type->tp_subclasses); - /* A type's tp_doc is heap allocated, unlike the tp_doc slots - * of most other objects. It's okay to cast it to char *. - */ + /* A type's tp_doc is heap allocated, unlike the tp_doc slots + * of most other objects. It's okay to cast it to char *. + */ PyObject_Free((char *)type->tp_doc); Py_XDECREF(et->ht_name); Py_XDECREF(et->ht_slots); @@ -2274,7 +2274,7 @@ sizeof(PyMemberDef), /* tp_itemsize */ (destructor)type_dealloc, /* tp_dealloc */ 0, /* tp_print */ - 0, /* tp_getattr */ + 0, /* tp_getattr */ 0, /* tp_setattr */ type_compare, /* tp_compare */ (reprfunc)type_repr, /* tp_repr */ @@ -2307,7 +2307,7 @@ 0, /* tp_init */ 0, /* tp_alloc */ type_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyObject_GC_Del, /* tp_free */ (inquiry)type_is_gc, /* tp_is_gc */ }; @@ -2770,13 +2770,13 @@ PyTypeObject PyBaseObject_Type = { PyObject_HEAD_INIT(&PyType_Type) - 0, /* ob_size */ + 0, /* ob_size */ "object", /* tp_name */ sizeof(PyObject), /* tp_basicsize */ 0, /* tp_itemsize */ object_dealloc, /* tp_dealloc */ 0, /* tp_print */ - 0, /* tp_getattr */ + 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ object_repr, /* tp_repr */ @@ -2808,7 +2808,7 @@ object_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ object_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyObject_Del, /* tp_free */ }; @@ -3195,9 +3195,9 @@ Py_INCREF(base); } - /* Now the only way base can still be NULL is if type is - * &PyBaseObject_Type. - */ + /* Now the only way base can still be NULL is if type is + * &PyBaseObject_Type. + */ /* Initialize the base class */ if (base && base->tp_dict == NULL) { @@ -3205,13 +3205,13 @@ goto error; } - /* Initialize ob_type if NULL. This means extensions that want to be + /* Initialize ob_type if NULL. This means extensions that want to be compilable separately on Windows can call PyType_Ready() instead of initializing the ob_type field of their type objects. */ - /* The test for base != NULL is really unnecessary, since base is only - NULL when type is &PyBaseObject_Type, and we know its ob_type is - not NULL (it's initialized to &PyType_Type). But coverity doesn't - know that. */ + /* The test for base != NULL is really unnecessary, since base is only + NULL when type is &PyBaseObject_Type, and we know its ob_type is + not NULL (it's initialized to &PyType_Type). But coverity doesn't + know that. */ if (type->ob_type == NULL && base != NULL) type->ob_type = base->ob_type; @@ -3275,9 +3275,9 @@ /* Sanity check for tp_free. */ if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) && (type->tp_free == NULL || type->tp_free == PyObject_Del)) { - /* This base class needs to call tp_free, but doesn't have - * one, or its tp_free is for non-gc'ed objects. - */ + /* This base class needs to call tp_free, but doesn't have + * one, or its tp_free is for non-gc'ed objects. + */ PyErr_Format(PyExc_TypeError, "type '%.100s' participates in " "gc and is a base type but has inappropriate " "tp_free slot", @@ -3404,7 +3404,7 @@ /* Generic wrappers for overloadable 'operators' such as __getitem__ */ /* There's a wrapper *function* for each distinct function typedef used - for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a + for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a wrapper *table* for each distinct operation (e.g. __len__, __add__). Most tables have only one entry; the tables for binary operators have two entries, one regular and one with reversed arguments. */ @@ -3773,8 +3773,8 @@ PyTypeObject *type = self->ob_type; while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) type = type->tp_base; - /* If type is NULL now, this is a really weird type. - In the spirit of backwards compatibility (?), just shut up. */ + /* If type is NULL now, this is a really weird type. + In the spirit of backwards compatibility (?), just shut up. */ if (type && type->tp_setattro != func) { PyErr_Format(PyExc_TypeError, "can't apply this %s to %s object", @@ -3990,8 +3990,8 @@ staticbase = subtype; while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE)) staticbase = staticbase->tp_base; - /* If staticbase is NULL now, it is a really weird type. - In the spirit of backwards compatibility (?), just shut up. */ + /* If staticbase is NULL now, it is a really weird type. + In the spirit of backwards compatibility (?), just shut up. */ if (staticbase && staticbase->tp_new != type->tp_new) { PyErr_Format(PyExc_TypeError, "%s.__new__(%s) is not safe, use %s.__new__()", @@ -4012,7 +4012,7 @@ static struct PyMethodDef tp_new_methoddef[] = { {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS, PyDoc_STR("T.__new__(S, ...) -> " - "a new object with type S, a subtype of T")}, + "a new object with type S, a subtype of T")}, {0} }; @@ -4341,7 +4341,7 @@ func = lookup_maybe(self, "__len__", &len_str); if (func == NULL) return PyErr_Occurred() ? -1 : 1; - } + } args = PyTuple_New(0); if (args != NULL) { PyObject *temp = PyObject_Call(func, args, NULL); @@ -5020,17 +5020,17 @@ user-defined methods has unexpected side-effects, as shown by test_descr.notimplemented() */ SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc, - "x.__add__(y) <==> x+y"), + "x.__add__(y) <==> x+y"), SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc, - "x.__mul__(n) <==> x*n"), + "x.__mul__(n) <==> x*n"), SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc, - "x.__rmul__(n) <==> n*x"), + "x.__rmul__(n) <==> n*x"), SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, "x.__getitem__(y) <==> x[y]"), SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc, "x.__getslice__(i, j) <==> x[i:j]\n\ - \n\ - Use of negative indices is not supported."), + \n\ + Use of negative indices is not supported."), SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, "x.__setitem__(i, y) <==> x[i]=y"), SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, @@ -5038,18 +5038,18 @@ SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice, wrap_ssizessizeobjargproc, "x.__setslice__(i, j, y) <==> x[i:j]=y\n\ - \n\ - Use of negative indices is not supported."), + \n\ + Use of negative indices is not supported."), SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice, "x.__delslice__(i, j) <==> del x[i:j]\n\ - \n\ - Use of negative indices is not supported."), + \n\ + Use of negative indices is not supported."), SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, "x.__contains__(y) <==> y in x"), SQSLOT("__iadd__", sq_inplace_concat, NULL, - wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), + wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), SQSLOT("__imul__", sq_inplace_repeat, NULL, - wrap_indexargfunc, "x.__imul__(y) <==> x*=y"), + wrap_indexargfunc, "x.__imul__(y) <==> x*=y"), MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc, "x.__len__() <==> len(x)"), @@ -5208,7 +5208,7 @@ }; /* Given a type pointer and an offset gotten from a slotdef entry, return a - pointer to the actual slot. This is not quite the same as simply adding + pointer to the actual slot. This is not quite the same as simply adding the offset to the type pointer, since it takes care to indirect through the proper indirection pointer (as_buffer, etc.); it returns NULL if the indirection pointer is NULL. */ @@ -5272,7 +5272,7 @@ } /* Look in all matching slots of the type; if exactly one of these has - a filled-in slot, return its value. Otherwise return NULL. */ + a filled-in slot, return its value. Otherwise return NULL. */ res = NULL; for (pp = ptrs; *pp; pp++) { ptr = slotptr(type, (*pp)->offset); @@ -5511,13 +5511,13 @@ dictionary with method descriptors for function slots. For each function slot (like tp_repr) that's defined in the type, one or more corresponding descriptors are added in the type's tp_dict dictionary - under the appropriate name (like __repr__). Some function slots + under the appropriate name (like __repr__). Some function slots cause more than one descriptor to be added (for example, the nb_add slot adds both __add__ and __radd__ descriptors) and some function slots compete for the same descriptor (for example both sq_item and mp_subscript generate a __getitem__ descriptor). - In the latter case, the first slotdef entry encoutered wins. Since + In the latter case, the first slotdef entry encoutered wins. Since slotdef entries are sorted by the offset of the slot in the PyHeapTypeObject, this gives us some control over disambiguating between competing slots: the members of PyHeapTypeObject are listed @@ -5691,7 +5691,7 @@ obj can be a new-style class, or an instance of one: - - If it is a class, it must be a subclass of 'type'. This case is + - If it is a class, it must be a subclass of 'type'. This case is used for class methods; the return value is obj. - If it is an instance, it must be an instance of 'type'. This is @@ -5742,7 +5742,7 @@ Py_DECREF(class_attr); } - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "super(type, obj): " "obj must be an instance or subtype of type"); return NULL; @@ -5763,7 +5763,7 @@ /* If su is an instance of a (strict) subclass of super, call its type */ return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type, - su->type, obj, NULL); + su->type, obj, NULL); else { /* Inline the common case */ PyTypeObject *obj_type = supercheck(su->type, obj); @@ -5816,7 +5816,7 @@ "Typical use to call a cooperative superclass method:\n" "class C(B):\n" " def meth(self, arg):\n" -" super(C, self).meth(arg)"); +" super(C, self).meth(arg)"); static int super_traverse(PyObject *self, visitproc visit, void *arg) @@ -5837,7 +5837,7 @@ sizeof(superobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ - super_dealloc, /* tp_dealloc */ + super_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -5845,7 +5845,7 @@ super_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ + 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ @@ -5854,9 +5854,9 @@ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ - super_doc, /* tp_doc */ - super_traverse, /* tp_traverse */ - 0, /* tp_clear */ + super_doc, /* tp_doc */ + super_traverse, /* tp_traverse */ + 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ @@ -5872,5 +5872,5 @@ super_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyObject_GC_Del, /* tp_free */ }; From python-checkins at python.org Tue Feb 27 19:29:50 2007 From: python-checkins at python.org (jeremy.hylton) Date: Tue, 27 Feb 2007 19:29:50 +0100 (CET) Subject: [Python-checkins] r53997 - in python/trunk: Lib/test/crashers/modify_dict_attr.py Lib/test/test_descr.py Objects/typeobject.c Message-ID: <20070227182950.28E361E4002@bag.python.org> Author: jeremy.hylton Date: Tue Feb 27 19:29:45 2007 New Revision: 53997 Removed: python/trunk/Lib/test/crashers/modify_dict_attr.py Modified: python/trunk/Lib/test/test_descr.py python/trunk/Objects/typeobject.c Log: Add checking for a number of metaclass error conditions. We add some new rules that are required for preserving internal invariants of types. 1. If type (or a subclass of type) appears in bases, it must appear before any non-type bases. If a non-type base (like a regular new-style class) occurred first, it could trick type into allocating the new class an __dict__ which must be impossible. 2. There are several checks that are made of bases when creating a type. Those checks are now repeated when assigning to __bases__. We also add the restriction that assignment to __bases__ may not change the metaclass of the type. Add new tests for these cases and for a few other oddball errors that were no previously tested. Remove a crasher test that was fixed. Also some internal refactoring: Extract the code to find the most derived metaclass of a type and its bases. It is now needed in two places. Rewrite the TypeError checks in test_descr to use doctest. The tests now clearly show what exception they expect to see. Deleted: /python/trunk/Lib/test/crashers/modify_dict_attr.py ============================================================================== --- /python/trunk/Lib/test/crashers/modify_dict_attr.py Tue Feb 27 19:29:45 2007 +++ (empty file) @@ -1,19 +0,0 @@ - -# http://python.org/sf/1303614 - -class Y(object): - pass - -class type_with_modifiable_dict(Y, type): - pass - -class MyClass(object): - """This class has its __dict__ attribute completely exposed: - user code can read, reassign and even delete it. - """ - __metaclass__ = type_with_modifiable_dict - - -if __name__ == '__main__': - del MyClass.__dict__ # if we set tp_dict to NULL, - print MyClass # doing anything with MyClass segfaults Modified: python/trunk/Lib/test/test_descr.py ============================================================================== --- python/trunk/Lib/test/test_descr.py (original) +++ python/trunk/Lib/test/test_descr.py Tue Feb 27 19:29:45 2007 @@ -1,6 +1,6 @@ # Test enhancements related to descriptors and new-style classes -from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout +from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout, run_doctest from copy import deepcopy import warnings @@ -820,6 +820,22 @@ except TypeError: pass else: raise TestFailed, "calling object w/o call method should raise TypeError" + # Testing code to find most derived baseclass + class A(type): + def __new__(*args, **kwargs): + return type.__new__(*args, **kwargs) + + class B(object): + pass + + class C(object): + __metaclass__ = A + + # The most derived metaclass of D is A rather than type. + class D(B, C): + pass + + def pymods(): if verbose: print "Testing Python subclass of module..." log = [] @@ -1411,49 +1427,89 @@ verify(someclass != object) def errors(): - if verbose: print "Testing errors..." - - try: - class C(list, dict): - pass - except TypeError: - pass - else: - verify(0, "inheritance from both list and dict should be illegal") - - try: - class C(object, None): - pass - except TypeError: - pass - else: - verify(0, "inheritance from non-type should be illegal") - class Classic: - pass + """Test that type can't be placed after an instance of type in bases. - try: - class C(type(len)): - pass - except TypeError: - pass - else: - verify(0, "inheritance from CFunction should be illegal") - - try: - class C(object): - __slots__ = 1 - except TypeError: - pass - else: - verify(0, "__slots__ = 1 should be illegal") - - try: - class C(object): - __slots__ = [1] - except TypeError: - pass - else: - verify(0, "__slots__ = [1] should be illegal") + >>> class C(list, dict): + ... pass + Traceback (most recent call last): + TypeError: Error when calling the metaclass bases + multiple bases have instance lay-out conflict + + >>> class C(object, None): + ... pass + Traceback (most recent call last): + TypeError: Error when calling the metaclass bases + bases must be types + + >>> class C(type(len)): + ... pass + Traceback (most recent call last): + TypeError: Error when calling the metaclass bases + type 'builtin_function_or_method' is not an acceptable base type + + >>> class Classic: + ... def __init__(*args): pass + >>> class C(object): + ... __metaclass__ = Classic + + >>> class C(object): + ... __slots__ = 1 + Traceback (most recent call last): + TypeError: Error when calling the metaclass bases + 'int' object is not iterable + + >>> class C(object): + ... __slots__ = [1] + Traceback (most recent call last): + TypeError: Error when calling the metaclass bases + __slots__ items must be strings, not 'int' + + >>> class A(object): + ... pass + + >>> class B(A, type): + ... pass + Traceback (most recent call last): + TypeError: Error when calling the metaclass bases + metaclass conflict: type must occur in bases before other non-classic base classes + + Create two different metaclasses in order to setup an error where + there is no inheritance relationship between the metaclass of a class + and the metaclass of its bases. + + >>> class M1(type): + ... pass + >>> class M2(type): + ... pass + >>> class A1(object): + ... __metaclass__ = M1 + >>> class A2(object): + ... __metaclass__ = M2 + >>> class B(A1, A2): + ... pass + Traceback (most recent call last): + TypeError: Error when calling the metaclass bases + metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases + >>> class B(A1): + ... pass + + Also check that assignment to bases is safe. + + >>> B.__bases__ = A1, A2 + Traceback (most recent call last): + TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases + >>> B.__bases__ = A2, + Traceback (most recent call last): + TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases + + >>> class M3(M1): + ... pass + >>> class C(object): + ... __metaclass__ = M3 + >>> B.__bases__ = C, + Traceback (most recent call last): + TypeError: assignment to __bases__ may not change metatype + """ def classmethods(): if verbose: print "Testing class methods..." @@ -4179,7 +4235,6 @@ slots() slotspecials() dynamics() - errors() classmethods() classmethods_in_c() staticmethods() @@ -4247,6 +4302,9 @@ methodwrapper() notimplemented() + from test import test_descr + run_doctest(test_descr, verbosity=True) + if verbose: print "All OK" if __name__ == "__main__": Modified: python/trunk/Objects/typeobject.c ============================================================================== --- python/trunk/Objects/typeobject.c (original) +++ python/trunk/Objects/typeobject.c Tue Feb 27 19:29:45 2007 @@ -127,6 +127,7 @@ return type->tp_bases; } +static PyTypeObject *most_derived_metaclass(PyTypeObject *, PyObject *); static PyTypeObject *best_base(PyObject *); static int mro_internal(PyTypeObject *); static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *); @@ -187,7 +188,7 @@ Py_ssize_t i; int r = 0; PyObject *ob, *temp; - PyTypeObject *new_base, *old_base; + PyTypeObject *new_base, *old_base, *metatype; PyObject *old_bases, *old_mro; if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { @@ -230,6 +231,17 @@ } } + + metatype = most_derived_metaclass(type->ob_type, value); + if (metatype == NULL) + return -1; + if (metatype != type->ob_type) { + PyErr_SetString(PyExc_TypeError, + "assignment to __bases__ may not change " + "metatype"); + return -1; + } + new_base = best_base(value); if (!new_base) { @@ -1355,7 +1367,14 @@ /* Calculate the best base amongst multiple base classes. - This is the first one that's on the path to the "solid base". */ + This is the first one that's on the path to the "solid base". + + Requires that all base classes be types or classic classes. + + Will return NULL with TypeError set if + 1) the base classes have conflicting layout instances, or + 2) all the bases are classic classes. +*/ static PyTypeObject * best_base(PyObject *bases) @@ -1373,12 +1392,7 @@ base_proto = PyTuple_GET_ITEM(bases, i); if (PyClass_Check(base_proto)) continue; - if (!PyType_Check(base_proto)) { - PyErr_SetString( - PyExc_TypeError, - "bases must be types"); - return NULL; - } + assert(PyType_Check(base_proto)); base_i = (PyTypeObject *)base_proto; if (base_i->tp_dict == NULL) { if (PyType_Ready(base_i) < 0) @@ -1431,6 +1445,8 @@ return t_size != b_size; } +/* Return the type object that will determine the layout of the instance. */ + static PyTypeObject * solid_base(PyTypeObject *type) { @@ -1446,6 +1462,71 @@ return base; } +/* Determine the proper metatype to deal with this, and check some + error cases while we're at it. Note that if some other metatype + wins to contract, it's possible that its instances are not types. + + Error cases of interest: 1. The metaclass is not a subclass of a + base class. 2. A non-type, non-classic base class appears before + type. +*/ + +static PyTypeObject * +most_derived_metaclass(PyTypeObject *metatype, PyObject *bases) +{ + Py_ssize_t nbases, i; + PyTypeObject *winner; + /* types_ordered: One of three states possible: + 0 type is in bases + 1 non-types also in bases + 2 type follows non-type in bases (error) + */ + int types_ordered = 0; + + nbases = PyTuple_GET_SIZE(bases); + winner = metatype; + for (i = 0; i < nbases; i++) { + PyObject *tmp = PyTuple_GET_ITEM(bases, i); + PyTypeObject *tmptype = tmp->ob_type; + if (tmptype == &PyClass_Type) + continue; /* Special case classic classes */ + if (!PyType_Check(tmp)) { + PyErr_SetString(PyExc_TypeError, + "bases must be types"); + return NULL; + } + if (PyObject_IsSubclass(tmp, (PyObject*)&PyType_Type)) { + if (types_ordered == 1) { + types_ordered = 2; + } + } + else if (!types_ordered) + types_ordered = 1; + if (winner == tmptype) + continue; + if (PyType_IsSubtype(winner, tmptype)) + continue; + if (PyType_IsSubtype(tmptype, winner)) { + winner = tmptype; + continue; + } + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "the metaclass of a derived class " + "must be a (non-strict) subclass " + "of the metaclasses of all its bases"); + return NULL; + } + if (types_ordered == 2) { + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "type must occur in bases before other " + "non-classic base classes"); + return NULL; + } + return winner; +} + static void object_dealloc(PyObject *); static int object_init(PyObject *, PyObject *, PyObject *); static int update_slot(PyTypeObject *, PyObject *); @@ -1642,37 +1723,18 @@ &PyDict_Type, &dict)) return NULL; - /* Determine the proper metatype to deal with this, - and check for metatype conflicts while we're at it. - Note that if some other metatype wins to contract, - it's possible that its instances are not types. */ - nbases = PyTuple_GET_SIZE(bases); - winner = metatype; - for (i = 0; i < nbases; i++) { - tmp = PyTuple_GET_ITEM(bases, i); - tmptype = tmp->ob_type; - if (tmptype == &PyClass_Type) - continue; /* Special case classic classes */ - if (PyType_IsSubtype(winner, tmptype)) - continue; - if (PyType_IsSubtype(tmptype, winner)) { - winner = tmptype; - continue; - } - PyErr_SetString(PyExc_TypeError, - "metaclass conflict: " - "the metaclass of a derived class " - "must be a (non-strict) subclass " - "of the metaclasses of all its bases"); + winner = most_derived_metaclass(metatype, bases); + if (winner == NULL) return NULL; - } if (winner != metatype) { - if (winner->tp_new != type_new) /* Pass it to the winner */ + if (winner->tp_new != type_new) /* Pass it to the winner */ { return winner->tp_new(winner, args, kwds); + } metatype = winner; } /* Adjust for empty tuple bases */ + nbases = PyTuple_GET_SIZE(bases); if (nbases == 0) { bases = PyTuple_Pack(1, &PyBaseObject_Type); if (bases == NULL) From python-checkins at python.org Tue Feb 27 19:33:32 2007 From: python-checkins at python.org (jeremy.hylton) Date: Tue, 27 Feb 2007 19:33:32 +0100 (CET) Subject: [Python-checkins] r53998 - python/trunk/Misc/NEWS Message-ID: <20070227183332.5945C1E4002@bag.python.org> Author: jeremy.hylton Date: Tue Feb 27 19:33:31 2007 New Revision: 53998 Modified: python/trunk/Misc/NEWS Log: Add news about changes to metaclasses and __bases__ error checking. Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue Feb 27 19:33:31 2007 @@ -126,6 +126,13 @@ - Bug #1664966: Fix crash in exec if Unicode filename can't be decoded. +- Add new requirements for metaclasses. 1) If type or a subclass of type + occurs in __bases__, it must occur before any non-type bases, e.g. + before regular classes. 2) If you assign to __bases__, you may not + change the metaclass. Many more illegal assignments to __bases__ + are now checked and raise TypeErrors. This changed fixed at least + one known crash. + Library ------- From python-checkins at python.org Wed Feb 28 00:02:13 2007 From: python-checkins at python.org (collin.winter) Date: Wed, 28 Feb 2007 00:02:13 +0100 (CET) Subject: [Python-checkins] r54005 - sandbox/trunk/2to3/fixes/fix_apply.py sandbox/trunk/2to3/fixes/fix_except.py sandbox/trunk/2to3/fixes/fix_exec.py sandbox/trunk/2to3/fixes/fix_has_key.py sandbox/trunk/2to3/fixes/fix_intern.py sandbox/trunk/2to3/fixes/fix_raise.py sandbox/trunk/2to3/fixes/fix_throw.py Message-ID: <20070227230213.1EAE11E401A@bag.python.org> Author: collin.winter Date: Wed Feb 28 00:02:12 2007 New Revision: 54005 Modified: sandbox/trunk/2to3/fixes/fix_apply.py sandbox/trunk/2to3/fixes/fix_except.py sandbox/trunk/2to3/fixes/fix_exec.py sandbox/trunk/2to3/fixes/fix_has_key.py sandbox/trunk/2to3/fixes/fix_intern.py sandbox/trunk/2to3/fixes/fix_raise.py sandbox/trunk/2to3/fixes/fix_throw.py Log: More comprehensive docstrings for fixer modules Modified: sandbox/trunk/2to3/fixes/fix_apply.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_apply.py (original) +++ sandbox/trunk/2to3/fixes/fix_apply.py Wed Feb 28 00:02:12 2007 @@ -1,7 +1,9 @@ # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. -"""Fixer for apply().""" +"""Fixer for apply(). + +This converts apply(func, v, k) into (func)(*v, **k).""" # Local imports import pytree Modified: sandbox/trunk/2to3/fixes/fix_except.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_except.py (original) +++ sandbox/trunk/2to3/fixes/fix_except.py Wed Feb 28 00:02:12 2007 @@ -1,4 +1,26 @@ -"""Fixer for except statements with named exceptions.""" +"""Fixer for except statements with named exceptions. + +The following cases will be converted: + +- "except E, T:" where T is a name: + + except E as T: + +- "except E, T:" where T is not a name, tuple or list: + + except E as t: + T = t + + This is done because the target of an "except" clause must be a + name. + +- "except E, T:" where T is a tuple or list literal: + + except E as t: + T = t.message + + This transformation is still under consideration. +""" # Author: Collin Winter # Local imports @@ -18,8 +40,6 @@ as_leaf = pytree.Leaf(token.NAME, "as") as_leaf.set_prefix(" ") -tuple_reason = "exception unpacking is going away" - class FixExcept(basefix.BaseFix): PATTERN = """ Modified: sandbox/trunk/2to3/fixes/fix_exec.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_exec.py (original) +++ sandbox/trunk/2to3/fixes/fix_exec.py Wed Feb 28 00:02:12 2007 @@ -1,7 +1,13 @@ # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. -"""Fixer for exec.""" +"""Fixer for exec. + +This converts usages of the exec statement into calls to a built-in +exec() function. + +exec code in ns1, ns2 -> exec(code, ns1, ns2) +""" # Local imports import pytree Modified: sandbox/trunk/2to3/fixes/fix_has_key.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_has_key.py (original) +++ sandbox/trunk/2to3/fixes/fix_has_key.py Wed Feb 28 00:02:12 2007 @@ -1,7 +1,33 @@ # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. -"""Fixer for has_key().""" +"""Fixer for has_key(). + +Calls to .has_key() methods are expressed in terms of the 'in' +operator: + + d.has_key(k) -> k in d + +CAVEATS: +1) While the primary target of this fixer is dict.has_key(), the + fixer will change any has_key() method call, regardless of its + class. + +2) Cases like this will not be converted: + + m = d.has_key + if m(k): + ... + + Only *calls* to has_key() are converted. While it is possible to + convert the above to something like + + m = d.__contains__ + if m(k): + ... + + this is currently not done. +""" # Local imports import pytree Modified: sandbox/trunk/2to3/fixes/fix_intern.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_intern.py (original) +++ sandbox/trunk/2to3/fixes/fix_intern.py Wed Feb 28 00:02:12 2007 @@ -1,7 +1,9 @@ # Copyright 2006 Georg Brandl. # Licensed to PSF under a Contributor Agreement. -"""Fixer for intern().""" +"""Fixer for intern(). + +intern(s) -> sys.intern(s)""" # Local imports import pytree Modified: sandbox/trunk/2to3/fixes/fix_raise.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_raise.py (original) +++ sandbox/trunk/2to3/fixes/fix_raise.py Wed Feb 28 00:02:12 2007 @@ -1,4 +1,24 @@ -"""Fixer for 'raise E, V, T'""" +"""Fixer for 'raise E, V, T' + +raise -> raise +raise E -> raise E +raise E, V -> raise E(V) +raise E, V, T -> raise E(V).with_traceback(T) + +raise (((E, E'), E''), E'''), V -> raise E(V) +raise "foo", V, T -> warns about string exceptions + + +CAVEATS: +1) "raise E, V" will be incorrectly translated if V is an exception + instance. The correct Python 3 idiom is + + raise E from V + + but since we can't detect instance-hood by syntax alone and since + any client code would have to be changed as well, we don't automate + this. +""" # Author: Collin Winter # Local imports Modified: sandbox/trunk/2to3/fixes/fix_throw.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_throw.py (original) +++ sandbox/trunk/2to3/fixes/fix_throw.py Wed Feb 28 00:02:12 2007 @@ -1,4 +1,10 @@ -"""Fixer for generator.throw(E, V, T)""" +"""Fixer for generator.throw(E, V, T). + +g.throw(E) -> g.throw(E) +g.throw(E, V) -> g.throw(E(V)) +g.throw(E, V, T) -> g.throw(E(V).with_traceback(T)) + +g.throw("foo"[, V[, T]]) will warn about string exceptions.""" # Author: Collin Winter # Local imports From python-checkins at python.org Wed Feb 28 00:06:39 2007 From: python-checkins at python.org (collin.winter) Date: Wed, 28 Feb 2007 00:06:39 +0100 (CET) Subject: [Python-checkins] r54006 - sandbox/trunk/2to3/README Message-ID: <20070227230639.CFBEF1E4002@bag.python.org> Author: collin.winter Date: Wed Feb 28 00:06:37 2007 New Revision: 54006 Modified: sandbox/trunk/2to3/README Log: Update to reflect that tokenize.py now lives in pgen2/ Modified: sandbox/trunk/2to3/README ============================================================================== --- sandbox/trunk/2to3/README (original) +++ sandbox/trunk/2to3/README Wed Feb 28 00:06:37 2007 @@ -10,19 +10,20 @@ patcomp.py - pattern compiler pytree.py - parse tree nodes (not specific to Python, despite the name!) pygram.py - code specific to the Python grammar -tokenize.py - modified version of stdlib tokenize.py (1) example.py - example input for play.py and fix_*.py Grammar.txt - Python grammar input (a copy of Python 2.5's Grammar/Grammar) Grammar.pickle - pickled grammar tables (generated file, not in subversion) PatternGrammar.txt - grammar for the pattern language used by patcomp.py PatternGrammar.pickle - pickled pattern grammar tables (generated file) -pgen2/ - Parser generator and driver (2) +pgen2/ - Parser generator and driver (1) (2) fixes/ - Individual transformations + Notes: (1) I modified tokenize.py to yield a NL pseudo-token for backslash continuations, so the original source can be reproduced exactly. + The modified version can be found at pgen2/tokenize.py. (2) I developed pgen2 while I was at Elemental Security. I modified it while at Google to suit the needs of this refactoring tool. From python-checkins at python.org Wed Feb 28 00:45:52 2007 From: python-checkins at python.org (collin.winter) Date: Wed, 28 Feb 2007 00:45:52 +0100 (CET) Subject: [Python-checkins] r54007 - in sandbox/trunk/2to3: README fixer_tests.py test.py tests tests.py tests/__init__.py tests/support.py tests/test_fixers.py tests/test_pytree.py Message-ID: <20070227234552.673D91E4009@bag.python.org> Author: collin.winter Date: Wed Feb 28 00:45:47 2007 New Revision: 54007 Added: sandbox/trunk/2to3/test.py (contents, props changed) sandbox/trunk/2to3/tests/ (props changed) sandbox/trunk/2to3/tests/__init__.py (contents, props changed) sandbox/trunk/2to3/tests/support.py (contents, props changed) sandbox/trunk/2to3/tests/test_fixers.py - copied, changed from r53996, sandbox/trunk/2to3/fixer_tests.py sandbox/trunk/2to3/tests/test_pytree.py - copied, changed from r53996, sandbox/trunk/2to3/tests.py Removed: sandbox/trunk/2to3/fixer_tests.py sandbox/trunk/2to3/tests.py Modified: sandbox/trunk/2to3/README Log: Move tests.py and fixer_tests.py into tests/, add testing infrastructure. Modified: sandbox/trunk/2to3/README ============================================================================== --- sandbox/trunk/2to3/README (original) +++ sandbox/trunk/2to3/README Wed Feb 28 00:45:47 2007 @@ -5,8 +5,8 @@ Files: README - this file +test.py - runs all unittests for 2to3 play.py - program to exercise the idempotency of pytree nodes -tests.py - unit tests for pytree.py patcomp.py - pattern compiler pytree.py - parse tree nodes (not specific to Python, despite the name!) pygram.py - code specific to the Python grammar @@ -17,6 +17,7 @@ PatternGrammar.pickle - pickled pattern grammar tables (generated file) pgen2/ - Parser generator and driver (1) (2) fixes/ - Individual transformations +tests/ - Test files for pytree, fixers, grammar, etc Notes: Deleted: /sandbox/trunk/2to3/fixer_tests.py ============================================================================== --- /sandbox/trunk/2to3/fixer_tests.py Wed Feb 28 00:45:47 2007 +++ (empty file) @@ -1,1126 +0,0 @@ -#!/usr/bin/env python2.5 -""" Test suite for the fixer modules """ -# Author: Collin Winter - -# Python imports -from StringIO import StringIO -import re -import unittest -import logging - -# Local imports -import pytree -import refactor - -skip_whitespace = re.compile(r"""\S""") - -def reformat(string): - indent = re.search(skip_whitespace, string).start() - if indent == 0: - code = string - else: - code = "\n".join(line[indent-1:] for line in string.split("\n")[1:]) - return code + "\n\n" - -# We wrap the RefactoringTool's fixer objects so we can intercept -# the call to set_filename() and so modify the fixers' logging objects. -# This allows us to make sure that certain code chunks produce certain -# warnings. -class Fixer(object): - def __init__(self, fixer, handler): - self.fixer = fixer - self.handler = handler - - def __getattr__(self, attr): - return getattr(self.fixer, attr) - - def set_filename(self, filename): - self.fixer.set_filename(filename) - self.fixer.logger.addHandler(self.handler) - -class Options: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - setattr(self, k, v) - - self.verbose = False - -class FixerTestCase(unittest.TestCase): - def setUp(self): - options = Options(fix=[self.fixer], print_function=False) - self.refactor = refactor.RefactoringTool(options) - - self.logging_stream = StringIO() - sh = logging.StreamHandler(self.logging_stream) - sh.setFormatter(logging.Formatter("%(message)s")) - self.refactor.fixers = [Fixer(f, sh) for f in self.refactor.fixers] - - def check(self, before, after): - before = reformat(before) - after = reformat(after) - refactored = self.refactor_stream("", StringIO(before)) - self.failUnlessEqual(after, refactored) - - def warns(self, before, after, message): - self.check(before, after) - - self.failUnless(message in self.logging_stream.getvalue()) - - def refactor_stream(self, stream_name, stream): - try: - tree = self.refactor.driver.parse_stream(stream) - except Exception, err: - raise - self.log_error("Can't parse %s: %s: %s", - filename, err.__class__.__name__, err) - return - self.refactor.refactor_tree(tree, stream_name) - return str(tree) - - -class Test_ne(FixerTestCase): - fixer = "ne" - - def test_1(self): - b = """if x <> y: - pass""" - - a = """if x != y: - pass""" - self.check(b, a) - - def test_2(self): - b = """if x<>y: - pass""" - - a = """if x!=y: - pass""" - self.check(b, a) - - def test_3(self): - b = """if x<>y<>z: - pass""" - - a = """if x!=y!=z: - pass""" - self.check(b, a) - -class Test_has_key(FixerTestCase): - fixer = "has_key" - - def test_1(self): - b = """x = d.has_key("x") or d.has_key("y")""" - a = """x = "x" in d or "y" in d""" - self.check(b, a) - - def test_2(self): - b = """x = a.b.c.d.has_key("x") ** 3""" - a = """x = ("x" in a.b.c.d) ** 3""" - self.check(b, a) - - def test_3(self): - b = """x = a.b.has_key(1 + 2).__repr__()""" - a = """x = (1 + 2 in a.b).__repr__()""" - self.check(b, a) - - def test_4(self): - b = """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4""" - a = """x = (1 + 2 in a.b).__repr__() ** -3 ** 4""" - self.check(b, a) - - def test_5(self): - b = """x = a.has_key(f or g)""" - a = """x = (f or g) in a""" - self.check(b, a) - - def test_6(self): - b = """x = a + b.has_key(c)""" - a = """x = a + (c in b)""" - self.check(b, a) - - def test_7(self): - b = """x = a.has_key(lambda: 12)""" - a = """x = (lambda: 12) in a""" - self.check(b, a) - - def test_8(self): - b = """x = a.has_key(a for a in b)""" - a = """x = (a for a in b) in a""" - self.check(b, a) - - def test_9(self): - b = """if not a.has_key(b): pass""" - a = """if b not in a: pass""" - self.check(b, a) - - def test_10(self): - b = """if not a.has_key(b).__repr__(): pass""" - a = """if not (b in a).__repr__(): pass""" - self.check(b, a) - - def test_11(self): - b = """if not a.has_key(b) ** 2: pass""" - a = """if not (b in a) ** 2: pass""" - self.check(b, a) - -class Test_apply(FixerTestCase): - fixer = "apply" - - def test_1(self): - b = """x = apply(f, g + h)""" - a = """x = f(*g + h)""" - self.check(b, a) - - def test_2(self): - b = """y = apply(f, g, h)""" - a = """y = f(*g, **h)""" - self.check(b, a) - - def test_3(self): - b = """z = apply(fs[0], g or h, h or g)""" - a = """z = fs[0](*g or h, **h or g)""" - self.check(b, a) - - def test_4(self): - b = """apply(f, (x, y) + t)""" - a = """f(*(x, y) + t)""" - self.check(b, a) - - def test_5(self): - b = """apply(f, args,)""" - a = """f(*args)""" - self.check(b, a) - - def test_6(self): - b = """apply(f, args, kwds,)""" - a = """f(*args, **kwds)""" - self.check(b, a) - - # Test that complex functions are parenthesized - - def test_7(self): - b = """x = apply(f+g, args)""" - a = """x = (f+g)(*args)""" - self.check(b, a) - - def test_8(self): - b = """x = apply(f*g, args)""" - a = """x = (f*g)(*args)""" - self.check(b, a) - - def test_9(self): - b = """x = apply(f**g, args)""" - a = """x = (f**g)(*args)""" - self.check(b, a) - - # But dotted names etc. not - - def test_10(self): - b = """x = apply(f.g, args)""" - a = """x = f.g(*args)""" - self.check(b, a) - - def test_11(self): - b = """x = apply(f[x], args)""" - a = """x = f[x](*args)""" - self.check(b, a) - - def test_12(self): - b = """x = apply(f(), args)""" - a = """x = f()(*args)""" - self.check(b, a) - - # Extreme case - def test_13(self): - b = """x = apply(a.b.c.d.e.f, args, kwds)""" - a = """x = a.b.c.d.e.f(*args, **kwds)""" - self.check(b, a) - - # XXX Comments in weird places still get lost - def test_14(self): - b = """apply( # foo - f, # bar - args)""" - a = """f(*args)""" - self.check(b, a) - - # These should *not* be touched - - def test_15(self): - b = """apply()""" - a = """apply()""" - self.check(b, a) - - def test_16(self): - b = """apply(f)""" - a = """apply(f)""" - self.check(b, a) - - def test_17(self): - b = """apply(f,)""" - a = """apply(f,)""" - self.check(b, a) - - def test_18(self): - b = """apply(f, args, kwds, extras)""" - a = """apply(f, args, kwds, extras)""" - self.check(b, a) - - def test_19(self): - b = """apply(f, *args, **kwds)""" - a = """apply(f, *args, **kwds)""" - self.check(b, a) - - def test_20(self): - b = """apply(f, *args)""" - a = """apply(f, *args)""" - self.check(b, a) - - def test_21(self): - b = """apply(func=f, args=args, kwds=kwds)""" - a = """apply(func=f, args=args, kwds=kwds)""" - self.check(b, a) - - def test_22(self): - b = """apply(f, args=args, kwds=kwds)""" - a = """apply(f, args=args, kwds=kwds)""" - self.check(b, a) - - def test_23(self): - b = """apply(f, args, kwds=kwds)""" - a = """apply(f, args, kwds=kwds)""" - self.check(b, a) - - -class Test_intern(FixerTestCase): - fixer = "intern" - - def test_1(self): - b = """x = intern(a)""" - a = """x = sys.intern(a)""" - self.check(b, a) - - def test_2(self): - b = """y = intern("b" # test - )""" - a = """y = sys.intern("b" # test - )""" - self.check(b, a) - - def test_3(self): - b = """z = intern(a+b+c.d,)""" - a = """z = sys.intern(a+b+c.d,)""" - self.check(b, a) - - def test_4(self): - b = """intern("y%s" % 5).replace("y", "")""" - a = """sys.intern("y%s" % 5).replace("y", "")""" - self.check(b, a) - - # These should not be refactored - - def test_5(self): - b = """intern(a=1)""" - a = """intern(a=1)""" - self.check(b, a) - - def test_6(self): - b = """intern(f, g)""" - a = """intern(f, g)""" - self.check(b, a) - - def test_7(self): - b = """intern(*h)""" - a = """intern(*h)""" - self.check(b, a) - - def test_8(self): - b = """intern(**i)""" - a = """intern(**i)""" - self.check(b, a) - -class Test_print(FixerTestCase): - fixer = "print" - - def test_1(self): - b = """print 1, 1+1, 1+1+1""" - a = """print(1, 1+1, 1+1+1)""" - self.check(b, a) - - def test_2(self): - b = """print 1, 2""" - a = """print(1, 2)""" - self.check(b, a) - - def test_3(self): - b = """print""" - a = """print()""" - self.check(b, a) - - # trailing commas - - def test_4(self): - b = """print 1, 2, 3,""" - a = """print(1, 2, 3, end=' ')""" - self.check(b, a) - - def test_5(self): - b = """print 1, 2,""" - a = """print(1, 2, end=' ')""" - self.check(b, a) - - def test_6(self): - b = """print 1,""" - a = """print(1, end=' ')""" - self.check(b, a) - - # >> stuff - - # no trailing comma - def test_7(self): - b = """print >>sys.stderr, 1, 2, 3""" - a = """print(1, 2, 3, file=sys.stderr)""" - self.check(b, a) - - # trailing comma - def test_8(self): - b = """print >>sys.stderr, 1, 2,""" - a = """print(1, 2, end=' ', file=sys.stderr)""" - self.check(b, a) - - # no trailing comma - def test_9(self): - b = """print >>sys.stderr, 1+1""" - a = """print(1+1, file=sys.stderr)""" - self.check(b, a) - - # spaces before sys.stderr - def test_10(self): - b = """print >> sys.stderr""" - a = """print(file=sys.stderr)""" - self.check(b, a) - - -class Test_exec(FixerTestCase): - fixer = "exec" - - def test_1(self): - b = """exec code""" - a = """exec(code)""" - self.check(b, a) - - def test_2(self): - b = """exec code in ns""" - a = """exec(code, ns)""" - self.check(b, a) - - def test_3(self): - b = """exec code in ns1, ns2""" - a = """exec(code, ns1, ns2)""" - self.check(b, a) - - def test_4(self): - b = """exec (a.b()) in ns""" - a = """exec((a.b()), ns)""" - self.check(b, a) - - def test_5(self): - b = """exec a.b() + c in ns""" - a = """exec(a.b() + c, ns)""" - self.check(b, a) - - # These should not be touched - - def test_6(self): - b = """exec(code)""" - a = """exec(code)""" - self.check(b, a) - - def test_7(self): - b = """exec (code)""" - a = """exec (code)""" - self.check(b, a) - - def test_8(self): - b = """exec(code, ns)""" - a = """exec(code, ns)""" - self.check(b, a) - - def test_9(self): - b = """exec(code, ns1, ns2)""" - a = """exec(code, ns1, ns2)""" - self.check(b, a) - - -class Test_repr(FixerTestCase): - fixer = "repr" - - def test_1(self): - b = """x = `1 + 2`""" - a = """x = repr(1 + 2)""" - self.check(b, a) - - def test_2(self): - b = """y = `x`""" - a = """y = repr(x)""" - self.check(b, a) - - def test_3(self): - b = """z = `y`.__repr__()""" - a = """z = repr(y).__repr__()""" - self.check(b, a) - - def test_4(self): - b = """x = `1, 2, 3`""" - a = """x = repr((1, 2, 3))""" - self.check(b, a) - - def test_5(self): - b = """x = `1 + `2``""" - a = """x = repr(1 + repr(2))""" - self.check(b, a) - - def test_6(self): - b = """x = `1, 2 + `3, 4``""" - a = """x = repr((1, 2 + repr((3, 4))))""" - self.check(b, a) - -class Test_except(FixerTestCase): - fixer = "except" - - def test_1(self): - b = """ - def foo(): - try: - pass - except Exception, (f, e): - pass - except ImportError, e: - pass""" - - a = """ - def foo(): - try: - pass - except Exception as xxx_todo_changeme: - (f, e) = xxx_todo_changeme.message - pass - except ImportError as e: - pass""" - self.check(b, a) - - def test_2(self): - b = """ - try: - pass - except (RuntimeError, ImportError), e: - pass""" - - a = """ - try: - pass - except (RuntimeError, ImportError) as e: - pass""" - self.check(b, a) - - def test_3(self): - b = """ - try: - pass - except Exception, (a, b): - pass""" - - a = """ - try: - pass - except Exception as xxx_todo_changeme1: - (a, b) = xxx_todo_changeme1.message - pass""" - self.check(b, a) - - def test_4(self): - b = """ - try: - pass - except Exception, d[5]: - pass""" - - a = """ - try: - pass - except Exception as xxx_todo_changeme2: - d[5] = xxx_todo_changeme2 - pass""" - self.check(b, a) - - def test_5(self): - b = """ - try: - pass - except Exception, a.foo: - pass""" - - a = """ - try: - pass - except Exception as xxx_todo_changeme3: - a.foo = xxx_todo_changeme3 - pass""" - self.check(b, a) - - def test_6(self): - b = """ - try: - pass - except Exception, a().foo: - pass""" - - a = """ - try: - pass - except Exception as xxx_todo_changeme4: - a().foo = xxx_todo_changeme4 - pass""" - self.check(b, a) - - # These should not be touched: - - def test_7(self): - b = """ - try: - pass - except: - pass""" - - a = """ - try: - pass - except: - pass""" - self.check(b, a) - - def test_8(self): - b = """ - try: - pass - except Exception: - pass""" - - a = """ - try: - pass - except Exception: - pass""" - self.check(b, a) - - def test_9(self): - b = """ - try: - pass - except (Exception, SystemExit): - pass""" - - a = """ - try: - pass - except (Exception, SystemExit): - pass""" - self.check(b, a) - - -class Test_raise(FixerTestCase): - fixer = "raise" - - def test_1(self): - b = """raise Exception, 5""" - a = """raise Exception(5)""" - self.check(b, a) - - def test_2(self): - b = """raise Exception,5""" - a = """raise Exception(5)""" - self.check(b, a) - - def test_3(self): - b = """raise Exception, (5, 6, 7)""" - a = """raise Exception(5, 6, 7)""" - self.check(b, a) - - def test_4(self): - b = """raise E, (5, 6) % (a, b)""" - a = """raise E((5, 6) % (a, b))""" - self.check(b, a) - - def test_5(self): - b = """raise (((E1, E2), E3), E4), V""" - a = """raise E1(V)""" - self.check(b, a) - - def test_6(self): - b = """raise (E1, (E2, E3), E4), V""" - a = """raise E1(V)""" - self.check(b, a) - - # These should produce a warning - - def test_warn_1(self): - s = """raise 'foo'""" - self.warns(s, s, "Python 3 does not support string exceptions") - - def test_warn_2(self): - s = """raise "foo", 5""" - self.warns(s, s, "Python 3 does not support string exceptions") - - def test_warn_3(self): - s = """raise "foo", 5, 6""" - self.warns(s, s, "Python 3 does not support string exceptions") - - # These should result in traceback-assignment - - def test_tb_1(self): - b = """def foo(): - raise Exception, 5, 6""" - a = """def foo(): - raise Exception(5).with_traceback(6)""" - self.check(b, a) - - def test_tb_2(self): - b = """def foo(): - a = 5 - raise Exception, 5, 6 - b = 6""" - a = """def foo(): - a = 5 - raise Exception(5).with_traceback(6) - b = 6""" - self.check(b, a) - - def test_tb_3(self): - b = """def foo(): - raise Exception,5,6""" - a = """def foo(): - raise Exception(5).with_traceback(6)""" - self.check(b, a) - - def test_tb_4(self): - b = """def foo(): - a = 5 - raise Exception,5,6 - b = 6""" - a = """def foo(): - a = 5 - raise Exception(5).with_traceback(6) - b = 6""" - self.check(b, a) - - def test_tb_5(self): - b = """def foo(): - raise Exception, (5, 6, 7), 6""" - a = """def foo(): - raise Exception(5, 6, 7).with_traceback(6)""" - self.check(b, a) - - def test_tb_6(self): - b = """def foo(): - a = 5 - raise Exception, (5, 6, 7), 6 - b = 6""" - a = """def foo(): - a = 5 - raise Exception(5, 6, 7).with_traceback(6) - b = 6""" - self.check(b, a) - - -class Test_throw(FixerTestCase): - fixer = "throw" - - def test_1(self): - b = """g.throw(Exception, 5)""" - a = """g.throw(Exception(5))""" - self.check(b, a) - - def test_2(self): - b = """g.throw(Exception,5)""" - a = """g.throw(Exception(5))""" - self.check(b, a) - - def test_3(self): - b = """g.throw(Exception, (5, 6, 7))""" - a = """g.throw(Exception(5, 6, 7))""" - self.check(b, a) - - def test_4(self): - b = """5 + g.throw(Exception, 5)""" - a = """5 + g.throw(Exception(5))""" - self.check(b, a) - - # These should produce warnings - - def test_warn_1(self): - s = """g.throw("foo")""" - self.warns(s, s, "Python 3 does not support string exceptions") - - def test_warn_2(self): - s = """g.throw("foo", 5)""" - self.warns(s, s, "Python 3 does not support string exceptions") - - def test_warn_3(self): - s = """g.throw("foo", 5, 6)""" - self.warns(s, s, "Python 3 does not support string exceptions") - - # These should not be touched - - def test_untouched_1(self): - b = """g.throw(Exception)""" - a = """g.throw(Exception)""" - self.check(b, a) - - def test_untouched_2(self): - b = """g.throw(Exception(5, 6))""" - a = """g.throw(Exception(5, 6))""" - self.check(b, a) - - def test_untouched_3(self): - b = """5 + g.throw(Exception(5, 6))""" - a = """5 + g.throw(Exception(5, 6))""" - self.check(b, a) - - # These should result in traceback-assignment - - def test_tb_1(self): - b = """def foo(): - g.throw(Exception, 5, 6)""" - a = """def foo(): - g.throw(Exception(5).with_traceback(6))""" - self.check(b, a) - - def test_tb_2(self): - b = """def foo(): - a = 5 - g.throw(Exception, 5, 6) - b = 6""" - a = """def foo(): - a = 5 - g.throw(Exception(5).with_traceback(6)) - b = 6""" - self.check(b, a) - - def test_tb_3(self): - b = """def foo(): - g.throw(Exception,5,6)""" - a = """def foo(): - g.throw(Exception(5).with_traceback(6))""" - self.check(b, a) - - def test_tb_4(self): - b = """def foo(): - a = 5 - g.throw(Exception,5,6) - b = 6""" - a = """def foo(): - a = 5 - g.throw(Exception(5).with_traceback(6)) - b = 6""" - self.check(b, a) - - def test_tb_5(self): - b = """def foo(): - g.throw(Exception, (5, 6, 7), 6)""" - a = """def foo(): - g.throw(Exception(5, 6, 7).with_traceback(6))""" - self.check(b, a) - - def test_tb_6(self): - b = """def foo(): - a = 5 - g.throw(Exception, (5, 6, 7), 6) - b = 6""" - a = """def foo(): - a = 5 - g.throw(Exception(5, 6, 7).with_traceback(6)) - b = 6""" - self.check(b, a) - - def test_tb_7(self): - b = """def foo(): - a + g.throw(Exception, 5, 6)""" - a = """def foo(): - a + g.throw(Exception(5).with_traceback(6))""" - self.check(b, a) - - def test_tb_8(self): - b = """def foo(): - a = 5 - a + g.throw(Exception, 5, 6) - b = 6""" - a = """def foo(): - a = 5 - a + g.throw(Exception(5).with_traceback(6)) - b = 6""" - self.check(b, a) - - -class Test_long(FixerTestCase): - fixer = "long" - - def test_1(self): - b = """x = long(x)""" - a = """x = int(x)""" - self.check(b, a) - - def test_2(self): - b = """y = isinstance(x, long)""" - a = """y = isinstance(x, int)""" - self.check(b, a) - - def test_3(self): - b = """z = type(x) in (int, long)""" - a = """z = type(x) in (int, int)""" - self.check(b, a) - - def test_4(self): - b = """a = 12L""" - a = """a = 12""" - self.check(b, a) - - def test_5(self): - b = """b = 0x12l""" - a = """b = 0x12""" - self.check(b, a) - - # These should not be touched - - def test_6(self): - b = """a = 12""" - a = """a = 12""" - self.check(b, a) - - def test_7(self): - b = """b = 0x12""" - a = """b = 0x12""" - self.check(b, a) - - def test_8(self): - b = """c = 3.14""" - a = """c = 3.14""" - self.check(b, a) - - -class Test_sysexcinfo(FixerTestCase): - fixer = "sysexcinfo" - - def test_1(self): - s = """sys.exc_info()""" - self.warns(s, s, "This function is going away") - - def test_2(self): - s = """if sys.exc_info()[1] == 1: - pass""" - - self.warns(s, s, "This function is going away") - - def test_3(self): - s = """f = sys.exc_info""" - self.warns(s, s, "This function is going away") - - def test_4(self): - s = """f = sys.exc_type + ":" + sys.exc_value""" - self.warns(s, s, "This attribute is going away") - - -class Test_dict(FixerTestCase): - fixer = "dict" - - def test_01(self): - b = "d.keys()" - a = "list(d.keys())" - self.check(b, a) - - def test_01a(self): - b = "a[0].foo().keys()" - a = "list(a[0].foo().keys())" - self.check(b, a) - - def test_02(self): - b = "d.items()" - a = "list(d.items())" - self.check(b, a) - - def test_03(self): - b = "d.values()" - a = "list(d.values())" - self.check(b, a) - - def test_04(self): - b = "d.iterkeys()" - a = "iter(d.keys())" - self.check(b, a) - - def test_05(self): - b = "d.iteritems()" - a = "iter(d.items())" - self.check(b, a) - - def test_06(self): - b = "d.itervalues()" - a = "iter(d.values())" - self.check(b, a) - - def test_07(self): - b = "list(d.keys())" - a = b - self.check(b, a) - - def test_08(self): - b = "sorted(d.keys())" - a = b - self.check(b, a) - - def test_09(self): - b = "iter(d.keys())" - a = "iter(list(d.keys()))" - self.check(b, a) - - def test_10(self): - b = "foo(d.keys())" - a = "foo(list(d.keys()))" - self.check(b, a) - - def test_11(self): - b = "for i in d.keys(): print i" - a = "for i in list(d.keys()): print i" - self.check(b, a) - - def test_12(self): - b = "for i in d.iterkeys(): print i" - a = "for i in d.keys(): print i" - self.check(b, a) - - def test_13(self): - b = "[i for i in d.keys()]" - a = "[i for i in list(d.keys())]" - self.check(b, a) - - def test_14(self): - b = "[i for i in d.iterkeys()]" - a = "[i for i in d.keys()]" - self.check(b, a) - - def test_15(self): - b = "(i for i in d.keys())" - a = "(i for i in list(d.keys()))" - self.check(b, a) - - def test_16(self): - b = "(i for i in d.iterkeys())" - a = "(i for i in d.keys())" - self.check(b, a) - - def test_17(self): - b = "iter(d.iterkeys())" - a = "iter(d.keys())" - self.check(b, a) - - def test_18(self): - b = "list(d.iterkeys())" - a = "list(d.keys())" - self.check(b, a) - - def test_19(self): - b = "sorted(d.iterkeys())" - a = "sorted(d.keys())" - self.check(b, a) - - def test_20(self): - b = "foo(d.iterkeys())" - a = "foo(iter(d.keys()))" - self.check(b, a) - - def test_21(self): - b = "print h.iterkeys().next()" - a = "print iter(h.keys()).next()" - self.check(b, a) - - def test_22(self): - b = "print h.keys()[0]" - a = "print list(h.keys())[0]" - self.check(b, a) - - def test_23(self): - b = "print list(h.iterkeys().next())" - a = "print list(iter(h.keys()).next())" - self.check(b, a) - - def test_24(self): - b = "for x in h.keys()[0]: print x" - a = "for x in list(h.keys())[0]: print x" - self.check(b, a) - -class Test_xrange(FixerTestCase): - fixer = "xrange" - - def test_1(self): - b = """x = xrange(10)""" - a = """x = range(10)""" - self.check(b, a) - - def test_2(self): - b = """x = xrange(1, 10)""" - a = """x = range(1, 10)""" - self.check(b, a) - - def test_3(self): - b = """x = xrange(0, 10, 2)""" - a = """x = range(0, 10, 2)""" - self.check(b, a) - - def test_4(self): - b = """for i in xrange(10):\n j=i""" - a = """for i in range(10):\n j=i""" - self.check(b, a) - - -class Test_raw_input(FixerTestCase): - fixer = "raw_input" - - def test_1(self): - b = """x = raw_input()""" - a = """x = input()""" - self.check(b, a) - - def test_2(self): - b = """x = raw_input('')""" - a = """x = input('')""" - self.check(b, a) - - def test_3(self): - b = """x = raw_input('prompt')""" - a = """x = input('prompt')""" - self.check(b, a) - - -class Test_input(FixerTestCase): - fixer = "input" - - def test_1(self): - b = """x = input()""" - a = """x = eval(input())""" - self.check(b, a) - - def test_2(self): - b = """x = input('')""" - a = """x = eval(input(''))""" - self.check(b, a) - - def test_3(self): - b = """x = input('prompt')""" - a = """x = eval(input('prompt'))""" - self.check(b, a) - - -if __name__ == "__main__": - import sys - if not sys.argv[1:]: - sys.argv.append("-v") - unittest.main() Added: sandbox/trunk/2to3/test.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/test.py Wed Feb 28 00:45:47 2007 @@ -0,0 +1,8 @@ +"""Main test file for 2to3. Running "python test.py" will run all +tests in tests/test_*.py.""" +# Author: Collin Winter + +import tests +import tests.support + +tests.support.run_all_tests(tests=tests.all_tests) Deleted: /sandbox/trunk/2to3/tests.py ============================================================================== --- /sandbox/trunk/2to3/tests.py Wed Feb 28 00:45:47 2007 +++ (empty file) @@ -1,239 +0,0 @@ -#!/usr/bin/env python2.5 -# Copyright 2006 Google, Inc. All Rights Reserved. -# Licensed to PSF under a Contributor Agreement. - -"""Unit tests for pytree.py. - -NOTE: Please *don't* add doc strings to individual test methods! -In verbose mode, printing of the module, class and method name is much -more helpful than printing of (the first line of) the docstring, -especially when debugging a test. -""" - -# Python imports -import unittest - -# Local imports (XXX should become a package) -import pytree - - -class TestNodes(unittest.TestCase): - - """Unit tests for nodes (Base, Leaf, Node).""" - - def testBaseCantConstruct(self): - if __debug__: - # Test that instantiating Base() raises an AssertionError - self.assertRaises(AssertionError, pytree.Base) - - def testLeaf(self): - l1 = pytree.Leaf(100, "foo") - self.assertEqual(l1.type, 100) - self.assertEqual(l1.value, "foo") - - def testLeafRepr(self): - l1 = pytree.Leaf(100, "foo") - self.assertEqual(repr(l1), "Leaf(100, 'foo')") - - def testLeafStr(self): - l1 = pytree.Leaf(100, "foo") - self.assertEqual(str(l1), "foo") - l2 = pytree.Leaf(100, "foo", context=(" ", (10, 1))) - self.assertEqual(str(l2), " foo") - - def testLeafEq(self): - l1 = pytree.Leaf(100, "foo") - l2 = pytree.Leaf(100, "foo", context=(" ", (1, 0))) - self.assertEqual(l1, l2) - l3 = pytree.Leaf(101, "foo") - l4 = pytree.Leaf(100, "bar") - self.assertNotEqual(l1, l3) - self.assertNotEqual(l1, l4) - - def testLeafPrefix(self): - l1 = pytree.Leaf(100, "foo") - self.assertEqual(l1.get_prefix(), "") - l1.set_prefix(" ##\n\n") - self.assertEqual(l1.get_prefix(), " ##\n\n") - - def testNode(self): - l1 = pytree.Leaf(100, "foo") - l2 = pytree.Leaf(200, "bar") - n1 = pytree.Node(1000, [l1, l2]) - self.assertEqual(n1.type, 1000) - self.assertEqual(n1.children, (l1, l2)) - - def testNodeRepr(self): - l1 = pytree.Leaf(100, "foo") - l2 = pytree.Leaf(100, "bar", context=(" ", (1, 0))) - n1 = pytree.Node(1000, [l1, l2]) - self.assertEqual(repr(n1), - "Node(1000, (%s, %s))" % (repr(l1), repr(l2))) - - def testNodeStr(self): - l1 = pytree.Leaf(100, "foo") - l2 = pytree.Leaf(100, "bar", context=(" ", (1, 0))) - n1 = pytree.Node(1000, [l1, l2]) - self.assertEqual(str(n1), "foo bar") - - def testNodePrefix(self): - l1 = pytree.Leaf(100, "foo") - self.assertEqual(l1.get_prefix(), "") - n1 = pytree.Node(1000, [l1]) - self.assertEqual(n1.get_prefix(), "") - n1.set_prefix(" ") - self.assertEqual(n1.get_prefix(), " ") - self.assertEqual(l1.get_prefix(), " ") - - def testNodeEq(self): - n1 = pytree.Node(1000, ()) - n2 = pytree.Node(1000, [], context=(" ", (1, 0))) - self.assertEqual(n1, n2) - n3 = pytree.Node(1001, ()) - self.assertNotEqual(n1, n3) - - def testNodeEqRecursive(self): - l1 = pytree.Leaf(100, "foo") - l2 = pytree.Leaf(100, "foo") - n1 = pytree.Node(1000, [l1]) - n2 = pytree.Node(1000, [l2]) - self.assertEqual(n1, n2) - l3 = pytree.Leaf(100, "bar") - n3 = pytree.Node(1000, [l3]) - self.assertNotEqual(n1, n3) - - def testReplace(self): - l1 = pytree.Leaf(100, "foo") - l2 = pytree.Leaf(100, "+") - l3 = pytree.Leaf(100, "bar") - n1 = pytree.Node(1000, [l1, l2, l3]) - self.assertEqual(n1.children, (l1, l2, l3)) - l2new = pytree.Leaf(100, "-") - l2.replace(l2new) - self.assertEqual(n1.children, (l1, l2new, l3)) - - def testConvert(self): - # XXX - pass - - -class TestPatterns(unittest.TestCase): - - """Unit tests for tree matching patterns.""" - - def testBasicPatterns(self): - # Build a tree - l1 = pytree.Leaf(100, "foo") - l2 = pytree.Leaf(100, "bar") - l3 = pytree.Leaf(100, "foo") - n1 = pytree.Node(1000, [l1, l2]) - n2 = pytree.Node(1000, [l3]) - root = pytree.Node(1000, [n1, n2]) - # Build a pattern matching a leaf - pl = pytree.LeafPattern(100, "foo", name="pl") - r = {} - self.assertEqual(pl.match(root, results=r), False) - self.assertEqual(r, {}) - self.assertEqual(pl.match(n1, results=r), False) - self.assertEqual(r, {}) - self.assertEqual(pl.match(n2, results=r), False) - self.assertEqual(r, {}) - self.assertEqual(pl.match(l1, results=r), True) - self.assertEqual(r, {"pl": l1}) - r = {} - self.assertEqual(pl.match(l2, results=r), False) - self.assertEqual(r, {}) - # Build a pattern matching a node - pn = pytree.NodePattern(1000, [pl], name="pn") - self.assertEqual(pn.match(root, results=r), False) - self.assertEqual(r, {}) - self.assertEqual(pn.match(n1, results=r), False) - self.assertEqual(r, {}) - self.assertEqual(pn.match(n2, results=r), True) - self.assertEqual(r, {"pn": n2, "pl": l3}) - r = {} - self.assertEqual(pn.match(l1, results=r), False) - self.assertEqual(r, {}) - self.assertEqual(pn.match(l2, results=r), False) - self.assertEqual(r, {}) - - def testWildcardPatterns(self): - # Build a tree for testing - l1 = pytree.Leaf(100, "foo") - l2 = pytree.Leaf(100, "bar") - l3 = pytree.Leaf(100, "foo") - n1 = pytree.Node(1000, [l1, l2]) - n2 = pytree.Node(1000, [l3]) - root = pytree.Node(1000, [n1, n2]) - # Build a pattern - pl = pytree.LeafPattern(100, "foo", name="pl") - pn = pytree.NodePattern(1000, [pl], name="pn") - pw = pytree.WildcardPattern([[pn], [pl, pl]], name="pw") - r = {} - self.assertEqual(pw.match_seq([root], r), False) - self.assertEqual(r, {}) - self.assertEqual(pw.match_seq([n1], r), False) - self.assertEqual(r, {}) - self.assertEqual(pw.match_seq([n2], r), True) - # These are easier to debug - self.assertEqual(sorted(r.keys()), ["pl", "pn", "pw"]) - self.assertEqual(r["pl"], l1) - self.assertEqual(r["pn"], n2) - self.assertEqual(r["pw"], (n2,)) - # But this is equivalent - self.assertEqual(r, {"pl": l1, "pn": n2, "pw": (n2,)}) - r = {} - self.assertEqual(pw.match_seq([l1, l3], r), True) - self.assertEqual(r, {"pl": l3, "pw": (l1, l3)}) - self.assert_(r["pl"] is l3) - r = {} - - def testGenerateMatches(self): - la = pytree.Leaf(1, "a") - lb = pytree.Leaf(1, "b") - lc = pytree.Leaf(1, "c") - ld = pytree.Leaf(1, "d") - le = pytree.Leaf(1, "e") - lf = pytree.Leaf(1, "f") - leaves = [la, lb, lc, ld, le, lf] - root = pytree.Node(1000, leaves) - pa = pytree.LeafPattern(1, "a", "pa") - pb = pytree.LeafPattern(1, "b", "pb") - pc = pytree.LeafPattern(1, "c", "pc") - pd = pytree.LeafPattern(1, "d", "pd") - pe = pytree.LeafPattern(1, "e", "pe") - pf = pytree.LeafPattern(1, "f", "pf") - pw = pytree.WildcardPattern([[pa, pb, pc], [pd, pe], - [pa, pb], [pc, pd], [pe, pf]], - min=1, max=4, name="pw") - self.assertEqual([x[0] for x in pw.generate_matches(leaves)], - [3, 5, 2, 4, 6]) - pr = pytree.NodePattern(type=1000, content=[pw], name="pr") - matches = list(pytree.generate_matches([pr], [root])) - self.assertEqual(len(matches), 1) - c, r = matches[0] - self.assertEqual(c, 1) - self.assertEqual(str(r["pr"]), "abcdef") - self.assertEqual(r["pw"], (la, lb, lc, ld, le, lf)) - for c in "abcdef": - self.assertEqual(r["p" + c], pytree.Leaf(1, c)) - - def testHasKeyExample(self): - pattern = pytree.NodePattern(331, - (pytree.LeafPattern(7), - pytree.WildcardPattern(name="args"), - pytree.LeafPattern(8))) - l1 = pytree.Leaf(7, "(") - l2 = pytree.Leaf(3, "x") - l3 = pytree.Leaf(8, ")") - node = pytree.Node(331, (l1, l2, l3)) - r = {} - self.assert_(pattern.match(node, r)) - self.assertEqual(r["args"], (l2,)) - - -if __name__ == "__main__": - import sys - if not sys.argv[1:]: - sys.argv.append("-v") - unittest.main() Added: sandbox/trunk/2to3/tests/__init__.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/tests/__init__.py Wed Feb 28 00:45:47 2007 @@ -0,0 +1,23 @@ +"""Make tests/ into a package. This allows us to "import tests" and +have tests.all_tests be a TestSuite representing all test cases +from all test_*.py files in tests/.""" +# Author: Collin Winter + +import os +import os.path +import unittest +import types + +import support + +all_tests = unittest.TestSuite() + +tests_dir = os.path.join(os.getcwd(), 'tests') +tests = [t[0:-3] for t in os.listdir(tests_dir) + if t.startswith('test_') and t.endswith('.py')] + +loader = unittest.TestLoader() +for t in tests: + __import__('tests.' + t) + mod = globals()[t] + all_tests.addTests(loader.loadTestsFromModule(mod)) Added: sandbox/trunk/2to3/tests/support.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/tests/support.py Wed Feb 28 00:45:47 2007 @@ -0,0 +1,17 @@ +"""Support code for test_*.py files""" +# Author: Collin Winter + +import unittest +import sys +import os.path + +def run_all_tests(test_mod=None, tests=None): + if tests is None: + tests = unittest.TestLoader().loadTestsFromModule(test_mod) + unittest.TextTestRunner(verbosity=2).run(tests) + +def adjust_path(): + parent_dir = os.path.split(sys.path[0])[0] + sys.path = [parent_dir] + sys.path + +TestCase = unittest.TestCase Copied: sandbox/trunk/2to3/tests/test_fixers.py (from r53996, sandbox/trunk/2to3/fixer_tests.py) ============================================================================== --- sandbox/trunk/2to3/fixer_tests.py (original) +++ sandbox/trunk/2to3/tests/test_fixers.py Wed Feb 28 00:45:47 2007 @@ -2,6 +2,11 @@ """ Test suite for the fixer modules """ # Author: Collin Winter +# Testing imports +import support +if __name__ == '__main__': + support.adjust_path() + # Python imports from StringIO import StringIO import re @@ -45,7 +50,7 @@ self.verbose = False -class FixerTestCase(unittest.TestCase): +class FixerTestCase(support.TestCase): def setUp(self): options = Options(fix=[self.fixer], print_function=False) self.refactor = refactor.RefactoringTool(options) @@ -1120,7 +1125,5 @@ if __name__ == "__main__": - import sys - if not sys.argv[1:]: - sys.argv.append("-v") - unittest.main() + import __main__ + support.run_all_tests(__main__) Copied: sandbox/trunk/2to3/tests/test_pytree.py (from r53996, sandbox/trunk/2to3/tests.py) ============================================================================== --- sandbox/trunk/2to3/tests.py (original) +++ sandbox/trunk/2to3/tests/test_pytree.py Wed Feb 28 00:45:47 2007 @@ -10,14 +10,16 @@ especially when debugging a test. """ -# Python imports -import unittest +# Testing imports +import support +if __name__ == '__main__': + support.adjust_path() # Local imports (XXX should become a package) import pytree -class TestNodes(unittest.TestCase): +class TestNodes(support.TestCase): """Unit tests for nodes (Base, Leaf, Node).""" @@ -117,7 +119,7 @@ pass -class TestPatterns(unittest.TestCase): +class TestPatterns(support.TestCase): """Unit tests for tree matching patterns.""" @@ -233,7 +235,5 @@ if __name__ == "__main__": - import sys - if not sys.argv[1:]: - sys.argv.append("-v") - unittest.main() + import __main__ + support.run_all_tests(__main__) From python-checkins at python.org Wed Feb 28 01:41:11 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 01:41:11 +0100 (CET) Subject: [Python-checkins] r54011 - python/branches/p3yk_no_args_on_exc Message-ID: <20070228004111.AB2EE1E4011@bag.python.org> Author: brett.cannon Date: Wed Feb 28 01:41:10 2007 New Revision: 54011 Added: python/branches/p3yk_no_args_on_exc/ - copied from r54010, python/branches/p3yk/ Log: Start a branch for working on removing the 'args' attribute from BaseException (assuming I don't lose my sanity before the work is done). From python-checkins at python.org Wed Feb 28 01:56:02 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 01:56:02 +0100 (CET) Subject: [Python-checkins] r54012 - python/branches/p3yk_no_args_on_exc Message-ID: <20070228005602.F0FF41E4002@bag.python.org> Author: brett.cannon Date: Wed Feb 28 01:56:00 2007 New Revision: 54012 Modified: python/branches/p3yk_no_args_on_exc/ (props changed) Log: svnmerge init. From python-checkins at python.org Wed Feb 28 02:04:24 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 02:04:24 +0100 (CET) Subject: [Python-checkins] r54013 - in python/branches/p3yk_no_args_on_exc: Include/pyerrors.h Lib/test/test_exception_variations.py Lib/test/test_exceptions.py Lib/test/test_pep352.py Misc/NEWS Objects/exceptions.c Message-ID: <20070228010424.C08291E4009@bag.python.org> Author: brett.cannon Date: Wed Feb 28 02:04:17 2007 New Revision: 54013 Modified: python/branches/p3yk_no_args_on_exc/Include/pyerrors.h python/branches/p3yk_no_args_on_exc/Lib/test/test_exception_variations.py python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py python/branches/p3yk_no_args_on_exc/Lib/test/test_pep352.py python/branches/p3yk_no_args_on_exc/Misc/NEWS python/branches/p3yk_no_args_on_exc/Objects/exceptions.c Log: Checkpoint of PyCon work done in local copy of p3yk. Modified: python/branches/p3yk_no_args_on_exc/Include/pyerrors.h ============================================================================== --- python/branches/p3yk_no_args_on_exc/Include/pyerrors.h (original) +++ python/branches/p3yk_no_args_on_exc/Include/pyerrors.h Wed Feb 28 02:04:17 2007 @@ -9,14 +9,12 @@ typedef struct { PyObject_HEAD PyObject *dict; - PyObject *args; PyObject *message; } PyBaseExceptionObject; typedef struct { PyObject_HEAD PyObject *dict; - PyObject *args; PyObject *message; PyObject *msg; PyObject *filename; @@ -30,7 +28,6 @@ typedef struct { PyObject_HEAD PyObject *dict; - PyObject *args; PyObject *message; PyObject *encoding; PyObject *object; @@ -43,7 +40,6 @@ typedef struct { PyObject_HEAD PyObject *dict; - PyObject *args; PyObject *message; PyObject *code; } PySystemExitObject; @@ -51,7 +47,6 @@ typedef struct { PyObject_HEAD PyObject *dict; - PyObject *args; PyObject *message; PyObject *myerrno; PyObject *strerror; @@ -62,7 +57,6 @@ typedef struct { PyObject_HEAD PyObject *dict; - PyObject *args; PyObject *message; PyObject *myerrno; PyObject *strerror; Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_exception_variations.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_exception_variations.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_exception_variations.py Wed Feb 28 02:04:17 2007 @@ -1,4 +1,3 @@ - from test.test_support import run_unittest import unittest Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py Wed Feb 28 02:04:17 2007 @@ -203,71 +203,51 @@ # test that exception attributes are happy exceptionList = [ - (BaseException, (), {'message' : '', 'args' : ()}), - (BaseException, (1, ), {'message' : 1, 'args' : (1,)}), + (BaseException, (), {'message' : ''}), + (BaseException, (1, ), {'message' : 1}), (BaseException, ('foo',), - {'message' : 'foo', 'args' : ('foo',)}), - (BaseException, ('foo', 1), - {'message' : '', 'args' : ('foo', 1)}), + {'message' : 'foo'}), (SystemExit, ('foo',), - {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}), + {'message' : 'foo', 'code' : 'foo'}), (IOError, ('foo',), - {'message' : 'foo', 'args' : ('foo',), 'filename' : None, - 'errno' : None, 'strerror' : None}), + {'message' : 'foo', 'filename' : None, 'errno' : 'foo', + 'strerror' : None}), (IOError, ('foo', 'bar'), - {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None, - 'errno' : 'foo', 'strerror' : 'bar'}), + {'message' : 'foo', 'filename' : None, 'errno' : 'foo', + 'strerror' : 'bar'}), (IOError, ('foo', 'bar', 'baz'), - {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz', - 'errno' : 'foo', 'strerror' : 'bar'}), - (IOError, ('foo', 'bar', 'baz', 'quux'), - {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}), + {'message' : 'foo', 'filename' : 'baz', 'errno' : 'foo', + 'strerror' : 'bar'}), (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'), - {'message' : '', 'args' : ('errnoStr', 'strErrorStr'), - 'strerror' : 'strErrorStr', 'errno' : 'errnoStr', - 'filename' : 'filenameStr'}), + {'message' : 'errnoStr', 'strerror' : 'strErrorStr', + 'errno' : 'errnoStr', 'filename' : 'filenameStr'}), (EnvironmentError, (1, 'strErrorStr', 'filenameStr'), - {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1, - 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}), + {'message' : 1, 'errno' : 1, 'strerror' : 'strErrorStr', + 'filename' : 'filenameStr'}), (SyntaxError, ('msgStr',), - {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None, - 'print_file_and_line' : None, 'msg' : 'msgStr', + {'message' : 'msgStr', 'text' : None, + 'print_file_and_line' : None, 'msg' : 'msgStr', 'filename' : None, 'lineno' : None, 'offset' : None}), (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', 'textStr')), - {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr', - 'args' : ('msgStr', ('filenameStr', 'linenoStr', - 'offsetStr', 'textStr')), + {'message' : 'msgStr', 'offset' : 'offsetStr', 'text' : 'textStr', 'print_file_and_line' : None, 'msg' : 'msgStr', 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}), - (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', - 'textStr', 'print_file_and_lineStr'), - {'message' : '', 'text' : None, - 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', - 'textStr', 'print_file_and_lineStr'), - 'print_file_and_line' : None, 'msg' : 'msgStr', - 'filename' : None, 'lineno' : None, 'offset' : None}), - (UnicodeError, (), {'message' : '', 'args' : (),}), + (UnicodeError, (), {'message' : ''}), (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'), - {'message' : '', 'args' : ('ascii', u'a', 0, 1, - 'ordinal not in range'), - 'encoding' : 'ascii', 'object' : u'a', + {'message' : 'ascii', 'encoding' : 'ascii', 'object' : u'a', 'start' : 0, 'reason' : 'ordinal not in range'}), (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'), - {'message' : '', 'args' : ('ascii', '\xff', 0, 1, - 'ordinal not in range'), - 'encoding' : 'ascii', 'object' : '\xff', + {'message' : 'ascii', 'encoding' : 'ascii', 'object' : '\xff', 'start' : 0, 'reason' : 'ordinal not in range'}), (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"), - {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'), - 'object' : u'\u3042', 'reason' : 'ouch', + {'message' : u"\u3042", 'object' : u'\u3042', 'reason' : 'ouch', 'start' : 0, 'end' : 1}), ] try: exceptionList.append( (WindowsError, (1, 'strErrorStr', 'filenameStr'), - {'message' : '', 'args' : (1, 'strErrorStr'), - 'strerror' : 'strErrorStr', 'winerror' : 1, + {'message' : 1, 'strerror' : 'strErrorStr', 'winerror' : 1, 'errno' : 22, 'filename' : 'filenameStr'}) ) except NameError: @@ -279,15 +259,17 @@ except BaseException as e: if type(e) is not exc: raise + print(repr(e), ':', args) # Verify module name self.assertEquals(type(e).__module__, '__builtin__') # Verify no ref leaks in Exc_str() s = str(e) for checkArgName in expected: - self.assertEquals(repr(getattr(e, checkArgName)), - repr(expected[checkArgName]), - 'exception "%s", attribute "%s"' % - (repr(e), checkArgName)) + got = repr(getattr(e, checkArgName)) + want = repr(expected[checkArgName]) + self.assertEquals(got, want, + 'exception "%s", attribute %s: %r != %r' % + (repr(e), checkArgName, got, want)) # test for pickling support for p in pickle, cPickle: @@ -299,8 +281,9 @@ got = repr(getattr(new, checkArgName)) want = repr(expected[checkArgName]) self.assertEquals(got, want, - 'pickled "%r", attribute "%s' % - (e, checkArgName)) + 'pickled "%r", attribute %s: ' + '%r != %r' % + (e, checkArgName, got, want)) def testKeywordArgs(self): # test that builtin exception don't take keyword args, Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_pep352.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_pep352.py Wed Feb 28 02:04:17 2007 @@ -14,7 +14,7 @@ self.failUnless(issubclass(Exception, object)) def verify_instance_interface(self, ins): - for attr in ("args", "message", "__str__", "__repr__"): + for attr in ("message", "__str__", "__repr__"): self.failUnless(hasattr(ins, attr), "%s missing %s attribute" % (ins.__class__.__name__, attr)) @@ -27,7 +27,6 @@ exc_set.add(object_.__name__) except TypeError: pass - inheritance_tree = open(os.path.join(os.path.split(__file__)[0], 'exception_hierarchy.txt')) try: @@ -78,39 +77,37 @@ inheritance_tree.close() self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set) - interface_tests = ("length", "args", "message", "str", "unicode", "repr") + interface_tests = ("message", "str", "unicode", "repr") def interface_test_driver(self, results): for test_name, (given, expected) in zip(self.interface_tests, results): self.failUnlessEqual(given, expected, "%s: %s != %s" % (test_name, given, expected)) + def make_repr(self, exc, message=None): + """Generate the expected str/repr of an exception based on the message + and a converter function.""" + name = exc.__class__.__name__ + if message: + args = '(%r)' % message + else: + args = '()' + return name + args + def test_interface_single_arg(self): # Make sure interface works properly when given a single argument arg = "spam" exc = Exception(arg) - results = ([len(exc.args), 1], [exc.args[0], arg], [exc.message, arg], - [str(exc), str(arg)], [unicode(exc), unicode(arg)], - [repr(exc), exc.__class__.__name__ + repr(exc.args)]) - self.interface_test_driver(results) - - def test_interface_multi_arg(self): - # Make sure interface correct when multiple arguments given - arg_count = 3 - args = tuple(range(arg_count)) - exc = Exception(*args) - results = ([len(exc.args), arg_count], [exc.args, args], - [exc.message, ''], [str(exc), str(args)], - [unicode(exc), unicode(args)], - [repr(exc), exc.__class__.__name__ + repr(exc.args)]) + results = ([exc.message, arg], [str(exc), str(arg)], + [unicode(exc), unicode(arg)], + [repr(exc), self.make_repr(exc, arg)]) self.interface_test_driver(results) def test_interface_no_arg(self): # Make sure that with no args that interface is correct exc = Exception() - results = ([len(exc.args), 0], [exc.args, tuple()], [exc.message, ''], - [str(exc), ''], [unicode(exc), u''], - [repr(exc), exc.__class__.__name__ + '()']) + results = ([exc.message, ''], [str(exc), ''], [unicode(exc), u''], + [repr(exc), self.make_repr(exc)]) self.interface_test_driver(results) class UsageTests(unittest.TestCase): Modified: python/branches/p3yk_no_args_on_exc/Misc/NEWS ============================================================================== --- python/branches/p3yk_no_args_on_exc/Misc/NEWS (original) +++ python/branches/p3yk_no_args_on_exc/Misc/NEWS Wed Feb 28 02:04:17 2007 @@ -28,7 +28,13 @@ Core and Builtins ----------------- -- Removing indexing/slicing on BaseException. +- SyntaxError now enforces the requirement of having two arguments, second of + which is a four-item tuple. + +- EnvironmentError always binds its first argument to 'message' and 'errno'. + Also don't call with no more than 3 arguments. + +- Remove indexing/slicing on BaseException. - Remove the exceptions module, all the exceptions are already builtin. Modified: python/branches/p3yk_no_args_on_exc/Objects/exceptions.c ============================================================================== --- python/branches/p3yk_no_args_on_exc/Objects/exceptions.c (original) +++ python/branches/p3yk_no_args_on_exc/Objects/exceptions.c Wed Feb 28 02:04:17 2007 @@ -9,8 +9,6 @@ #include "structmember.h" #include "osdefs.h" -#define MAKE_IT_NONE(x) (x) = Py_None; Py_INCREF(Py_None); - /* NOTE: If the exception class hierarchy changes, don't forget to update * Lib/test/exception_hierarchy.txt */ @@ -27,12 +25,6 @@ /* the dict is created on the fly in PyObject_GenericSetAttr */ self->message = self->dict = NULL; - self->args = PyTuple_New(0); - if (!self->args) { - Py_DECREF(self); - return NULL; - } - self->message = PyString_FromString(""); if (!self->message) { Py_DECREF(self); @@ -45,26 +37,50 @@ static int BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds) { + PyObject *message = NULL; + if (!_PyArg_NoKeywords(self->ob_type->tp_name, kwds)) return -1; - Py_DECREF(self->args); - self->args = args; - Py_INCREF(self->args); - - if (PyTuple_GET_SIZE(self->args) == 1) { - Py_CLEAR(self->message); - self->message = PyTuple_GET_ITEM(self->args, 0); - Py_INCREF(self->message); + if (!PyArg_ParseTuple(args, "|O", &message)) + return -1; + + if (message) { + Py_CLEAR(self->message); + self->message = message; + Py_INCREF(self->message); } + return 0; } static int +BaseException_super_init(PyBaseExceptionObject *self, PyObject *args, + PyObject *kwds) +{ + PyObject *short_tuple = NULL; + PyObject *tuple_item = NULL; + int ret; + + /* BaseException.__init__ can handle an argument tuple of length 0 or 1. */ + if (PyTuple_GET_SIZE(args) <= 1) + return BaseException_init(self, args, kwds); + + short_tuple = PyTuple_New(1); + if (!short_tuple) + return -1; + tuple_item = PyTuple_GET_ITEM(args, 0); + PyTuple_SET_ITEM(short_tuple, 0, tuple_item); + Py_INCREF(tuple_item); + ret = BaseException_init(self, short_tuple, kwds); + Py_DECREF(short_tuple); + return ret; +} + +static int BaseException_clear(PyBaseExceptionObject *self) { Py_CLEAR(self->dict); - Py_CLEAR(self->args); Py_CLEAR(self->message); return 0; } @@ -81,7 +97,6 @@ BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg) { Py_VISIT(self->dict); - Py_VISIT(self->args); Py_VISIT(self->message); return 0; } @@ -89,34 +104,34 @@ static PyObject * BaseException_str(PyBaseExceptionObject *self) { - PyObject *out; - - switch (PyTuple_GET_SIZE(self->args)) { - case 0: - out = PyString_FromString(""); - break; - case 1: - out = PyObject_Str(PyTuple_GET_ITEM(self->args, 0)); - break; - default: - out = PyObject_Str(self->args); - break; - } - - return out; + return PyObject_Str(self->message); } static PyObject * BaseException_repr(PyBaseExceptionObject *self) { PyObject *repr_suffix; + PyObject *message_repr; PyObject *repr; char *name; char *dot; - repr_suffix = PyObject_Repr(self->args); - if (!repr_suffix) - return NULL; + if (PyString_Check(self->message) && PyString_Size(self->message) == 0) { + repr_suffix = PyString_FromString("()"); + } + else { + message_repr = PyObject_Repr(self->message); + if (!message_repr) + return NULL; + + repr_suffix = PyString_FromFormat("(%s)", + PyString_AS_STRING(message_repr)); + if (!repr_suffix) { + Py_DECREF(message_repr); + return NULL; + } + Py_DECREF(message_repr); + } name = (char *)self->ob_type->tp_name; dot = strrchr(name, '.'); @@ -136,10 +151,11 @@ static PyObject * BaseException_reduce(PyBaseExceptionObject *self) { - if (self->args && self->dict) - return PyTuple_Pack(3, self->ob_type, self->args, self->dict); + if (self->dict) + return Py_BuildValue("(O, (O), O)", self->ob_type, self->message, + self->dict); else - return PyTuple_Pack(2, self->ob_type, self->args); + return Py_BuildValue("(O, (O))", self->ob_type, self->message); } /* @@ -210,35 +226,9 @@ return 0; } -static PyObject * -BaseException_get_args(PyBaseExceptionObject *self) -{ - if (self->args == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(self->args); - return self->args; -} - -static int -BaseException_set_args(PyBaseExceptionObject *self, PyObject *val) -{ - PyObject *seq; - if (val == NULL) { - PyErr_SetString(PyExc_TypeError, "args may not be deleted"); - return -1; - } - seq = PySequence_Tuple(val); - if (!seq) return -1; - Py_CLEAR(self->args); - self->args = seq; - return 0; -} static PyGetSetDef BaseException_getset[] = { {"__dict__", (getter)BaseException_get_dict, (setter)BaseException_set_dict}, - {"args", (getter)BaseException_get_args, (setter)BaseException_set_args}, {NULL}, }; @@ -388,7 +378,8 @@ { Py_ssize_t size = PyTuple_GET_SIZE(args); - if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) + if (BaseException_super_init((PyBaseExceptionObject *)self, args, kwds) == + -1) return -1; if (size == 0) @@ -453,29 +444,26 @@ /* * EnvironmentError extends StandardError */ - -/* Where a function has a single filename, such as open() or some - * of the os module functions, PyErr_SetFromErrnoWithFilename() is - * called, giving a third argument which is the filename. But, so - * that old code using in-place unpacking doesn't break, e.g.: - * - * except IOError, (errno, strerror): - * - * we hack args so that it only contains two items. This also - * means we need our own __str__() which prints out the filename - * when it was supplied. - */ static int EnvironmentError_init(PyEnvironmentErrorObject *self, PyObject *args, PyObject *kwds) { PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL; - PyObject *subslice = NULL; + Py_ssize_t args_len = 0; - if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) + if (BaseException_super_init((PyBaseExceptionObject *)self, args, kwds) == + -1) return -1; - if (PyTuple_GET_SIZE(args) <= 1 || PyTuple_GET_SIZE(args) > 3) { + args_len = PyTuple_GET_SIZE(args); + + if (args_len == 0 || args_len == 1) { + Py_INCREF(self->message); + self->myerrno = self->message; + Py_INCREF(Py_None); + self->strerror = Py_None; + Py_INCREF(Py_None); + self->filename = Py_None; return 0; } @@ -496,13 +484,10 @@ Py_CLEAR(self->filename); /* replacing */ self->filename = filename; Py_INCREF(self->filename); - - subslice = PyTuple_GetSlice(args, 0, 2); - if (!subslice) - return -1; - - Py_DECREF(self->args); /* replacing args */ - self->args = subslice; + } + else { + Py_INCREF(Py_None); + self->filename = Py_None; } return 0; } @@ -560,22 +545,11 @@ return NULL; } - if (self->myerrno) { - Py_INCREF(self->myerrno); - PyTuple_SET_ITEM(tuple, 0, self->myerrno); - } - else { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(tuple, 0, Py_None); - } - if (self->strerror) { - Py_INCREF(self->strerror); - PyTuple_SET_ITEM(tuple, 1, self->strerror); - } - else { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(tuple, 1, Py_None); - } + Py_INCREF(self->myerrno); + PyTuple_SET_ITEM(tuple, 0, self->myerrno); + + Py_INCREF(self->strerror); + PyTuple_SET_ITEM(tuple, 1, self->strerror); PyTuple_SET_ITEM(tuple, 2, repr); @@ -642,27 +616,26 @@ static PyObject * EnvironmentError_reduce(PyEnvironmentErrorObject *self) { - PyObject *args = self->args; - PyObject *res = NULL, *tmp; + PyObject *args = PyTuple_New(3); + PyObject *res = NULL; + + if (!args) + return NULL; + + if (self->myerrno == Py_None) { + Py_INCREF(self->message); + PyTuple_SET_ITEM(args, 0, self->message); + } + else { + Py_INCREF(self->myerrno); + PyTuple_SET_ITEM(args, 0, self->myerrno); + } - /* self->args is only the first two real arguments if there was a - * file name given to EnvironmentError. */ - if (PyTuple_GET_SIZE(args) == 2 && self->filename) { - args = PyTuple_New(3); - if (!args) return NULL; - - tmp = PyTuple_GET_ITEM(self->args, 0); - Py_INCREF(tmp); - PyTuple_SET_ITEM(args, 0, tmp); - - tmp = PyTuple_GET_ITEM(self->args, 1); - Py_INCREF(tmp); - PyTuple_SET_ITEM(args, 1, tmp); + Py_INCREF(self->strerror); + PyTuple_SET_ITEM(args, 1, self->strerror); Py_INCREF(self->filename); PyTuple_SET_ITEM(args, 2, self->filename); - } else - Py_INCREF(args); if (self->dict) res = PyTuple_Pack(3, self->ob_type, args, self->dict); @@ -938,15 +911,25 @@ PyObject *info = NULL; Py_ssize_t lenargs = PyTuple_GET_SIZE(args); - if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) + if (BaseException_super_init((PyBaseExceptionObject *)self, args, kwds) == + -1) return -1; - if (lenargs >= 1) { - Py_CLEAR(self->msg); - self->msg = PyTuple_GET_ITEM(args, 0); - Py_INCREF(self->msg); + Py_CLEAR(self->msg); + self->msg = self->message; + Py_INCREF(self->msg); + + if (lenargs == 1) { + Py_INCREF(Py_None); + self->filename = Py_None; + Py_INCREF(Py_None); + self->lineno = Py_None; + Py_INCREF(Py_None); + self->offset = Py_None; + Py_INCREF(Py_None); + self->text = Py_None; } - if (lenargs == 2) { + else if (lenargs == 2) { info = PyTuple_GET_ITEM(args, 1); info = PySequence_Tuple(info); if (!info) return -1; @@ -976,6 +959,10 @@ Py_DECREF(info); } + else { + PyErr_SetString(PyExc_TypeError, "expect either 0, 1, or 2 arguments"); + return -1; + } return 0; } @@ -1091,6 +1078,26 @@ return result; } + +static PyObject * +SyntaxError_reduce(PySyntaxErrorObject *self) +{ + if (self->dict) + return Py_BuildValue("(O, (O, (O, O, O, O)), O)", self->ob_type, + self->message, self->filename, self->lineno, + self->offset, self->text, self->dict); + else + return Py_BuildValue("(O, (O, (O, O, O, O)))", self->ob_type, + self->message, self->filename, self->lineno, + self->offset, self->text); +} + + +static PyMethodDef SyntaxError_methods[] = { + {"__reduce__", (PyCFunction)SyntaxError_reduce, METH_NOARGS}, + {NULL} +}; + static PyMemberDef SyntaxError_members[] = { {"message", T_OBJECT, offsetof(PySyntaxErrorObject, message), 0, PyDoc_STR("exception message")}, @@ -1110,9 +1117,11 @@ {NULL} /* Sentinel */ }; + ComplexExtendsException(PyExc_StandardError, SyntaxError, SyntaxError, - SyntaxError_dealloc, 0, SyntaxError_members, - SyntaxError_str, "Invalid syntax."); + SyntaxError_dealloc, SyntaxError_methods, + SyntaxError_members, SyntaxError_str, + "Invalid syntax."); /* @@ -1158,9 +1167,9 @@ string, that string will be displayed in quotes. Too bad. If args is anything else, use the default BaseException__str__(). */ - if (PyTuple_GET_SIZE(self->args) == 1) { - return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0)); - } + if (PyString_Check(self->message) && PyString_Size(self->message) == 0) + return PyObject_Repr(self->message); + return BaseException_str(self); } @@ -1549,7 +1558,8 @@ static int UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds) { - if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) + if (BaseException_super_init((PyBaseExceptionObject *)self, args, kwds) == + -1) return -1; return UnicodeError_init((PyUnicodeErrorObject *)self, args, kwds, &PyUnicode_Type); @@ -1625,7 +1635,8 @@ static int UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds) { - if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) + if (BaseException_super_init((PyBaseExceptionObject *)self, args, kwds) == + -1) return -1; return UnicodeError_init((PyUnicodeErrorObject *)self, args, kwds, &PyString_Type); @@ -1701,7 +1712,8 @@ UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args, PyObject *kwds) { - if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) + if (BaseException_super_init((PyBaseExceptionObject *)self, args, kwds) == + -1) return -1; Py_CLEAR(self->object); From python-checkins at python.org Wed Feb 28 02:33:52 2007 From: python-checkins at python.org (collin.winter) Date: Wed, 28 Feb 2007 02:33:52 +0100 (CET) Subject: [Python-checkins] r54014 - sandbox/trunk/2to3/tests/support.py sandbox/trunk/2to3/tests/test_fixers.py Message-ID: <20070228013352.46A621E4009@bag.python.org> Author: collin.winter Date: Wed Feb 28 02:33:51 2007 New Revision: 54014 Modified: sandbox/trunk/2to3/tests/support.py sandbox/trunk/2to3/tests/test_fixers.py Log: Move reformat() into tests.support Modified: sandbox/trunk/2to3/tests/support.py ============================================================================== --- sandbox/trunk/2to3/tests/support.py (original) +++ sandbox/trunk/2to3/tests/support.py Wed Feb 28 02:33:51 2007 @@ -4,14 +4,26 @@ import unittest import sys import os.path +import re + +TestCase = unittest.TestCase def run_all_tests(test_mod=None, tests=None): if tests is None: tests = unittest.TestLoader().loadTestsFromModule(test_mod) unittest.TextTestRunner(verbosity=2).run(tests) + def adjust_path(): parent_dir = os.path.split(sys.path[0])[0] sys.path = [parent_dir] + sys.path -TestCase = unittest.TestCase + +skip_whitespace = re.compile(r"""\S""") +def reformat(string): + indent = re.search(skip_whitespace, string).start() + if indent == 0: + code = string + else: + code = "\n".join(line[indent-1:] for line in string.split("\n")[1:]) + return code + "\n\n" Modified: sandbox/trunk/2to3/tests/test_fixers.py ============================================================================== --- sandbox/trunk/2to3/tests/test_fixers.py (original) +++ sandbox/trunk/2to3/tests/test_fixers.py Wed Feb 28 02:33:51 2007 @@ -9,7 +9,6 @@ # Python imports from StringIO import StringIO -import re import unittest import logging @@ -17,16 +16,6 @@ import pytree import refactor -skip_whitespace = re.compile(r"""\S""") - -def reformat(string): - indent = re.search(skip_whitespace, string).start() - if indent == 0: - code = string - else: - code = "\n".join(line[indent-1:] for line in string.split("\n")[1:]) - return code + "\n\n" - # We wrap the RefactoringTool's fixer objects so we can intercept # the call to set_filename() and so modify the fixers' logging objects. # This allows us to make sure that certain code chunks produce certain @@ -61,8 +50,8 @@ self.refactor.fixers = [Fixer(f, sh) for f in self.refactor.fixers] def check(self, before, after): - before = reformat(before) - after = reformat(after) + before = support.reformat(before) + after = support.reformat(after) refactored = self.refactor_stream("", StringIO(before)) self.failUnlessEqual(after, refactored) From python-checkins at python.org Wed Feb 28 05:56:21 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 05:56:21 +0100 (CET) Subject: [Python-checkins] r54015 - in python/branches/p3yk_no_args_on_exc: Lib/test/test_exceptions.py Objects/exceptions.c Message-ID: <20070228045621.26CC91E4009@bag.python.org> Author: brett.cannon Date: Wed Feb 28 05:56:17 2007 New Revision: 54015 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py python/branches/p3yk_no_args_on_exc/Objects/exceptions.c Log: Get 'args' removal from exceptions to be able to pass test_exceptions, test_exception_variations, and test_pep352. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py Wed Feb 28 05:56:17 2007 @@ -259,7 +259,6 @@ except BaseException as e: if type(e) is not exc: raise - print(repr(e), ':', args) # Verify module name self.assertEquals(type(e).__module__, '__builtin__') # Verify no ref leaks in Exc_str() Modified: python/branches/p3yk_no_args_on_exc/Objects/exceptions.c ============================================================================== --- python/branches/p3yk_no_args_on_exc/Objects/exceptions.c (original) +++ python/branches/p3yk_no_args_on_exc/Objects/exceptions.c Wed Feb 28 05:56:17 2007 @@ -1534,6 +1534,27 @@ return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg); } + +static PyObject * +UnicodeError_reduce(PyUnicodeErrorObject *self) +{ + if (self->dict) + return Py_BuildValue("(O, (O, O, O, O, O), O)", self->ob_type, + self->encoding, self->object, self->start, + self->end, self->reason, self->dict); + else + return Py_BuildValue("(O, (O, O, O, O, O))", self->ob_type, + self->encoding, self->object, self->start, + self->end, self->reason); + +} + + +static PyMethodDef UnicodeError_methods[] = { + {"__reduce__", (PyCFunction)UnicodeError_reduce, METH_NOARGS}, + {NULL} +}; + static PyMemberDef UnicodeError_members[] = { {"message", T_OBJECT, offsetof(PyUnicodeErrorObject, message), 0, PyDoc_STR("exception message")}, @@ -1612,8 +1633,9 @@ (reprfunc)UnicodeEncodeError_str, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse, - (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, - 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), + (inquiry)UnicodeError_clear, 0, 0, 0, 0, UnicodeError_methods, + UnicodeError_members, 0, &_PyExc_UnicodeError, 0, 0, 0, + offsetof(PyUnicodeErrorObject, dict), (initproc)UnicodeEncodeError_init, 0, BaseException_new, }; PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError; @@ -1685,9 +1707,10 @@ (reprfunc)UnicodeDecodeError_str, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse, - (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, - 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), - (initproc)UnicodeDecodeError_init, 0, BaseException_new, + (inquiry)UnicodeError_clear, 0, 0, 0, 0, UnicodeError_methods, + UnicodeError_members, 0, &_PyExc_UnicodeError, 0, 0, 0, + offsetof(PyUnicodeErrorObject, dict), (initproc)UnicodeDecodeError_init, 0, + BaseException_new, }; PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError; @@ -1775,6 +1798,27 @@ ); } + +static PyObject * +UnicodeTranslateError_reduce(PyUnicodeErrorObject *self) +{ + if (self->dict) + return Py_BuildValue("(O, (O, O, O, O), O)", self->ob_type, + self->object, self->start, self->end, + self->reason, self->dict); + else + return Py_BuildValue("(O, (O, O, O, O))", self->ob_type, + self->object, self->start, self->end, + self->reason); +} + + +static PyMethodDef UnicodeTranslateError_methods[] = { + {"__reduce__", (PyCFunction)UnicodeTranslateError_reduce, METH_NOARGS}, + {NULL} +}; + + static PyTypeObject _PyExc_UnicodeTranslateError = { PyObject_HEAD_INIT(NULL) 0, @@ -1784,8 +1828,9 @@ (reprfunc)UnicodeTranslateError_str, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse, - (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, - 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), + (inquiry)UnicodeError_clear, 0, 0, 0, 0, UnicodeTranslateError_methods, + UnicodeError_members, 0, &_PyExc_UnicodeError, 0, 0, 0, + offsetof(PyUnicodeErrorObject, dict), (initproc)UnicodeTranslateError_init, 0, BaseException_new, }; PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError; From python-checkins at python.org Wed Feb 28 10:25:31 2007 From: python-checkins at python.org (armin.rigo) Date: Wed, 28 Feb 2007 10:25:31 +0100 (CET) Subject: [Python-checkins] r54016 - python/trunk/Lib/test/crashers/modify_dict_attr.py Message-ID: <20070228092531.41F761E401A@bag.python.org> Author: armin.rigo Date: Wed Feb 28 10:25:29 2007 New Revision: 54016 Added: python/trunk/Lib/test/crashers/modify_dict_attr.py - copied, changed from r53996, python/trunk/Lib/test/crashers/modify_dict_attr.py Log: Modify the segfaulting example to show why r53997 is not a solution to it. Copied: python/trunk/Lib/test/crashers/modify_dict_attr.py (from r53996, python/trunk/Lib/test/crashers/modify_dict_attr.py) ============================================================================== --- python/trunk/Lib/test/crashers/modify_dict_attr.py (original) +++ python/trunk/Lib/test/crashers/modify_dict_attr.py Wed Feb 28 10:25:29 2007 @@ -4,16 +4,17 @@ class Y(object): pass -class type_with_modifiable_dict(Y, type): +class type_with_modifiable_dict(type, Y): pass class MyClass(object): - """This class has its __dict__ attribute completely exposed: - user code can read, reassign and even delete it. + """This class has its __dict__ attribute indirectly + exposed via the __dict__ getter/setter of Y. """ __metaclass__ = type_with_modifiable_dict if __name__ == '__main__': - del MyClass.__dict__ # if we set tp_dict to NULL, + dictattr = Y.__dict__['__dict__'] + dictattr.__delete__(MyClass) # if we set tp_dict to NULL, print MyClass # doing anything with MyClass segfaults From python-checkins at python.org Wed Feb 28 18:15:12 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 18:15:12 +0100 (CET) Subject: [Python-checkins] r54017 - python/branches/p3yk_no_args_on_exc/Lib/test/test_grammar.py Message-ID: <20070228171512.00F191E4003@bag.python.org> Author: brett.cannon Date: Wed Feb 28 18:15:10 2007 New Revision: 54017 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_grammar.py Log: Make test_grammar pass for the removal of BaseException.args. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_grammar.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_grammar.py Wed Feb 28 18:15:10 2007 @@ -492,7 +492,7 @@ try: assert 0, "msg" except AssertionError as e: - self.assertEquals(e.args[0], "msg") + self.assertEquals(e.message, "msg") else: if __debug__: self.fail("AssertionError not raised by assert 0") From python-checkins at python.org Wed Feb 28 18:37:57 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 18:37:57 +0100 (CET) Subject: [Python-checkins] r54018 - python/branches/p3yk_no_args_on_exc/Lib/test/test_cgi.py python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py Message-ID: <20070228173757.985531E4003@bag.python.org> Author: brett.cannon Date: Wed Feb 28 18:37:52 2007 New Revision: 54018 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_cgi.py python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py Log: Fixes for BaseException.args removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_cgi.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_cgi.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_cgi.py Wed Feb 28 18:37:52 2007 @@ -30,7 +30,7 @@ if not isinstance(anExc, Exception): return NotImplemented return (self.err.__class__ == anExc.__class__ and - self.err.args == anExc.args) + self.err.message == anExc.message) def __getattr__(self, attr): return getattr(self.err, attr) Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py Wed Feb 28 18:37:52 2007 @@ -50,9 +50,7 @@ try: compiler.compile(buf, basename, "exec") except Exception as e: - args = list(e.args) - args[0] += "[in file %s]" % basename - e.args = tuple(args) + args.message += "[in file %s]" % basename raise def testNewClassSyntax(self): From python-checkins at python.org Wed Feb 28 18:39:09 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 18:39:09 +0100 (CET) Subject: [Python-checkins] r54019 - python/branches/p3yk_no_args_on_exc/Lib/test/test_contextlib.py Message-ID: <20070228173909.210ED1E4003@bag.python.org> Author: brett.cannon Date: Wed Feb 28 18:39:04 2007 New Revision: 54019 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_contextlib.py Log: Another BaseException.args removal fix. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_contextlib.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_contextlib.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_contextlib.py Wed Feb 28 18:39:04 2007 @@ -77,7 +77,7 @@ try: yield 42 except ZeroDivisionError as e: - state.append(e.args[0]) + state.append(e.message) self.assertEqual(state, [1, 42, 999]) with woohoo() as x: self.assertEqual(state, [1]) From python-checkins at python.org Wed Feb 28 18:39:54 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 18:39:54 +0100 (CET) Subject: [Python-checkins] r54020 - python/branches/p3yk_no_args_on_exc/Lib/test/test_defaultdict.py Message-ID: <20070228173954.4690F1E4003@bag.python.org> Author: brett.cannon Date: Wed Feb 28 18:39:53 2007 New Revision: 54020 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_defaultdict.py Log: Fix for BaseException.args removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_defaultdict.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_defaultdict.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_defaultdict.py Wed Feb 28 18:39:53 2007 @@ -44,7 +44,7 @@ try: d2[15] except KeyError as err: - self.assertEqual(err.args, (15,)) + self.assertEqual(err.message, 15) else: self.fail("d2[15] didn't raise KeyError") self.assertRaises(TypeError, defaultdict, 1) From python-checkins at python.org Wed Feb 28 19:15:04 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 19:15:04 +0100 (CET) Subject: [Python-checkins] r54022 - python/trunk/Lib/test/test_exceptions.py Message-ID: <20070228181504.EB7E71E4003@bag.python.org> Author: brett.cannon Date: Wed Feb 28 19:15:00 2007 New Revision: 54022 Modified: python/trunk/Lib/test/test_exceptions.py Log: Add a test for instantiating SyntaxError with no arguments. Modified: python/trunk/Lib/test/test_exceptions.py ============================================================================== --- python/trunk/Lib/test/test_exceptions.py (original) +++ python/trunk/Lib/test/test_exceptions.py Wed Feb 28 19:15:00 2007 @@ -225,6 +225,9 @@ (EnvironmentError, (1, 'strErrorStr', 'filenameStr'), {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1, 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}), + (SyntaxError, (), {'message' : '', 'msg' : None, 'text' : None, + 'filename' : None, 'lineno' : None, 'offset' : None, + 'print_file_and_line' : None}), (SyntaxError, ('msgStr',), {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None, 'print_file_and_line' : None, 'msg' : 'msgStr', From python-checkins at python.org Wed Feb 28 19:15:38 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 19:15:38 +0100 (CET) Subject: [Python-checkins] r54023 - in python/branches/p3yk_no_args_on_exc: Lib/test/test_exceptions.py Objects/exceptions.c Message-ID: <20070228181538.501DF1E4003@bag.python.org> Author: brett.cannon Date: Wed Feb 28 19:15:35 2007 New Revision: 54023 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py python/branches/p3yk_no_args_on_exc/Objects/exceptions.c Log: Allow SyntaxError to be instantiated with no arguments. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_exceptions.py Wed Feb 28 19:15:35 2007 @@ -224,6 +224,9 @@ (EnvironmentError, (1, 'strErrorStr', 'filenameStr'), {'message' : 1, 'errno' : 1, 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}), + (SyntaxError, (), {'message' : '', 'text' : None, + 'print_file_and_line' : None, 'msg' : '', 'filename' : None, + 'lineno' : None, 'offset' : None}), (SyntaxError, ('msgStr',), {'message' : 'msgStr', 'text' : None, 'print_file_and_line' : None, 'msg' : 'msgStr', Modified: python/branches/p3yk_no_args_on_exc/Objects/exceptions.c ============================================================================== --- python/branches/p3yk_no_args_on_exc/Objects/exceptions.c (original) +++ python/branches/p3yk_no_args_on_exc/Objects/exceptions.c Wed Feb 28 19:15:35 2007 @@ -919,7 +919,7 @@ self->msg = self->message; Py_INCREF(self->msg); - if (lenargs == 1) { + if (lenargs == 0 || lenargs == 1) { Py_INCREF(Py_None); self->filename = Py_None; Py_INCREF(Py_None); @@ -960,7 +960,7 @@ Py_DECREF(info); } else { - PyErr_SetString(PyExc_TypeError, "expect either 0, 1, or 2 arguments"); + PyErr_SetString(PyExc_TypeError, "0, 1, or 2 arguments required"); return -1; } return 0; From python-checkins at python.org Wed Feb 28 19:19:32 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 19:19:32 +0100 (CET) Subject: [Python-checkins] r54024 - python/branches/p3yk_no_args_on_exc/Lib/test/test_dict.py Message-ID: <20070228181932.DE49B1E4003@bag.python.org> Author: brett.cannon Date: Wed Feb 28 19:19:30 2007 New Revision: 54024 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_dict.py Log: Fix the test for the exception 'args' removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_dict.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_dict.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_dict.py Wed Feb 28 19:19:30 2007 @@ -423,7 +423,7 @@ try: e[42] except RuntimeError as err: - self.assertEqual(err.args, (42,)) + self.assertEqual(err.message, 42) else: self.fail_("e[42] didn't raise RuntimeError") class F(dict): @@ -434,7 +434,7 @@ try: f[42] except KeyError as err: - self.assertEqual(err.args, (42,)) + self.assertEqual(err.message, 42) else: self.fail_("f[42] didn't raise KeyError") class G(dict): @@ -443,7 +443,7 @@ try: g[42] except KeyError as err: - self.assertEqual(err.args, (42,)) + self.assertEqual(err.message, 42) else: self.fail_("g[42] didn't raise KeyError") @@ -453,7 +453,7 @@ try: d[(1,)] except KeyError as e: - self.assertEqual(e.args, ((1,),)) + self.assertEqual(e.message, (1,)) else: self.fail("missing KeyError") From python-checkins at python.org Wed Feb 28 19:26:32 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 19:26:32 +0100 (CET) Subject: [Python-checkins] r54025 - python/branches/p3yk_no_args_on_exc/Lib/doctest.py Message-ID: <20070228182632.004001E4004@bag.python.org> Author: brett.cannon Date: Wed Feb 28 19:26:32 2007 New Revision: 54025 Modified: python/branches/p3yk_no_args_on_exc/Lib/doctest.py Log: Fix for removal of 'args' from exceptions. Modified: python/branches/p3yk_no_args_on_exc/Lib/doctest.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/doctest.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/doctest.py Wed Feb 28 19:26:32 2007 @@ -1611,7 +1611,7 @@ >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... - KeyError + KeyError: '' We wrap the original exception to give the calling application access to the test and example information. @@ -2050,7 +2050,7 @@ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: - raise ValueError("Only reporting flags allowed", flags) + raise ValueError(("Only reporting flags allowed", flags)) old = _unittest_reportflags _unittest_reportflags = flags return old @@ -2151,7 +2151,7 @@ >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... - KeyError + KeyError: '' If the output doesn't match, then a DocTestFailure is raised: From python-checkins at python.org Wed Feb 28 19:27:43 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 28 Feb 2007 19:27:43 +0100 (CET) Subject: [Python-checkins] r54026 - python/trunk/Lib/heapq.py Message-ID: <20070228182743.0F3DA1E4003@bag.python.org> Author: raymond.hettinger Date: Wed Feb 28 19:27:41 2007 New Revision: 54026 Modified: python/trunk/Lib/heapq.py Log: Docstring nit. Modified: python/trunk/Lib/heapq.py ============================================================================== --- python/trunk/Lib/heapq.py (original) +++ python/trunk/Lib/heapq.py Wed Feb 28 19:27:41 2007 @@ -311,7 +311,7 @@ def merge(*iterables): '''Merge multiple sorted inputs into a single sorted output. - Similar to sorted(itertools.chain(*iterables)) but returns an iterable, + Similar to sorted(itertools.chain(*iterables)) but returns a generator, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). From python-checkins at python.org Wed Feb 28 19:31:05 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 19:31:05 +0100 (CET) Subject: [Python-checkins] r54027 - python/branches/p3yk_no_args_on_exc/Lib/getopt.py Message-ID: <20070228183105.10FAB1E4003@bag.python.org> Author: brett.cannon Date: Wed Feb 28 19:31:02 2007 New Revision: 54027 Modified: python/branches/p3yk_no_args_on_exc/Lib/getopt.py Log: Fix getopt for BaseException.args removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/getopt.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/getopt.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/getopt.py Wed Feb 28 19:31:02 2007 @@ -42,7 +42,7 @@ def __init__(self, msg, opt=''): self.msg = msg self.opt = opt - Exception.__init__(self, msg, opt) + Exception.__init__(self, (msg, opt)) def __str__(self): return self.msg From python-checkins at python.org Wed Feb 28 19:32:13 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 19:32:13 +0100 (CET) Subject: [Python-checkins] r54028 - python/branches/p3yk_no_args_on_exc/Lib/test/test_itertools.py Message-ID: <20070228183213.A31E21E4003@bag.python.org> Author: brett.cannon Date: Wed Feb 28 19:32:11 2007 New Revision: 54028 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_itertools.py Log: Fix for removal of 'args' from exceptions. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_itertools.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_itertools.py Wed Feb 28 19:32:11 2007 @@ -809,7 +809,7 @@ Subclass(newarg=1) except TypeError as err: # we expect type errors because of wrong argument count - self.failIf("does not take keyword arguments" in err.args[0]) + self.failIf("does not take keyword arguments" in err.message) libreftest = """ Doctest for examples in the library reference: libitertools.tex From python-checkins at python.org Wed Feb 28 19:33:39 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 19:33:39 +0100 (CET) Subject: [Python-checkins] r54029 - python/branches/p3yk_no_args_on_exc/Lib/string.py Message-ID: <20070228183339.D844A1E4004@bag.python.org> Author: brett.cannon Date: Wed Feb 28 19:33:35 2007 New Revision: 54029 Modified: python/branches/p3yk_no_args_on_exc/Lib/string.py Log: Fix for BaseException.args removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/string.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/string.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/string.py Wed Feb 28 19:33:35 2007 @@ -165,8 +165,8 @@ return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) - raise ValueError('Unrecognized named group in pattern', - self.pattern) + raise ValueError(('Unrecognized named group in pattern', + self.pattern)) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): @@ -198,8 +198,8 @@ return self.delimiter if mo.group('invalid') is not None: return self.delimiter - raise ValueError('Unrecognized named group in pattern', - self.pattern) + raise ValueError(('Unrecognized named group in pattern', + self.pattern)) return self.pattern.sub(convert, self.template) From python-checkins at python.org Wed Feb 28 19:34:47 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 19:34:47 +0100 (CET) Subject: [Python-checkins] r54030 - python/branches/p3yk_no_args_on_exc/Lib/test/test_pyexpat.py Message-ID: <20070228183447.994AF1E401D@bag.python.org> Author: brett.cannon Date: Wed Feb 28 19:34:47 2007 New Revision: 54030 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_pyexpat.py Log: Fix for BaseException.args removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_pyexpat.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_pyexpat.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_pyexpat.py Wed Feb 28 19:34:47 2007 @@ -322,7 +322,7 @@ try: parser.Parse("", 1) except RuntimeError as e: - if e.args[0] != "a": + if e.message != "a": print("Expected RuntimeError for element 'a'; found %r" % e.args[0]) else: print("Expected RuntimeError for 'a'") From python-checkins at python.org Wed Feb 28 19:36:13 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 19:36:13 +0100 (CET) Subject: [Python-checkins] r54031 - python/branches/p3yk_no_args_on_exc/Lib/test/test_set.py Message-ID: <20070228183613.885E41E4004@bag.python.org> Author: brett.cannon Date: Wed Feb 28 19:36:09 2007 New Revision: 54031 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_set.py Log: Remove usage of BaseException.args. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_set.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_set.py Wed Feb 28 19:36:09 2007 @@ -353,7 +353,7 @@ try: self.s.remove(v1) except KeyError as e: - v2 = e.args[0] + v2 = e.message self.assertEqual(v1, v2) else: self.fail() From python-checkins at python.org Wed Feb 28 19:38:00 2007 From: python-checkins at python.org (raymond.hettinger) Date: Wed, 28 Feb 2007 19:38:00 +0100 (CET) Subject: [Python-checkins] r54033 - in python/trunk: Lib/collections.py Modules/_collectionsmodule.c Modules/collectionsmodule.c PC/config.c PCbuild/pythoncore.vcproj PCbuild8/pythoncore.vcproj setup.py Message-ID: <20070228183800.4B7451E4003@bag.python.org> Author: raymond.hettinger Date: Wed Feb 28 19:37:52 2007 New Revision: 54033 Added: python/trunk/Lib/collections.py python/trunk/Modules/_collectionsmodule.c - copied, changed from r54020, python/trunk/Modules/collectionsmodule.c Removed: python/trunk/Modules/collectionsmodule.c Modified: python/trunk/PC/config.c python/trunk/PCbuild/pythoncore.vcproj python/trunk/PCbuild8/pythoncore.vcproj python/trunk/setup.py Log: Prepare collections module for pure python code entries. Added: python/trunk/Lib/collections.py ============================================================================== --- (empty file) +++ python/trunk/Lib/collections.py Wed Feb 28 19:37:52 2007 @@ -0,0 +1,3 @@ +__all__ = ['deque', 'defaultdict'] + +from _collections import deque, defaultdict Copied: python/trunk/Modules/_collectionsmodule.c (from r54020, python/trunk/Modules/collectionsmodule.c) ============================================================================== --- python/trunk/Modules/collectionsmodule.c (original) +++ python/trunk/Modules/_collectionsmodule.c Wed Feb 28 19:37:52 2007 @@ -1337,11 +1337,11 @@ "); PyMODINIT_FUNC -initcollections(void) +init_collections(void) { PyObject *m; - m = Py_InitModule3("collections", NULL, module_doc); + m = Py_InitModule3("_collections", NULL, module_doc); if (m == NULL) return; Deleted: /python/trunk/Modules/collectionsmodule.c ============================================================================== --- /python/trunk/Modules/collectionsmodule.c Wed Feb 28 19:37:52 2007 +++ (empty file) @@ -1,1366 +0,0 @@ -#include "Python.h" -#include "structmember.h" - -/* collections module implementation of a deque() datatype - Written and maintained by Raymond D. Hettinger - Copyright (c) 2004 Python Software Foundation. - All rights reserved. -*/ - -/* The block length may be set to any number over 1. Larger numbers - * reduce the number of calls to the memory allocator but take more - * memory. Ideally, BLOCKLEN should be set with an eye to the - * length of a cache line. - */ - -#define BLOCKLEN 62 -#define CENTER ((BLOCKLEN - 1) / 2) - -/* A `dequeobject` is composed of a doubly-linked list of `block` nodes. - * This list is not circular (the leftmost block has leftlink==NULL, - * and the rightmost block has rightlink==NULL). A deque d's first - * element is at d.leftblock[leftindex] and its last element is at - * d.rightblock[rightindex]; note that, unlike as for Python slice - * indices, these indices are inclusive on both ends. By being inclusive - * on both ends, algorithms for left and right operations become - * symmetrical which simplifies the design. - * - * The list of blocks is never empty, so d.leftblock and d.rightblock - * are never equal to NULL. - * - * The indices, d.leftindex and d.rightindex are always in the range - * 0 <= index < BLOCKLEN. - * Their exact relationship is: - * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex. - * - * Empty deques have d.len == 0; d.leftblock==d.rightblock; - * d.leftindex == CENTER+1; and d.rightindex == CENTER. - * Checking for d.len == 0 is the intended way to see whether d is empty. - * - * Whenever d.leftblock == d.rightblock, - * d.leftindex + d.len - 1 == d.rightindex. - * - * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex - * become indices into distinct blocks and either may be larger than the - * other. - */ - -typedef struct BLOCK { - struct BLOCK *leftlink; - struct BLOCK *rightlink; - PyObject *data[BLOCKLEN]; -} block; - -static block * -newblock(block *leftlink, block *rightlink, int len) { - block *b; - /* To prevent len from overflowing INT_MAX on 64-bit machines, we - * refuse to allocate new blocks if the current len is dangerously - * close. There is some extra margin to prevent spurious arithmetic - * overflows at various places. The following check ensures that - * the blocks allocated to the deque, in the worst case, can only - * have INT_MAX-2 entries in total. - */ - if (len >= INT_MAX - 2*BLOCKLEN) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more blocks to the deque"); - return NULL; - } - b = PyMem_Malloc(sizeof(block)); - if (b == NULL) { - PyErr_NoMemory(); - return NULL; - } - b->leftlink = leftlink; - b->rightlink = rightlink; - return b; -} - -typedef struct { - PyObject_HEAD - block *leftblock; - block *rightblock; - int leftindex; /* in range(BLOCKLEN) */ - int rightindex; /* in range(BLOCKLEN) */ - int len; - long state; /* incremented whenever the indices move */ - PyObject *weakreflist; /* List of weak references */ -} dequeobject; - -static PyTypeObject deque_type; - -static PyObject * -deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - dequeobject *deque; - block *b; - - if (type == &deque_type && !_PyArg_NoKeywords("deque()", kwds)) - return NULL; - - /* create dequeobject structure */ - deque = (dequeobject *)type->tp_alloc(type, 0); - if (deque == NULL) - return NULL; - - b = newblock(NULL, NULL, 0); - if (b == NULL) { - Py_DECREF(deque); - return NULL; - } - - assert(BLOCKLEN >= 2); - deque->leftblock = b; - deque->rightblock = b; - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - deque->len = 0; - deque->state = 0; - deque->weakreflist = NULL; - - return (PyObject *)deque; -} - -static PyObject * -deque_append(dequeobject *deque, PyObject *item) -{ - deque->state++; - if (deque->rightindex == BLOCKLEN-1) { - block *b = newblock(deque->rightblock, NULL, deque->len); - if (b == NULL) - return NULL; - assert(deque->rightblock->rightlink == NULL); - deque->rightblock->rightlink = b; - deque->rightblock = b; - deque->rightindex = -1; - } - Py_INCREF(item); - deque->len++; - deque->rightindex++; - deque->rightblock->data[deque->rightindex] = item; - Py_RETURN_NONE; -} - -PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque."); - -static PyObject * -deque_appendleft(dequeobject *deque, PyObject *item) -{ - deque->state++; - if (deque->leftindex == 0) { - block *b = newblock(NULL, deque->leftblock, deque->len); - if (b == NULL) - return NULL; - assert(deque->leftblock->leftlink == NULL); - deque->leftblock->leftlink = b; - deque->leftblock = b; - deque->leftindex = BLOCKLEN; - } - Py_INCREF(item); - deque->len++; - deque->leftindex--; - deque->leftblock->data[deque->leftindex] = item; - Py_RETURN_NONE; -} - -PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque."); - -static PyObject * -deque_pop(dequeobject *deque, PyObject *unused) -{ - PyObject *item; - block *prevblock; - - if (deque->len == 0) { - PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); - return NULL; - } - item = deque->rightblock->data[deque->rightindex]; - deque->rightindex--; - deque->len--; - deque->state++; - - if (deque->rightindex == -1) { - if (deque->len == 0) { - assert(deque->leftblock == deque->rightblock); - assert(deque->leftindex == deque->rightindex+1); - /* re-center instead of freeing a block */ - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - } else { - prevblock = deque->rightblock->leftlink; - assert(deque->leftblock != deque->rightblock); - PyMem_Free(deque->rightblock); - prevblock->rightlink = NULL; - deque->rightblock = prevblock; - deque->rightindex = BLOCKLEN - 1; - } - } - return item; -} - -PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element."); - -static PyObject * -deque_popleft(dequeobject *deque, PyObject *unused) -{ - PyObject *item; - block *prevblock; - - if (deque->len == 0) { - PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); - return NULL; - } - assert(deque->leftblock != NULL); - item = deque->leftblock->data[deque->leftindex]; - deque->leftindex++; - deque->len--; - deque->state++; - - if (deque->leftindex == BLOCKLEN) { - if (deque->len == 0) { - assert(deque->leftblock == deque->rightblock); - assert(deque->leftindex == deque->rightindex+1); - /* re-center instead of freeing a block */ - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - } else { - assert(deque->leftblock != deque->rightblock); - prevblock = deque->leftblock->rightlink; - PyMem_Free(deque->leftblock); - assert(prevblock != NULL); - prevblock->leftlink = NULL; - deque->leftblock = prevblock; - deque->leftindex = 0; - } - } - return item; -} - -PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element."); - -static PyObject * -deque_extend(dequeobject *deque, PyObject *iterable) -{ - PyObject *it, *item; - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - while ((item = PyIter_Next(it)) != NULL) { - deque->state++; - if (deque->rightindex == BLOCKLEN-1) { - block *b = newblock(deque->rightblock, NULL, - deque->len); - if (b == NULL) { - Py_DECREF(item); - Py_DECREF(it); - return NULL; - } - assert(deque->rightblock->rightlink == NULL); - deque->rightblock->rightlink = b; - deque->rightblock = b; - deque->rightindex = -1; - } - deque->len++; - deque->rightindex++; - deque->rightblock->data[deque->rightindex] = item; - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; -} - -PyDoc_STRVAR(extend_doc, -"Extend the right side of the deque with elements from the iterable"); - -static PyObject * -deque_extendleft(dequeobject *deque, PyObject *iterable) -{ - PyObject *it, *item; - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - while ((item = PyIter_Next(it)) != NULL) { - deque->state++; - if (deque->leftindex == 0) { - block *b = newblock(NULL, deque->leftblock, - deque->len); - if (b == NULL) { - Py_DECREF(item); - Py_DECREF(it); - return NULL; - } - assert(deque->leftblock->leftlink == NULL); - deque->leftblock->leftlink = b; - deque->leftblock = b; - deque->leftindex = BLOCKLEN; - } - deque->len++; - deque->leftindex--; - deque->leftblock->data[deque->leftindex] = item; - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; -} - -PyDoc_STRVAR(extendleft_doc, -"Extend the left side of the deque with elements from the iterable"); - -static int -_deque_rotate(dequeobject *deque, Py_ssize_t n) -{ - int i, len=deque->len, halflen=(len+1)>>1; - PyObject *item, *rv; - - if (len == 0) - return 0; - if (n > halflen || n < -halflen) { - n %= len; - if (n > halflen) - n -= len; - else if (n < -halflen) - n += len; - } - - for (i=0 ; in ; i--) { - item = deque_popleft(deque, NULL); - assert (item != NULL); - rv = deque_append(deque, item); - Py_DECREF(item); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; -} - -static PyObject * -deque_rotate(dequeobject *deque, PyObject *args) -{ - int n=1; - - if (!PyArg_ParseTuple(args, "|i:rotate", &n)) - return NULL; - if (_deque_rotate(deque, n) == 0) - Py_RETURN_NONE; - return NULL; -} - -PyDoc_STRVAR(rotate_doc, -"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left."); - -static Py_ssize_t -deque_len(dequeobject *deque) -{ - return deque->len; -} - -static PyObject * -deque_remove(dequeobject *deque, PyObject *value) -{ - Py_ssize_t i, n=deque->len; - - for (i=0 ; ileftblock->data[deque->leftindex]; - int cmp = PyObject_RichCompareBool(item, value, Py_EQ); - - if (deque->len != n) { - PyErr_SetString(PyExc_IndexError, - "deque mutated during remove()."); - return NULL; - } - if (cmp > 0) { - PyObject *tgt = deque_popleft(deque, NULL); - assert (tgt != NULL); - Py_DECREF(tgt); - if (_deque_rotate(deque, i) == -1) - return NULL; - Py_RETURN_NONE; - } - else if (cmp < 0) { - _deque_rotate(deque, i); - return NULL; - } - _deque_rotate(deque, -1); - } - PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque"); - return NULL; -} - -PyDoc_STRVAR(remove_doc, -"D.remove(value) -- remove first occurrence of value."); - -static int -deque_clear(dequeobject *deque) -{ - PyObject *item; - - while (deque->len) { - item = deque_pop(deque, NULL); - assert (item != NULL); - Py_DECREF(item); - } - assert(deque->leftblock == deque->rightblock && - deque->leftindex - 1 == deque->rightindex && - deque->len == 0); - return 0; -} - -static PyObject * -deque_item(dequeobject *deque, int i) -{ - block *b; - PyObject *item; - int n, index=i; - - if (i < 0 || i >= deque->len) { - PyErr_SetString(PyExc_IndexError, - "deque index out of range"); - return NULL; - } - - if (i == 0) { - i = deque->leftindex; - b = deque->leftblock; - } else if (i == deque->len - 1) { - i = deque->rightindex; - b = deque->rightblock; - } else { - i += deque->leftindex; - n = i / BLOCKLEN; - i %= BLOCKLEN; - if (index < (deque->len >> 1)) { - b = deque->leftblock; - while (n--) - b = b->rightlink; - } else { - n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n; - b = deque->rightblock; - while (n--) - b = b->leftlink; - } - } - item = b->data[i]; - Py_INCREF(item); - return item; -} - -/* delitem() implemented in terms of rotate for simplicity and reasonable - performance near the end points. If for some reason this method becomes - popular, it is not hard to re-implement this using direct data movement - (similar to code in list slice assignment) and achieve a two or threefold - performance boost. -*/ - -static int -deque_del_item(dequeobject *deque, Py_ssize_t i) -{ - PyObject *item; - - assert (i >= 0 && i < deque->len); - if (_deque_rotate(deque, -i) == -1) - return -1; - - item = deque_popleft(deque, NULL); - assert (item != NULL); - Py_DECREF(item); - - return _deque_rotate(deque, i); -} - -static int -deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v) -{ - PyObject *old_value; - block *b; - Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i; - - if (i < 0 || i >= len) { - PyErr_SetString(PyExc_IndexError, - "deque index out of range"); - return -1; - } - if (v == NULL) - return deque_del_item(deque, i); - - i += deque->leftindex; - n = i / BLOCKLEN; - i %= BLOCKLEN; - if (index <= halflen) { - b = deque->leftblock; - while (n--) - b = b->rightlink; - } else { - n = (deque->leftindex + len - 1) / BLOCKLEN - n; - b = deque->rightblock; - while (n--) - b = b->leftlink; - } - Py_INCREF(v); - old_value = b->data[i]; - b->data[i] = v; - Py_DECREF(old_value); - return 0; -} - -static PyObject * -deque_clearmethod(dequeobject *deque) -{ - int rv; - - rv = deque_clear(deque); - assert (rv != -1); - Py_RETURN_NONE; -} - -PyDoc_STRVAR(clear_doc, "Remove all elements from the deque."); - -static void -deque_dealloc(dequeobject *deque) -{ - PyObject_GC_UnTrack(deque); - if (deque->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) deque); - if (deque->leftblock != NULL) { - deque_clear(deque); - assert(deque->leftblock != NULL); - PyMem_Free(deque->leftblock); - } - deque->leftblock = NULL; - deque->rightblock = NULL; - deque->ob_type->tp_free(deque); -} - -static int -deque_traverse(dequeobject *deque, visitproc visit, void *arg) -{ - block *b; - PyObject *item; - int index; - int indexlo = deque->leftindex; - - for (b = deque->leftblock; b != NULL; b = b->rightlink) { - const int indexhi = b == deque->rightblock ? - deque->rightindex : - BLOCKLEN - 1; - - for (index = indexlo; index <= indexhi; ++index) { - item = b->data[index]; - Py_VISIT(item); - } - indexlo = 0; - } - return 0; -} - -static long -deque_nohash(PyObject *self) -{ - PyErr_SetString(PyExc_TypeError, "deque objects are unhashable"); - return -1; -} - -static PyObject * -deque_copy(PyObject *deque) -{ - return PyObject_CallFunctionObjArgs((PyObject *)(deque->ob_type), - deque, NULL); -} - -PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque."); - -static PyObject * -deque_reduce(dequeobject *deque) -{ - PyObject *dict, *result, *it; - - dict = PyObject_GetAttrString((PyObject *)deque, "__dict__"); - if (dict == NULL) { - PyErr_Clear(); - dict = Py_None; - Py_INCREF(dict); - } - it = PyObject_GetIter((PyObject *)deque); - if (it == NULL) { - Py_DECREF(dict); - return NULL; - } - result = Py_BuildValue("O()ON", deque->ob_type, dict, it); - Py_DECREF(dict); - return result; -} - -PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); - -static PyObject * -deque_repr(PyObject *deque) -{ - PyObject *aslist, *result, *fmt; - int i; - - i = Py_ReprEnter(deque); - if (i != 0) { - if (i < 0) - return NULL; - return PyString_FromString("[...]"); - } - - aslist = PySequence_List(deque); - if (aslist == NULL) { - Py_ReprLeave(deque); - return NULL; - } - - fmt = PyString_FromString("deque(%r)"); - if (fmt == NULL) { - Py_DECREF(aslist); - Py_ReprLeave(deque); - return NULL; - } - result = PyString_Format(fmt, aslist); - Py_DECREF(fmt); - Py_DECREF(aslist); - Py_ReprLeave(deque); - return result; -} - -static int -deque_tp_print(PyObject *deque, FILE *fp, int flags) -{ - PyObject *it, *item; - char *emit = ""; /* No separator emitted on first pass */ - char *separator = ", "; - int i; - - i = Py_ReprEnter(deque); - if (i != 0) { - if (i < 0) - return i; - fputs("[...]", fp); - return 0; - } - - it = PyObject_GetIter(deque); - if (it == NULL) - return -1; - - fputs("deque([", fp); - while ((item = PyIter_Next(it)) != NULL) { - fputs(emit, fp); - emit = separator; - if (PyObject_Print(item, fp, 0) != 0) { - Py_DECREF(item); - Py_DECREF(it); - Py_ReprLeave(deque); - return -1; - } - Py_DECREF(item); - } - Py_ReprLeave(deque); - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - fputs("])", fp); - return 0; -} - -static PyObject * -deque_richcompare(PyObject *v, PyObject *w, int op) -{ - PyObject *it1=NULL, *it2=NULL, *x, *y; - int b, vs, ws, cmp=-1; - - if (!PyObject_TypeCheck(v, &deque_type) || - !PyObject_TypeCheck(w, &deque_type)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - /* Shortcuts */ - vs = ((dequeobject *)v)->len; - ws = ((dequeobject *)w)->len; - if (op == Py_EQ) { - if (v == w) - Py_RETURN_TRUE; - if (vs != ws) - Py_RETURN_FALSE; - } - if (op == Py_NE) { - if (v == w) - Py_RETURN_FALSE; - if (vs != ws) - Py_RETURN_TRUE; - } - - /* Search for the first index where items are different */ - it1 = PyObject_GetIter(v); - if (it1 == NULL) - goto done; - it2 = PyObject_GetIter(w); - if (it2 == NULL) - goto done; - for (;;) { - x = PyIter_Next(it1); - if (x == NULL && PyErr_Occurred()) - goto done; - y = PyIter_Next(it2); - if (x == NULL || y == NULL) - break; - b = PyObject_RichCompareBool(x, y, Py_EQ); - if (b == 0) { - cmp = PyObject_RichCompareBool(x, y, op); - Py_DECREF(x); - Py_DECREF(y); - goto done; - } - Py_DECREF(x); - Py_DECREF(y); - if (b == -1) - goto done; - } - /* We reached the end of one deque or both */ - Py_XDECREF(x); - Py_XDECREF(y); - if (PyErr_Occurred()) - goto done; - switch (op) { - case Py_LT: cmp = y != NULL; break; /* if w was longer */ - case Py_LE: cmp = x == NULL; break; /* if v was not longer */ - case Py_EQ: cmp = x == y; break; /* if we reached the end of both */ - case Py_NE: cmp = x != y; break; /* if one deque continues */ - case Py_GT: cmp = x != NULL; break; /* if v was longer */ - case Py_GE: cmp = y == NULL; break; /* if w was not longer */ - } - -done: - Py_XDECREF(it1); - Py_XDECREF(it2); - if (cmp == 1) - Py_RETURN_TRUE; - if (cmp == 0) - Py_RETURN_FALSE; - return NULL; -} - -static int -deque_init(dequeobject *deque, PyObject *args, PyObject *kwds) -{ - PyObject *iterable = NULL; - - if (!PyArg_UnpackTuple(args, "deque", 0, 1, &iterable)) - return -1; - - if (iterable != NULL) { - PyObject *rv = deque_extend(deque, iterable); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; -} - -static PySequenceMethods deque_as_sequence = { - (lenfunc)deque_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - (ssizeargfunc)deque_item, /* sq_item */ - 0, /* sq_slice */ - (ssizeobjargproc)deque_ass_item, /* sq_ass_item */ -}; - -/* deque object ********************************************************/ - -static PyObject *deque_iter(dequeobject *deque); -static PyObject *deque_reviter(dequeobject *deque); -PyDoc_STRVAR(reversed_doc, - "D.__reversed__() -- return a reverse iterator over the deque"); - -static PyMethodDef deque_methods[] = { - {"append", (PyCFunction)deque_append, - METH_O, append_doc}, - {"appendleft", (PyCFunction)deque_appendleft, - METH_O, appendleft_doc}, - {"clear", (PyCFunction)deque_clearmethod, - METH_NOARGS, clear_doc}, - {"__copy__", (PyCFunction)deque_copy, - METH_NOARGS, copy_doc}, - {"extend", (PyCFunction)deque_extend, - METH_O, extend_doc}, - {"extendleft", (PyCFunction)deque_extendleft, - METH_O, extendleft_doc}, - {"pop", (PyCFunction)deque_pop, - METH_NOARGS, pop_doc}, - {"popleft", (PyCFunction)deque_popleft, - METH_NOARGS, popleft_doc}, - {"__reduce__", (PyCFunction)deque_reduce, - METH_NOARGS, reduce_doc}, - {"remove", (PyCFunction)deque_remove, - METH_O, remove_doc}, - {"__reversed__", (PyCFunction)deque_reviter, - METH_NOARGS, reversed_doc}, - {"rotate", (PyCFunction)deque_rotate, - METH_VARARGS, rotate_doc}, - {NULL, NULL} /* sentinel */ -}; - -PyDoc_STRVAR(deque_doc, -"deque(iterable) --> deque object\n\ -\n\ -Build an ordered collection accessible from endpoints only."); - -static PyTypeObject deque_type = { - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ - "collections.deque", /* tp_name */ - sizeof(dequeobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)deque_dealloc, /* tp_dealloc */ - deque_tp_print, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - deque_repr, /* tp_repr */ - 0, /* tp_as_number */ - &deque_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - deque_nohash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */ - deque_doc, /* tp_doc */ - (traverseproc)deque_traverse, /* tp_traverse */ - (inquiry)deque_clear, /* tp_clear */ - (richcmpfunc)deque_richcompare, /* tp_richcompare */ - offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/ - (getiterfunc)deque_iter, /* tp_iter */ - 0, /* tp_iternext */ - deque_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)deque_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - deque_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ -}; - -/*********************** Deque Iterator **************************/ - -typedef struct { - PyObject_HEAD - int index; - block *b; - dequeobject *deque; - long state; /* state when the iterator is created */ - int counter; /* number of items remaining for iteration */ -} dequeiterobject; - -PyTypeObject dequeiter_type; - -static PyObject * -deque_iter(dequeobject *deque) -{ - dequeiterobject *it; - - it = PyObject_New(dequeiterobject, &dequeiter_type); - if (it == NULL) - return NULL; - it->b = deque->leftblock; - it->index = deque->leftindex; - Py_INCREF(deque); - it->deque = deque; - it->state = deque->state; - it->counter = deque->len; - return (PyObject *)it; -} - -static void -dequeiter_dealloc(dequeiterobject *dio) -{ - Py_XDECREF(dio->deque); - dio->ob_type->tp_free(dio); -} - -static PyObject * -dequeiter_next(dequeiterobject *it) -{ - PyObject *item; - - 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)); - - item = it->b->data[it->index]; - it->index++; - it->counter--; - if (it->index == BLOCKLEN && it->counter > 0) { - assert (it->b->rightlink != NULL); - it->b = it->b->rightlink; - it->index = 0; - } - Py_INCREF(item); - return item; -} - -static PyObject * -dequeiter_len(dequeiterobject *it) -{ - return PyInt_FromLong(it->counter); -} - -PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); - -static PyMethodDef dequeiter_methods[] = { - {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ -}; - -PyTypeObject dequeiter_type = { - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ - "deque_iterator", /* tp_name */ - sizeof(dequeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dequeiter_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dequeiter_next, /* tp_iternext */ - dequeiter_methods, /* tp_methods */ - 0, -}; - -/*********************** Deque Reverse Iterator **************************/ - -PyTypeObject dequereviter_type; - -static PyObject * -deque_reviter(dequeobject *deque) -{ - dequeiterobject *it; - - it = PyObject_New(dequeiterobject, &dequereviter_type); - if (it == NULL) - return NULL; - it->b = deque->rightblock; - it->index = deque->rightindex; - Py_INCREF(deque); - it->deque = deque; - it->state = deque->state; - it->counter = deque->len; - return (PyObject *)it; -} - -static PyObject * -dequereviter_next(dequeiterobject *it) -{ - 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; - } - assert (!(it->b == it->deque->leftblock && - it->index < it->deque->leftindex)); - - item = it->b->data[it->index]; - it->index--; - it->counter--; - if (it->index == -1 && it->counter > 0) { - assert (it->b->leftlink != NULL); - it->b = it->b->leftlink; - it->index = BLOCKLEN - 1; - } - Py_INCREF(item); - return item; -} - -PyTypeObject dequereviter_type = { - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ - "deque_reverse_iterator", /* tp_name */ - sizeof(dequeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dequeiter_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dequereviter_next, /* tp_iternext */ - dequeiter_methods, /* tp_methods */ - 0, -}; - -/* defaultdict type *********************************************************/ - -typedef struct { - PyDictObject dict; - PyObject *default_factory; -} defdictobject; - -static PyTypeObject defdict_type; /* Forward */ - -PyDoc_STRVAR(defdict_missing_doc, -"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\ - if self.default_factory is None: raise KeyError(key)\n\ - self[key] = value = self.default_factory()\n\ - return value\n\ -"); - -static PyObject * -defdict_missing(defdictobject *dd, PyObject *key) -{ - PyObject *factory = dd->default_factory; - PyObject *value; - if (factory == NULL || factory == Py_None) { - /* XXX Call dict.__missing__(key) */ - PyErr_SetObject(PyExc_KeyError, key); - return NULL; - } - value = PyEval_CallObject(factory, NULL); - if (value == NULL) - return value; - if (PyObject_SetItem((PyObject *)dd, key, value) < 0) { - Py_DECREF(value); - return NULL; - } - return value; -} - -PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D."); - -static PyObject * -defdict_copy(defdictobject *dd) -{ - /* This calls the object's class. That only works for subclasses - whose class constructor has the same signature. Subclasses that - define a different constructor signature must override copy(). - */ - return PyObject_CallFunctionObjArgs((PyObject *)dd->dict.ob_type, - dd->default_factory, dd, NULL); -} - -static PyObject * -defdict_reduce(defdictobject *dd) -{ - /* __reduce__ must return a 5-tuple as follows: - - - factory function - - tuple of args for the factory function - - additional state (here None) - - sequence iterator (here None) - - dictionary iterator (yielding successive (key, value) pairs - - This API is used by pickle.py and copy.py. - - For this to be useful with pickle.py, the default_factory - must be picklable; e.g., None, a built-in, or a global - function in a module or package. - - Both shallow and deep copying are supported, but for deep - copying, the default_factory must be deep-copyable; e.g. None, - or a built-in (functions are not copyable at this time). - - This only works for subclasses as long as their constructor - signature is compatible; the first argument must be the - optional default_factory, defaulting to None. - */ - PyObject *args; - PyObject *items; - PyObject *result; - if (dd->default_factory == NULL || dd->default_factory == Py_None) - args = PyTuple_New(0); - else - args = PyTuple_Pack(1, dd->default_factory); - if (args == NULL) - return NULL; - items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()"); - if (items == NULL) { - Py_DECREF(args); - return NULL; - } - result = PyTuple_Pack(5, dd->dict.ob_type, args, - Py_None, Py_None, items); - Py_DECREF(items); - Py_DECREF(args); - return result; -} - -static PyMethodDef defdict_methods[] = { - {"__missing__", (PyCFunction)defdict_missing, METH_O, - defdict_missing_doc}, - {"copy", (PyCFunction)defdict_copy, METH_NOARGS, - defdict_copy_doc}, - {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS, - defdict_copy_doc}, - {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS, - reduce_doc}, - {NULL} -}; - -static PyMemberDef defdict_members[] = { - {"default_factory", T_OBJECT, - offsetof(defdictobject, default_factory), 0, - PyDoc_STR("Factory for default value called by __missing__().")}, - {NULL} -}; - -static void -defdict_dealloc(defdictobject *dd) -{ - Py_CLEAR(dd->default_factory); - PyDict_Type.tp_dealloc((PyObject *)dd); -} - -static int -defdict_print(defdictobject *dd, FILE *fp, int flags) -{ - int sts; - fprintf(fp, "defaultdict("); - if (dd->default_factory == NULL) - fprintf(fp, "None"); - else { - PyObject_Print(dd->default_factory, fp, 0); - } - fprintf(fp, ", "); - sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0); - fprintf(fp, ")"); - return sts; -} - -static PyObject * -defdict_repr(defdictobject *dd) -{ - PyObject *defrepr; - PyObject *baserepr; - PyObject *result; - baserepr = PyDict_Type.tp_repr((PyObject *)dd); - if (baserepr == NULL) - return NULL; - if (dd->default_factory == NULL) - defrepr = PyString_FromString("None"); - else - defrepr = PyObject_Repr(dd->default_factory); - if (defrepr == NULL) { - Py_DECREF(baserepr); - return NULL; - } - result = PyString_FromFormat("defaultdict(%s, %s)", - PyString_AS_STRING(defrepr), - PyString_AS_STRING(baserepr)); - Py_DECREF(defrepr); - Py_DECREF(baserepr); - return result; -} - -static int -defdict_traverse(PyObject *self, visitproc visit, void *arg) -{ - Py_VISIT(((defdictobject *)self)->default_factory); - return PyDict_Type.tp_traverse(self, visit, arg); -} - -static int -defdict_tp_clear(defdictobject *dd) -{ - Py_CLEAR(dd->default_factory); - return PyDict_Type.tp_clear((PyObject *)dd); -} - -static int -defdict_init(PyObject *self, PyObject *args, PyObject *kwds) -{ - defdictobject *dd = (defdictobject *)self; - PyObject *olddefault = dd->default_factory; - PyObject *newdefault = NULL; - PyObject *newargs; - int result; - if (args == NULL || !PyTuple_Check(args)) - newargs = PyTuple_New(0); - else { - Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n > 0) { - newdefault = PyTuple_GET_ITEM(args, 0); - if (!PyCallable_Check(newdefault)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return -1; - } - } - newargs = PySequence_GetSlice(args, 1, n); - } - if (newargs == NULL) - return -1; - Py_XINCREF(newdefault); - dd->default_factory = newdefault; - result = PyDict_Type.tp_init(self, newargs, kwds); - Py_DECREF(newargs); - Py_XDECREF(olddefault); - return result; -} - -PyDoc_STRVAR(defdict_doc, -"defaultdict(default_factory) --> dict with default factory\n\ -\n\ -The default factory is called without arguments to produce\n\ -a new value when a key is not present, in __getitem__ only.\n\ -A defaultdict compares equal to a dict with the same items.\n\ -"); - -/* See comment in xxsubtype.c */ -#define DEFERRED_ADDRESS(ADDR) 0 - -static PyTypeObject defdict_type = { - PyObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type)) - 0, /* ob_size */ - "collections.defaultdict", /* tp_name */ - sizeof(defdictobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)defdict_dealloc, /* tp_dealloc */ - (printfunc)defdict_print, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - (reprfunc)defdict_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */ - defdict_doc, /* tp_doc */ - defdict_traverse, /* tp_traverse */ - (inquiry)defdict_tp_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset*/ - 0, /* tp_iter */ - 0, /* tp_iternext */ - defdict_methods, /* tp_methods */ - defdict_members, /* tp_members */ - 0, /* tp_getset */ - DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - defdict_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ -}; - -/* module level code ********************************************************/ - -PyDoc_STRVAR(module_doc, -"High performance data structures.\n\ -- deque: ordered collection accessible from endpoints only\n\ -- defaultdict: dict subclass with a default value factory\n\ -"); - -PyMODINIT_FUNC -initcollections(void) -{ - PyObject *m; - - m = Py_InitModule3("collections", NULL, module_doc); - if (m == NULL) - return; - - if (PyType_Ready(&deque_type) < 0) - return; - Py_INCREF(&deque_type); - PyModule_AddObject(m, "deque", (PyObject *)&deque_type); - - defdict_type.tp_base = &PyDict_Type; - if (PyType_Ready(&defdict_type) < 0) - return; - Py_INCREF(&defdict_type); - PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type); - - if (PyType_Ready(&dequeiter_type) < 0) - return; - - if (PyType_Ready(&dequereviter_type) < 0) - return; - - return; -} Modified: python/trunk/PC/config.c ============================================================================== --- python/trunk/PC/config.c (original) +++ python/trunk/PC/config.c Wed Feb 28 19:37:52 2007 @@ -43,7 +43,7 @@ extern void initzipimport(void); extern void init_random(void); extern void inititertools(void); -extern void initcollections(void); +extern void init_collections(void); extern void init_heapq(void); extern void init_bisect(void); extern void init_symtable(void); @@ -124,7 +124,7 @@ {"_heapq", init_heapq}, {"_lsprof", init_lsprof}, {"itertools", inititertools}, - {"collections", initcollections}, + {"_collections", init_collections}, {"_symtable", init_symtable}, {"mmap", initmmap}, {"_csv", init_csv}, Modified: python/trunk/PCbuild/pythoncore.vcproj ============================================================================== --- python/trunk/PCbuild/pythoncore.vcproj (original) +++ python/trunk/PCbuild/pythoncore.vcproj Wed Feb 28 19:37:52 2007 @@ -458,7 +458,7 @@ RelativePath="..\Objects\codeobject.c"> + RelativePath="..\Modules\_collectionsmodule.c"> Modified: python/trunk/PCbuild8/pythoncore.vcproj ============================================================================== --- python/trunk/PCbuild8/pythoncore.vcproj (original) +++ python/trunk/PCbuild8/pythoncore.vcproj Wed Feb 28 19:37:52 2007 @@ -1381,7 +1381,7 @@ > Author: brett.cannon Date: Wed Feb 28 19:40:13 2007 New Revision: 54034 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_signal.py Log: Fix for BaseException.args removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_signal.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_signal.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_signal.py Wed Feb 28 19:40:13 2007 @@ -46,7 +46,7 @@ b_called = True if verbose: print("handlerB invoked", args) - raise HandlerBCalled, args + raise HandlerBCalled(args) # Set up a child to send signals to us (the parent) after waiting long # enough to receive the alarm. It seems we miss the alarm for some From python-checkins at python.org Wed Feb 28 21:51:05 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 21:51:05 +0100 (CET) Subject: [Python-checkins] r54036 - python/branches/p3yk_no_args_on_exc/Lib/codeop.py Message-ID: <20070228205105.7A1511E4017@bag.python.org> Author: brett.cannon Date: Wed Feb 28 21:51:03 2007 New Revision: 54036 Modified: python/branches/p3yk_no_args_on_exc/Lib/codeop.py Log: Fix codeop to compare against all attributes of the exception instead of just its repr since it no longer properly reflects all fields of the exception. Better solution would probably be to write a custom __eq__ the compares the attributes or something. Modified: python/branches/p3yk_no_args_on_exc/Lib/codeop.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/codeop.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/codeop.py Wed Feb 28 21:51:03 2007 @@ -95,8 +95,13 @@ if code: return code - if not code1 and repr(err1) == repr(err2): - raise SyntaxError, err1 + if not code1: + for attr in ('message', 'msg', 'filename', 'lineno', 'offset', + 'print_file_and_line', 'text'): + if getattr(err1, attr) != getattr(err2, attr): + break + else: + raise SyntaxError(err1) def _compile(source, filename, symbol): return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT) From python-checkins at python.org Wed Feb 28 22:02:29 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 22:02:29 +0100 (CET) Subject: [Python-checkins] r54037 - in python/branches/p3yk_no_args_on_exc: Lib/keyword.py Message-ID: <20070228210229.3674F1E401C@bag.python.org> Author: brett.cannon Date: Wed Feb 28 22:02:25 2007 New Revision: 54037 Modified: python/branches/p3yk_no_args_on_exc/ (props changed) python/branches/p3yk_no_args_on_exc/Lib/keyword.py Log: Merged revisions 54011-54036 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/p3yk ........ r54035 | jack.diederich | 2007-02-28 14:21:30 -0600 (Wed, 28 Feb 2007) | 1 line regenerated to reflect the addition of 'nonlocal' and removal of 'print' ........ Modified: python/branches/p3yk_no_args_on_exc/Lib/keyword.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/keyword.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/keyword.py Wed Feb 28 22:02:25 2007 @@ -34,10 +34,10 @@ 'in', 'is', 'lambda', + 'nonlocal', 'not', 'or', 'pass', - 'print', 'raise', 'return', 'try', From python-checkins at python.org Wed Feb 28 22:10:05 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 22:10:05 +0100 (CET) Subject: [Python-checkins] r54038 - python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/hooks.py python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/userfunctions.py Message-ID: <20070228211005.EC71E1E4004@bag.python.org> Author: brett.cannon Date: Wed Feb 28 22:10:02 2007 New Revision: 54038 Modified: python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/hooks.py python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/userfunctions.py Log: Fix sqlite3's tests for BaseException.args removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/hooks.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/hooks.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/hooks.py Wed Feb 28 22:10:02 2007 @@ -37,7 +37,7 @@ con.create_collation("X", 42) self.fail("should have raised a TypeError") except TypeError as e: - self.failUnlessEqual(e.args[0], "parameter must be callable") + self.failUnlessEqual(e.message, "parameter must be callable") def CheckCreateCollationNotAscii(self): con = sqlite.connect(":memory:") @@ -102,7 +102,7 @@ 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 as e: - if not e.args[0].startswith("no such collation sequence"): + if not e.message.startswith("no such collation sequence"): self.fail("wrong OperationalError raised") def suite(): Modified: python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/userfunctions.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/userfunctions.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/sqlite3/test/userfunctions.py Wed Feb 28 22:10:02 2007 @@ -206,7 +206,8 @@ cur.fetchone() self.fail("should have raised OperationalError") except sqlite.OperationalError as e: - self.failUnlessEqual(e.args[0], 'user-defined function raised exception') + self.failUnlessEqual(e.message, + 'user-defined function raised exception') def CheckParamString(self): cur = self.con.cursor() @@ -280,7 +281,8 @@ cur.execute("select nostep(t) from test") self.fail("should have raised an AttributeError") except AttributeError as e: - self.failUnlessEqual(e.args[0], "'AggrNoStep' object has no attribute 'step'") + self.failUnlessEqual(e.message, + "'AggrNoStep' object has no attribute 'step'") def CheckAggrNoFinalize(self): cur = self.con.cursor() @@ -289,7 +291,8 @@ val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError as e: - self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") + self.failUnlessEqual(e.message, + "user-defined aggregate's 'finalize' method raised error") def CheckAggrExceptionInInit(self): cur = self.con.cursor() @@ -298,7 +301,8 @@ val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError as e: - self.failUnlessEqual(e.args[0], "user-defined aggregate's '__init__' method raised error") + self.failUnlessEqual(e.message, + "user-defined aggregate's '__init__' method raised error") def CheckAggrExceptionInStep(self): cur = self.con.cursor() @@ -307,7 +311,8 @@ val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError as e: - self.failUnlessEqual(e.args[0], "user-defined aggregate's 'step' method raised error") + self.failUnlessEqual(e.message, + "user-defined aggregate's 'step' method raised error") def CheckAggrExceptionInFinalize(self): cur = self.con.cursor() @@ -316,7 +321,8 @@ val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError as e: - self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") + self.failUnlessEqual(e.message, + "user-defined aggregate's 'finalize' method raised error") def CheckAggrCheckParamStr(self): cur = self.con.cursor() @@ -385,7 +391,7 @@ try: self.con.execute("select * from t2") except sqlite.DatabaseError as e: - if not e.args[0].endswith("prohibited"): + if not e.message.endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return self.fail("should have raised an exception due to missing privileges") @@ -394,7 +400,7 @@ try: self.con.execute("select c2 from t1") except sqlite.DatabaseError as e: - if not e.args[0].endswith("prohibited"): + if not e.message.endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return self.fail("should have raised an exception due to missing privileges") From python-checkins at python.org Wed Feb 28 22:12:09 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 22:12:09 +0100 (CET) Subject: [Python-checkins] r54039 - python/branches/p3yk_no_args_on_exc/Lib/_strptime.py Message-ID: <20070228211209.76B0C1E4014@bag.python.org> Author: brett.cannon Date: Wed Feb 28 22:12:06 2007 New Revision: 54039 Modified: python/branches/p3yk_no_args_on_exc/Lib/_strptime.py Log: Fix time.strptime for the removal of BaseException.args. Modified: python/branches/p3yk_no_args_on_exc/Lib/_strptime.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/_strptime.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/_strptime.py Wed Feb 28 22:12:06 2007 @@ -309,7 +309,7 @@ # 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 as err: - bad_directive = err.args[0] + bad_directive = err.message if bad_directive == "\\": bad_directive = "%" del err From python-checkins at python.org Wed Feb 28 22:26:34 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 22:26:34 +0100 (CET) Subject: [Python-checkins] r54040 - python/branches/p3yk_no_args_on_exc/Lib/traceback.py Message-ID: <20070228212634.BF14C1E401A@bag.python.org> Author: brett.cannon Date: Wed Feb 28 22:26:34 2007 New Revision: 54040 Modified: python/branches/p3yk_no_args_on_exc/Lib/traceback.py Log: Fix 'traceback' for BaseException.args removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/traceback.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/traceback.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/traceback.py Wed Feb 28 22:26:34 2007 @@ -178,7 +178,12 @@ # It was a syntax error; show exactly where the problem was found. lines = [] try: - msg, (filename, lineno, offset, badline) = value.args + message = value.message + filename = value.filename + lineno = value.lineno + offset = value.offset + badline = value.text + msg = value.message except Exception: pass else: From python-checkins at python.org Wed Feb 28 22:29:49 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 22:29:49 +0100 (CET) Subject: [Python-checkins] r54041 - python/branches/p3yk_no_args_on_exc/Lib/test/test_userdict.py Message-ID: <20070228212949.9F0351E4004@bag.python.org> Author: brett.cannon Date: Wed Feb 28 22:29:47 2007 New Revision: 54041 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_userdict.py Log: Fix for BaseException.args removal. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_userdict.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_userdict.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_userdict.py Wed Feb 28 22:29:47 2007 @@ -169,7 +169,7 @@ try: e[42] except RuntimeError as err: - self.assertEqual(err.args, (42,)) + self.assertEqual(err.message, 42) else: self.fail_("e[42] didn't raise RuntimeError") class F(UserDict.UserDict): @@ -181,7 +181,7 @@ try: f[42] except KeyError as err: - self.assertEqual(err.args, (42,)) + self.assertEqual(err.message, 42) else: self.fail_("f[42] didn't raise KeyError") class G(UserDict.UserDict): @@ -190,7 +190,7 @@ try: g[42] except KeyError as err: - self.assertEqual(err.args, (42,)) + self.assertEqual(err.message, 42) else: self.fail_("g[42] didn't raise KeyError") From python-checkins at python.org Wed Feb 28 22:41:32 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 22:41:32 +0100 (CET) Subject: [Python-checkins] r54042 - python/branches/p3yk_no_args_on_exc/Lib/traceback.py Message-ID: <20070228214132.562AD1E401A@bag.python.org> Author: brett.cannon Date: Wed Feb 28 22:41:27 2007 New Revision: 54042 Modified: python/branches/p3yk_no_args_on_exc/Lib/traceback.py Log: Fix for test_syntax failure. Modified: python/branches/p3yk_no_args_on_exc/Lib/traceback.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/traceback.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/traceback.py Wed Feb 28 22:41:27 2007 @@ -180,7 +180,7 @@ try: message = value.message filename = value.filename - lineno = value.lineno + lineno = value.lineno if value.lineno is not None else 0 offset = value.offset badline = value.text msg = value.message From python-checkins at python.org Wed Feb 28 23:34:01 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 23:34:01 +0100 (CET) Subject: [Python-checkins] r54044 - python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py Message-ID: <20070228223401.2206E1E4002@bag.python.org> Author: brett.cannon Date: Wed Feb 28 23:33:57 2007 New Revision: 54044 Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py Log: Fix a mistake made from the last attempt to fix this test for the BaseException.args removal. Only triggered when test_compiler run from regrtest with -uall. Modified: python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py ============================================================================== --- python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py (original) +++ python/branches/p3yk_no_args_on_exc/Lib/test/test_compiler.py Wed Feb 28 23:33:57 2007 @@ -50,7 +50,7 @@ try: compiler.compile(buf, basename, "exec") except Exception as e: - args.message += "[in file %s]" % basename + e.message += "[in file %s]" % basename raise def testNewClassSyntax(self): From python-checkins at python.org Wed Feb 28 23:34:22 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 23:34:22 +0100 (CET) Subject: [Python-checkins] r54045 - python/branches/p3yk_no_args_on_exc/BROKEN Message-ID: <20070228223422.996001E4002@bag.python.org> Author: brett.cannon Date: Wed Feb 28 23:34:21 2007 New Revision: 54045 Added: python/branches/p3yk_no_args_on_exc/BROKEN (contents, props changed) Log: Add a list of tests currently failing. Added: python/branches/p3yk_no_args_on_exc/BROKEN ============================================================================== --- (empty file) +++ python/branches/p3yk_no_args_on_exc/BROKEN Wed Feb 28 23:34:21 2007 @@ -0,0 +1,10 @@ +* Construction of exception at C level passing too many arguments? + + test_bsddb + + test_socket + + test_socket_ssl + + test_timeout + + test_urllib2net + + test_urllibnet + +* doctest oddness (need to change how SyntaxError is handled?) + + test_xml_etree