From buildbot at python.org Mon Jan 1 22:19:24 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 01 Jan 2007 21:19:24 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP-2 2.5 Message-ID: <20070101211924.7D3F51E4007@bag.python.org> The Buildbot has detected a new failure of x86 XP-2 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/x86%2520XP-2%25202.5/builds/44 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: andrew.kuchling,lars.gustaebel,neal.norwitz,raymond.hettinger,thomas.heller,thomas.wouters Build had warnings: warnings test Excerpt from the test logfile: 1 test failed: test_socket_ssl sincerely, -The Buildbot From buildbot at python.org Mon Jan 1 22:36:13 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 01 Jan 2007 21:36:13 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP-2 trunk Message-ID: <20070101213613.A00031E4010@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/948 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: andrew.kuchling,lars.gustaebel,neal.norwitz,raymond.hettinger Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_dumbdbm test_uu ====================================================================== FAIL: test_dumbdbm_creation_mode (test.test_dumbdbm.DumbDBMTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Code\bb_slave\trunk.peters-windows\build\lib\test\test_dumbdbm.py", line 55, in test_dumbdbm_creation_mode self.assertEqual(stat.S_IMODE(st.st_mode), 0635) AssertionError: 438 != 413 ====================================================================== FAIL: test_encode (test.test_uu.UUFileTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Code\bb_slave\trunk.peters-windows\build\lib\test\test_uu.py", line 137, in test_encode self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) AssertionError: 'begin 644 @testi\nM5&AE(\'-M;V]T:"US8V%L960@<\'ET:&]N(&-R97!T(&]V97(@=&AE(\'-L965P\n):6YG(&1O9PT*\n \nend\n' != 'begin 644 @testi\nM5&AE(\'-M;V]T:"US8V%L960@<\'ET:&]N(&-R97!T(&]V97(@=&AE(\'-L965P\n(:6YG(&1O9PH \n \nend\n' sincerely, -The Buildbot From python-checkins at python.org Tue Jan 2 01:02:42 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 2 Jan 2007 01:02:42 +0100 (CET) Subject: [Python-checkins] r53204 - peps/trunk/pep-0000.txt peps/trunk/pep-3108.txt Message-ID: <20070102000242.331871E4007@bag.python.org> Author: brett.cannon Date: Tue Jan 2 01:02:41 2007 New Revision: 53204 Added: peps/trunk/pep-3108.txt (contents, props changed) Modified: peps/trunk/pep-0000.txt Log: Add PEP 3108: Standard Library Reorganization. Modified: peps/trunk/pep-0000.txt ============================================================================== --- peps/trunk/pep-0000.txt (original) +++ peps/trunk/pep-0000.txt Tue Jan 2 01:02:41 2007 @@ -106,6 +106,7 @@ 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 Finished PEPs (done, implemented in Subversion) @@ -445,6 +446,7 @@ 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 Key Added: peps/trunk/pep-3108.txt ============================================================================== --- (empty file) +++ peps/trunk/pep-3108.txt Tue Jan 2 01:02:41 2007 @@ -0,0 +1,597 @@ +PEP: 3108 +Title: Standard Library Reorganization +Version: $Revision$ +Last-Modified: $Date$ +Author: David Goodger , +Status: Draft +Type: Informational +Python-Version: 3.0 +Content-Type: text/x-rst +Created: 01-Jan-2007 +Post-History: + + +Abstract +======== + +Just like the language itself, Python's standard library (stdlib) has +grown over the years to be very rich. But over time some modules +have lost their need to be included with Python. There has also been +an introduction of a naming convention for modules since Python's +inception that not all modules follow. + +With Python 3.0 a chance to remove modules that do not have long term +usefulness has presented itself. This chance also allows for the +renaming of modules so that they follow the Python style guide +[#pep-0008]_. This PEP lists modules that should not be included in +Python 3.0 and what modules need to be renamed. + + +Modules to Remove +================= + +Guido pronounced that "silly old stuff" is to be deleted from the +stdlib for Py3K [#silly-old-stuff]_. This is open-ended on purpose. +Each module to be removed needs to have a justification as to why it +should no longer be distributed with Python. This can range from the +module being deprecated in Python 2.x to being for a platform that is +no longer widely used. + +This section of the PEP lists the various modules to be removed. Each +subsection represents a different reason for modules to be +removed. Each module must have a specific justification on top of +being listed in a specific subsection so as to make sure only modules +that truly deserve to be removed are in fact removed. + +When a reason mentions how long it has been since a module has been +"uniquely edited", it is in reference to how long it has been since a +checkin was done specifically for the module and not for a change that +applied universally across the entire stdlib. If an edit time is not +denoted as "unique" then it is the last time the file was edited, +period. + + +Previously deprecated +--------------------- + +Modules in this section have been deprecated at some point in the +Python 2.x release series but are currently still distributed with +Python. Deprecation information is gathered either from PEP 4 or the +Global Module Index [#pep-0004]_, [#module-index]_. Each module is +listed with the Python version that the deprecation started in. + +* buildtools + 2.3 +* cfmfile + 2.4 +* gopherlib + 2.5 +* macfs + 2.3 +* md5 + 2.5 +* mimetools + 2.3 +* MimeWriter + 2.3 +* mimefy + 2.3 +* multifile + 2.3 +* posixfile + 1.5 +* rfc822 + 2.3 +* rgbimg + 2.5 +* sha + 2.5 + + +Platform-specific with minimal use +---------------------------------- + +Python supports many platforms, some of which are not widely held. +And on some of these platforms there are modules that have limited use +to people on those platforms. Because of their limited usefulness it +would be better to no longer burden the Python development team with +their maintenance. + +* IRIX (which is no longer produced [#irix-retirement]_) + + AL/al + - Provides sound support on Indy and Indigo workstations. + * Both workstations are no longer available. + - Code has not been uniquely edited in three years. + + cd + - CD drive control for SGI systems. + * SGI no longer sells machines with IRIX on them. + - Code has not been uniquely edited in 14 years. + + DEVICE/GL/gl/cgen/cgensuport + - OpenGL access. + - Has not been edited in at least eight years. + - Third-party libraries provide better support. + * PyOpenGL [#pyopengl]_ + + FL/fl/flp + - Wrapper for the FORMS library [#irix-forms]_ + * FORMS has not been edited in 12 years. + - Library is not widely used. + * First eight hits on Google are for Python docs for fl. + + fm + - Wrapper to the IRIS Font Manager library. + * Only available on SGI machines which no longer come with + IRIX. + + imgfile + - Wrapper for SGI libimage library for imglib image files + (``.rgb`` files). + - Python Imaging Library provdes read-only support [#pil]_. + - Not uniquely edited in 13 years. + + jpeg + - Wrapper for JPEG (de)compressor. + - Code not uniquely edited in nine years. + - Third-party libraries provide better support. + * Python Imaging Library [#pil]_ + + sv + - Wrapper for Indigo video card. + * Harware is no longer manufactured. + - Undocumented. + - Code not uniquely edited in 13 years. +* Solaris + + SUNAUDIODEV/sunaudiodev + - Access to the sound card on Sun machines. + - Code not uniquely edited in over eight years. +* Mac + + applesingle + - Undocumented. + * AppleSingle is a binary file format for A/UX. + + A/UX no longer distributed. +* UNIX + + nis + - Wrapper for NIS. + * NIS has been replaced by LDAP, DNS, and Kerberos. + + +Minimal usage +------------- + +Some modules that are platform-independent have minimal usage. This +can be from how easy it is to implement the functionality from scratch +or because the audience for the code is small. + +* audiodev + + Undocumented. + + Not edited in five years. + + If removed sunaudio should go as well. + - Undocumented. + - Not edited in over seven years. +* fileinput + + Basic functionality handled by ``itertools.chain``. + + Using ``enumerate`` (for the line number in the file), + ``itertools.repeat`` (for returning the filename with each + line), and ``zip`` (for connecting the ``enumerate`` object and + ``itertools.repeat`` object) provides 95% of other unique + abilities of fileinput. +* imputil + + Undocumented. + + Never updated to support absolute imports. +* mutex + + Easy to implement using a semaphore and a queue. + + Cannot block on a lock attempt. + + Not uniquely edited since its addition 15 years ago. +* repr + + Controls output of the repr of objects. + - String slicing and string interpolation can do similar work. + + Used by pdb, but do not need to expose API. +* symtable/_symtable + + Undocumented. +* telnetlib + + Telnet is not used very much anymore. + - Telnet is unsafe. + - Most people use SSH instead. +* toaiff + + Undocumented. + + Requires ``sox`` library to be installed on the system. +* user + + Easily handled by allowing the application specify its own + module name, check for existence, and import if found. +* new + + Just a rebinding of names from the 'types' module. + + Can also call ``type`` built-in to get most types easily. +* pure + + Written before Pure Atria was bought by Rational which was then + bought by IBM (in other words, very old). + +Obsolete +-------- + +Becoming obsolete signifies that either another module in the stdlib +or a widely distributed third-party library provides a better solution +for what the module is meant for. + +* base64/quopri/uu + + Support exists in the codecs module. + + If removed (along with binhex), also remove binascii. + - C implementation of base64, binhex, and uu modules. +* asynchat/asyncore + + Third-party libraries provide better solutions. + - twisted [#twisted]_ + + Deprecation previously supported [#py-dev-summary-2004-11-01]_ +* Bastion/rexec + + Restricted execution / security. + + Turned off in Python 2.3. + + Modules deemed unsafe. +* dl + + ctypes provides better support for same functionality. +* fpformat + + All functionality is supported by string interpolation. +* getopt + + optparse provides better functionality. +* ihooks + + Documented except for saying that module might be obsolete. + + For use with rexec which has been turned off since Python 2.3. +* imageop + + Better support by third-party libraries. + - Python Imaging Library [#pil]_. +* linuxaudiodev + + Replaced by ossaudiodev. +* stat + + ``os.stat`` now returns a tuple with attributes. +* statvfs + + ``os.statvfs`` now returns a tuple with attributes. +* strop + + Implements functions used by 'string' module that have now + become methods on the str type. +* thread + + People should use 'threading' instead. + - Rename 'thread' to _thread. + - Deprecate dummy_thread. + * Rename to _mockthread. + * Change of name better reflects modules purpose. + + Guido has previously supported the deprecation + [#thread-deprecation]_. +* timing + + Use timeit or time. + + Documentation says the module is obsolete [#timing-module]_. + + +Modules to Rename +================= + +Along with the stdlib gaining some modules that are no longer +relevant, there is also the issue of naming. Many modules existed in +the stdlib before PEP 8 came into existence [#pep-0008]_. This has +led to some naming inconsistencies that should be addressed. + +Any module that has been suggested for removal and does not meet the +required naming scheme is *not* listed below. + + +PEP 8 violations +---------------- + +PEP 8 specifies that modules "should have short, lowercase names, +without underscores" [#pep-0008]_. There is no mention, though, if +this rule extends to modules contained within a package. The +assumption is that underscores are acceptable in module names when +they are contained within a package but that any uppercase letters is +not. + +* _winreg + winreg (rename also because module has a public interface). +* autoGIL + autogil +* BaseHTTPServer + basehttpserver +* Carbon + carbon +* CGIHTTPServer + cgihttpserver +* ColorPicker + colorpicker +* ConfigParser + configparser +* Cookie + cookie +* copy_reg + copyreg +* cProfile +* DocXMLRPCServer + docxmlrpcserver +* dummy_threading + mockthreading (rename because "mock" makes more sense than + "dummy" and rename already required). +* EasyDialogs + easydialogs +* FrameWork + framework +* HTMLParser + htmlparser +* MacOS + macos +* MiniAEFrame + miniaeframe +* Nav + nav +* PixMapWrapper + pixmapwrapper +* py_compile + pycompile +* Queue + queue +* repr + reprlib (rename because module name shadows a built-in). +* ScrolledText + scrolledtext +* SimpleHTTPServer + simplehttpserver +* SimpleXMLRPCServer + simplexmlrpcserver +* SocketServer + socketserver +* StringIO + stringio +* Tix + tix +* Tkinter + tkinter +* UserDict + userdict +* UserList + userlist +* UserString + userstring +* W + w + + +Merging C and Python implementations of the same interface +---------------------------------------------------------- + +Several interfaces have both a Python and C implementation. While it +is great to have a C implementation for speed with a Python +implementation as fallback, there is no need to expose the two +implementations independently in the stdlib. For Python 3.0 all +interfaces with two implementations will be merged into a single +public interface. + +The C module is to be given a leading underscore to delineate the fact +that it is not the reference implementation (the Python implementation +is). This means that any semantic difference between the C and Python +versions must be dealt with before Python 3.0 or else the C +implementation will be removed until it can be fixed. + +One interface that is not listed below is xml.etree.ElementTree. This +is an externally maintained module and thus is not under the direct +control of the Python development team for renaming. See `Open +Issues`_ for a discussion on this. + +* pickle/cPickle + + Rename cPickle to _pickle. + + Semantic completeness of C implementation *not* verified. +* profile/cProfile + + Rename cProfile to profile. + + Semantic completeness of C implementation *not* verified. +* StringIO/cStringIO + + Rename StringIO to stringio. + + Rename cStringIO to _stringio. + + Semantic completeness of C implementation *not* verified. + + +No public, documented interface +------------------------------- + +There are several modules in the stdlib that have no defined public +interface. These modules exist as support code for other modules that +are exposed. Because they are not meant to be used directly they +should be renamed to reflect this fact. + +* bdb + _bdb +* markupbase + _markupbase +* opcode + _opcode +* dummythread + _mockthread (assuming the deprecation of 'thread' occurs). + + +Transition Plan +=============== + +For modules to be removed +------------------------- + +A PendingDeprecationWarning will be set in Python 2.6 for all modules +slated to be removed in Python 3.0. This will allow people to know +which modules will not exist but without being overly noisy since +PendingDeprecationWarning is by default silenced. + + +For modules to be renamed +------------------------- + +Modules will be renamed in Python 2.6 . The original names of the +modules will still work but will raise ImportWarning upon import. The +refactoring tool for transitioning to Python 3.0 will refactor imports +that use the original names to the new names. + + +Open Issues +=========== + +Consolidate dependent modules together into a single module or package? +----------------------------------------------------------------------- + +The stdlib has several modules that have a level of dependency between +them (e.g., urllib and urllib2). Usually one is a low-level module +that provides basic abilities with a corresponding higher-level API is +given in another module for simple use-cases. In Python 3.0 we could +group these dependent modules together into a single module or package +to better reflect their relationship. + +Keep in mind when looking at the groupings that deprecation or removal +is also a possibility if there is enough overlap or a module is +obsolete. + +* Cookie/cookielib +* urllib/urllib2 + + urlparse? + + httplib? +* cgi/cgitb +* Tix/Tkinter +* getpass/pwd/spwd/grp +* mailbox/mhlib +* anydbm/whichdbm +* bsddb/dbhash +* pickle/pickletools +* HTMLParser/htmllib +* ftplib/netrc +* parser/symbol + + +Consolidate certain modules with similar themes together in a package? +---------------------------------------------------------------------- + +Packages are often used to group together modules that have a similar +theme but do not have any direct relationship or dependency upon each +other. For Python 3.0 obvious groupings could be done since renaming +of various modules is already occurring. + +* collections + + heapq + + Queue + + sets + + UserDist + + UserList + + What to do with UserString? + - Have a package for Python implementations of built-in types + instead of putting the User* modules into 'collections'? +* mac + + Various Mac-specific modules. + + Same can be done for other platform-specific code. +* Profiling + + cProfile + + profile + + hotshot + + pstats +* email + + mailbox + + mhlib +* Databases + + anydbm + + dbhash + + dbm + + bsddb + + dumbdbm + + gdbm + + whichdb +* Audio + + aifc + + audioop + + chunk + + ossaudiodev + + sunau + + wave + + winsound +* Servers + + BaseHTTPServer + + CGIHTTPServer + + DocXMLRPCServer + + SimpleHTTPServer + + SimpleXMLRPCServer + + SocketServer + + +Modules reliant on obsolete/rarely used file formats? +----------------------------------------------------- + +Several modules in the stdlib work on a specific file format. It is +possible some of these formats are no longer used and thus the stdlib +modules for them can go. Below is a list of some modules which rely +on a file format that may be obsolete. + +* aifc + AIFF and AIFF-C audio files. Appears to be only user of the cl + module (which is undocumented). +* audioop + Raw (8|16|32)-bit wide audio files (as generated by the al and + sunaudiodev modules). +* binhex + binhex4 encoding. +* chunk + AIFF, AIFF-C, and RMFF audio files. +* sunau + Sun AU audio files [#sun-au]_. + + +Renaming of modules maintained outside of the stdlib +---------------------------------------------------- + +xml.etree.ElementTree not only does not meet PEP 8 naming standards +but it also has an exposed C implementation [#pep-0008]_. It is an +externally maintained package, though [#pep-0360]_. A request will be +made for the maintainer to change the name so that it matches PEP 8 +and hides the C implementation. + + +References +========== + +.. [#pep-0004] PEP 4: Deprecation of Standard Modules + (http://www.python.org/dev/pep-0004/) + +.. [#pep-0008] PEP 8: Style Guide for Python Code + (http://www.python.org/dev/pep-0008/) + +.. [#pep-0360] PEP 360: Externally Maintained Packages + (http://www.python.org/peps/pep-0360/) + +.. [#module-index] Python Documentation: Global Module Index + (http://docs.python.org/modindex.html) + +.. [#timing-module] Python Library Reference: Obsolete + (http://docs.python.org/lib/obsolete-modules.html) + +.. [#silly-old-stuff] Python-Dev email: "Py3k release schedule worries" + (http://mail.python.org/pipermail/python-3000/2006-December/005130.html) + +.. [#thread-deprecation] Python-Dev email: Autoloading? + (http://mail.python.org/pipermail/python-dev/2005-October/057244.html) + +.. [#py-dev-summary-2004-11-01] Python-Dev Summary: 2004-11-01 + (http://www.python.org/dev/summary/2004-11-01_2004-11-15/#id10) + +.. [#pyopengl] PyOpenGL + (http://pyopengl.sourceforge.net/) + +.. [#pil] Python Imaging Library (PIL) + (http://www.pythonware.com/products/pil/) + +.. [#twisted] Twisted + (http://twistedmatrix.com/trac/) + +.. [#irix-retirement] SGI Press Release: + End of General Availability for MIPS IRIX Products -- December 2006 + (http://www.sgi.com/support/mips_irix.html) + +.. [#irix-forms] FORMS Library by Mark Overmars + (ftp://ftp.cs.ruu.nl/pub/SGI/FORMS) + +.. [#sun-au] Wikipedia: Au file format + (http://en.wikipedia.org/wiki/Au_file_format) + + +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 Tue Jan 2 04:34:24 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 2 Jan 2007 04:34:24 +0100 (CET) Subject: [Python-checkins] r53205 - peps/trunk/pep-3108.txt Message-ID: <20070102033424.3B1A41E4007@bag.python.org> Author: brett.cannon Date: Tue Jan 2 04:34:23 2007 New Revision: 53205 Modified: peps/trunk/pep-3108.txt Log: Fix a typo on the renaming of cProfile. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Tue Jan 2 04:34:23 2007 @@ -293,7 +293,6 @@ cookie * copy_reg copyreg -* cProfile * DocXMLRPCServer docxmlrpcserver * dummy_threading @@ -368,7 +367,7 @@ + Rename cPickle to _pickle. + Semantic completeness of C implementation *not* verified. * profile/cProfile - + Rename cProfile to profile. + + Rename cProfile to _profile. + Semantic completeness of C implementation *not* verified. * StringIO/cStringIO + Rename StringIO to stringio. From python-checkins at python.org Tue Jan 2 05:45:57 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 2 Jan 2007 05:45:57 +0100 (CET) Subject: [Python-checkins] r53206 - peps/trunk/pep-3108.txt Message-ID: <20070102044557.A7B2A1E4007@bag.python.org> Author: brett.cannon Date: Tue Jan 2 05:45:57 2007 New Revision: 53206 Modified: peps/trunk/pep-3108.txt Log: Change the warning raised for module renames to PendingDeprecationWarning so that it is a silent warning by default. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Tue Jan 2 05:45:57 2007 @@ -409,9 +409,9 @@ ------------------------- Modules will be renamed in Python 2.6 . The original names of the -modules will still work but will raise ImportWarning upon import. The -refactoring tool for transitioning to Python 3.0 will refactor imports -that use the original names to the new names. +modules will still work but will raise a PendingDeprecationWarning +upon import. The refactoring tool for transitioning to Python 3.0 +will refactor imports that use the new names. Open Issues From python-checkins at python.org Tue Jan 2 07:04:26 2007 From: python-checkins at python.org (david.goodger) Date: Tue, 2 Jan 2007 07:04:26 +0100 (CET) Subject: [Python-checkins] r53207 - peps/trunk/pep-3108.txt Message-ID: <20070102060426.18A741E4008@bag.python.org> Author: david.goodger Date: Tue Jan 2 07:04:25 2007 New Revision: 53207 Modified: peps/trunk/pep-3108.txt Log: take credit where credit is due, dude Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Tue Jan 2 07:04:25 2007 @@ -2,7 +2,7 @@ Title: Standard Library Reorganization Version: $Revision$ Last-Modified: $Date$ -Author: David Goodger , +Author: Brett Cannon Status: Draft Type: Informational Python-Version: 3.0 From python-checkins at python.org Tue Jan 2 07:53:48 2007 From: python-checkins at python.org (david.goodger) Date: Tue, 2 Jan 2007 07:53:48 +0100 (CET) Subject: [Python-checkins] r53208 - peps/trunk/pep-3108.txt Message-ID: <20070102065348.1D1F21E4008@bag.python.org> Author: david.goodger Date: Tue Jan 2 07:53:47 2007 New Revision: 53208 Modified: peps/trunk/pep-3108.txt Log: simplified lists (flat is better than nested); some minor edits Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Tue Jan 2 07:53:47 2007 @@ -20,11 +20,11 @@ an introduction of a naming convention for modules since Python's inception that not all modules follow. -With Python 3.0 a chance to remove modules that do not have long term -usefulness has presented itself. This chance also allows for the -renaming of modules so that they follow the Python style guide -[#pep-0008]_. This PEP lists modules that should not be included in -Python 3.0 and what modules need to be renamed. +Python 3.0 has presented a chance to remove modules that do not have +long term usefulness. This chance also allows for the renaming of +modules so that they follow the Python style guide [#pep-0008]_. This +PEP lists modules that should not be included in Python 3.0 and what +modules need to be renamed. Modules to Remove @@ -58,34 +58,25 @@ Python 2.x release series but are currently still distributed with Python. Deprecation information is gathered either from PEP 4 or the Global Module Index [#pep-0004]_, [#module-index]_. Each module is -listed with the Python version that the deprecation started in. +listed with the Python version of initial deprecation. -* buildtools - 2.3 -* cfmfile - 2.4 -* gopherlib - 2.5 -* macfs - 2.3 -* md5 - 2.5 -* mimetools - 2.3 -* MimeWriter - 2.3 -* mimefy - 2.3 -* multifile - 2.3 -* posixfile - 1.5 -* rfc822 - 2.3 -* rgbimg - 2.5 -* sha - 2.5 +============== ========== +Module Deprecated +============== ========== +buildtools 2.3 +cfmfile 2.4 +gopherlib 2.5 +macfs 2.3 +md5 2.5 +mimetools 2.3 +MimeWriter 2.3 +mimefy 2.3 +multifile 2.3 +posixfile 1.5 +rfc822 2.3 +rgbimg 2.5 +sha 2.5 +============== ========== Platform-specific with minimal use @@ -98,56 +89,79 @@ their maintenance. * IRIX (which is no longer produced [#irix-retirement]_) - + AL/al - - Provides sound support on Indy and Indigo workstations. - * Both workstations are no longer available. - - Code has not been uniquely edited in three years. - + cd - - CD drive control for SGI systems. - * SGI no longer sells machines with IRIX on them. - - Code has not been uniquely edited in 14 years. - + DEVICE/GL/gl/cgen/cgensuport - - OpenGL access. - - Has not been edited in at least eight years. - - Third-party libraries provide better support. - * PyOpenGL [#pyopengl]_ - + FL/fl/flp - - Wrapper for the FORMS library [#irix-forms]_ - * FORMS has not been edited in 12 years. - - Library is not widely used. - * First eight hits on Google are for Python docs for fl. - + fm - - Wrapper to the IRIS Font Manager library. - * Only available on SGI machines which no longer come with - IRIX. - + imgfile - - Wrapper for SGI libimage library for imglib image files - (``.rgb`` files). - - Python Imaging Library provdes read-only support [#pil]_. - - Not uniquely edited in 13 years. - + jpeg - - Wrapper for JPEG (de)compressor. - - Code not uniquely edited in nine years. - - Third-party libraries provide better support. - * Python Imaging Library [#pil]_ - + sv - - Wrapper for Indigo video card. - * Harware is no longer manufactured. - - Undocumented. - - Code not uniquely edited in 13 years. + + + AL/al + + - Provides sound support on Indy and Indigo workstations. + - Both workstations are no longer available. + - Code has not been uniquely edited in three years. + + + cd + + - CD drive control for SGI systems. + - SGI no longer sells machines with IRIX on them. + - Code has not been uniquely edited in 14 years. + + + DEVICE/GL/gl/cgen/cgensuport + + - OpenGL access. + - Has not been edited in at least eight years. + - Third-party libraries provide better support (PyOpenGL [#pyopengl]_). + + + FL/fl/flp + + - Wrapper for the FORMS library [#irix-forms]_ + - FORMS has not been edited in 12 years. + - Library is not widely used. + - First eight hits on Google are for Python docs for fl. + + + fm + + - Wrapper to the IRIS Font Manager library. + - Only available on SGI machines which no longer come with IRIX. + + + imgfile + + - Wrapper for SGI libimage library for imglib image files + (``.rgb`` files). + - Python Imaging Library provdes read-only support [#pil]_. + - Not uniquely edited in 13 years. + + + jpeg + + - Wrapper for JPEG (de)compressor. + - Code not uniquely edited in nine years. + - Third-party libraries provide better support + (Python Imaging Library [#pil]_). + + + sv + + - Wrapper for Indigo video card. + - Harware is no longer manufactured. + - Undocumented. + - Code not uniquely edited in 13 years. + * Solaris - + SUNAUDIODEV/sunaudiodev - - Access to the sound card on Sun machines. - - Code not uniquely edited in over eight years. + + + SUNAUDIODEV/sunaudiodev + + - Access to the sound card on Sun machines. + - Code not uniquely edited in over eight years. + * Mac - + applesingle - - Undocumented. - * AppleSingle is a binary file format for A/UX. - + A/UX no longer distributed. + + + applesingle + + - Undocumented. + - AppleSingle is a binary file format for A/UX. + - A/UX no longer distributed. + * UNIX - + nis - - Wrapper for NIS. - * NIS has been replaced by LDAP, DNS, and Kerberos. + + + nis + + - Wrapper for NIS. + - NIS has been replaced by LDAP, DNS, and Kerberos. Minimal usage @@ -158,47 +172,68 @@ or because the audience for the code is small. * audiodev - + Undocumented. - + Not edited in five years. - + If removed sunaudio should go as well. - - Undocumented. - - Not edited in over seven years. + + + Undocumented. + + Not edited in five years. + + If removed sunaudio should go as well (also undocumented; not + edited in over seven years). + * fileinput - + Basic functionality handled by ``itertools.chain``. - + Using ``enumerate`` (for the line number in the file), - ``itertools.repeat`` (for returning the filename with each - line), and ``zip`` (for connecting the ``enumerate`` object and - ``itertools.repeat`` object) provides 95% of other unique - abilities of fileinput. + + + Basic functionality handled by ``itertools.chain``. + + Using ``enumerate`` (for the line number in the file), + ``itertools.repeat`` (for returning the filename with each + line), and ``zip`` (for connecting the ``enumerate`` object and + ``itertools.repeat`` object) provides 95% of other unique + abilities of fileinput. + * imputil - + Undocumented. - + Never updated to support absolute imports. + + + Undocumented. + + Never updated to support absolute imports. + * mutex - + Easy to implement using a semaphore and a queue. - + Cannot block on a lock attempt. - + Not uniquely edited since its addition 15 years ago. + + + Easy to implement using a semaphore and a queue. + + Cannot block on a lock attempt. + + Not uniquely edited since its addition 15 years ago. + * repr - + Controls output of the repr of objects. - - String slicing and string interpolation can do similar work. - + Used by pdb, but do not need to expose API. + + + Controls output of the repr of objects. + + String slicing and string interpolation can do similar work. + + Used by pdb, but do not need to expose API. + * symtable/_symtable - + Undocumented. + + + Undocumented. + * telnetlib - + Telnet is not used very much anymore. - - Telnet is unsafe. - - Most people use SSH instead. + + + Telnet is not used very much anymore. + + Telnet is unsafe. + + Most people use SSH instead. + * toaiff - + Undocumented. - + Requires ``sox`` library to be installed on the system. + + + Undocumented. + + Requires ``sox`` library to be installed on the system. + * user - + Easily handled by allowing the application specify its own - module name, check for existence, and import if found. + + + Easily handled by allowing the application specify its own + module name, check for existence, and import if found. + * new - + Just a rebinding of names from the 'types' module. - + Can also call ``type`` built-in to get most types easily. + + + Just a rebinding of names from the 'types' module. + + Can also call ``type`` built-in to get most types easily. + * pure - + Written before Pure Atria was bought by Rational which was then - bought by IBM (in other words, very old). + + + Written before Pure Atria was bought by Rational which was then + bought by IBM (in other words, very old). + Obsolete -------- @@ -208,49 +243,79 @@ for what the module is meant for. * base64/quopri/uu - + Support exists in the codecs module. - + If removed (along with binhex), also remove binascii. - - C implementation of base64, binhex, and uu modules. + + + Support exists in the codecs module. + + If removed (along with binhex), also remove binascii + (C implementation of base64, binhex, and uu modules). + * asynchat/asyncore - + Third-party libraries provide better solutions. - - twisted [#twisted]_ - + Deprecation previously supported [#py-dev-summary-2004-11-01]_ + + + Third-party libraries provide better solutions + (twisted [#twisted]_). + + Deprecation previously supported [#py-dev-summary-2004-11-01]_ + * Bastion/rexec - + Restricted execution / security. - + Turned off in Python 2.3. - + Modules deemed unsafe. + + + Restricted execution / security. + + Turned off in Python 2.3. + + Modules deemed unsafe. + * dl - + ctypes provides better support for same functionality. + + + ctypes provides better support for same functionality. + * fpformat - + All functionality is supported by string interpolation. + + + All functionality is supported by string interpolation. + * getopt - + optparse provides better functionality. + + + optparse provides better functionality. + * ihooks - + Documented except for saying that module might be obsolete. - + For use with rexec which has been turned off since Python 2.3. + + + Documented except for saying that module might be obsolete. + + For use with rexec which has been turned off since Python 2.3. + * imageop - + Better support by third-party libraries. - - Python Imaging Library [#pil]_. + + + Better support by third-party libraries + (Python Imaging Library [#pil]_). + * linuxaudiodev - + Replaced by ossaudiodev. + + + Replaced by ossaudiodev. + * stat - + ``os.stat`` now returns a tuple with attributes. + + + ``os.stat`` now returns a tuple with attributes. + * statvfs - + ``os.statvfs`` now returns a tuple with attributes. + + + ``os.statvfs`` now returns a tuple with attributes. + * strop - + Implements functions used by 'string' module that have now - become methods on the str type. + + + Implements functions used by 'string' module that have now + become methods on the str type. + * thread - + People should use 'threading' instead. - - Rename 'thread' to _thread. - - Deprecate dummy_thread. - * Rename to _mockthread. - * Change of name better reflects modules purpose. - + Guido has previously supported the deprecation - [#thread-deprecation]_. + + + People should use 'threading' instead. + + - Rename 'thread' to _thread. + - Deprecate dummy_thread. + + * Rename to _mockthread. + * Change of name better reflects modules purpose. + + + Guido has previously supported the deprecation + [#thread-deprecation]_. + * timing - + Use timeit or time. - + Documentation says the module is obsolete [#timing-module]_. + + + Use timeit or time. + + Documentation says the module is obsolete [#timing-module]_. Modules to Rename @@ -275,71 +340,45 @@ they are contained within a package but that any uppercase letters is not. -* _winreg - winreg (rename also because module has a public interface). -* autoGIL - autogil -* BaseHTTPServer - basehttpserver -* Carbon - carbon -* CGIHTTPServer - cgihttpserver -* ColorPicker - colorpicker -* ConfigParser - configparser -* Cookie - cookie -* copy_reg - copyreg -* DocXMLRPCServer - docxmlrpcserver -* dummy_threading - mockthreading (rename because "mock" makes more sense than - "dummy" and rename already required). -* EasyDialogs - easydialogs -* FrameWork - framework -* HTMLParser - htmlparser -* MacOS - macos -* MiniAEFrame - miniaeframe -* Nav - nav -* PixMapWrapper - pixmapwrapper -* py_compile - pycompile -* Queue - queue -* repr - reprlib (rename because module name shadows a built-in). -* ScrolledText - scrolledtext -* SimpleHTTPServer - simplehttpserver -* SimpleXMLRPCServer - simplexmlrpcserver -* SocketServer - socketserver -* StringIO - stringio -* Tix - tix -* Tkinter - tkinter -* UserDict - userdict -* UserList - userlist -* UserString - userstring -* W - w +================== ================================================== +Current Name Replacement Name +================== ================================================== +_winreg winreg (rename also because module has a public + interface) +autoGIL autogil +BaseHTTPServer basehttpserver +Carbon carbon +CGIHTTPServer cgihttpserver +ColorPicker colorpicker +ConfigParser configparser +Cookie cookie +copy_reg copyreg +DocXMLRPCServer docxmlrpcserver +dummy_threading mockthreading (rename because "mock" makes more + sense than "dummy" and rename already required) +EasyDialogs easydialogs +FrameWork framework +HTMLParser htmlparser +MacOS macos +MiniAEFrame miniaeframe +Nav nav +PixMapWrapper pixmapwrapper +py_compile pycompile +Queue queue +repr reprlib (rename because module name shadows a + built-in) +ScrolledText scrolledtext +SimpleHTTPServer simplehttpserver +SimpleXMLRPCServer simplexmlrpcserver +SocketServer socketserver +StringIO stringio +Tix tix +Tkinter tkinter +UserDict userdict +UserList userlist +UserString userstring +W w +================== ================================================== Merging C and Python implementations of the same interface @@ -364,15 +403,20 @@ Issues`_ for a discussion on this. * pickle/cPickle - + Rename cPickle to _pickle. - + Semantic completeness of C implementation *not* verified. + + + Rename cPickle to _pickle. + + Semantic completeness of C implementation *not* verified. + * profile/cProfile - + Rename cProfile to _profile. - + Semantic completeness of C implementation *not* verified. + + + Rename cProfile to _profile. + + Semantic completeness of C implementation *not* verified. + * StringIO/cStringIO - + Rename StringIO to stringio. - + Rename cStringIO to _stringio. - + Semantic completeness of C implementation *not* verified. + + + Rename StringIO to stringio. + + Rename cStringIO to _stringio. + + Semantic completeness of C implementation *not* verified. No public, documented interface @@ -383,14 +427,15 @@ are exposed. Because they are not meant to be used directly they should be renamed to reflect this fact. -* bdb - _bdb -* markupbase - _markupbase -* opcode - _opcode -* dummythread - _mockthread (assuming the deprecation of 'thread' occurs). +============ =============================== +Current Name Replacement Name +============ =============================== +bdb _bdb +markupbase _markupbase +opcode _opcode +dummythread _mockthread (assuming the + deprecation of 'thread' occurs) +============ =============================== Transition Plan @@ -408,7 +453,7 @@ For modules to be renamed ------------------------- -Modules will be renamed in Python 2.6 . The original names of the +Modules will be renamed in Python 2.6. The original names of the modules will still work but will raise a PendingDeprecationWarning upon import. The refactoring tool for transitioning to Python 3.0 will refactor imports that use the new names. @@ -432,9 +477,7 @@ obsolete. * Cookie/cookielib -* urllib/urllib2 - + urlparse? - + httplib? +* urllib/urllib2 (urlparse? httplib?) * cgi/cgitb * Tix/Tkinter * getpass/pwd/spwd/grp @@ -456,48 +499,61 @@ of various modules is already occurring. * collections - + heapq - + Queue - + sets - + UserDist - + UserList - + What to do with UserString? - - Have a package for Python implementations of built-in types - instead of putting the User* modules into 'collections'? + + + heapq + + Queue + + sets + + UserDist + + UserList + + What to do with UserString? + Have a package for Python implementations of built-in types + instead of putting the User* modules into 'collections'? + * mac - + Various Mac-specific modules. - + Same can be done for other platform-specific code. + + + Various Mac-specific modules. + + Same can be done for other platform-specific code. + * Profiling - + cProfile - + profile - + hotshot - + pstats + + + cProfile + + profile + + hotshot + + pstats + * email - + mailbox - + mhlib + + + mailbox + + mhlib + * Databases - + anydbm - + dbhash - + dbm - + bsddb - + dumbdbm - + gdbm - + whichdb + + + anydbm + + dbhash + + dbm + + bsddb + + dumbdbm + + gdbm + + whichdb + * Audio - + aifc - + audioop - + chunk - + ossaudiodev - + sunau - + wave - + winsound + + + aifc + + audioop + + chunk + + ossaudiodev + + sunau + + wave + + winsound + * Servers - + BaseHTTPServer - + CGIHTTPServer - + DocXMLRPCServer - + SimpleHTTPServer - + SimpleXMLRPCServer - + SocketServer + + + BaseHTTPServer + + CGIHTTPServer + + DocXMLRPCServer + + SimpleHTTPServer + + SimpleXMLRPCServer + + SocketServer Modules reliant on obsolete/rarely used file formats? @@ -508,17 +564,17 @@ modules for them can go. Below is a list of some modules which rely on a file format that may be obsolete. -* aifc +aifc AIFF and AIFF-C audio files. Appears to be only user of the cl module (which is undocumented). -* audioop +audioop Raw (8|16|32)-bit wide audio files (as generated by the al and sunaudiodev modules). -* binhex +binhex binhex4 encoding. -* chunk +chunk AIFF, AIFF-C, and RMFF audio files. -* sunau +sunau Sun AU audio files [#sun-au]_. From python-checkins at python.org Wed Jan 3 00:00:52 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 00:00:52 +0100 (CET) Subject: [Python-checkins] r53211 - peps/trunk/pep-3108.txt Message-ID: <20070102230052.30DAD1E401E@bag.python.org> Author: brett.cannon Date: Wed Jan 3 00:00:51 2007 New Revision: 53211 Modified: peps/trunk/pep-3108.txt Log: Clarify that the suggested packaging sections are not suggested package names. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 00:00:51 2007 @@ -496,7 +496,9 @@ Packages are often used to group together modules that have a similar theme but do not have any direct relationship or dependency upon each other. For Python 3.0 obvious groupings could be done since renaming -of various modules is already occurring. +of various modules is already occurring. Below is a list sectioned +off into what types of obvious groupings there seem to be. No name +for the suggested package (if not already existent) is being proposed. * collections From python-checkins at python.org Wed Jan 3 00:18:37 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 00:18:37 +0100 (CET) Subject: [Python-checkins] r53212 - peps/trunk/pep-3108.txt Message-ID: <20070102231837.1D9E11E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 00:18:36 2007 New Revision: 53212 Modified: peps/trunk/pep-3108.txt Log: telnetlib is going to stick around. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 00:18:36 2007 @@ -208,12 +208,6 @@ + Undocumented. -* telnetlib - - + Telnet is not used very much anymore. - + Telnet is unsafe. - + Most people use SSH instead. - * toaiff + Undocumented. @@ -590,6 +584,18 @@ and hides the C implementation. +Rejected Ideas +============== + +Modules that will stay +---------------------- + +* telnetlib + + + Really handy for quick-and-dirty remote access. + + Some hardware supports telnet for accessing it. + + References ========== From python-checkins at python.org Wed Jan 3 00:23:16 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 00:23:16 +0100 (CET) Subject: [Python-checkins] r53213 - peps/trunk/pep-3108.txt Message-ID: <20070102232316.E62F41E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 00:23:15 2007 New Revision: 53213 Modified: peps/trunk/pep-3108.txt Log: Add mention that the function in the stat module should migrate to the object returned by os.stat. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 00:23:15 2007 @@ -283,6 +283,8 @@ * stat + ``os.stat`` now returns a tuple with attributes. + + Functions in the module should be made into methods for the object + returned by os.stat. * statvfs From python-checkins at python.org Wed Jan 3 00:37:21 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 00:37:21 +0100 (CET) Subject: [Python-checkins] r53214 - peps/trunk/pep-3108.txt Message-ID: <20070102233721.1A86D1E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 00:37:20 2007 New Revision: 53214 Modified: peps/trunk/pep-3108.txt Log: Save fileinput from the chopping block. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 00:37:20 2007 @@ -178,15 +178,6 @@ + If removed sunaudio should go as well (also undocumented; not edited in over seven years). -* fileinput - - + Basic functionality handled by ``itertools.chain``. - + Using ``enumerate`` (for the line number in the file), - ``itertools.repeat`` (for returning the filename with each - line), and ``zip`` (for connecting the ``enumerate`` object and - ``itertools.repeat`` object) provides 95% of other unique - abilities of fileinput. - * imputil + Undocumented. @@ -589,8 +580,12 @@ Rejected Ideas ============== -Modules that will stay ----------------------- +Modules that were suggested for removal but were saved +------------------------------------------------------ + +* fileinput + + + Useful when having to work with stdin. * telnetlib From python-checkins at python.org Wed Jan 3 00:45:12 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 00:45:12 +0100 (CET) Subject: [Python-checkins] r53215 - peps/trunk/pep-3108.txt Message-ID: <20070102234512.BCAA01E4013@bag.python.org> Author: brett.cannon Date: Wed Jan 3 00:45:12 2007 New Revision: 53215 Modified: peps/trunk/pep-3108.txt Log: asyncore/asynchat will stay. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 00:45:12 2007 @@ -233,12 +233,6 @@ + If removed (along with binhex), also remove binascii (C implementation of base64, binhex, and uu modules). -* asynchat/asyncore - - + Third-party libraries provide better solutions - (twisted [#twisted]_). - + Deprecation previously supported [#py-dev-summary-2004-11-01]_ - * Bastion/rexec + Restricted execution / security. @@ -583,6 +577,10 @@ Modules that were suggested for removal but were saved ------------------------------------------------------ +* asynchat/asyncore + + + Josiah Carlson has said he will help to maintain the modules. + * fileinput + Useful when having to work with stdin. From python-checkins at python.org Wed Jan 3 01:42:29 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 01:42:29 +0100 (CET) Subject: [Python-checkins] r53216 - peps/trunk/pep-3108.txt Message-ID: <20070103004229.B85BE1E400C@bag.python.org> Author: brett.cannon Date: Wed Jan 3 01:42:29 2007 New Revision: 53216 Modified: peps/trunk/pep-3108.txt Log: Punt on the idea of a new top-level package for all of the stdlib. Someone else can tackle that idea in a separate PEP. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 01:42:29 2007 @@ -591,6 +591,16 @@ + Some hardware supports telnet for accessing it. +Introducing a new top-level package +----------------------------------- + +It has been suggested that the entire stdlib be placed within its own +package. This PEP will not address this issue as it has its own +design issues (naming, does it deserve special consideration in import +semantics, etc.). Everything within this PEP can easily be handled if +a new top-level package is introduced. + + References ========== From python-checkins at python.org Wed Jan 3 01:54:07 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 01:54:07 +0100 (CET) Subject: [Python-checkins] r53217 - peps/trunk/pep-3108.txt Message-ID: <20070103005407.214E31E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 01:54:06 2007 New Revision: 53217 Modified: peps/trunk/pep-3108.txt Log: Fix links to PEP 4 and 8 (thanks Bill Janssen). Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 01:54:06 2007 @@ -605,10 +605,10 @@ ========== .. [#pep-0004] PEP 4: Deprecation of Standard Modules - (http://www.python.org/dev/pep-0004/) + (http://www.python.org/dev/peps/pep-0004/) .. [#pep-0008] PEP 8: Style Guide for Python Code - (http://www.python.org/dev/pep-0008/) + (http://www.python.org/dev/peps/pep-0008/) .. [#pep-0360] PEP 360: Externally Maintained Packages (http://www.python.org/peps/pep-0360/) From python-checkins at python.org Wed Jan 3 02:02:09 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 02:02:09 +0100 (CET) Subject: [Python-checkins] r53218 - peps/trunk/pep-3108.txt Message-ID: <20070103010209.E34161E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 02:02:09 2007 New Revision: 53218 Modified: peps/trunk/pep-3108.txt Log: Add a suggestion from Bill Janssen of having a Web package. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 02:02:09 2007 @@ -538,6 +538,23 @@ + SimpleXMLRPCServer + SocketServer +* Web + + + urllib + + urllib + + urlparse + + httplib + + cgi + + cgitb + + BaseHTTPServer + + BaseCGIServer + + SimpleHTTPServer + + htmllib + + htmlentitydefs + + HTMLParser + + Cookie + + cookielib + Modules reliant on obsolete/rarely used file formats? ----------------------------------------------------- @@ -579,16 +596,16 @@ * asynchat/asyncore - + Josiah Carlson has said he will help to maintain the modules. + + Josiah Carlson has said he will help to maintain the modules. * fileinput - + Useful when having to work with stdin. + + Useful when having to work with stdin. * telnetlib - + Really handy for quick-and-dirty remote access. - + Some hardware supports telnet for accessing it. + + Really handy for quick-and-dirty remote access. + + Some hardware supports telnet for accessing it. Introducing a new top-level package From python-checkins at python.org Wed Jan 3 02:17:12 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 02:17:12 +0100 (CET) Subject: [Python-checkins] r53219 - peps/trunk/pep-3108.txt Message-ID: <20070103011712.C85D01E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 02:17:11 2007 New Revision: 53219 Modified: peps/trunk/pep-3108.txt Log: Remove server package suggestion, add an XML-RPC one, and not that an HTTP server package might be reasonable. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 02:17:11 2007 @@ -529,14 +529,10 @@ + wave + winsound -* Servers +* XML-RPC - + BaseHTTPServer - + CGIHTTPServer + DocXMLRPCServer - + SimpleHTTPServer + SimpleXMLRPCServer - + SocketServer * Web @@ -554,6 +550,7 @@ + HTMLParser + Cookie + cookielib + + Could also just gather HTTP servers. Modules reliant on obsolete/rarely used file formats? From python-checkins at python.org Wed Jan 3 06:05:33 2007 From: python-checkins at python.org (david.goodger) Date: Wed, 3 Jan 2007 06:05:33 +0100 (CET) Subject: [Python-checkins] r53220 - peps/trunk/pep-3108.txt Message-ID: <20070103050533.64C131E4009@bag.python.org> Author: david.goodger Date: Wed Jan 3 06:05:32 2007 New Revision: 53220 Modified: peps/trunk/pep-3108.txt Log: PEP URL correction Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 06:05:32 2007 @@ -625,7 +625,7 @@ (http://www.python.org/dev/peps/pep-0008/) .. [#pep-0360] PEP 360: Externally Maintained Packages - (http://www.python.org/peps/pep-0360/) + (http://www.python.org/dev/peps/pep-0360/) .. [#module-index] Python Documentation: Global Module Index (http://docs.python.org/modindex.html) From python-checkins at python.org Wed Jan 3 08:39:04 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 08:39:04 +0100 (CET) Subject: [Python-checkins] r53221 - peps/trunk/pep-3108.txt Message-ID: <20070103073904.2AA2B1E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 08:39:03 2007 New Revision: 53221 Modified: peps/trunk/pep-3108.txt Log: Save nis. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 08:39:03 2007 @@ -156,13 +156,6 @@ - AppleSingle is a binary file format for A/UX. - A/UX no longer distributed. -* UNIX - - + nis - - - Wrapper for NIS. - - NIS has been replaced by LDAP, DNS, and Kerberos. - Minimal usage ------------- @@ -599,6 +592,11 @@ + Useful when having to work with stdin. +* nis + + + Testimonials from people that new installations of NIS are still + occurring out in the world. + * telnetlib + Really handy for quick-and-dirty remote access. From python-checkins at python.org Wed Jan 3 17:38:20 2007 From: python-checkins at python.org (stefan.seefeld) Date: Wed, 3 Jan 2007 17:38:20 +0100 (CET) Subject: [Python-checkins] r53223 - tracker/instances/python-dev/schema.py Message-ID: <20070103163820.C6A321E4009@bag.python.org> Author: stefan.seefeld Date: Wed Jan 3 17:38:20 2007 New Revision: 53223 Modified: tracker/instances/python-dev/schema.py Log: Make title editable by users. Modified: tracker/instances/python-dev/schema.py ============================================================================== --- tracker/instances/python-dev/schema.py (original) +++ tracker/instances/python-dev/schema.py Wed Jan 3 17:38:20 2007 @@ -159,7 +159,7 @@ db.security.addPermissionToRole('User', p) p = db.security.addPermission(name='Edit', klass='issue', - properties=('type', + properties=('title', 'type', 'components', 'versions', 'severity', 'messages', 'files', 'nosy'), From python-checkins at python.org Wed Jan 3 21:12:10 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 21:12:10 +0100 (CET) Subject: [Python-checkins] r53224 - peps/trunk/pep-3108.txt Message-ID: <20070103201210.705E71E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 21:12:09 2007 New Revision: 53224 Modified: peps/trunk/pep-3108.txt Log: Saved base64, quopri, and uu (which also saves binascii). Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 21:12:09 2007 @@ -220,12 +220,6 @@ or a widely distributed third-party library provides a better solution for what the module is meant for. -* base64/quopri/uu - - + Support exists in the codecs module. - + If removed (along with binhex), also remove binascii - (C implementation of base64, binhex, and uu modules). - * Bastion/rexec + Restricted execution / security. @@ -588,6 +582,12 @@ + Josiah Carlson has said he will help to maintain the modules. +* base64/quopri/uu + + + All still widely used. + + 'codecs' module does not provide as nice of an API for basic + usage. + * fileinput + Useful when having to work with stdin. From python-checkins at python.org Wed Jan 3 21:16:25 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 21:16:25 +0100 (CET) Subject: [Python-checkins] r53225 - peps/trunk/pep-3108.txt Message-ID: <20070103201625.5AC9E1E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 21:16:24 2007 New Revision: 53225 Modified: peps/trunk/pep-3108.txt Log: Add commands and popen2 to the list of modules to remove thanks to subprocess. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 21:16:24 2007 @@ -226,6 +226,10 @@ + Turned off in Python 2.3. + Modules deemed unsafe. +* commands/popen2 + + + subprocess module replaces them [#pep-0324]_. + * dl + ctypes provides better support for same functionality. @@ -622,6 +626,9 @@ .. [#pep-0008] PEP 8: Style Guide for Python Code (http://www.python.org/dev/peps/pep-0008/) +.. [#pep-0324] PEP 324: subprocess -- New process module + (http://www.python.org/dev/peps/pep-0324/) + .. [#pep-0360] PEP 360: Externally Maintained Packages (http://www.python.org/dev/peps/pep-0360/) From python-checkins at python.org Wed Jan 3 21:20:19 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 21:20:19 +0100 (CET) Subject: [Python-checkins] r53226 - peps/trunk/pep-3108.txt Message-ID: <20070103202019.7002E1E4011@bag.python.org> Author: brett.cannon Date: Wed Jan 3 21:20:17 2007 New Revision: 53226 Modified: peps/trunk/pep-3108.txt Log: Add arguments against removing getopt. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 21:20:17 2007 @@ -241,6 +241,11 @@ * getopt + optparse provides better functionality. + + But ... + + - getopt is still widely used. + - optparse does not handle the issue of when people set + incompatible options very well. * ihooks From python-checkins at python.org Wed Jan 3 22:09:30 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 22:09:30 +0100 (CET) Subject: [Python-checkins] r53227 - peps/trunk/pep-3108.txt Message-ID: <20070103210930.0D5E71E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 22:09:29 2007 New Revision: 53227 Modified: peps/trunk/pep-3108.txt Log: Remove aifc as a possible module to remove. This leads to the suggestion of renaming cl to _cl since aifc is the only user of this undocumented module. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 22:09:29 2007 @@ -408,6 +408,7 @@ Current Name Replacement Name ============ =============================== bdb _bdb +cl _cl markupbase _markupbase opcode _opcode dummythread _mockthread (assuming the @@ -557,9 +558,6 @@ modules for them can go. Below is a list of some modules which rely on a file format that may be obsolete. -aifc - AIFF and AIFF-C audio files. Appears to be only user of the cl - module (which is undocumented). audioop Raw (8|16|32)-bit wide audio files (as generated by the al and sunaudiodev modules). From python-checkins at python.org Wed Jan 3 22:29:30 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 22:29:30 +0100 (CET) Subject: [Python-checkins] r53228 - peps/trunk/pep-3108.txt Message-ID: <20070103212930.CE97B1E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 22:29:30 2007 New Revision: 53228 Modified: peps/trunk/pep-3108.txt Log: Flesh out suggested Internet, XML-RPC, and HTTP server packages. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 22:29:30 2007 @@ -503,8 +503,11 @@ * email + + imaplib + mailbox + + mailcap + mhlib + + poplib * Databases @@ -530,24 +533,38 @@ + DocXMLRPCServer + SimpleXMLRPCServer + + xmlrpclib -* Web +* Internet - + urllib - + urllib - + urlparse - + httplib + + BaseHTTPServer + cgi + + CGIHTTPServer + cgitb - + BaseHTTPServer - + BaseCGIServer - + SimpleHTTPServer - + htmllib - + htmlentitydefs - + HTMLParser + Cookie + cookielib - + Could also just gather HTTP servers. + + ftplib (?) + + htmlentitydefs + + htmllib + + HTMLParser + + httplib + + netrc (?) + + nntplib (?) + + sgmllib (?) + + SimpleHTTPServer + + stringprep + + urllib + + urllib2 + + urlparse + + webbrowser + +* HTTP servers + + + BaseHTTPServer + + CGIHTTPServer + + DocXMLRPCServer + + SimpleHTTPServer + + SimpleXMLRPCServer Modules reliant on obsolete/rarely used file formats? From python-checkins at python.org Wed Jan 3 22:31:18 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 22:31:18 +0100 (CET) Subject: [Python-checkins] r53229 - peps/trunk/pep-3108.txt Message-ID: <20070103213118.EC9B21E400C@bag.python.org> Author: brett.cannon Date: Wed Jan 3 22:31:18 2007 New Revision: 53229 Modified: peps/trunk/pep-3108.txt Log: Add wsgiref to the proper suggested packages. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 22:31:18 2007 @@ -557,6 +557,7 @@ + urllib2 + urlparse + webbrowser + + wsgiref * HTTP servers @@ -565,6 +566,7 @@ + DocXMLRPCServer + SimpleHTTPServer + SimpleXMLRPCServer + + wsgiref Modules reliant on obsolete/rarely used file formats? From python-checkins at python.org Wed Jan 3 23:00:02 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 23:00:02 +0100 (CET) Subject: [Python-checkins] r53230 - peps/trunk/pep-3108.txt Message-ID: <20070103220002.EEDB91E4010@bag.python.org> Author: brett.cannon Date: Wed Jan 3 23:00:02 2007 New Revision: 53230 Modified: peps/trunk/pep-3108.txt Log: Add ae* modules and MiniAEFRame to be removed (thanks to Ronald Oussoren). Also removed binhex as an Open Issue suggested removal. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 23:00:02 2007 @@ -150,12 +150,25 @@ * Mac + + aetools/aepack/aetypes/MiniAEFrame + + - OSA support is better through third-party modules. + + * Applescript/OSA [#applescript-osa]_. + + - Hard-coded endianness which breaks on Intel Macs. + + applesingle - Undocumented. - AppleSingle is a binary file format for A/UX. - A/UX no longer distributed. + + FrameWork + + - Poorly documented. + - Not updated to support Carbon Events. + Minimal usage ------------- @@ -334,10 +347,8 @@ dummy_threading mockthreading (rename because "mock" makes more sense than "dummy" and rename already required) EasyDialogs easydialogs -FrameWork framework HTMLParser htmlparser MacOS macos -MiniAEFrame miniaeframe Nav nav PixMapWrapper pixmapwrapper py_compile pycompile @@ -580,8 +591,6 @@ audioop Raw (8|16|32)-bit wide audio files (as generated by the al and sunaudiodev modules). -binhex - binhex4 encoding. chunk AIFF, AIFF-C, and RMFF audio files. sunau From python-checkins at python.org Wed Jan 3 23:59:33 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 3 Jan 2007 23:59:33 +0100 (CET) Subject: [Python-checkins] r53231 - peps/trunk/pep-3108.txt Message-ID: <20070103225933.51F651E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 3 23:59:32 2007 New Revision: 53231 Modified: peps/trunk/pep-3108.txt Log: Add autoGIL for removal. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 3 23:59:32 2007 @@ -164,6 +164,11 @@ - AppleSingle is a binary file format for A/UX. - A/UX no longer distributed. + + autoGIL + + - Very bad model for using Python with the CFRunLoop. + - Rename to _autogil if needed by Carbon package. + + FrameWork - Poorly documented. @@ -335,7 +340,6 @@ ================== ================================================== _winreg winreg (rename also because module has a public interface) -autoGIL autogil BaseHTTPServer basehttpserver Carbon carbon CGIHTTPServer cgihttpserver From python-checkins at python.org Thu Jan 4 01:23:50 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 4 Jan 2007 01:23:50 +0100 (CET) Subject: [Python-checkins] r53232 - in python/trunk: Doc/lib/libtest.tex Lib/test/test_support.py Misc/NEWS Message-ID: <20070104002350.CB9EA1E4009@bag.python.org> Author: brett.cannon Date: Thu Jan 4 01:23:49 2007 New Revision: 53232 Modified: python/trunk/Doc/lib/libtest.tex python/trunk/Lib/test/test_support.py python/trunk/Misc/NEWS Log: Add EnvironmentVarGuard to test.test_support. Provides a context manager to temporarily set or unset environment variables. Modified: python/trunk/Doc/lib/libtest.tex ============================================================================== --- python/trunk/Doc/lib/libtest.tex (original) +++ python/trunk/Doc/lib/libtest.tex Thu Jan 4 01:23:49 2007 @@ -281,4 +281,22 @@ The optional argument \var{testclass} accepts one of the test classes in the suite so as to print out more detailed information on where the testing suite originated from. + +The \module{test.test_support} module defines the following classes: + +\begin{classdesc}{EnvironmentVarGuard}{} +Class used to temporarily set or unset environment variables. Instances can be +used as a context manager. +\versionadded{2.6} +\end{classdesc} + +\begin{methoddesc}{set}{envvar, value} +Temporarily set the environment variable \code{envvar} to the value of +\code{value}. +\end{methoddesc} + +\begin{methoddesc}{unset}{envvar} +Temporarily unset the environment variable \code{envvar}. +\end{methoddesc} + \end{funcdesc} Modified: python/trunk/Lib/test/test_support.py ============================================================================== --- python/trunk/Lib/test/test_support.py (original) +++ python/trunk/Lib/test/test_support.py Thu Jan 4 01:23:49 2007 @@ -279,7 +279,39 @@ yield finally: warnings.filters = original_filters - + +class EnvironmentVarGuard(object): + + """Class to help protect the environment variable properly. Can be used as + a context manager.""" + + def __init__(self): + from os import environ + self._environ = environ + self._unset = set() + self._reset = dict() + + def set(self, envvar, value): + if envvar not in self._environ: + self._unset.add(envvar) + else: + self._reset[envvar] = self._environ[envvar] + self._environ[envvar] = value + + def unset(self, envvar): + if envvar in self._environ: + self._reset[envvar] = self._environ[envvar] + del self._environ[envvar] + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + for envvar, value in self._reset.iteritems(): + self._environ[envvar] = value + for unset in self._unset: + del self._environ[unset] + #======================================================================= # Decorator for running a function in a different locale, correctly resetting Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu Jan 4 01:23:49 2007 @@ -323,6 +323,10 @@ Tests ----- +- Added test.test_support.EnvironmentVarGuard. It's a class that provides a + context manager so that one can temporarily set or unset environment + variables. + - Added guard_warnings_filter to test.test_support. It returns a context manager that protects the 'warnings' module's filter from being mutated once the context has been exited. From python-checkins at python.org Thu Jan 4 01:34:40 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 4 Jan 2007 01:34:40 +0100 (CET) Subject: [Python-checkins] r53233 - sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/test_importer.py Message-ID: <20070104003440.400561E4009@bag.python.org> Author: brett.cannon Date: Thu Jan 4 01:34:39 2007 New Revision: 53233 Modified: sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/test_importer.py Log: Add case-sensitivity. Modified: sandbox/trunk/import_in_py/importer.py ============================================================================== --- sandbox/trunk/import_in_py/importer.py (original) +++ sandbox/trunk/import_in_py/importer.py Thu Jan 4 01:34:39 2007 @@ -101,6 +101,28 @@ x |= ord(bytes[3]) << 24 return x +def case_ok(directory, file_name): + """Verify that file_name (as found in 'directory') has the proper case. + + The path is assumed to already exist. + + XXX Temporary until imp's case_ok function can be exposed. + + XXX Better to roll this into a single function some how so that existence + check can be part of case check and thus cut down on stat calls? + + """ + if sys.platform not in ('win32', 'mac', 'riscos', 'darwin', 'cygwin', + 'os2emx') or os.environ.get('PYTHONCASEOK'): + # Platform is case-sensitive so existence check already handle + # case-sensitivity. + return True + directory_contents = os.listdir(directory) + if file_name in directory_contents: + return True + else: + return False + class BuiltinFrozenBaseImporter(object): @@ -217,23 +239,26 @@ for each directory in __path__ for a package. """ - # XXX Does not worry about case-insensitive filesystems. tail_module = fullname.rsplit('.', 1)[-1] package_directory = os.path.join(self.path_entry, tail_module) for handler in self.handlers: for file_ext in handler.handles: # XXX Backwards-incompatible to use anything but .py/.pyc # files for __init__? - package_init = os.path.join(package_directory, - '__init__'+file_ext) - if os.path.isfile(package_init): + init_filename = '__init__' + file_ext + package_init = os.path.join(package_directory, init_filename) + if (os.path.isfile(package_init) and + case_ok(self.path_entry, tail_module) and + case_ok(package_directory, init_filename)): return self.loader(package_init, handler, package_directory) file_name = tail_module + file_ext file_path = os.path.join(self.path_entry, file_name) - if os.path.isfile(file_path): + if (os.path.isfile(file_path) and + case_ok(self.path_entry, file_name)): return self.loader(file_path, handler) else: - if os.path.isdir(package_directory): + if (os.path.isdir(package_directory) and + case_ok(self.path_entry, tail_module)): warnings.warn("Not importing directory %s: missing __init__.py" % package_directory, ImportWarning) Modified: sandbox/trunk/import_in_py/test_importer.py ============================================================================== --- sandbox/trunk/import_in_py/test_importer.py (original) +++ sandbox/trunk/import_in_py/test_importer.py Thu Jan 4 01:34:39 2007 @@ -337,7 +337,57 @@ self.importer = importer.FileSystemImporter(self.directory, self.handler) self.importer.loader = mock_importer.MockPyPycLoader - + + def test_module_case_sensitivity(self): + # Case-sensitivity should always matter as long as PYTHONCASEOK is not + # set. + name_len = len(self.top_level_module_name) + bad_case_name = (self.top_level_module_name[:name_len/2].upper() + + self.top_level_module_name[name_len/2:].lower()) + env_guard = test_support.EnvironmentVarGuard() + env_guard.unset('PYTHONCASEOK') + with env_guard: + self.failUnless(not self.importer.find_module(bad_case_name)) + if sys.platform not in ('win32', 'mac', 'darwin', 'cygwin', 'os2emx', + 'riscos'): + return + env_guard = test_support.EnvironmentVarGuard() + env_guard.set('PYTHONCASEOK', '1') + with env_guard: + assert os.environ['PYTHONCASEOK'] + self.failUnless(self.importer.find_module(bad_case_name)) + + def test_package_case_sensitivity(self): + # Case-sensitivity should always matter as long as PYTHONCASEOK is not + # set. + name_len = len(self.pkg_name) + bad_case_name = (self.pkg_name[:name_len/2].upper() + + self.pkg_name[name_len/2:].lower()) + bad_init_name = os.path.join(self.directory, self.pkg_name, + '__INit__.py') + env_guard = test_support.EnvironmentVarGuard() + env_guard.unset('PYTHONCASEOK') + with env_guard: + self.failUnless(not self.importer.find_module(bad_case_name)) + os.unlink(self.pkg_init_path) + with open(bad_init_name, 'w') as init_file: + init_file.write('# Test case-sensitivity of imports.') + self.failUnless(not self.importer.find_module(self.pkg_name)) + if sys.platform not in ('win32', 'mac', 'darwin', 'cygwin', 'os2emx', + 'riscos'): + return + os.unlink(bad_init_name) + with open(self.pkg_init_path, 'w') as init_file: + init_file.write('# Used for testing import.') + env_guard = test_support.EnvironmentVarGuard() + env_guard.set('PYTHONCASEOK', '1') + with env_guard: + assert os.environ['PYTHONCASEOK'] + self.failUnless(self.importer.find_module(bad_case_name)) + with open(bad_init_name, 'w') as init_file: + init_file.write('# Used to test case-insensitivity of import.') + self.failUnless(self.importer.find_module(self.pkg_name)) + def test_find_module_single_handler(self): # Having a single handler should work without issue. loader = self.importer.find_module(self.module_name) From python-checkins at python.org Thu Jan 4 03:53:06 2007 From: python-checkins at python.org (ka-ping.yee) Date: Thu, 4 Jan 2007 03:53:06 +0100 (CET) Subject: [Python-checkins] r53234 - peps/trunk/pep-0344.txt Message-ID: <20070104025306.4380D1E4009@bag.python.org> Author: ka-ping.yee Date: Thu Jan 4 03:53:05 2007 New Revision: 53234 Modified: peps/trunk/pep-0344.txt Log: Add a discussion of the cyclic garbage issue. Modified: peps/trunk/pep-0344.txt ============================================================================== --- peps/trunk/pep-0344.txt (original) +++ peps/trunk/pep-0344.txt Thu Jan 4 03:53:05 2007 @@ -339,7 +339,7 @@ library contains no mention of such attributes. -Open Issues +Open Issue: Extra Information Walter D?rwald [11] expressed a desire to attach extra information to an exception during its upward propagation without changing its @@ -348,10 +348,16 @@ establishing conventions for other informational attributes on exceptions. + +Open Issue: Suppressing Context + As written, this PEP makes it impossible to suppress '__context__', since setting exc.__context__ to None in an 'except' or 'finally' clause will only result in it being set again when exc is raised. + +Open Issue: Limiting Exception Types + To improve encapsulation, library implementors may want to wrap all implementation-level exceptions with an application-level exception. One could try to wrap exceptions by writing this: @@ -378,6 +384,9 @@ except *, exc: raise ApplicationError from exc + +Open Issue: yield + The exception context is lost when a 'yield' statement is executed; resuming the frame after the 'yield' does not restore the context. Addressing this problem is out of the scope of this PEP; it is not a @@ -398,6 +407,36 @@ (deprecated), not NoneType +Open Issue: Garbage Collection + + The strongest objection to this proposal has been that it creates + cycles between exceptions and stack frames [12]. Collection of + cyclic garbage (and therefore resource release) can be greatly + delayed. + + >>> try: + >>> 1/0 + >>> except Exception, err: + >>> pass + + will introduce a cycle from err -> traceback -> stack frame -> err, + keeping all locals in the same scope alive until the next GC happens. + + Today, these locals would go out of scope. There is lots of code + which assumes that "local" resources -- particularly open files -- will + be closed quickly. If closure has to wait for the next GC, a program + (which runs fine today) may run out of file handles. + + Making the __traceback__ attribute a weak reference would avoid the + problems with cyclic garbage. Unfortunately, it would make saving + the Exception for later (as unittest does) more awkward, and it would + not allow as much cleanup of the sys module. + + A possible alternate solution, suggested by Adam Olsen, would be to + instead turn the reference from the stack frame to the 'err' variable + into a weak reference when the variable goes out of scope [13]. + + Possible Future Compatible Changes These changes are consistent with the appearance of exceptions as @@ -478,6 +517,12 @@ [11] Walter D?rwald suggests wrapping exceptions to add details http://mail.python.org/pipermail/python-dev/2003-June/036148.html + [12] Guido van Rossum restates the objection to cyclic trash + http://mail.python.org/pipermail/python-3000/2007-January/005322.html + + [13] Adam Olsen suggests using a weakref from stack frame to exception + http://mail.python.org/pipermail/python-3000/2007-January/005363.html + Copyright From python-checkins at python.org Thu Jan 4 07:25:32 2007 From: python-checkins at python.org (neal.norwitz) Date: Thu, 4 Jan 2007 07:25:32 +0100 (CET) Subject: [Python-checkins] r53235 - python/trunk/Doc/mac/toolbox.tex Message-ID: <20070104062532.1F7711E400B@bag.python.org> Author: neal.norwitz Date: Thu Jan 4 07:25:31 2007 New Revision: 53235 Modified: python/trunk/Doc/mac/toolbox.tex Log: SF #1627373, fix typo in CarbonEvt. Modified: python/trunk/Doc/mac/toolbox.tex ============================================================================== --- python/trunk/Doc/mac/toolbox.tex (original) +++ python/trunk/Doc/mac/toolbox.tex Thu Jan 4 07:25:31 2007 @@ -65,7 +65,7 @@ \modulesynopsis{Interface to the Component Manager.} \section{\module{Carbon.CarbonEvt} --- Carbon Event Manager} -\declaremodule{standard}{Carbon.CaronEvt} +\declaremodule{standard}{Carbon.CarbonEvt} \platform{Mac} \modulesynopsis{Interface to the Carbon Event Manager.} From python-checkins at python.org Thu Jan 4 07:26:23 2007 From: python-checkins at python.org (neal.norwitz) Date: Thu, 4 Jan 2007 07:26:23 +0100 (CET) Subject: [Python-checkins] r53236 - python/branches/release25-maint/Doc/mac/toolbox.tex Message-ID: <20070104062623.241D11E400B@bag.python.org> Author: neal.norwitz Date: Thu Jan 4 07:26:22 2007 New Revision: 53236 Modified: python/branches/release25-maint/Doc/mac/toolbox.tex Log: SF #1627373, fix typo in CarbonEvt. Modified: python/branches/release25-maint/Doc/mac/toolbox.tex ============================================================================== --- python/branches/release25-maint/Doc/mac/toolbox.tex (original) +++ python/branches/release25-maint/Doc/mac/toolbox.tex Thu Jan 4 07:26:22 2007 @@ -65,7 +65,7 @@ \modulesynopsis{Interface to the Component Manager.} \section{\module{Carbon.CarbonEvt} --- Carbon Event Manager} -\declaremodule{standard}{Carbon.CaronEvt} +\declaremodule{standard}{Carbon.CarbonEvt} \platform{Mac} \modulesynopsis{Interface to the Carbon Event Manager.} From python-checkins at python.org Thu Jan 4 18:53:19 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 4 Jan 2007 18:53:19 +0100 (CET) Subject: [Python-checkins] r53243 - in python/branches/release25-maint: Lib/heapq.py Lib/test/test_heapq.py Misc/NEWS Message-ID: <20070104175319.DD1381E400B@bag.python.org> Author: raymond.hettinger Date: Thu Jan 4 18:53:16 2007 New Revision: 53243 Modified: python/branches/release25-maint/Lib/heapq.py python/branches/release25-maint/Lib/test/test_heapq.py python/branches/release25-maint/Misc/NEWS Log: Fix stability of heapq's nlargest() and nsmallest(). Modified: python/branches/release25-maint/Lib/heapq.py ============================================================================== --- python/branches/release25-maint/Lib/heapq.py (original) +++ python/branches/release25-maint/Lib/heapq.py Thu Jan 4 18:53:16 2007 @@ -130,7 +130,7 @@ 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee -from operator import itemgetter +from operator import itemgetter, neg import bisect def heappush(heap, item): @@ -315,8 +315,6 @@ Equivalent to: sorted(iterable, key=key)[:n] """ - if key is None: - return _nsmallest(n, iterable) in1, in2 = tee(iterable) it = izip(imap(key, in1), count(), in2) # decorate result = _nsmallest(n, it) @@ -328,10 +326,8 @@ Equivalent to: sorted(iterable, key=key, reverse=True)[:n] """ - if key is None: - return _nlargest(n, iterable) in1, in2 = tee(iterable) - it = izip(imap(key, in1), count(), in2) # decorate + it = izip(imap(key, in1), imap(neg, count()), in2) # decorate result = _nlargest(n, it) return map(itemgetter(2), result) # undecorate Modified: python/branches/release25-maint/Lib/test/test_heapq.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_heapq.py (original) +++ python/branches/release25-maint/Lib/test/test_heapq.py Thu Jan 4 18:53:16 2007 @@ -104,20 +104,20 @@ self.assertEqual(heap_sorted, sorted(data)) def test_nsmallest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nsmallest(n, data), sorted(data)[:n]) - self.assertEqual(nsmallest(n, data, key=f), - sorted(data, key=f)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nsmallest(n, data), sorted(data)[:n]) + self.assertEqual(nsmallest(n, data, key=f), + sorted(data, key=f)[:n]) def test_nlargest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) - self.assertEqual(nlargest(n, data, key=f), - sorted(data, key=f, reverse=True)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) + self.assertEqual(nlargest(n, data, key=f), + sorted(data, key=f, reverse=True)[:n]) #============================================================================== Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Thu Jan 4 18:53:16 2007 @@ -125,6 +125,8 @@ Library ------- +- Fix sort stability in heapq.nlargest() and nsmallest(). + - Patch #1504073: Fix tarfile.open() for mode "r" with a fileobj argument. - Patch #1262036: Prevent TarFiles from being added to themselves under From python-checkins at python.org Thu Jan 4 18:53:35 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 4 Jan 2007 18:53:35 +0100 (CET) Subject: [Python-checkins] r53244 - in python/trunk/Lib: heapq.py test/test_heapq.py Message-ID: <20070104175335.40E7A1E400B@bag.python.org> Author: raymond.hettinger Date: Thu Jan 4 18:53:34 2007 New Revision: 53244 Modified: python/trunk/Lib/heapq.py python/trunk/Lib/test/test_heapq.py Log: Fix stability of heapq's nlargest() and nsmallest(). Modified: python/trunk/Lib/heapq.py ============================================================================== --- python/trunk/Lib/heapq.py (original) +++ python/trunk/Lib/heapq.py Thu Jan 4 18:53:34 2007 @@ -130,7 +130,7 @@ 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee -from operator import itemgetter +from operator import itemgetter, neg import bisect def heappush(heap, item): @@ -315,8 +315,6 @@ Equivalent to: sorted(iterable, key=key)[:n] """ - if key is None: - return _nsmallest(n, iterable) in1, in2 = tee(iterable) it = izip(imap(key, in1), count(), in2) # decorate result = _nsmallest(n, it) @@ -328,10 +326,8 @@ Equivalent to: sorted(iterable, key=key, reverse=True)[:n] """ - if key is None: - return _nlargest(n, iterable) in1, in2 = tee(iterable) - it = izip(imap(key, in1), count(), in2) # decorate + it = izip(imap(key, in1), imap(neg, count()), in2) # decorate result = _nlargest(n, it) return map(itemgetter(2), result) # undecorate Modified: python/trunk/Lib/test/test_heapq.py ============================================================================== --- python/trunk/Lib/test/test_heapq.py (original) +++ python/trunk/Lib/test/test_heapq.py Thu Jan 4 18:53:34 2007 @@ -104,20 +104,20 @@ self.assertEqual(heap_sorted, sorted(data)) def test_nsmallest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nsmallest(n, data), sorted(data)[:n]) - self.assertEqual(nsmallest(n, data, key=f), - sorted(data, key=f)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nsmallest(n, data), sorted(data)[:n]) + self.assertEqual(nsmallest(n, data, key=f), + sorted(data, key=f)[:n]) def test_nlargest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) - self.assertEqual(nlargest(n, data, key=f), - sorted(data, key=f, reverse=True)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) + self.assertEqual(nlargest(n, data, key=f), + sorted(data, key=f, reverse=True)[:n]) #============================================================================== From python-checkins at python.org Thu Jan 4 19:19:55 2007 From: python-checkins at python.org (david.goodger) Date: Thu, 4 Jan 2007 19:19:55 +0100 (CET) Subject: [Python-checkins] r53245 - peps/trunk/pep-3107.txt Message-ID: <20070104181955.727CF1E400C@bag.python.org> Author: david.goodger Date: Thu Jan 4 19:19:54 2007 New Revision: 53245 Modified: peps/trunk/pep-3107.txt Log: update from the authors Modified: peps/trunk/pep-3107.txt ============================================================================== --- peps/trunk/pep-3107.txt (original) +++ peps/trunk/pep-3107.txt Thu Jan 4 19:19:54 2007 @@ -24,9 +24,8 @@ ========= Because Python's 2.x series lacks a standard way of annotating a -function's parameters and return values (e.g., with information about -what type a function's return value should be), a variety of tools -and libraries have appeared to fill this gap [#tailexamp]_. Some +function's parameters and return values, a variety of tools +and libraries have appeared to fill this gap. Some utilise the decorators introduced in "PEP 318", while others parse a function's docstring, looking for annotations there. @@ -81,14 +80,6 @@ any kind of standard semantics, even for the built-in types. This work will be left to third-party libraries. - There is no worry that these libraries will assign semantics at - random, or that a variety of libraries will appear, each with - varying semantics and interpretations of what, say, a tuple of - strings means. The difficulty inherent in writing annotation - interpreting libraries will keep their number low and their - authorship in the hands of people who, frankly, know what they're - doing. - Syntax ====== @@ -97,11 +88,9 @@ ---------- Annotations for parameters take the form of optional expressions that -follow the parameter name. This example indicates that parameters -'a' and 'c' should both be an ``int``, while parameter 'b' should -be a ``dict``:: +follow the parameter name:: - def foo(a: int, b: dict, c: int = 5): + def foo(a: expression, b: expression = 5): ... In pseudo-grammar, parameters now look like ``identifier [: @@ -109,26 +98,23 @@ parameter's default value and both annotations and default values are optional. Just like how equal signs are used to indicate a default value, colons are used to mark annotations. All annotation -expressions are evaluated when the function definition is executed. +expressions are evaluated when the function definition is executed, +just like default values. Annotations for excess parameters (i.e., ``*args`` and ``**kwargs``) -are indicated similarly. In the following function definition, -``*args`` is flagged as a tuple of ``int``, and ``**kwargs`` is -marked as a dict whose keys are strings and whose values are of type -``str``:: +are indicated similarly:: - def foo(*args: int, **kwargs: str): + def foo(*args: expression, **kwargs: expression): ... + +Annotations for nested parameters always follow the name of the +parameter, not the last parenthesis. Annotating all parameters of a +nested parameter is not required:: -Note that, depending on what annotation-interpreting library you're -using, the following might also be a valid spelling of the above:: - - def foo(*args: [int], **kwargs: {str: str}): + def foo((x1, y1: expression), + (x2: expression, y2: expression)=(None, None)): ... -Only the first, however, has the BDFL's blessing [#blessedexcess]_ as -the One Obvious Way. - Return Values ------------- @@ -136,11 +122,11 @@ The examples thus far have omitted examples of how to annotate the type of a function's return value. This is done like so:: - def sum(*args: int) -> int: + def sum() -> expression: ... -The parameter list can now be followed by a literal ``->`` and a -Python expression. Like the annotations for parameters, this +That is, the parameter list can now be followed by a literal ``->`` +and a Python expression. Like the annotations for parameters, this expression will be evaluated when the function definition is executed. The grammar for function definitions [#grammar]_ is now:: @@ -162,7 +148,7 @@ ``lambda``'s syntax does not support annotations. The syntax of ``lambda`` could be changed to support annotations, by requiring -parentheses around the parameter list. However it was decided +parentheses around the parameter list. However it was decided [#lambda]_ not to make this change because: 1. It would be an incompatible change. @@ -179,12 +165,12 @@ the evaluated annotation expression There is a special key in the ``func_annotations`` mapping, -``"return"``. This key is present only if an annotation was supplied +``"return"``. This key is present only if an annotation was supplied for the function's return value. For example, the following annotation:: - def foo(a: 'x', b: 5 + 6, c: list) -> str: + def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9): ... would result in a ``func_annotation`` mapping of :: @@ -192,16 +178,39 @@ {'a': 'x', 'b': 11, 'c': list, - 'return': str} + 'return': 9} The ``return`` key was chosen because it cannot conflict with the name of a parameter; any attempt to use ``return`` as a parameter name would result in a ``SyntaxError``. ``func_annotations`` is an empty dictionary if no there are no -annotations on the function. ``func_annotations`` is always an empty +annotations on the function. ``func_annotations`` is always an empty dictionary for functions created from ``lambda`` expressions. +Use Cases +========= + +In the course of discussing annotations, a number of use-cases have +been raised. Some of these are presented here, grouped by what kind +of information they convey. Also included are examples of existing +products and packages that could make use of annotations. + +* Providing typing information + + + Type checking ([#typecheck]_, [#maxime]_) + + Let IDEs show what types a function expects and returns ([#idle]_) + + Function overloading / generic functions ([#scaling]_) + + Foreign-language bridges ([#jython]_, [#ironpython]_) + + Adaptation ([#adaptationpost]_, [#pyprotocols]_) + + Predicate logic functions + + Database query mapping + + RPC parameter marshaling ([#rpyc]_) + +* Other information + + + Documentation for parameters and return values ([#pydoc]_) + Standard Library ================ @@ -210,7 +219,7 @@ ----------------- The ``pydoc`` module should display the function annotations when -displaying help for a function. The ``inspect`` module should change +displaying help for a function. The ``inspect`` module should change to support annotations. @@ -245,8 +254,16 @@ + Despite considerable discussion about a standard type parameterisation syntax, it was decided that this should also be - left to third-party libraries. ([#threadimmlist]_, - [#threadmixing]_, [#emphasistpls]_) + left to third-party libraries. ([#threadimmlist]_, + [#threadmixing]_, [#emphasistpls]_). + ++ Despite yet more discussion, it was decided not to standardize + a mechanism for annotation interoperability. Standardizing + interoperability conventions at this point would be premature. + We would rather let these conventions develop organically, based + on real-world usage and necessity, than try to force all users + into some contrived scheme. ([#interop0]_, [#interop1]_, + [#interop2]_). References and Footnotes @@ -255,20 +272,13 @@ .. [#functerm] Unless specifically stated, "function" is generally used as a synonym for "callable" throughout this document. -.. [#tailexamp] The author's typecheck_ library makes use of - decorators, while `Maxime Bourget's own typechecker`_ utilises - parsed docstrings. - -.. [#blessedexcess] - http://mail.python.org/pipermail/python-3000/2006-May/002173.html - .. [#rejectgensyn] http://mail.python.org/pipermail/python-3000/2006-May/002103.html -.. _typecheck: +.. [#typecheck] http://oakwinter.com/code/typecheck/ -.. _Maxime Bourget's own typechecker: +.. [#maxime] http://maxrepo.info/taxonomy/term/3,6/all .. [#threadgen] @@ -289,15 +299,6 @@ .. [#implementation] http://python.org/sf/1607548 -.. _numeric: - http://docs.python.org/lib/typesnumeric.html - -.. _mapping: - http://docs.python.org/lib/typesmapping.html - -.. _sequence protocols: - http://docs.python.org/lib/typesseq.html - .. [#grammar] http://www.python.org/doc/current/ref/function.html @@ -306,7 +307,39 @@ .. [#pep-362] http://www.python.org/dev/peps/pep-0362/ + +.. [#interop0] + http://mail.python.org/pipermail/python-3000/2006-August/002895.html + +.. [#interop1] + http://mail.python.org/pipermail/python-ideas/2007-January/000032.html +.. [#interop2] + http://mail.python.org/pipermail/python-list/2006-December/420645.html + +.. [#idle] + http://www.python.org/idle/doc/idle2.html#Tips + +.. [#jython] + http://www.jython.org/Project/index.html + +.. [#ironpython] + http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython + +.. [#pyprotocols] + http://peak.telecommunity.com/PyProtocols.html + +.. [#adaptationpost] + http://www.artima.com/weblogs/viewpost.jsp?thread=155123 + +.. [#scaling] + http://www-128.ibm.com/developerworks/library/l-cppeak2/ + +.. [#rpyc] + http://rpyc.wikispaces.com/ + +.. [#pydoc] + http://docs.python.org/lib/module-pydoc.html Copyright @@ -323,4 +356,3 @@ fill-column: 70 coding: utf-8 End: - From python-checkins at python.org Thu Jan 4 19:54:35 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 4 Jan 2007 19:54:35 +0100 (CET) Subject: [Python-checkins] r53246 - peps/trunk/pep-3108.txt Message-ID: <20070104185435.426121E401B@bag.python.org> Author: brett.cannon Date: Thu Jan 4 19:54:34 2007 New Revision: 53246 Modified: peps/trunk/pep-3108.txt Log: Add some Mac modules to be removed. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Thu Jan 4 19:54:34 2007 @@ -169,11 +169,24 @@ - Very bad model for using Python with the CFRunLoop. - Rename to _autogil if needed by Carbon package. + + Carbon.CF + + - Half-heared attempt. + + FrameWork - Poorly documented. - Not updated to support Carbon Events. + + ic + + - Meant as a replacement for 'open' when the function itself + should gain any special abilities ic has. + + + icopen + + - Never used. + Minimal usage ------------- From python-checkins at python.org Thu Jan 4 20:13:45 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 4 Jan 2007 20:13:45 +0100 (CET) Subject: [Python-checkins] r53247 - sandbox/trunk/datetime/US.py Message-ID: <20070104191345.F1A8F1E400B@bag.python.org> Author: guido.van.rossum Date: Thu Jan 4 20:13:45 2007 New Revision: 53247 Modified: sandbox/trunk/datetime/US.py Log: Add an XXX comment warning that US DST is changing per 2007. Modified: sandbox/trunk/datetime/US.py ============================================================================== --- sandbox/trunk/datetime/US.py (original) +++ sandbox/trunk/datetime/US.py Thu Jan 4 20:13:45 2007 @@ -8,6 +8,9 @@ class USTimeZone(tzinfo): "A class capturing the current (2002) rules for United States time zones." + # XXX Note that in 2007 the rules are changing: + # XXX 2nd Sunday in March, 1st Sunday in November. + # XXX Anybody want to volunteer a fix for this code? # A seemingly intractable problem: when DST ends, there's a one-hour # slice that repeats in "naive time". That is, when the naive clock From python-checkins at python.org Thu Jan 4 20:43:28 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 4 Jan 2007 20:43:28 +0100 (CET) Subject: [Python-checkins] r53248 - peps/trunk/pep-3108.txt Message-ID: <20070104194328.031E81E400B@bag.python.org> Author: brett.cannon Date: Thu Jan 4 20:43:27 2007 New Revision: 53248 Modified: peps/trunk/pep-3108.txt Log: Add another argument for why getopt should be removed because of a shortcoming of optparse. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Thu Jan 4 20:43:27 2007 @@ -277,6 +277,7 @@ - getopt is still widely used. - optparse does not handle the issue of when people set incompatible options very well. + - optparse does not allow option arguments to be optional. * ihooks From python-checkins at python.org Thu Jan 4 22:06:13 2007 From: python-checkins at python.org (martin.v.loewis) Date: Thu, 4 Jan 2007 22:06:13 +0100 (CET) Subject: [Python-checkins] r53249 - in python/trunk: Lib/threading.py Misc/NEWS Modules/main.c Message-ID: <20070104210613.7BE2A1E4002@bag.python.org> Author: martin.v.loewis Date: Thu Jan 4 22:06:12 2007 New Revision: 53249 Modified: python/trunk/Lib/threading.py python/trunk/Misc/NEWS python/trunk/Modules/main.c Log: Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, to avoid relying on atexit. Will backport to 2.5. Modified: python/trunk/Lib/threading.py ============================================================================== --- python/trunk/Lib/threading.py (original) +++ python/trunk/Lib/threading.py Thu Jan 4 22:06:12 2007 @@ -636,13 +636,11 @@ _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() - import atexit - atexit.register(self.__exitfunc) def _set_daemon(self): return False - def __exitfunc(self): + def _exitfunc(self): self._Thread__stop() t = _pickSomeNonDaemonThread() if t: @@ -715,9 +713,11 @@ from thread import stack_size -# Create the main thread object +# Create the main thread object, +# and make it available for the interpreter +# (Py_Main) as threading._shutdown. -_MainThread() +_shutdown = _MainThread()._exitfunc # get thread-local implementation, either from the thread # module, or from the python fallback Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu Jan 4 22:06:12 2007 @@ -12,6 +12,9 @@ Core and builtins ----------------- +- Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, + to avoid relying on atexit. + - Bug #1590891: random.randrange don't return correct value for big number - Patch #1586791: Better exception messages for some operations on strings, Modified: python/trunk/Modules/main.c ============================================================================== --- python/trunk/Modules/main.c (original) +++ python/trunk/Modules/main.c Thu Jan 4 22:06:12 2007 @@ -177,6 +177,33 @@ return 0; } +/* Wait until threading._shutdown completes, provided + the threading module was imported in the first place. + The shutdown routine will wait until all non-daemon + "threading" threads have completed. */ +#include "abstract.h" +static void +WaitForThreadShutdown() +{ +#ifdef WITH_THREAD + PyObject *result; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_shutdown", ""); + if (result == NULL) + PyErr_WriteUnraisable(threading); + else + Py_DECREF(result); + Py_DECREF(threading); +#endif +} + /* Main program */ int @@ -514,6 +541,8 @@ /* XXX */ sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + WaitForThreadShutdown(); + Py_Finalize(); #ifdef RISCOS if (Py_RISCOSWimpFlag) From python-checkins at python.org Thu Jan 4 22:06:58 2007 From: python-checkins at python.org (martin.v.loewis) Date: Thu, 4 Jan 2007 22:06:58 +0100 (CET) Subject: [Python-checkins] r53250 - in python/branches/release25-maint: Lib/threading.py Misc/NEWS Modules/main.c Message-ID: <20070104210658.64B7F1E4002@bag.python.org> Author: martin.v.loewis Date: Thu Jan 4 22:06:57 2007 New Revision: 53250 Modified: python/branches/release25-maint/Lib/threading.py python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Modules/main.c Log: Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, to avoid relying on atexit. Modified: python/branches/release25-maint/Lib/threading.py ============================================================================== --- python/branches/release25-maint/Lib/threading.py (original) +++ python/branches/release25-maint/Lib/threading.py Thu Jan 4 22:06:57 2007 @@ -636,13 +636,11 @@ _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() - import atexit - atexit.register(self.__exitfunc) def _set_daemon(self): return False - def __exitfunc(self): + def _exitfunc(self): self._Thread__stop() t = _pickSomeNonDaemonThread() if t: @@ -715,9 +713,11 @@ from thread import stack_size -# Create the main thread object +# Create the main thread object, +# and make it available for the interpreter +# (Py_Main) as threading._shutdown. -_MainThread() +_shutdown = _MainThread()._exitfunc # get thread-local implementation, either from the thread # module, or from the python fallback Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Thu Jan 4 22:06:57 2007 @@ -12,6 +12,9 @@ Core and builtins ----------------- +- Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, + to avoid relying on atexit. + - Bug #1590891: random.randrange don't return correct value for big number - Bug #1456209: In some obscure cases it was possible for a class with a Modified: python/branches/release25-maint/Modules/main.c ============================================================================== --- python/branches/release25-maint/Modules/main.c (original) +++ python/branches/release25-maint/Modules/main.c Thu Jan 4 22:06:57 2007 @@ -176,6 +176,33 @@ return 0; } +/* Wait until threading._shutdown completes, provided + the threading module was imported in the first place. + The shutdown routine will wait until all non-daemon + "threading" threads have completed. */ +#include "abstract.h" +static void +WaitForThreadShutdown() +{ +#ifdef WITH_THREAD + PyObject *result; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_shutdown", ""); + if (result == NULL) + PyErr_WriteUnraisable(threading); + else + Py_DECREF(result); + Py_DECREF(threading); +#endif +} + /* Main program */ int @@ -513,6 +540,8 @@ /* XXX */ sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + WaitForThreadShutdown(); + Py_Finalize(); #ifdef RISCOS if (Py_RISCOSWimpFlag) From python-checkins at python.org Fri Jan 5 01:08:12 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 5 Jan 2007 01:08:12 +0100 (CET) Subject: [Python-checkins] r53251 - peps/trunk/pep-3108.txt Message-ID: <20070105000812.A16FE1E4002@bag.python.org> Author: brett.cannon Date: Fri Jan 5 01:08:12 2007 New Revision: 53251 Modified: peps/trunk/pep-3108.txt Log: Work on the list of Mac modules to remove. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Fri Jan 5 01:08:12 2007 @@ -157,6 +157,7 @@ * Applescript/OSA [#applescript-osa]_. - Hard-coded endianness which breaks on Intel Macs. + - Might need to rename if Carbon package dependent. + applesingle @@ -173,19 +174,27 @@ - Half-heared attempt. + + findertools + + - No longer useful. + + FrameWork - Poorly documented. - Not updated to support Carbon Events. - + ic + + icopen + + - Not needed on OS X. + - Meant to replace 'open' which is usually a bad thing to do. - - Meant as a replacement for 'open' when the function itself - should gain any special abilities ic has. + + videoreader - + icopen + - No longer used. + + + W - - Never used. + - No longer distributed with Python. Minimal usage @@ -383,7 +392,6 @@ UserDict userdict UserList userlist UserString userstring -W w ================== ================================================== From python-checkins at python.org Fri Jan 5 02:59:44 2007 From: python-checkins at python.org (gregory.p.smith) Date: Fri, 5 Jan 2007 02:59:44 +0100 (CET) Subject: [Python-checkins] r53252 - in python/trunk: Doc/lib/libbsddb.tex Lib/bsddb/dbobj.py Lib/bsddb/test/test_1413192.py Misc/NEWS Modules/_bsddb.c setup.py Message-ID: <20070105015944.45E9A1E4002@bag.python.org> Author: gregory.p.smith Date: Fri Jan 5 02:59:42 2007 New Revision: 53252 Modified: python/trunk/Doc/lib/libbsddb.tex python/trunk/Lib/bsddb/dbobj.py python/trunk/Lib/bsddb/test/test_1413192.py python/trunk/Misc/NEWS python/trunk/Modules/_bsddb.c python/trunk/setup.py Log: Support linking of the bsddb module against BerkeleyDB 4.5.x (will backport to 2.5) Modified: python/trunk/Doc/lib/libbsddb.tex ============================================================================== --- python/trunk/Doc/lib/libbsddb.tex (original) +++ python/trunk/Doc/lib/libbsddb.tex Fri Jan 5 02:59:42 2007 @@ -16,7 +16,7 @@ \function{pickle.dumps()}. The \module{bsddb} module requires a Berkeley DB library version from -3.3 thru 4.4. +3.3 thru 4.5. \begin{seealso} \seeurl{http://pybsddb.sourceforge.net/} Modified: python/trunk/Lib/bsddb/dbobj.py ============================================================================== --- python/trunk/Lib/bsddb/dbobj.py (original) +++ python/trunk/Lib/bsddb/dbobj.py Fri Jan 5 02:59:42 2007 @@ -55,8 +55,9 @@ return apply(self._cobj.set_lg_max, args, kwargs) def set_lk_detect(self, *args, **kwargs): return apply(self._cobj.set_lk_detect, args, kwargs) - def set_lk_max(self, *args, **kwargs): - return apply(self._cobj.set_lk_max, args, kwargs) + if db.version() < (4,5): + def set_lk_max(self, *args, **kwargs): + return apply(self._cobj.set_lk_max, args, kwargs) def set_lk_max_locks(self, *args, **kwargs): return apply(self._cobj.set_lk_max_locks, args, kwargs) def set_lk_max_lockers(self, *args, **kwargs): Modified: python/trunk/Lib/bsddb/test/test_1413192.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_1413192.py (original) +++ python/trunk/Lib/bsddb/test/test_1413192.py Fri Jan 5 02:59:42 2007 @@ -14,7 +14,7 @@ env_name = '.' env = db.DBEnv() -env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN) +env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN | db.DB_INIT_MPOOL) the_txn = env.txn_begin() map = db.DB(env) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri Jan 5 02:59:42 2007 @@ -322,6 +322,8 @@ been defined. This prevents an interactive Python from waking up 10 times per second. Patch by Richard Boulton. +- Added support for linking the bsddb module against BerkeleyDB 4.5.x. + Tests ----- Modified: python/trunk/Modules/_bsddb.c ============================================================================== --- python/trunk/Modules/_bsddb.c (original) +++ python/trunk/Modules/_bsddb.c Fri Jan 5 02:59:42 2007 @@ -4127,6 +4127,7 @@ } +#if (DBVER < 45) static PyObject* DBEnv_set_lk_max(DBEnvObject* self, PyObject* args) { @@ -4142,6 +4143,7 @@ RETURN_IF_ERR(); RETURN_NONE(); } +#endif #if (DBVER >= 32) @@ -5231,7 +5233,9 @@ {"set_lg_regionmax",(PyCFunction)DBEnv_set_lg_regionmax, METH_VARARGS}, #endif {"set_lk_detect", (PyCFunction)DBEnv_set_lk_detect, METH_VARARGS}, +#if (DBVER < 45) {"set_lk_max", (PyCFunction)DBEnv_set_lk_max, METH_VARARGS}, +#endif #if (DBVER >= 32) {"set_lk_max_locks", (PyCFunction)DBEnv_set_lk_max_locks, METH_VARARGS}, {"set_lk_max_lockers", (PyCFunction)DBEnv_set_lk_max_lockers, METH_VARARGS}, @@ -5833,7 +5837,9 @@ ADD_INT(d, DB_AFTER); ADD_INT(d, DB_APPEND); ADD_INT(d, DB_BEFORE); +#if (DBVER < 45) ADD_INT(d, DB_CACHED_COUNTS); +#endif #if (DBVER >= 41) _addIntToDict(d, "DB_CHECKPOINT", 0); #else @@ -5868,7 +5874,9 @@ ADD_INT(d, DB_POSITION); ADD_INT(d, DB_PREV); ADD_INT(d, DB_PREV_NODUP); +#if (DBVER < 45) ADD_INT(d, DB_RECORDCOUNT); +#endif ADD_INT(d, DB_SET); ADD_INT(d, DB_SET_RANGE); ADD_INT(d, DB_SET_RECNO); Modified: python/trunk/setup.py ============================================================================== --- python/trunk/setup.py (original) +++ python/trunk/setup.py Fri Jan 5 02:59:42 2007 @@ -606,7 +606,7 @@ # a release. Most open source OSes come with one or more # versions of BerkeleyDB already installed. - max_db_ver = (4, 4) + max_db_ver = (4, 5) min_db_ver = (3, 3) db_setup_debug = False # verbose debug prints from this script? @@ -623,7 +623,7 @@ '/sw/include/db3', ] # 4.x minor number specific paths - for x in (0,1,2,3,4): + for x in (0,1,2,3,4,5): db_inc_paths.append('/usr/include/db4%d' % x) db_inc_paths.append('/usr/include/db4.%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x) @@ -631,7 +631,7 @@ db_inc_paths.append('/pkg/db-4.%d/include' % x) db_inc_paths.append('/opt/db-4.%d/include' % x) # 3.x minor number specific paths - for x in (2,3): + for x in (3,): db_inc_paths.append('/usr/include/db3%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x) db_inc_paths.append('/usr/local/include/db3%d' % x) From python-checkins at python.org Fri Jan 5 03:06:19 2007 From: python-checkins at python.org (gregory.p.smith) Date: Fri, 5 Jan 2007 03:06:19 +0100 (CET) Subject: [Python-checkins] r53253 - python/trunk/Modules/_bsddb.c Message-ID: <20070105020619.521CD1E4002@bag.python.org> Author: gregory.p.smith Date: Fri Jan 5 03:06:17 2007 New Revision: 53253 Modified: python/trunk/Modules/_bsddb.c Log: bump module version to match supported berkeleydb version Modified: python/trunk/Modules/_bsddb.c ============================================================================== --- python/trunk/Modules/_bsddb.c (original) +++ python/trunk/Modules/_bsddb.c Fri Jan 5 03:06:17 2007 @@ -98,7 +98,7 @@ #error "eek! DBVER can't handle minor versions > 9" #endif -#define PY_BSDDB_VERSION "4.4.6" +#define PY_BSDDB_VERSION "4.5.0" static char *rcs_id = "$Id$"; From python-checkins at python.org Fri Jan 5 03:09:08 2007 From: python-checkins at python.org (gregory.p.smith) Date: Fri, 5 Jan 2007 03:09:08 +0100 (CET) Subject: [Python-checkins] r53254 - in python/branches/release25-maint: Doc/lib/libbsddb.tex Lib/bsddb/dbobj.py Lib/bsddb/test/test_1413192.py Misc/NEWS Modules/_bsddb.c setup.py Message-ID: <20070105020908.5A4CE1E4002@bag.python.org> Author: gregory.p.smith Date: Fri Jan 5 03:09:06 2007 New Revision: 53254 Modified: python/branches/release25-maint/Doc/lib/libbsddb.tex python/branches/release25-maint/Lib/bsddb/dbobj.py python/branches/release25-maint/Lib/bsddb/test/test_1413192.py python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Modules/_bsddb.c python/branches/release25-maint/setup.py Log: support linking the _bsddb extension module against BerkeleyDB 4.5 [backport of r53252] Modified: python/branches/release25-maint/Doc/lib/libbsddb.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libbsddb.tex (original) +++ python/branches/release25-maint/Doc/lib/libbsddb.tex Fri Jan 5 03:09:06 2007 @@ -16,7 +16,7 @@ \function{pickle.dumps()}. The \module{bsddb} module requires a Berkeley DB library version from -3.3 thru 4.4. +3.3 thru 4.5. \begin{seealso} \seeurl{http://pybsddb.sourceforge.net/} Modified: python/branches/release25-maint/Lib/bsddb/dbobj.py ============================================================================== --- python/branches/release25-maint/Lib/bsddb/dbobj.py (original) +++ python/branches/release25-maint/Lib/bsddb/dbobj.py Fri Jan 5 03:09:06 2007 @@ -55,8 +55,9 @@ return apply(self._cobj.set_lg_max, args, kwargs) def set_lk_detect(self, *args, **kwargs): return apply(self._cobj.set_lk_detect, args, kwargs) - def set_lk_max(self, *args, **kwargs): - return apply(self._cobj.set_lk_max, args, kwargs) + if db.version() < (4,5): + def set_lk_max(self, *args, **kwargs): + return apply(self._cobj.set_lk_max, args, kwargs) def set_lk_max_locks(self, *args, **kwargs): return apply(self._cobj.set_lk_max_locks, args, kwargs) def set_lk_max_lockers(self, *args, **kwargs): Modified: python/branches/release25-maint/Lib/bsddb/test/test_1413192.py ============================================================================== --- python/branches/release25-maint/Lib/bsddb/test/test_1413192.py (original) +++ python/branches/release25-maint/Lib/bsddb/test/test_1413192.py Fri Jan 5 03:09:06 2007 @@ -14,7 +14,7 @@ env_name = '.' env = db.DBEnv() -env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN) +env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN | db.DB_INIT_MPOOL) the_txn = env.txn_begin() map = db.DB(env) Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Fri Jan 5 03:09:06 2007 @@ -124,6 +124,8 @@ - Make regex engine raise MemoryError if allocating memory fails. +- Added support for linking the bsddb module against BerkeleyDB 4.5.x. + Library ------- Modified: python/branches/release25-maint/Modules/_bsddb.c ============================================================================== --- python/branches/release25-maint/Modules/_bsddb.c (original) +++ python/branches/release25-maint/Modules/_bsddb.c Fri Jan 5 03:09:06 2007 @@ -98,7 +98,7 @@ #error "eek! DBVER can't handle minor versions > 9" #endif -#define PY_BSDDB_VERSION "4.4.5.1" +#define PY_BSDDB_VERSION "4.4.5.2" static char *rcs_id = "$Id$"; @@ -4127,6 +4127,7 @@ } +#if (DBVER < 45) static PyObject* DBEnv_set_lk_max(DBEnvObject* self, PyObject* args) { @@ -4142,6 +4143,7 @@ RETURN_IF_ERR(); RETURN_NONE(); } +#endif #if (DBVER >= 32) @@ -5231,7 +5233,9 @@ {"set_lg_regionmax",(PyCFunction)DBEnv_set_lg_regionmax, METH_VARARGS}, #endif {"set_lk_detect", (PyCFunction)DBEnv_set_lk_detect, METH_VARARGS}, +#if (DBVER < 45) {"set_lk_max", (PyCFunction)DBEnv_set_lk_max, METH_VARARGS}, +#endif #if (DBVER >= 32) {"set_lk_max_locks", (PyCFunction)DBEnv_set_lk_max_locks, METH_VARARGS}, {"set_lk_max_lockers", (PyCFunction)DBEnv_set_lk_max_lockers, METH_VARARGS}, @@ -5833,7 +5837,9 @@ ADD_INT(d, DB_AFTER); ADD_INT(d, DB_APPEND); ADD_INT(d, DB_BEFORE); +#if (DBVER < 45) ADD_INT(d, DB_CACHED_COUNTS); +#endif #if (DBVER >= 41) _addIntToDict(d, "DB_CHECKPOINT", 0); #else @@ -5868,7 +5874,9 @@ ADD_INT(d, DB_POSITION); ADD_INT(d, DB_PREV); ADD_INT(d, DB_PREV_NODUP); +#if (DBVER < 45) ADD_INT(d, DB_RECORDCOUNT); +#endif ADD_INT(d, DB_SET); ADD_INT(d, DB_SET_RANGE); ADD_INT(d, DB_SET_RECNO); Modified: python/branches/release25-maint/setup.py ============================================================================== --- python/branches/release25-maint/setup.py (original) +++ python/branches/release25-maint/setup.py Fri Jan 5 03:09:06 2007 @@ -606,7 +606,7 @@ # a release. Most open source OSes come with one or more # versions of BerkeleyDB already installed. - max_db_ver = (4, 4) + max_db_ver = (4, 5) min_db_ver = (3, 3) db_setup_debug = False # verbose debug prints from this script? @@ -623,7 +623,7 @@ '/sw/include/db3', ] # 4.x minor number specific paths - for x in (0,1,2,3,4): + for x in (0,1,2,3,4,5): db_inc_paths.append('/usr/include/db4%d' % x) db_inc_paths.append('/usr/include/db4.%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x) @@ -631,7 +631,7 @@ db_inc_paths.append('/pkg/db-4.%d/include' % x) db_inc_paths.append('/opt/db-4.%d/include' % x) # 3.x minor number specific paths - for x in (2,3): + for x in (3,): db_inc_paths.append('/usr/include/db3%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x) db_inc_paths.append('/usr/local/include/db3%d' % x) From buildbot at python.org Fri Jan 5 03:23:25 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 02:23:25 +0000 Subject: [Python-checkins] buildbot warnings in amd64 gentoo trunk Message-ID: <20070105022325.3EC6D1E400B@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/1736 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Fri Jan 5 03:24:16 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 02:24:16 +0000 Subject: [Python-checkins] buildbot warnings in x86 mvlgcc trunk Message-ID: <20070105022416.568081E400B@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/142 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Fri Jan 5 03:24:17 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 02:24:17 +0000 Subject: [Python-checkins] buildbot warnings in x86 gentoo trunk Message-ID: <20070105022417.3CBBF1E400B@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/1818 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Fri Jan 5 03:41:59 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 02:41:59 +0000 Subject: [Python-checkins] buildbot warnings in x86 gentoo 2.5 Message-ID: <20070105024159.DCDAC1E4002@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/161 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Fri Jan 5 03:42:03 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 02:42:03 +0000 Subject: [Python-checkins] buildbot warnings in amd64 gentoo 2.5 Message-ID: <20070105024203.EE3701E400D@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/162 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Fri Jan 5 03:43:17 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 02:43:17 +0000 Subject: [Python-checkins] buildbot warnings in x86 mvlgcc 2.5 Message-ID: <20070105024317.52BC41E4002@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/73 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Fri Jan 5 03:52:40 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 02:52:40 +0000 Subject: [Python-checkins] buildbot warnings in ia64 Ubuntu trunk trunk Message-ID: <20070105025251.C12831E400B@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/294 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Fri Jan 5 03:57:13 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 02:57:13 +0000 Subject: [Python-checkins] buildbot warnings in S-390 Debian trunk Message-ID: <20070105025720.70B111E4002@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/575 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Fri Jan 5 04:39:38 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 03:39:38 +0000 Subject: [Python-checkins] buildbot warnings in ia64 Ubuntu trunk 2.5 Message-ID: <20070105033938.388B81E4010@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/150 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From buildbot at python.org Fri Jan 5 04:50:03 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 03:50:03 +0000 Subject: [Python-checkins] buildbot warnings in S-390 Debian 2.5 Message-ID: <20070105035004.0882A1E4002@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/138 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: gregory.p.smith Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From python-checkins at python.org Fri Jan 5 06:25:45 2007 From: python-checkins at python.org (neal.norwitz) Date: Fri, 5 Jan 2007 06:25:45 +0100 (CET) Subject: [Python-checkins] r53255 - in python/trunk: Misc/NEWS Python/errors.c Message-ID: <20070105052545.99D951E4002@bag.python.org> Author: neal.norwitz Date: Fri Jan 5 06:25:22 2007 New Revision: 53255 Modified: python/trunk/Misc/NEWS python/trunk/Python/errors.c Log: Prevent crash on shutdown which can occur if we are finalizing and the module dict has been cleared already and some object raises a warning (like in a __del__). Will backport. Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri Jan 5 06:25:22 2007 @@ -12,6 +12,9 @@ Core and builtins ----------------- +- Prevent seg fault on shutdown which could occur if an object + raised a warning. + - Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, to avoid relying on atexit. Modified: python/trunk/Python/errors.c ============================================================================== --- python/trunk/Python/errors.c (original) +++ python/trunk/Python/errors.c Fri Jan 5 06:25:22 2007 @@ -640,7 +640,8 @@ if (warnings_module != NULL) { dict = PyModule_GetDict(warnings_module); - func = PyDict_GetItemString(dict, "warn"); + if (dict != NULL) + func = PyDict_GetItemString(dict, "warn"); } if (func == NULL) { PySys_WriteStderr("warning: %s\n", message); From python-checkins at python.org Fri Jan 5 06:29:25 2007 From: python-checkins at python.org (neal.norwitz) Date: Fri, 5 Jan 2007 06:29:25 +0100 (CET) Subject: [Python-checkins] r53256 - in python/branches/release25-maint: Misc/NEWS Python/errors.c Message-ID: <20070105052925.2C4F81E4002@bag.python.org> Author: neal.norwitz Date: Fri Jan 5 06:28:50 2007 New Revision: 53256 Modified: python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Python/errors.c Log: Backport: Prevent crash on shutdown which can occur if we are finalizing and the module dict has been cleared already and some object raises a warning (like in a __del__). Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Fri Jan 5 06:28:50 2007 @@ -12,6 +12,9 @@ Core and builtins ----------------- +- Prevent seg fault on shutdown which could occur if an object + raised a warning. + - Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, to avoid relying on atexit. Modified: python/branches/release25-maint/Python/errors.c ============================================================================== --- python/branches/release25-maint/Python/errors.c (original) +++ python/branches/release25-maint/Python/errors.c Fri Jan 5 06:28:50 2007 @@ -640,7 +640,8 @@ if (warnings_module != NULL) { dict = PyModule_GetDict(warnings_module); - func = PyDict_GetItemString(dict, "warn"); + if (dict != NULL) + func = PyDict_GetItemString(dict, "warn"); } if (func == NULL) { PySys_WriteStderr("warning: %s\n", message); From python-checkins at python.org Fri Jan 5 07:00:49 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 5 Jan 2007 07:00:49 +0100 (CET) Subject: [Python-checkins] r53257 - peps/trunk/pep-3108.txt Message-ID: <20070105060049.94C9D1E400B@bag.python.org> Author: brett.cannon Date: Fri Jan 5 07:00:48 2007 New Revision: 53257 Modified: peps/trunk/pep-3108.txt Log: Fix a missing footnote. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Fri Jan 5 07:00:48 2007 @@ -154,7 +154,7 @@ - OSA support is better through third-party modules. - * Applescript/OSA [#applescript-osa]_. + * Appscript [#appscript]_. - Hard-coded endianness which breaks on Intel Macs. - Might need to rename if Carbon package dependent. @@ -723,6 +723,9 @@ .. [#sun-au] Wikipedia: Au file format (http://en.wikipedia.org/wiki/Au_file_format) +.. [#appscript] appscript + (http://appscript.sourceforge.net/) + Copyright ========= From python-checkins at python.org Fri Jan 5 08:21:36 2007 From: python-checkins at python.org (gregory.p.smith) Date: Fri, 5 Jan 2007 08:21:36 +0100 (CET) Subject: [Python-checkins] r53258 - python/trunk/Doc/lib/libsimplexmlrpc.tex Message-ID: <20070105072136.0D2921E4016@bag.python.org> Author: gregory.p.smith Date: Fri Jan 5 08:21:35 2007 New Revision: 53258 Modified: python/trunk/Doc/lib/libsimplexmlrpc.tex Log: typo fix Modified: python/trunk/Doc/lib/libsimplexmlrpc.tex ============================================================================== --- python/trunk/Doc/lib/libsimplexmlrpc.tex (original) +++ python/trunk/Doc/lib/libsimplexmlrpc.tex Fri Jan 5 08:21:35 2007 @@ -15,7 +15,7 @@ \begin{classdesc}{SimpleXMLRPCServer}{addr\optional{, requestHandler\optional{, - logRequests\optional{allow_none\optional{, encoding}}}}} + logRequests\optional{, allow_none\optional{, encoding}}}}} Create a new server instance. This class provides methods for registration of functions that can be called by From python-checkins at python.org Fri Jan 5 08:22:29 2007 From: python-checkins at python.org (gregory.p.smith) Date: Fri, 5 Jan 2007 08:22:29 +0100 (CET) Subject: [Python-checkins] r53259 - python/branches/release25-maint/Doc/lib/libsimplexmlrpc.tex Message-ID: <20070105072229.5955F1E4002@bag.python.org> Author: gregory.p.smith Date: Fri Jan 5 08:22:29 2007 New Revision: 53259 Modified: python/branches/release25-maint/Doc/lib/libsimplexmlrpc.tex Log: typo fix Modified: python/branches/release25-maint/Doc/lib/libsimplexmlrpc.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libsimplexmlrpc.tex (original) +++ python/branches/release25-maint/Doc/lib/libsimplexmlrpc.tex Fri Jan 5 08:22:29 2007 @@ -15,7 +15,7 @@ \begin{classdesc}{SimpleXMLRPCServer}{addr\optional{, requestHandler\optional{, - logRequests\optional{allow_none\optional{, encoding}}}}} + logRequests\optional{, allow_none\optional{, encoding}}}}} Create a new server instance. This class provides methods for registration of functions that can be called by From python-checkins at python.org Fri Jan 5 09:06:52 2007 From: python-checkins at python.org (neal.norwitz) Date: Fri, 5 Jan 2007 09:06:52 +0100 (CET) Subject: [Python-checkins] r53260 - python/trunk/Misc/developers.txt Message-ID: <20070105080652.3707A1E4002@bag.python.org> Author: neal.norwitz Date: Fri Jan 5 09:06:43 2007 New Revision: 53260 Modified: python/trunk/Misc/developers.txt Log: Add Collin Winter for access to update PEP 3107 Modified: python/trunk/Misc/developers.txt ============================================================================== --- python/trunk/Misc/developers.txt (original) +++ python/trunk/Misc/developers.txt Fri Jan 5 09:06:43 2007 @@ -17,6 +17,9 @@ Permissions History ------------------- +- Collin Winter was given SVN access on 05 Jan 2007 by NCN, for PEP + update access. + - Lars Gustaebel was given SVN access on 20 Dec 2006 by NCN, for tarfile.py related work. From theller at ctypes.org Fri Jan 5 11:04:21 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 05 Jan 2007 11:04:21 +0100 Subject: [Python-checkins] r53249 - in python/trunk: Lib/threading.py Misc/NEWS Modules/main.c In-Reply-To: <20070104210613.7BE2A1E4002@bag.python.org> References: <20070104210613.7BE2A1E4002@bag.python.org> Message-ID: martin.v.loewis schrieb: > Modified: python/trunk/Modules/main.c > ============================================================================== > --- python/trunk/Modules/main.c (original) > +++ python/trunk/Modules/main.c Thu Jan 4 22:06:12 2007 > @@ -177,6 +177,33 @@ > return 0; > } > > +/* Wait until threading._shutdown completes, provided > + the threading module was imported in the first place. > + The shutdown routine will wait until all non-daemon > + "threading" threads have completed. */ > +#include "abstract.h" > +static void > +WaitForThreadShutdown() > +{ > +#ifdef WITH_THREAD > + PyObject *result; > + PyThreadState *tstate = PyThreadState_GET(); > + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, > + "threading"); > + if (threading == NULL) { > + /* threading not imported */ > + PyErr_Clear(); > + return; > + } > + result = PyObject_CallMethod(threading, "_shutdown", ""); > + if (result == NULL) > + PyErr_WriteUnraisable(threading); > + else > + Py_DECREF(result); > + Py_DECREF(threading); > +#endif > +} > + > /* Main program */ > > int > @@ -514,6 +541,8 @@ > /* XXX */ > sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; > > + WaitForThreadShutdown(); > + > Py_Finalize(); > #ifdef RISCOS > if (Py_RISCOSWimpFlag) Does this mean that programs embedding Python (providing their own Py_Main function) have to implement a WaitForThreadShutdown() function and call it themselves, before calling Py_Finalize()? Wouldn't it be better to wait in Py_Finalize()? Thanks, Thomas From python-checkins at python.org Fri Jan 5 15:03:42 2007 From: python-checkins at python.org (barry.warsaw) Date: Fri, 5 Jan 2007 15:03:42 +0100 (CET) Subject: [Python-checkins] r53261 - peps/trunk/pep-0008.txt Message-ID: <20070105140342.C80631E4002@bag.python.org> Author: barry.warsaw Date: Fri Jan 5 15:03:42 2007 New Revision: 53261 Modified: peps/trunk/pep-0008.txt Log: Updated the rules for package names and module names, clarifying the use of underscores. Modified: peps/trunk/pep-0008.txt ============================================================================== --- peps/trunk/pep-0008.txt (original) +++ peps/trunk/pep-0008.txt Fri Jan 5 15:03:42 2007 @@ -468,9 +468,12 @@ In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use `l', use `L' instead. - Module Names + Package and Module Names - Modules should have short, lowercase names, without underscores. + Modules should have short, all-lowercase names. Underscores can be used + in the module name if it improves readability. Python packages should + also have short, all-lowercase names, although the use of underscores is + discouraged. Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module @@ -482,9 +485,6 @@ module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket). - Like modules, Python packages should have short, all-lowercase names, - without underscores. - Class Names Almost without exception, class names use the CapWords convention. From python-checkins at python.org Fri Jan 5 15:22:17 2007 From: python-checkins at python.org (andrew.kuchling) Date: Fri, 5 Jan 2007 15:22:17 +0100 (CET) Subject: [Python-checkins] r53262 - python/trunk/Lib/StringIO.py python/trunk/Lib/difflib.py Message-ID: <20070105142217.CDC1C1E4002@bag.python.org> Author: andrew.kuchling Date: Fri Jan 5 15:22:17 2007 New Revision: 53262 Modified: python/trunk/Lib/StringIO.py python/trunk/Lib/difflib.py Log: [Bug #1622533] Make docstrings raw strings because they contain control characters (\0, \1) Modified: python/trunk/Lib/StringIO.py ============================================================================== --- python/trunk/Lib/StringIO.py (original) +++ python/trunk/Lib/StringIO.py Fri Jan 5 15:22:17 2007 @@ -137,7 +137,7 @@ return r def readline(self, length=None): - """Read one entire line from the file. + r"""Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is Modified: python/trunk/Lib/difflib.py ============================================================================== --- python/trunk/Lib/difflib.py (original) +++ python/trunk/Lib/difflib.py Fri Jan 5 15:22:17 2007 @@ -1311,7 +1311,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, charjunk=IS_CHARACTER_JUNK): - """Returns generator yielding marked up from/to side by side differences. + r"""Returns generator yielding marked up from/to side by side differences. Arguments: fromlines -- list of text lines to compared to tolines From python-checkins at python.org Fri Jan 5 15:24:37 2007 From: python-checkins at python.org (andrew.kuchling) Date: Fri, 5 Jan 2007 15:24:37 +0100 (CET) Subject: [Python-checkins] r53263 - python/branches/release25-maint/Lib/StringIO.py python/branches/release25-maint/Lib/difflib.py Message-ID: <20070105142437.3F9D81E4002@bag.python.org> Author: andrew.kuchling Date: Fri Jan 5 15:24:36 2007 New Revision: 53263 Modified: python/branches/release25-maint/Lib/StringIO.py python/branches/release25-maint/Lib/difflib.py Log: [Bug #1622533] Make docstrings raw strings because they contain control characters (\0, \1) Modified: python/branches/release25-maint/Lib/StringIO.py ============================================================================== --- python/branches/release25-maint/Lib/StringIO.py (original) +++ python/branches/release25-maint/Lib/StringIO.py Fri Jan 5 15:24:36 2007 @@ -137,7 +137,7 @@ return r def readline(self, length=None): - """Read one entire line from the file. + r"""Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is Modified: python/branches/release25-maint/Lib/difflib.py ============================================================================== --- python/branches/release25-maint/Lib/difflib.py (original) +++ python/branches/release25-maint/Lib/difflib.py Fri Jan 5 15:24:36 2007 @@ -1311,7 +1311,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, charjunk=IS_CHARACTER_JUNK): - """Returns generator yielding marked up from/to side by side differences. + r"""Returns generator yielding marked up from/to side by side differences. Arguments: fromlines -- list of text lines to compared to tolines From python-checkins at python.org Fri Jan 5 16:51:27 2007 From: python-checkins at python.org (andrew.kuchling) Date: Fri, 5 Jan 2007 16:51:27 +0100 (CET) Subject: [Python-checkins] r53264 - python/trunk/Lib/bsddb/test/test_associate.py python/trunk/Lib/bsddb/test/test_basics.py python/trunk/Lib/bsddb/test/test_dbobj.py python/trunk/Lib/bsddb/test/test_dbshelve.py python/trunk/Lib/bsddb/test/test_dbtables.py python/trunk/Lib/bsddb/test/test_env_close.py python/trunk/Lib/bsddb/test/test_join.py python/trunk/Lib/bsddb/test/test_lock.py python/trunk/Lib/bsddb/test/test_misc.py python/trunk/Lib/bsddb/test/test_recno.py python/trunk/Lib/bsddb/test/test_thread.py Message-ID: <20070105155127.1687A1E400B@bag.python.org> Author: andrew.kuchling Date: Fri Jan 5 16:51:24 2007 New Revision: 53264 Modified: python/trunk/Lib/bsddb/test/test_associate.py python/trunk/Lib/bsddb/test/test_basics.py python/trunk/Lib/bsddb/test/test_dbobj.py python/trunk/Lib/bsddb/test/test_dbshelve.py python/trunk/Lib/bsddb/test/test_dbtables.py python/trunk/Lib/bsddb/test/test_env_close.py python/trunk/Lib/bsddb/test/test_join.py python/trunk/Lib/bsddb/test/test_lock.py python/trunk/Lib/bsddb/test/test_misc.py python/trunk/Lib/bsddb/test/test_recno.py python/trunk/Lib/bsddb/test/test_thread.py Log: [Patch #1520904] Fix bsddb tests to write to the temp directory instead of the Lib/bsddb/test directory Modified: python/trunk/Lib/bsddb/test/test_associate.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_associate.py (original) +++ python/trunk/Lib/bsddb/test/test_associate.py Fri Jan 5 16:51:24 2007 @@ -91,7 +91,7 @@ class AssociateErrorTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/trunk/Lib/bsddb/test/test_basics.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_basics.py (original) +++ python/trunk/Lib/bsddb/test/test_basics.py Fri Jan 5 16:51:24 2007 @@ -54,7 +54,7 @@ def setUp(self): if self.useEnv: - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: shutil.rmtree(homeDir) Modified: python/trunk/Lib/bsddb/test/test_dbobj.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_dbobj.py (original) +++ python/trunk/Lib/bsddb/test/test_dbobj.py Fri Jan 5 16:51:24 2007 @@ -2,6 +2,7 @@ import sys, os, string import unittest import glob +import tempfile try: # For Pythons w/distutils pybsddb @@ -19,7 +20,7 @@ db_name = 'test-dbobj.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/trunk/Lib/bsddb/test/test_dbshelve.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_dbshelve.py (original) +++ python/trunk/Lib/bsddb/test/test_dbshelve.py Fri Jan 5 16:51:24 2007 @@ -231,7 +231,7 @@ class BasicEnvShelveTestCase(DBShelveTestCase): def do_open(self): self.homeDir = homeDir = os.path.join( - os.path.dirname(sys.argv[0]), 'db_home') + tempfile.gettempdir(), 'db_home') try: os.mkdir(homeDir) except os.error: pass self.env = db.DBEnv() Modified: python/trunk/Lib/bsddb/test/test_dbtables.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_dbtables.py (original) +++ python/trunk/Lib/bsddb/test/test_dbtables.py Fri Jan 5 16:51:24 2007 @@ -26,6 +26,7 @@ pickle = cPickle except ImportError: import pickle +import tempfile import unittest from test_all import verbose @@ -46,7 +47,7 @@ db_name = 'test-table.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/trunk/Lib/bsddb/test/test_env_close.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_env_close.py (original) +++ python/trunk/Lib/bsddb/test/test_env_close.py Fri Jan 5 16:51:24 2007 @@ -33,7 +33,7 @@ class DBEnvClosedEarlyCrash(unittest.TestCase): def setUp(self): - self.homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + self.homeDir = os.path.join(tempfile.gettempdir(), 'db_home') try: os.mkdir(self.homeDir) except os.error: pass tempfile.tempdir = self.homeDir Modified: python/trunk/Lib/bsddb/test/test_join.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_join.py (original) +++ python/trunk/Lib/bsddb/test/test_join.py Fri Jan 5 16:51:24 2007 @@ -49,7 +49,7 @@ def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/trunk/Lib/bsddb/test/test_lock.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_lock.py (original) +++ python/trunk/Lib/bsddb/test/test_lock.py Fri Jan 5 16:51:24 2007 @@ -30,7 +30,7 @@ class LockingTestCase(unittest.TestCase): def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/trunk/Lib/bsddb/test/test_misc.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_misc.py (original) +++ python/trunk/Lib/bsddb/test/test_misc.py Fri Jan 5 16:51:24 2007 @@ -4,6 +4,7 @@ import os import sys import unittest +import tempfile try: # For Pythons w/distutils pybsddb @@ -17,7 +18,7 @@ class MiscTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/trunk/Lib/bsddb/test/test_recno.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_recno.py (original) +++ python/trunk/Lib/bsddb/test/test_recno.py Fri Jan 5 16:51:24 2007 @@ -203,10 +203,10 @@ just a line in the file, but you can set a different record delimiter if needed. """ - source = os.path.join(os.path.dirname(sys.argv[0]), - 'db_home/test_recno.txt') - if not os.path.isdir('db_home'): - os.mkdir('db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') + source = os.path.join(homeDir, 'test_recno.txt') + if not os.path.isdir(homeDir): + os.mkdir(homeDir) f = open(source, 'w') # create the file f.close() Modified: python/trunk/Lib/bsddb/test/test_thread.py ============================================================================== --- python/trunk/Lib/bsddb/test/test_thread.py (original) +++ python/trunk/Lib/bsddb/test/test_thread.py Fri Jan 5 16:51:24 2007 @@ -53,7 +53,7 @@ if verbose: dbutils._deadlock_VerboseFile = sys.stdout - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) From python-checkins at python.org Fri Jan 5 17:59:58 2007 From: python-checkins at python.org (collin.winter) Date: Fri, 5 Jan 2007 17:59:58 +0100 (CET) Subject: [Python-checkins] r53265 - peps/trunk/pep-3107.txt Message-ID: <20070105165958.C00EC1E4002@bag.python.org> Author: collin.winter Date: Fri Jan 5 17:59:58 2007 New Revision: 53265 Modified: peps/trunk/pep-3107.txt Log: Clarify that the annotation dictionaries are mutable Modified: peps/trunk/pep-3107.txt ============================================================================== --- peps/trunk/pep-3107.txt (original) +++ peps/trunk/pep-3107.txt Fri Jan 5 17:59:58 2007 @@ -161,8 +161,8 @@ Once compiled, a function's annotations are available via the function's ``func_annotations`` attribute. This attribute is -a dictionary, mapping parameter names to an object representing -the evaluated annotation expression +a mutable dictionary, mapping parameter names to an object +representing the evaluated annotation expression There is a special key in the ``func_annotations`` mapping, ``"return"``. This key is present only if an annotation was supplied @@ -184,9 +184,9 @@ of a parameter; any attempt to use ``return`` as a parameter name would result in a ``SyntaxError``. -``func_annotations`` is an empty dictionary if no there are no -annotations on the function. ``func_annotations`` is always an empty -dictionary for functions created from ``lambda`` expressions. +``func_annotations`` is an empty, mutable dictionary if there are no +annotations on the function or if the functions was created from +a ``lambda`` expression. Use Cases ========= From python-checkins at python.org Fri Jan 5 19:15:32 2007 From: python-checkins at python.org (phillip.eby) Date: Fri, 5 Jan 2007 19:15:32 +0100 (CET) Subject: [Python-checkins] r53268 - sandbox/trunk/setuptools/setuptools/command/install_egg_info.py Message-ID: <20070105181532.3A3C11E4002@bag.python.org> Author: phillip.eby Date: Fri Jan 5 19:15:31 2007 New Revision: 53268 Modified: sandbox/trunk/setuptools/setuptools/command/install_egg_info.py Log: Fix not generating correct .pth for parent namespace packages when installing --single-version-externally-managed. Modified: sandbox/trunk/setuptools/setuptools/command/install_egg_info.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/install_egg_info.py (original) +++ sandbox/trunk/setuptools/setuptools/command/install_egg_info.py Fri Jan 5 19:15:31 2007 @@ -57,9 +57,8 @@ unpack_archive(self.source, self.target, skimmer) def install_namespaces(self): - nsp = (self.distribution.namespace_packages or [])[:] + nsp = self._get_all_ns_packages() if not nsp: return - nsp.sort() # set up shorter names first filename,ext = os.path.splitext(self.target) filename += '-nspkg.pth'; self.outputs.append(filename) log.info("Installing %s",filename) @@ -79,3 +78,46 @@ % locals() ) f.close() + + + def _get_all_ns_packages(self): + nsp = {} + for pkg in self.distribution.namespace_packages or []: + pkg = pkg.split('.') + while pkg: + nsp['.'.join(pkg)] = 1 + pkg.pop() + nsp=list(nsp) + nsp.sort() # set up shorter names first + return nsp + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From python-checkins at python.org Fri Jan 5 20:24:13 2007 From: python-checkins at python.org (thomas.heller) Date: Fri, 5 Jan 2007 20:24:13 +0100 (CET) Subject: [Python-checkins] r53269 - python/branches/release25-maint/Lib/ctypes Message-ID: <20070105192413.8742D1E4002@bag.python.org> Author: thomas.heller Date: Fri Jan 5 20:24:12 2007 New Revision: 53269 Modified: python/branches/release25-maint/Lib/ctypes/ (props changed) Log: Initialized merge tracking via "svnmerge" with revisions "1-51333" from svn+ssh://pythondev at svn.python.org/python/trunk/Lib/ctypes From python-checkins at python.org Fri Jan 5 20:35:13 2007 From: python-checkins at python.org (thomas.heller) Date: Fri, 5 Jan 2007 20:35:13 +0100 (CET) Subject: [Python-checkins] r53270 - python/branches/release25-maint/Lib/ctypes Message-ID: <20070105193513.D08271E4002@bag.python.org> Author: thomas.heller Date: Fri Jan 5 20:35:13 2007 New Revision: 53270 Modified: python/branches/release25-maint/Lib/ctypes/ (props changed) Log: Mark changes already backported as merged, so "svnmerge avail" does not list them any longer. From python-checkins at python.org Fri Jan 5 20:39:39 2007 From: python-checkins at python.org (phillip.eby) Date: Fri, 5 Jan 2007 20:39:39 +0100 (CET) Subject: [Python-checkins] r53271 - in sandbox/branches/setuptools-0.6: setuptools.txt setuptools/command/install_egg_info.py Message-ID: <20070105193939.8C2A91E4002@bag.python.org> Author: phillip.eby Date: Fri Jan 5 20:39:39 2007 New Revision: 53271 Modified: sandbox/branches/setuptools-0.6/setuptools.txt sandbox/branches/setuptools-0.6/setuptools/command/install_egg_info.py Log: Fix a problem installing eggs with a system packaging tool if the project contained an implicit namespace package; for example if the ``setup()`` listed a namespace package ``foo.bar`` without explicitly listing ``foo`` as a namespace package. (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 Fri Jan 5 20:39:39 2007 @@ -2623,6 +2623,11 @@ ``develop`` and the source directory is a subdirectory of the installation target directory. + * Fix a problem installing eggs with a system packaging tool if the project + contained an implicit namespace package; for example if the ``setup()`` + listed a namespace package ``foo.bar`` without explicitly listing ``foo`` + as a namespace package. + 0.6c3 * Fixed breakages caused by Subversion 1.4's new "working copy" format Modified: sandbox/branches/setuptools-0.6/setuptools/command/install_egg_info.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/install_egg_info.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/install_egg_info.py Fri Jan 5 20:39:39 2007 @@ -22,7 +22,7 @@ None, None, ei_cmd.egg_name, ei_cmd.egg_version ).egg_name()+'.egg-info' self.source = ei_cmd.egg_info - self.target = os.path.join(self.install_dir, basename) + self.target = os.path.join(self.install_dir, basename) self.outputs = [self.target] def run(self): @@ -43,7 +43,7 @@ return self.outputs def copytree(self): - # Copy the .egg-info tree to site-packages + # Copy the .egg-info tree to site-packages def skimmer(src,dst): # filter out source-control directories; note that 'src' is always # a '/'-separated path, regardless of platform. 'dst' is a @@ -57,9 +57,8 @@ unpack_archive(self.source, self.target, skimmer) def install_namespaces(self): - nsp = (self.distribution.namespace_packages or [])[:] + nsp = self._get_all_ns_packages() if not nsp: return - nsp.sort() # set up shorter names first filename,ext = os.path.splitext(self.target) filename += '-nspkg.pth'; self.outputs.append(filename) log.info("Installing %s",filename) @@ -78,5 +77,47 @@ "(p not in mp) and mp.append(p)\n" % locals() ) - f.close() + f.close() + + + def _get_all_ns_packages(self): + nsp = {} + for pkg in self.distribution.namespace_packages or []: + pkg = pkg.split('.') + while pkg: + nsp['.'.join(pkg)] = 1 + pkg.pop() + nsp=list(nsp) + nsp.sort() # set up shorter names first + return nsp + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From python-checkins at python.org Fri Jan 5 20:54:06 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 5 Jan 2007 20:54:06 +0100 (CET) Subject: [Python-checkins] r53272 - peps/trunk/pep-3108.txt Message-ID: <20070105195406.D22D01E4002@bag.python.org> Author: brett.cannon Date: Fri Jan 5 20:54:06 2007 New Revision: 53272 Modified: peps/trunk/pep-3108.txt Log: The various file format modules that were an Open Issue for removal have been found to still be useful, so the whole question has been removed. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Fri Jan 5 20:54:06 2007 @@ -606,23 +606,6 @@ + wsgiref -Modules reliant on obsolete/rarely used file formats? ------------------------------------------------------ - -Several modules in the stdlib work on a specific file format. It is -possible some of these formats are no longer used and thus the stdlib -modules for them can go. Below is a list of some modules which rely -on a file format that may be obsolete. - -audioop - Raw (8|16|32)-bit wide audio files (as generated by the al and - sunaudiodev modules). -chunk - AIFF, AIFF-C, and RMFF audio files. -sunau - Sun AU audio files [#sun-au]_. - - Renaming of modules maintained outside of the stdlib ---------------------------------------------------- From python-checkins at python.org Fri Jan 5 20:59:21 2007 From: python-checkins at python.org (thomas.heller) Date: Fri, 5 Jan 2007 20:59:21 +0100 (CET) Subject: [Python-checkins] r53273 - python/branches/release25-maint/Lib/ctypes Message-ID: <20070105195921.BC3E61E4002@bag.python.org> Author: thomas.heller Date: Fri Jan 5 20:59:21 2007 New Revision: 53273 Modified: python/branches/release25-maint/Lib/ctypes/ (props changed) Log: Blocked revisions 52945 via svnmerge ........ r52945 | brett.cannon | 2006-12-07 00:38:48 +0100 (Thu, 07 Dec 2006) | 3 lines Fix a bad assumption that all objects assigned to '__loader__' on a module will have a '_files' attribute. ........ From python-checkins at python.org Fri Jan 5 21:03:20 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 5 Jan 2007 21:03:20 +0100 (CET) Subject: [Python-checkins] r53274 - peps/trunk/pep-3108.txt Message-ID: <20070105200320.4C3BD1E4002@bag.python.org> Author: brett.cannon Date: Fri Jan 5 21:03:19 2007 New Revision: 53274 Modified: peps/trunk/pep-3108.txt Log: Add sndhdr to the audio package suggestion. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Fri Jan 5 21:03:19 2007 @@ -562,6 +562,7 @@ + audioop + chunk + ossaudiodev + + sndhdr + sunau + wave + winsound From jimjjewett at gmail.com Fri Jan 5 21:07:46 2007 From: jimjjewett at gmail.com (Jim Jewett) Date: Fri, 5 Jan 2007 15:07:46 -0500 Subject: [Python-checkins] r53272 - peps/trunk/pep-3108.txt In-Reply-To: <20070105195406.D22D01E4002@bag.python.org> References: <20070105195406.D22D01E4002@bag.python.org> Message-ID: >From a learner's perspective, it would still be useful to group them. Whether they should all go under "formats", or be broken down more meaningfully ("audio") is a different question, but either would have been an improvement for me. -jJ On 1/5/07, brett.cannon wrote: > Author: brett.cannon > Date: Fri Jan 5 20:54:06 2007 > New Revision: 53272 > > Modified: > peps/trunk/pep-3108.txt > Log: > The various file format modules that were an Open Issue for removal have been > found to still be useful, so the whole question has been removed. > > > Modified: peps/trunk/pep-3108.txt > ============================================================================== > --- peps/trunk/pep-3108.txt (original) > +++ peps/trunk/pep-3108.txt Fri Jan 5 20:54:06 2007 > @@ -606,23 +606,6 @@ > + wsgiref > > > -Modules reliant on obsolete/rarely used file formats? > ------------------------------------------------------ > - > -Several modules in the stdlib work on a specific file format. It is > -possible some of these formats are no longer used and thus the stdlib > -modules for them can go. Below is a list of some modules which rely > -on a file format that may be obsolete. > - > -audioop > - Raw (8|16|32)-bit wide audio files (as generated by the al and > - sunaudiodev modules). > -chunk > - AIFF, AIFF-C, and RMFF audio files. > -sunau > - Sun AU audio files [#sun-au]_. > - > - > Renaming of modules maintained outside of the stdlib > ---------------------------------------------------- > > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From python-checkins at python.org Fri Jan 5 21:22:00 2007 From: python-checkins at python.org (thomas.heller) Date: Fri, 5 Jan 2007 21:22:00 +0100 (CET) Subject: [Python-checkins] r53275 - python/branches/release25-maint/Modules/_ctypes Message-ID: <20070105202200.81E141E4002@bag.python.org> Author: thomas.heller Date: Fri Jan 5 21:21:59 2007 New Revision: 53275 Modified: python/branches/release25-maint/Modules/_ctypes/ (props changed) Log: Revisions 52418,52841,52855 have already been merged. From python-checkins at python.org Fri Jan 5 21:23:59 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 5 Jan 2007 21:23:59 +0100 (CET) Subject: [Python-checkins] r53276 - peps/trunk/pep-3108.txt Message-ID: <20070105202359.49D491E4002@bag.python.org> Author: brett.cannon Date: Fri Jan 5 21:23:56 2007 New Revision: 53276 Modified: peps/trunk/pep-3108.txt Log: Update PEP based on new wording in PEP 8 (allowing the use of underscores in module names). Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Fri Jan 5 21:23:56 2007 @@ -197,12 +197,12 @@ - No longer distributed with Python. -Minimal usage -------------- +Hardly used +------------ -Some modules that are platform-independent have minimal usage. This +Some modules that are platform-independent are hardly used. This can be from how easy it is to implement the functionality from scratch -or because the audience for the code is small. +or because the audience for the code is very small. * audiodev @@ -351,40 +351,35 @@ PEP 8 violations ---------------- -PEP 8 specifies that modules "should have short, lowercase names, -without underscores" [#pep-0008]_. There is no mention, though, if -this rule extends to modules contained within a package. The -assumption is that underscores are acceptable in module names when -they are contained within a package but that any uppercase letters is -not. +PEP 8 specifies that modules "should have short, all-lowercase names" +where "underscores can be used ... if it improves readability" +[#pep-0008]_. The use of underscores is discouraged in package names. ================== ================================================== Current Name Replacement Name ================== ================================================== _winreg winreg (rename also because module has a public - interface) -BaseHTTPServer basehttpserver + interface and thus should not have a leading + underscore) +BaseHTTPServer base_http_server Carbon carbon -CGIHTTPServer cgihttpserver +CGIHTTPServer cgi_http_server ColorPicker colorpicker ConfigParser configparser Cookie cookie copy_reg copyreg -DocXMLRPCServer docxmlrpcserver -dummy_threading mockthreading (rename because "mock" makes more - sense than "dummy" and rename already required) +DocXMLRPCServer doc_xmlrpc_server EasyDialogs easydialogs HTMLParser htmlparser MacOS macos Nav nav -PixMapWrapper pixmapwrapper -py_compile pycompile +PixMapWrapper pixmap_wrapper Queue queue repr reprlib (rename because module name shadows a built-in) ScrolledText scrolledtext -SimpleHTTPServer simplehttpserver -SimpleXMLRPCServer simplexmlrpcserver +SimpleHTTPServer simple_http_server +SimpleXMLRPCServer simple_xmlrpc_server SocketServer socketserver StringIO stringio Tix tix @@ -448,8 +443,8 @@ cl _cl markupbase _markupbase opcode _opcode -dummythread _mockthread (assuming the - deprecation of 'thread' occurs) +dummy_thread _dummy_thread (assuming thread + is deprecated) ============ =============================== @@ -526,10 +521,10 @@ Have a package for Python implementations of built-in types instead of putting the User* modules into 'collections'? -* mac +* Platform-specific - + Various Mac-specific modules. - + Same can be done for other platform-specific code. + + All platform-specific modules should be placed in a package + representing the platform. * Profiling From amk at amk.ca Fri Jan 5 21:28:15 2007 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 5 Jan 2007 15:28:15 -0500 Subject: [Python-checkins] r53274 - peps/trunk/pep-3108.txt In-Reply-To: <20070105200320.4C3BD1E4002@bag.python.org> References: <20070105200320.4C3BD1E4002@bag.python.org> Message-ID: <20070105202815.GA10348@localhost.localdomain> On Fri, Jan 05, 2007 at 09:03:20PM +0100, brett.cannon wrote: > Author: brett.cannon > Date: Fri Jan 5 21:03:19 2007 > New Revision: 53274 > > Modified: > peps/trunk/pep-3108.txt > Log: > Add sndhdr to the audio package suggestion. Not to pick on sndhdr, but the stdlib reorganization seems to be losing its purpose. Sure, for any module X you can probably find someone who's using it, but the point of the reorganization is to remove modules that aren't being *maintained*. For example, asyncore is now listed as being kept, but no one is fixing bugs in asyncore or adding new features, so why do we want to continue dragging the module onward? --amk From python-checkins at python.org Fri Jan 5 21:49:25 2007 From: python-checkins at python.org (david.goodger) Date: Fri, 5 Jan 2007 21:49:25 +0100 (CET) Subject: [Python-checkins] r53277 - peps/trunk/pep-0287.txt Message-ID: <20070105204925.88AB41E4002@bag.python.org> Author: david.goodger Date: Fri Jan 5 21:49:24 2007 New Revision: 53277 Modified: peps/trunk/pep-0287.txt Log: URL fixes; bring up to date with Docutils rev. 4564 Modified: peps/trunk/pep-0287.txt ============================================================================== --- peps/trunk/pep-0287.txt (original) +++ peps/trunk/pep-0287.txt Fri Jan 5 21:49:24 2007 @@ -757,14 +757,14 @@ .. _TeX: http://www.tug.org/interest.html -.. _Perl POD: http://www.perldoc.com/perl5.6/pod/perlpod.html +.. _Perl POD: http://perldoc.perl.org/perlpod.html .. _JavaDoc: http://java.sun.com/j2se/javadoc/ .. _Setext: http://docutils.sourceforge.net/mirror/setext.html .. _StructuredText: - http://dev.zope.org/Members/jim/StructuredTextWiki/FrontPage + http://www.zope.org/DevHome/Members/jim/StructuredTextWiki/FrontPage .. _A ReStructuredText Primer: http://docutils.sourceforge.net/docs/user/rst/quickstart.html From python-checkins at python.org Fri Jan 5 22:41:45 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 5 Jan 2007 22:41:45 +0100 (CET) Subject: [Python-checkins] r53278 - peps/trunk/pep-3108.txt Message-ID: <20070105214145.9F0281E4002@bag.python.org> Author: brett.cannon Date: Fri Jan 5 22:41:45 2007 New Revision: 53278 Modified: peps/trunk/pep-3108.txt Log: Cleanup thread deprecation proposal. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Fri Jan 5 22:41:45 2007 @@ -322,10 +322,8 @@ + People should use 'threading' instead. - Rename 'thread' to _thread. - - Deprecate dummy_thread. - - * Rename to _mockthread. - * Change of name better reflects modules purpose. + - Deprecate dummy_thread and rename _dummy_thread. + - Move thread.get_ident over to threading. + Guido has previously supported the deprecation [#thread-deprecation]_. From python-checkins at python.org Fri Jan 5 22:45:10 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 5 Jan 2007 22:45:10 +0100 (CET) Subject: [Python-checkins] r53279 - python/trunk/Modules/main.c Message-ID: <20070105214510.9C4541E400F@bag.python.org> Author: brett.cannon Date: Fri Jan 5 22:45:09 2007 New Revision: 53279 Modified: python/trunk/Modules/main.c Log: Silence a warning from gcc 4.0.1 by specifying a function's parameter list is 'void' instead of just a set of empty parentheses. Modified: python/trunk/Modules/main.c ============================================================================== --- python/trunk/Modules/main.c (original) +++ python/trunk/Modules/main.c Fri Jan 5 22:45:09 2007 @@ -183,7 +183,7 @@ "threading" threads have completed. */ #include "abstract.h" static void -WaitForThreadShutdown() +WaitForThreadShutdown(void) { #ifdef WITH_THREAD PyObject *result; From python-checkins at python.org Fri Jan 5 22:59:40 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 5 Jan 2007 22:59:40 +0100 (CET) Subject: [Python-checkins] r53280 - sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/mock_importer.py sandbox/trunk/import_in_py/test_importer.py Message-ID: <20070105215940.B4F2A1E4002@bag.python.org> Author: brett.cannon Date: Fri Jan 5 22:59:39 2007 New Revision: 53280 Modified: sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/mock_importer.py sandbox/trunk/import_in_py/test_importer.py Log: Tighten up API to just what needs to be publicly exposed by adding underscores to various functions and methods. Modified: sandbox/trunk/import_in_py/importer.py ============================================================================== --- sandbox/trunk/import_in_py/importer.py (original) +++ sandbox/trunk/import_in_py/importer.py Fri Jan 5 22:59:39 2007 @@ -1,7 +1,5 @@ """Re-implementation of import machinery in Python source code. -XXX See http://docs.google.com/View?docid=dg7fctr4_4d8tdbq on current status. - ==================== References on import ==================== @@ -30,38 +28,39 @@ AttributeError. + Possible fix - Implement optional interface for loaders. + - Do not have new loaders set __loader__. + * Might happen because of security issues. * warnings and stack level. + Affected tests - test___all__ - test_imageop + 'warnings' assumes that the import code does not show up in the call stack. - + Because import now in Python, import does show up in the call stack. - + Trick of specifying that going back two levels will cause the warning - to be raised in the caller for an import statement no longer holds true. + + Because import now implemented in Python, import does show up in the + call stack. + + Trick of specifying going back in the call stack two levels so warning + shows up in the caller will cause the warning no longer holds true. + Possible fixes - Special module deprecation function. - - Code in warnings.warn to handle import case. + - Code in warnings.warn to handle special import case. - Flag on warnings.warn that warning is for an import and ignore stack level argument. * Could also infer from type of warning. * test_pkg + Old-style test that compares output. + Setting of __loader__ leads to different output. -* PEP 235 not implemented. """ from __future__ import with_statement +# Built-in modules. import imp import sys import marshal -# XXX Following imports will eventually need to be removed since they are not -# built-in modules. +# Not built-in. import errno import os import contextlib -import py_compile import warnings @@ -76,7 +75,7 @@ _set__import__ was called previously).""" __builtins__['__import__'] = original__import__ -def w_long(x): +def _w_long(x): """Convert a 32-bit integer to little-endian. XXX Temporary until marshal's long functions are exposed. @@ -89,7 +88,7 @@ bytes.append((x >> 24) & 0xFF) return ''.join(chr(x) for x in bytes) -def r_long(bytes): +def _r_long(bytes): """Convert 4 bytes in little-endian to an integer. XXX Temporary until marshal's long function are exposed. @@ -101,7 +100,7 @@ x |= ord(bytes[3]) << 24 return x -def case_ok(directory, file_name): +def _case_ok(directory, file_name): """Verify that file_name (as found in 'directory') has the proper case. The path is assumed to already exist. @@ -114,8 +113,6 @@ """ if sys.platform not in ('win32', 'mac', 'riscos', 'darwin', 'cygwin', 'os2emx') or os.environ.get('PYTHONCASEOK'): - # Platform is case-sensitive so existence check already handle - # case-sensitivity. return True directory_contents = os.listdir(directory) if file_name in directory_contents: @@ -124,7 +121,7 @@ return False -class BuiltinFrozenBaseImporter(object): +class _BuiltinFrozenBaseImporter(object): """Base class for meta_path importers for built-in and frozen modules. @@ -164,7 +161,7 @@ return mod -class BuiltinImporter(BuiltinFrozenBaseImporter): +class BuiltinImporter(_BuiltinFrozenBaseImporter): """sys.meta_path class for importing built-in modules. @@ -177,7 +174,7 @@ _load = imp.init_builtin -class FrozenImporter(BuiltinFrozenBaseImporter): +class FrozenImporter(_BuiltinFrozenBaseImporter): """sys.meta_path class for importing frozen modules.""" @@ -248,17 +245,17 @@ init_filename = '__init__' + file_ext package_init = os.path.join(package_directory, init_filename) if (os.path.isfile(package_init) and - case_ok(self.path_entry, tail_module) and - case_ok(package_directory, init_filename)): + _case_ok(self.path_entry, tail_module) and + _case_ok(package_directory, init_filename)): return self.loader(package_init, handler, package_directory) file_name = tail_module + file_ext file_path = os.path.join(self.path_entry, file_name) if (os.path.isfile(file_path) and - case_ok(self.path_entry, file_name)): + _case_ok(self.path_entry, file_name)): return self.loader(file_path, handler) else: if (os.path.isdir(package_directory) and - case_ok(self.path_entry, tail_module)): + _case_ok(self.path_entry, tail_module)): warnings.warn("Not importing directory %s: missing __init__.py" % package_directory, ImportWarning) @@ -367,7 +364,7 @@ def parse_pyc(self, data): """Split data into magic number, timestamp, and bytecode.""" - return data[:4], r_long(data[4:8]), data[8:] + return data[:4], _r_long(data[4:8]), data[8:] def check_magic(self, magic): """Check whether the magic number is valid or not.""" @@ -389,7 +386,7 @@ def create_pyc(self, bytecode, timestamp): """Create data for a .pyc file.""" data = imp.get_magic() - data += w_long(timestamp) + data += _w_long(timestamp) data += marshal.dumps(bytecode) return data @@ -551,7 +548,7 @@ handlers = ExtensionFileHandler(), PyPycHandler() self.default_path_hook = FileSystemFactory(*handlers) - def search_meta_path(self, name, path=None): + def _search_meta_path(self, name, path=None): """Check the importers on sys.meta_path for a loader along with the extended meta path sequence stored within this instance. @@ -566,7 +563,7 @@ else: raise ImportError("No module named %s" % name) - def sys_path_importer(self, path_entry): + def _sys_path_importer(self, path_entry): """Return the importer for the specified path. If None is stored in sys.path_importer_cache then use the default path @@ -608,7 +605,7 @@ sys.path_importer_cache[path_entry] = None raise ImportError("no importer found for %s" % path_entry) - def search_std_path(self, name, path=None): + def _search_std_path(self, name, path=None): """Check sys.path or 'path' (depending if 'path' is set) for the named module and return its loader.""" if path: @@ -617,7 +614,7 @@ search_paths = sys.path for entry in search_paths: try: - importer = self.sys_path_importer(entry) + importer = self._sys_path_importer(entry) except ImportError: continue loader = importer.find_module(name) @@ -626,7 +623,7 @@ else: raise ImportError("No module found named %s" % name) - def import_module(self, name, path=None): + def _import_module(self, name, path=None): """Import the specified module with no handling of parent modules. If None is set for a value in sys.modules (to signify that a relative @@ -641,16 +638,16 @@ return value try: # Attempt to find a loader on sys.meta_path. - loader = self.search_meta_path(name, path) + loader = self._search_meta_path(name, path) except ImportError: # sys.meta_path search failed. Attempt to find a loader on # sys.path. If this fails then module cannot be found. - loader = self.search_std_path(name, path) + 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) - def import_full_module(self, name): + def _import_full_module(self, name): """Import a module along with its parent modules and set into sys.modules.""" # Import the module (importing its parent modules first). @@ -671,12 +668,12 @@ path_list = parent_module.__path__ except AttributeError: pass - module = self.import_module(current_name, path_list) + module = self._import_module(current_name, path_list) if parent_module: setattr(parent_module, name_part, module) parent_module = module - def classic_resolve_name(self, name, caller_name, caller_is_package): + def _classic_resolve_name(self, name, caller_name, caller_is_package): """Return the absolute name of the module specified in 'name' as based on the name of the caller and whether it is a package.""" if caller_is_package: @@ -689,7 +686,7 @@ base_name = caller_name.rsplit('.', 1)[0] return base_name + '.' + name - def resolve_name(self, name, caller_name, caller_is_package, level): + def _resolve_name(self, name, caller_name, caller_is_package, level): """Return the absolute name of the module specified by 'name' based on where the module is being imported and the requested change in dotted name level. @@ -711,7 +708,7 @@ else: return base_name - def return_module(self, absolute_name, relative_name, fromlist): + 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. @@ -755,10 +752,10 @@ if item == '*': continue if not hasattr(module, item): - resolved_name = self.resolve_name(item, module.__name__, + resolved_name = self._resolve_name(item, module.__name__, True, 1) try: - self.import_full_module(resolved_name) + self._import_full_module(resolved_name) except ImportError: pass return module @@ -808,30 +805,30 @@ # Handle the classic style of import: relative first, then # absolute. if level == -1: - relative_name = self.classic_resolve_name(name, caller_name, + relative_name = self._classic_resolve_name(name, caller_name, is_pkg) imported_name = relative_name try: # Try a relative import. - self.import_full_module(imported_name) + self._import_full_module(imported_name) except ImportError: # If the relative import fails (or is redirected), try an # absolute import. imported_name = name - self.import_full_module(imported_name) + self._import_full_module(imported_name) # Redirection entry for resolved relative name to instead # redirect to the absolute import. sys.modules[relative_name] = None # If using absolute imports with a relative path, only attempt with # the fully-resolved module name. else: - imported_name = self.resolve_name(name, caller_name, is_pkg, + imported_name = self._resolve_name(name, caller_name, is_pkg, level) # This call will also handle setting the attribute on the # package. - self.import_full_module(imported_name) + self._import_full_module(imported_name) else: imported_name = name - self.import_full_module(name) + self._import_full_module(name) relative_name = '' if imported_name == name else name - return self.return_module(imported_name, relative_name, fromlist) + return self._return_module(imported_name, relative_name, fromlist) Modified: sandbox/trunk/import_in_py/mock_importer.py ============================================================================== --- sandbox/trunk/import_in_py/mock_importer.py (original) +++ sandbox/trunk/import_in_py/mock_importer.py Fri Jan 5 22:59:39 2007 @@ -2,8 +2,7 @@ import marshal import imp from test import test_support -# XXX for w_long and r_long -from importer import w_long, r_long +from importer import _w_long def log_call(method): """Log method calls to self.log.""" @@ -94,9 +93,9 @@ magic = imp.get_magic() pyc = magic[:3] + chr(ord(magic[3]) - 1) if good_timestamp: - pyc += w_long(self.modification_time) + pyc += _w_long(self.modification_time) else: - pyc += w_long(self.modification_time - 1) + pyc += _w_long(self.modification_time - 1) # Needed for read_data on .pyc path. if good_bytecode: self.pyc = pyc + bytecode @@ -198,7 +197,7 @@ assert path[1] == self.pyc_ext, "%s != %s" % (path[1], self.pyc_ext) assert binary assert data[:4] == imp.get_magic() - assert w_long(self.modification_time) == data[4:8] + assert _w_long(self.modification_time) == data[4:8] module = MockModule(self.module_name) code = marshal.loads(data[8:]) exec code in module.__dict__ Modified: sandbox/trunk/import_in_py/test_importer.py ============================================================================== --- sandbox/trunk/import_in_py/test_importer.py (original) +++ sandbox/trunk/import_in_py/test_importer.py Fri Jan 5 22:59:39 2007 @@ -653,7 +653,7 @@ data = self.handler.create_pyc(bytecode, timestamp) self.failUnlessEqual(imp.get_magic(), data[:4]) # XXX Using importer module's marshal long function. - self.failUnlessEqual(timestamp, importer.r_long(data[4:8])) + self.failUnlessEqual(timestamp, importer._r_long(data[4:8])) self.failUnlessEqual(marshal.dumps(bytecode), data[8:]) @@ -865,7 +865,7 @@ # Importing from within a package's __init__ file should lead to a # resolved import name of the package name tacked on to the name of the # module being imported. - resolved_name = self.importer.classic_resolve_name(self.child_name, + resolved_name = self.importer._classic_resolve_name(self.child_name, self.parent_name, True) self.failUnlessEqual(resolved_name, self.full_child_name) @@ -875,7 +875,7 @@ # module name being removed and replaced with the name of what is to be # imported. calling_from = self.parent_name + '.' + '' - resolved_name = self.importer.classic_resolve_name(self.child_name, + resolved_name = self.importer._classic_resolve_name(self.child_name, calling_from, False) self.failUnlessEqual(resolved_name, self.full_child_name) @@ -884,7 +884,7 @@ # Trying to import a single level within a package within it's __init__ # module should stay within the package. # ``from .child_name import ...`` in a package. - resolved_name = self.importer.resolve_name(self.child_name, + resolved_name = self.importer._resolve_name(self.child_name, self.parent_name, True, 1) self.failUnlessEqual(resolved_name, self.full_child_name) @@ -893,7 +893,7 @@ # within the same directory as the module requesting the import. # ``from .child_name import ...`` in a package module. calling_from = self.parent_name + '.' + '' - resolved_name = self.importer.resolve_name(self.child_name, + resolved_name = self.importer._resolve_name(self.child_name, calling_from, False, 1) self.failUnlessEqual(resolved_name, self.full_child_name) @@ -902,7 +902,7 @@ depth = 10 name_extension = (str(x) for x in xrange(10)) calling_from = self.parent_name + '.' + '.'.join(name_extension) - resolved_name = self.importer.resolve_name(self.child_name, + resolved_name = self.importer._resolve_name(self.child_name, calling_from, False, depth) self.failUnlessEqual(resolved_name, self.full_child_name) @@ -910,7 +910,7 @@ # Attempting to go too high out of a package in its __init__ file # should raise ImportError. # ``from ..child_name import ...`` in a top-level package. - self.failUnlessRaises(ImportError, self.importer.resolve_name, + self.failUnlessRaises(ImportError, self.importer._resolve_name, self.child_name, self.parent_name, True, 2) def test_attempt_to_escape_out_of_package_module(self): @@ -918,25 +918,25 @@ # ImportError. # ``from ..child_name import ...`` in a top-level package module. calling_from = self.parent_name + '.' + '' - self.failUnlessRaises(ImportError, self.importer.resolve_name, + self.failUnlessRaises(ImportError, self.importer._resolve_name, self.child_name, calling_from, False, 2) def test_relative_import_in_top_level(self): # Attempting a relative import in a top-level location should raise # ImportError. # ``from .child_name import ...`` outside of a package. - self.failUnlessRaises(ImportError, self.importer.resolve_name, + self.failUnlessRaises(ImportError, self.importer._resolve_name, self.child_name, self.parent_name, False, 1) def test_relative_import_in_package_init(self): # ``from . import ...`` in a package. - resolved_name = self.importer.resolve_name('', self.parent_name, True, + resolved_name = self.importer._resolve_name('', self.parent_name, True, 1) self.failUnlessEqual(resolved_name, self.parent_name) def test_relative_import_in_package_module(self): # ``from . import ...`` in a package module. - resolved_name = self.importer.resolve_name('', self.full_child_name, + resolved_name = self.importer._resolve_name('', self.full_child_name, False, 1) self.failUnlessEqual(resolved_name, self.parent_name) @@ -973,7 +973,7 @@ succeed = mock_importer.SucceedImporter() sys.meta_path.append(succeed) # Import the package with a fromlist of the module. - module = self.importer.return_module(pkg_name, '', + module = self.importer._return_module(pkg_name, '', fromlist=[module_name]) self.failUnless(hasattr(module, module_name)) fromlist_module = getattr(module, module_name) @@ -986,7 +986,7 @@ pkg_module = mock_importer.MockModule(pkg_name, pkg_list=['some path']) sys.modules[pkg_name] = pkg_module nonexistent_attr = 'asdfsdfd' - module = self.importer.return_module(pkg_name, '', + module = self.importer._return_module(pkg_name, '', fromlist=[nonexistent_attr]) self.failUnless(not hasattr(module, nonexistent_attr)) @@ -1036,7 +1036,7 @@ # An empty fromlist means that the root module is returned. sys.modules[self.parent_name] = self.parent_module sys.modules[self.full_child_name] = self.child_module - module = self.importer.return_module(self.full_child_name, '', []) + module = self.importer._return_module(self.full_child_name, '', []) self.failUnless(module is self.parent_module) def test_nonempty_fromlist(self): @@ -1045,7 +1045,7 @@ sys.modules[self.full_child_name] = self.child_module test_attr_name = 'test_attr' setattr(self.child_module, test_attr_name, None) - module = self.importer.return_module(self.full_child_name, '', + module = self.importer._return_module(self.full_child_name, '', [test_attr_name]) self.failUnless(module is self.child_module) @@ -1054,7 +1054,7 @@ # then the module specified in the relative name is returned. sys.modules[self.full_child_name] = self.child_module sys.modules[self.parent_name] = self.parent_module - module = self.importer.return_module(self.full_child_name, + module = self.importer._return_module(self.full_child_name, self.child_name, []) self.failUnless(module is self.child_module) @@ -1066,7 +1066,7 @@ extra_depth = '.baz' absolute_name = self.full_child_name + extra_depth relative_name = self.child_name + extra_depth - module = self.importer.return_module(absolute_name, relative_name, []) + module = self.importer._return_module(absolute_name, relative_name, []) self.failUnless(module is self.child_module) @@ -1082,14 +1082,14 @@ def test_sys_module_return(self): # A module found in sys.modules should be returned immediately. sys.modules[self.parent_name] = self.parent_module - module = self.importer.import_module(self.parent_name) + module = self.importer._import_module(self.parent_name) self.failUnless(module is self.parent_module) def test_sys_module_None(self): # If sys.modules contains None for a module name, then raise ImportError. module_name = '' sys.modules[module_name] = None - self.failUnlessRaises(ImportError, self.importer.import_module, + self.failUnlessRaises(ImportError, self.importer._import_module, module_name) def test_parent_missing(self): @@ -1150,13 +1150,13 @@ # Test search method of sys.meta_path. # Should raise ImportError on error. self.clear_sys_modules('sys') - self.failUnlessRaises(ImportError, self.importer.search_meta_path, + self.failUnlessRaises(ImportError, self.importer._search_meta_path, 'sys') # Verify call order. meta_path = (mock_importer.PassImporter(), mock_importer.SucceedImporter()) sys.meta_path = meta_path - loader = self.importer.search_meta_path('sys') + loader = self.importer._search_meta_path('sys') for entry in meta_path: self.failUnlessEqual(entry.find_request, ('sys', None)) self.failUnless(loader is meta_path[-1]) @@ -1169,7 +1169,7 @@ sys.meta_path = [pass_importer] succeed_importer = mock_importer.SucceedImporter() importer_ = importer.Import(extended_meta_path=(succeed_importer,)) - module = importer_.import_module('sys') + module = importer_._import_module('sys') for meta_importer in (pass_importer, succeed_importer): self.failUnlessEqual(meta_importer.find_request, ('sys', None)) self.failUnless(module in succeed_importer.loaded_modules) @@ -1207,7 +1207,7 @@ sys.meta_path = [] sys.path = [''] sys.path_importer_cache[''] = None - module = importer_.import_module(module_name) + module = importer_._import_module(module_name) self.failUnlessEqual(succeed_importer.find_request, (module_name, None)) self.failUnless(module in succeed_importer.loaded_modules) @@ -1221,7 +1221,7 @@ pass_importer = mock_importer.PassImporter.set_on_sys_path() succeed_importer = mock_importer.SucceedImporter.set_on_sys_path() sys_path = (pass_importer, succeed_importer) - module = importer_.import_module(module_name) + module = importer_._import_module(module_name) for entry in sys_path: self.failUnlessEqual(entry.find_request, (module_name, None)) self.failUnless(module in succeed_importer.loaded_modules) @@ -1233,7 +1233,7 @@ self.clear_sys_modules(module_name) sys.path = [] succeed_importer = mock_importer.SucceedImporter.set_on_sys_path() - loader = self.importer.search_std_path(module_name) + loader = self.importer._search_std_path(module_name) self.failUnless(loader is succeed_importer) def test_importer_cache_from_path_hooks(self): @@ -1247,7 +1247,7 @@ sys.path = [path_entry] sys.path_importer_cache.clear() sys.path_hooks = [succeed_importer] - loader = self.importer.search_std_path(module_name) + loader = self.importer._search_std_path(module_name) self.failUnless(loader is succeed_importer) self.failUnless(sys.path_importer_cache[path_entry] is succeed_importer) @@ -1261,7 +1261,7 @@ sys.path = [path_entry] sys.path_hooks = [] sys.path_importer_cache.clear() - self.failUnlessRaises(ImportError, self.importer.search_std_path, + self.failUnlessRaises(ImportError, self.importer._search_std_path, module_name) self.failUnless(sys.path_importer_cache[path_entry] is None) @@ -1272,7 +1272,7 @@ sys.path_hooks.append(succeed_importer) search_paths = ['test path'] module_name = '.' - loader = self.importer.search_std_path(module_name, search_paths) + loader = self.importer._search_std_path(module_name, search_paths) self.failUnless(loader is succeed_importer) self.failUnless(search_paths[0] in succeed_importer.path_entries) self.failUnlessEqual(succeed_importer.find_request, @@ -1281,7 +1281,7 @@ self.clear_sys_modules(module_name) del sys.path_importer_cache[search_paths[0]] succeed_importer.path_entries = [] - self.importer.import_module(module_name, search_paths) + self.importer._import_module(module_name, search_paths) self.failUnless(search_paths[0] in succeed_importer.path_entries) @@ -1404,8 +1404,8 @@ data = pyc_file.read() self.failUnlessEqual(data[:4], imp.get_magic()) py_mod = int(os.stat(self.py_path).st_mtime) - # XXX Using importer's r_long. - pyc_mod = importer.r_long(data[4:8]) + # XXX Using importer's _r_long. + pyc_mod = importer._r_long(data[4:8]) self.failUnlessEqual(py_mod, pyc_mod) code = marshal.loads(data[8:]) module = mock_importer.MockModule(self.module_name) From jimjjewett at gmail.com Fri Jan 5 23:16:48 2007 From: jimjjewett at gmail.com (Jim Jewett) Date: Fri, 5 Jan 2007 17:16:48 -0500 Subject: [Python-checkins] r53276 - peps/trunk/pep-3108.txt In-Reply-To: <20070105202359.49D491E4002@bag.python.org> References: <20070105202359.49D491E4002@bag.python.org> Message-ID: > +PEP 8 specifies that modules "should have short, all-lowercase names" > +where "underscores can be used ... if it improves readability" > +[#pep-0008]_. The use of underscores is discouraged in package names. ... > -BaseHTTPServer basehttpserver > +BaseHTTPServer base_http_server > -CGIHTTPServer cgihttpserver > +CGIHTTPServer cgi_http_server And so we circle round to (namespace) packages, because is a dot really any worse than an underscore? http.server.base http.server.cgi http.server.simple I had thought Guido had said "no", as a matter of scope creep, but this rename doesn't seem to be any more disruptive than base_http_server. On the other hand, I'm used to >>> from package.subpackage.module import Class1 as C1, func_abcde as myfunc If I correctly read a recent note on google standards, then there are people who can't rename on import, and might be stuck using several dots (or worse, writing the semi-generic "server.base") on every reference. -jJ From buildbot at python.org Fri Jan 5 23:23:37 2007 From: buildbot at python.org (buildbot at python.org) Date: Fri, 05 Jan 2007 22:23:37 +0000 Subject: [Python-checkins] buildbot warnings in x86 OpenBSD trunk Message-ID: <20070105222337.D68F01E4002@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/1469 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: brett.cannon 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 Fri Jan 5 23:24:18 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 5 Jan 2007 23:24:18 +0100 (CET) Subject: [Python-checkins] r53281 - sandbox/trunk/import_in_py/importer.py Message-ID: <20070105222418.69CAB1E4002@bag.python.org> Author: brett.cannon Date: Fri Jan 5 23:24:17 2007 New Revision: 53281 Modified: sandbox/trunk/import_in_py/importer.py Log: Very minor code cleanup. Modified: sandbox/trunk/import_in_py/importer.py ============================================================================== --- sandbox/trunk/import_in_py/importer.py (original) +++ sandbox/trunk/import_in_py/importer.py Fri Jan 5 23:24:17 2007 @@ -213,8 +213,7 @@ if os.path.isdir(absolute_path): return FileSystemImporter(absolute_path, *self.handlers) else: - raise ImportError("can only handle directory entries from " - "sys.path") + raise ImportError("can only handle directories") class FileSystemImporter(object): @@ -244,16 +243,19 @@ # files for __init__? init_filename = '__init__' + file_ext package_init = os.path.join(package_directory, init_filename) + # Check if it is a package with an __init__ file. if (os.path.isfile(package_init) and _case_ok(self.path_entry, tail_module) and _case_ok(package_directory, init_filename)): return self.loader(package_init, handler, package_directory) + # See if it is a module. file_name = tail_module + file_ext file_path = os.path.join(self.path_entry, file_name) if (os.path.isfile(file_path) and _case_ok(self.path_entry, file_name)): return self.loader(file_path, handler) else: + # Raise a warning if it matches a directory w/o an __init__ file. if (os.path.isdir(package_directory) and _case_ok(self.path_entry, tail_module)): warnings.warn("Not importing directory %s: missing __init__.py" @@ -286,11 +288,13 @@ try: module = self.handler.handle_code(self, fullname, self.file_path, self.package) + # Don't leave any partially initialised modules behind. except: if fullname in sys.modules: del sys.modules[fullname] raise - return module + else: + return module def mod_time(self, path): """Return the modification time for the specified path as an integer.""" @@ -304,7 +308,8 @@ def create_path(self, base_path, type_, must_exist=False): """Create a new path based on a base path and requested path type. - If must_exist is True, the path must already exist. + If must_exist is True, the path must already exist in order to return a + path instead of None. """ path = base_path + type_ @@ -320,7 +325,11 @@ return data def write_data(self, data, path, binary=False): - """Write data to a specified path as either binary or textual data.""" + """Write data to a specified path as either binary or textual data. + + If the path cannot be accessed, then exit silently. + + """ try: with open(path, 'wb' if binary else 'w') as data_file: data_file.write(data) @@ -492,7 +501,7 @@ loader.write_data(pyc, bytecode_path, True) exec code in module.__dict__ return module - + class ExtensionFileHandler(object): @@ -744,7 +753,7 @@ # When fromlist has a value and the imported module is a # package, then if a name in fromlist is not found as an # attribute on module, try a relative import to find it. - # Failure is fine and is the exception is suppressed. + # Failure is fine and the exception is suppressed. check_for = list(fromlist) if '*' in check_for and hasattr(module, '__all__'): check_for.extend(module.__all__) @@ -827,6 +836,7 @@ # This call will also handle setting the attribute on the # package. self._import_full_module(imported_name) + # Absolute module import of a top-level module. else: imported_name = name self._import_full_module(name) From python-checkins at python.org Sat Jan 6 00:02:38 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 6 Jan 2007 00:02:38 +0100 (CET) Subject: [Python-checkins] r53282 - peps/trunk/pep-3108.txt Message-ID: <20070105230238.31D811E400E@bag.python.org> Author: brett.cannon Date: Sat Jan 6 00:02:37 2007 New Revision: 53282 Modified: peps/trunk/pep-3108.txt Log: Add a link to the wiki page with more grouping suggestions. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Sat Jan 6 00:02:37 2007 @@ -508,6 +508,10 @@ off into what types of obvious groupings there seem to be. No name for the suggested package (if not already existent) is being proposed. +Some other suggestions beyond the ones listed here are available at +http://wiki.python.org/moin/CodingProjectIdeas/StandardLibrary/RestructuredStandardLibrary +. + * collections + heapq From janssen at parc.com Sat Jan 6 00:10:48 2007 From: janssen at parc.com (Bill Janssen) Date: Fri, 5 Jan 2007 15:10:48 PST Subject: [Python-checkins] [Python-3000] r53276 - peps/trunk/pep-3108.txt In-Reply-To: References: <20070105202359.49D491E4002@bag.python.org> Message-ID: <07Jan5.151053pst."58648"@synergy1.parc.xerox.com> > > -BaseHTTPServer basehttpserver > > +BaseHTTPServer base_http_server > > -CGIHTTPServer cgihttpserver > > +CGIHTTPServer cgi_http_server > > And so we circle round to (namespace) packages, because is a dot > really any worse than an underscore? > > http.server.base > http.server.cgi > http.server.simple > We should probably scrap either Base or Simple for Py3K. Bill From python-checkins at python.org Sat Jan 6 00:54:44 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 6 Jan 2007 00:54:44 +0100 (CET) Subject: [Python-checkins] r53283 - sandbox/trunk/import_in_py/importer.py Message-ID: <20070105235444.ECC701E4002@bag.python.org> Author: brett.cannon Date: Sat Jan 6 00:54:43 2007 New Revision: 53283 Modified: sandbox/trunk/import_in_py/importer.py Log: Clean up docstrings. Modified: sandbox/trunk/import_in_py/importer.py ============================================================================== --- sandbox/trunk/import_in_py/importer.py (original) +++ sandbox/trunk/import_in_py/importer.py Sat Jan 6 00:54:43 2007 @@ -1,4 +1,33 @@ -"""Re-implementation of import machinery in Python source code. +"""Implementation of Python's import machinery in Python source code. + +The Import class implements the semantics of import. This means that an +instance of this class can be called to properly check sys.modules, +sys.meta_path, sys.path, etc. to import the requested module. + +The importing of built-in, frozen, extension, .py, and .pyc files are all +handled by implementing importers and loaders as specified by PEP 302. This +leads to the ability to easily control imports based on the type of module. +There is also a clear distinction between how the module is stored and how it +is formatted (e.g., a Python source file does not require it be stored as a +file on a filesystem). + +To help with the distinction between how a module is stored compared to its +format the idea of handlers is introduced. A handler implements a specific +interface while specifying the type of module it handles (usually by the what +one would expect as a file extension if the module was on a filesystem). This +allows a PEP 302 importer/loader to represent how a module is stored while the +handler deals with how the module is formatted. + +A handler is expected to implement the handle_code method only. The handler +for Python source and bytecode modules goes farther and defines an extensive +interface that is designed so that alternatives on module formatting can be +supported easily without needing to write a new importer/loader. The Python +source and bytecode handler also expects loaders to define a more extensive +interface to allow for different backend stores (e.g., databases) to use the +handler without modification. All of this helps with code reuse and possible +errors from the complicated relationship between Python source and bytecode +modules. + ==================== References on import @@ -132,12 +161,8 @@ @classmethod def find_module(cls, fullname, path=None): - """See if import is for a built-in or frozen module. - - Since built-in and frozen modules should never have a path, - short-circuit if one is specified. - - """ + """See if a built-in or frozen module can be imported based on the + specified name.""" if cls._find(fullname): return cls else: @@ -166,7 +191,7 @@ """sys.meta_path class for importing built-in modules. XXX Possible optimization is to bail out in find_module() if 'path' is set - to a value. Also can then raise an error in load_module() if 'path' is set. + to a value. """ @@ -184,11 +209,17 @@ class FileSystemFactory(object): - """Factory object for sys.path_hooks for directory entries on sys.path. + """Factory function for sys.path_hooks for directory entries on sys.path. The path to be handled, if it is a filesystem directory, is used to - initialize a new FileSystemImporter for that path entry. The handlers are - also passed on to the importer. + initialize a new FileSystemImporter for that path entry. An instantiated + object stores various handlers that are to be used to decide if the path + entry contains the module to be imported. + + XXX Possible optimization would be to get the directory's contents and make + sure that only handlers for the files in the directory are given to the + returned importer. This would kill the ability to add a new module into + the directory during run-time that is a new type of file, though. """ @@ -221,6 +252,11 @@ """Importer for the filesystem using the passed-in handlers.""" def __init__(self, path_entry, *handlers): + """Store the path this importer handles and the handlers to use. + + The order of the handlers determines precedence of file types. + + """ self.path_entry = path_entry self.handlers = handlers self.loader = FileSystemLoader @@ -232,7 +268,7 @@ 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 __path__ for a package. + for each directory in the __path__ attribute for a package. """ tail_module = fullname.rsplit('.', 1)[-1] @@ -273,7 +309,9 @@ """ def __init__(self, file_path, handler, package=None): - """Store arguments on to the instance.""" + """Store the path to the file to use for the import and the handler to + use along with whether this is a package (this does not include modules + within a package).""" self.file_path = file_path self.handler = handler self.package = package @@ -297,12 +335,21 @@ return module def mod_time(self, path): - """Return the modification time for the specified path as an integer.""" + """Return the modification time for the specified path as an integer. + + This method is required as part of the interface needed for + PyPycHandler. + + """ return int(os.stat(path).st_mtime) def split_path(self, path): """Split the specified path into a base path and the type of the - path.""" + path. + + This method is required for PyPycHandler. + + """ return os.path.splitext(path) def create_path(self, base_path, type_, must_exist=False): @@ -310,6 +357,8 @@ If must_exist is True, the path must already exist in order to return a path instead of None. + + This method is required for PyPycHandler. """ path = base_path + type_ @@ -319,7 +368,11 @@ def read_data(self, path, binary=False): """Open the path and return the data read from it in the specified - format.""" + format. + + This method is required for PyPycHandler. + + """ with open(path, 'rb' if binary else 'U') as data_file: data = data_file.read() return data @@ -328,6 +381,8 @@ """Write data to a specified path as either binary or textual data. If the path cannot be accessed, then exit silently. + + This method is required for PyPycHandler. """ try: @@ -350,11 +405,11 @@ """ def __init__(self, source_handles=None, bytecode_handles=None): - """Specify the handles for source and bytecode to be handled by this - handler and set 'handles' appropriately. - - If either source code or bytecode are not to be used, pass in a false - value for the appropriate argument. + """Specify the file types for source and bytecode to be handled by this + handler and set 'handles' appropriately as tuples (empty tuples are + acceptable). + + Not specifying handles will lead to reasonable defaults being used. """ if source_handles is None: @@ -376,7 +431,8 @@ return data[:4], _r_long(data[4:8]), data[8:] def check_magic(self, magic): - """Check whether the magic number is valid or not.""" + """Check whether the magic number is correct or not for the current + running interpreter.""" return imp.get_magic() == magic def code_from_bytecode(self, bytecode): @@ -393,7 +449,7 @@ return compile(source, str(path), 'exec') def create_pyc(self, bytecode, timestamp): - """Create data for a .pyc file.""" + """Create data to be written out for a .pyc file.""" data = imp.get_magic() data += _w_long(timestamp) data += marshal.dumps(bytecode) @@ -408,7 +464,7 @@ 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 for the loader: + to keep state: * split_path(path) Take in an opaque path object and split it into a base path and a @@ -535,7 +591,7 @@ class Import(object): - """Class that re-implements __import__. + """Class that implements the __import__ interface. Backwards compatibility is maintained by extending sys.meta_path interally (for handling built-in and frozen modules) and providing a @@ -573,7 +629,8 @@ raise ImportError("No module named %s" % name) def _sys_path_importer(self, path_entry): - """Return the importer for the specified path. + """Return the importer for the specified path, from + sys.path_importer_cache if possible. If None is stored in sys.path_importer_cache then use the default path hook. @@ -775,11 +832,10 @@ The 'name' argument is the name of the module to be imported (e.g., 'foo' in ``import foo`` or ``from foo import ...``). - 'globals' and - 'locals' are the global and local namespace dictionaries of the module - where the import statement appears. 'globals' is used to introspect - the __path__ and __name__ attributes of the module making the call. - 'local's is ignored. + 'globals' and 'locals' are the global and local namespace dictionaries + of the module where the import statement appears. 'globals' is used to + introspect the __path__ and __name__ attributes of the module making + the call. 'local's is ignored. 'fromlist' lists any specific objects that are to eventually be put into the namespace (e.g., ``from for.bar import baz`` would have 'baz' @@ -789,10 +845,8 @@ attributes on the module, attempting a module import relative to 'name' to set that attribute. - When 'name' is a dotted name, - there are two - different situations to consider for the return value. One is when - the fromlist is empty. + When 'name' is a dotted name, there are two different situations to + consider for the return value. One is when the fromlist is empty. In this situation the import statement imports and returns the name up to the first dot. All subsequent names are imported but set as attributes as needed on parent modules. When fromlist is not empty From python-checkins at python.org Sat Jan 6 01:02:29 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 6 Jan 2007 01:02:29 +0100 (CET) Subject: [Python-checkins] r53284 - sandbox/trunk/import_in_py/regrtest.sh Message-ID: <20070106000229.C93C61E400F@bag.python.org> Author: brett.cannon Date: Sat Jan 6 01:02:29 2007 New Revision: 53284 Added: sandbox/trunk/import_in_py/regrtest.sh (contents, props changed) Log: Add a shell script that runs Python's regression test suite using the import rewrite. Added: sandbox/trunk/import_in_py/regrtest.sh ============================================================================== --- (empty file) +++ sandbox/trunk/import_in_py/regrtest.sh Sat Jan 6 01:02:29 2007 @@ -0,0 +1,3 @@ +#!/bin/sh + +$1 -c "import importer; importer._set__import__(); from test.regrtest import main; main()" From python-checkins at python.org Sat Jan 6 02:14:42 2007 From: python-checkins at python.org (raymond.hettinger) Date: Sat, 6 Jan 2007 02:14:42 +0100 (CET) Subject: [Python-checkins] r53285 - python/trunk/Python/ceval.c Message-ID: <20070106011442.388CD1E4002@bag.python.org> Author: raymond.hettinger Date: Sat Jan 6 02:14:41 2007 New Revision: 53285 Modified: python/trunk/Python/ceval.c Log: SF# 1409443: Expand comment to cover the interaction between f->f_lasti and the PREDICT macros. Modified: python/trunk/Python/ceval.c ============================================================================== --- python/trunk/Python/ceval.c (original) +++ python/trunk/Python/ceval.c Sat Jan 6 02:14:41 2007 @@ -741,7 +741,16 @@ this wasn't always true before 2.3! PyFrame_New now sets f->f_lasti to -1 (i.e. the index *before* the first instruction) and YIELD_VALUE doesn't fiddle with f_lasti any more. So this - does work. Promise. */ + does work. Promise. + + When the PREDICT() macros are enabled, some opcode pairs follow in + direct succession without updating f->f_lasti. A successful + prediction effectively links the two codes together as if they + were a single new opcode; accordingly,f->f_lasti will point to + the first code in the pair (for instance, GET_ITER followed by + FOR_ITER is effectively a single opcode and f->f_lasti will point + at to the beginning of the combined pair.) + */ next_instr = first_instr + f->f_lasti + 1; stack_pointer = f->f_stacktop; assert(stack_pointer != NULL); From buildbot at python.org Sat Jan 6 03:06:52 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 06 Jan 2007 02:06:52 +0000 Subject: [Python-checkins] buildbot warnings in ia64 Ubuntu trunk trunk Message-ID: <20070106020652.8193C1E4002@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/300 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 anthony at interlink.com.au Sat Jan 6 04:08:18 2007 From: anthony at interlink.com.au (Anthony Baxter) Date: Sat, 6 Jan 2007 14:08:18 +1100 Subject: [Python-checkins] r53274 - peps/trunk/pep-3108.txt In-Reply-To: <20070105202815.GA10348@localhost.localdomain> References: <20070105200320.4C3BD1E4002@bag.python.org> <20070105202815.GA10348@localhost.localdomain> Message-ID: <200701061408.19551.anthony@interlink.com.au> On Saturday 06 January 2007 07:28, A.M. Kuchling wrote: > Not to pick on sndhdr, but the stdlib reorganization seems to be > losing its purpose. Sure, for any module X you can probably find > someone who's using it, but the point of the reorganization is to > remove modules that aren't being *maintained*. For example, > asyncore is now listed as being kept, but no one is fixing bugs > in asyncore or adding new features, so why do we want to continue > dragging the module onward? Someone volunteered to maintain asyncore on the p3yk list. I'm happy to be down as the maintainer for the audio modules. Anthony -- Anthony Baxter It's never too late to have a happy childhood. From python-checkins at python.org Sat Jan 6 05:45:56 2007 From: python-checkins at python.org (anthony.baxter) Date: Sat, 6 Jan 2007 05:45:56 +0100 (CET) Subject: [Python-checkins] r53286 - in python/trunk: Doc/README LICENSE PC/python_nt.rc PCbuild/python20.wse PCbuild8/python20.wse Python/getcopyright.c README Message-ID: <20070106044556.4875D1E400C@bag.python.org> Author: anthony.baxter Date: Sat Jan 6 05:45:54 2007 New Revision: 53286 Modified: python/trunk/Doc/README python/trunk/LICENSE python/trunk/PC/python_nt.rc python/trunk/PCbuild/python20.wse python/trunk/PCbuild8/python20.wse python/trunk/Python/getcopyright.c python/trunk/README Log: update to (c) years to include 2007 Modified: python/trunk/Doc/README ============================================================================== --- python/trunk/Doc/README (original) +++ python/trunk/Doc/README Sat Jan 6 05:45:54 2007 @@ -229,7 +229,7 @@ as long as you don't change or remove the copyright notice: ---------------------------------------------------------------------- -Copyright (c) 2000-2006 Python Software Foundation. +Copyright (c) 2000-2007 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/trunk/LICENSE ============================================================================== --- python/trunk/LICENSE (original) +++ python/trunk/LICENSE Sat Jan 6 05:45:54 2007 @@ -88,9 +88,9 @@ prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) -2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights -Reserved" are retained in Python alone or in any derivative version -prepared by Licensee. +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make Modified: python/trunk/PC/python_nt.rc ============================================================================== --- python/trunk/PC/python_nt.rc (original) +++ python/trunk/PC/python_nt.rc Sat Jan 6 05:45:54 2007 @@ -61,7 +61,7 @@ VALUE "FileDescription", "Python Core\0" VALUE "FileVersion", PYTHON_VERSION VALUE "InternalName", "Python DLL\0" - VALUE "LegalCopyright", "Copyright ? 2001-2006 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" + VALUE "LegalCopyright", "Copyright ? 2001-2007 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" VALUE "OriginalFilename", PYTHON_DLL_NAME "\0" VALUE "ProductName", "Python\0" VALUE "ProductVersion", PYTHON_VERSION Modified: python/trunk/PCbuild/python20.wse ============================================================================== --- python/trunk/PCbuild/python20.wse (original) +++ python/trunk/PCbuild/python20.wse Sat Jan 6 05:45:54 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/trunk/PCbuild8/python20.wse ============================================================================== --- python/trunk/PCbuild8/python20.wse (original) +++ python/trunk/PCbuild8/python20.wse Sat Jan 6 05:45:54 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/trunk/Python/getcopyright.c ============================================================================== --- python/trunk/Python/getcopyright.c (original) +++ python/trunk/Python/getcopyright.c Sat Jan 6 05:45:54 2007 @@ -4,7 +4,7 @@ static char cprt[] = "\ -Copyright (c) 2001-2006 Python Software Foundation.\n\ +Copyright (c) 2001-2007 Python Software Foundation.\n\ All Rights Reserved.\n\ \n\ Copyright (c) 2000 BeOpen.com.\n\ Modified: python/trunk/README ============================================================================== --- python/trunk/README (original) +++ python/trunk/README Sat Jan 6 05:45:54 2007 @@ -1,7 +1,8 @@ This is Python version 2.6 alpha 0 ================================== -Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 +Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. From python-checkins at python.org Sat Jan 6 05:50:44 2007 From: python-checkins at python.org (anthony.baxter) Date: Sat, 6 Jan 2007 05:50:44 +0100 (CET) Subject: [Python-checkins] r53287 - in python/branches/release25-maint: Doc/README LICENSE PC/python_nt.rc PCbuild/python20.wse PCbuild8/python20.wse Python/getcopyright.c README Message-ID: <20070106045044.B0C821E4002@bag.python.org> Author: anthony.baxter Date: Sat Jan 6 05:50:44 2007 New Revision: 53287 Modified: python/branches/release25-maint/Doc/README python/branches/release25-maint/LICENSE python/branches/release25-maint/PC/python_nt.rc python/branches/release25-maint/PCbuild/python20.wse python/branches/release25-maint/PCbuild8/python20.wse python/branches/release25-maint/Python/getcopyright.c python/branches/release25-maint/README Log: update to (c) years to include 2007 Modified: python/branches/release25-maint/Doc/README ============================================================================== --- python/branches/release25-maint/Doc/README (original) +++ python/branches/release25-maint/Doc/README Sat Jan 6 05:50:44 2007 @@ -229,7 +229,7 @@ as long as you don't change or remove the copyright notice: ---------------------------------------------------------------------- -Copyright (c) 2000-2006 Python Software Foundation. +Copyright (c) 2000-2007 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/branches/release25-maint/LICENSE ============================================================================== --- python/branches/release25-maint/LICENSE (original) +++ python/branches/release25-maint/LICENSE Sat Jan 6 05:50:44 2007 @@ -88,9 +88,9 @@ prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) -2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights -Reserved" are retained in Python alone or in any derivative version -prepared by Licensee. +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make Modified: python/branches/release25-maint/PC/python_nt.rc ============================================================================== --- python/branches/release25-maint/PC/python_nt.rc (original) +++ python/branches/release25-maint/PC/python_nt.rc Sat Jan 6 05:50:44 2007 @@ -61,7 +61,7 @@ VALUE "FileDescription", "Python Core\0" VALUE "FileVersion", PYTHON_VERSION VALUE "InternalName", "Python DLL\0" - VALUE "LegalCopyright", "Copyright ? 2001-2006 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" + VALUE "LegalCopyright", "Copyright ? 2001-2007 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" VALUE "OriginalFilename", PYTHON_DLL_NAME "\0" VALUE "ProductName", "Python\0" VALUE "ProductVersion", PYTHON_VERSION Modified: python/branches/release25-maint/PCbuild/python20.wse ============================================================================== --- python/branches/release25-maint/PCbuild/python20.wse (original) +++ python/branches/release25-maint/PCbuild/python20.wse Sat Jan 6 05:50:44 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/branches/release25-maint/PCbuild8/python20.wse ============================================================================== --- python/branches/release25-maint/PCbuild8/python20.wse (original) +++ python/branches/release25-maint/PCbuild8/python20.wse Sat Jan 6 05:50:44 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/branches/release25-maint/Python/getcopyright.c ============================================================================== --- python/branches/release25-maint/Python/getcopyright.c (original) +++ python/branches/release25-maint/Python/getcopyright.c Sat Jan 6 05:50:44 2007 @@ -4,7 +4,7 @@ static char cprt[] = "\ -Copyright (c) 2001-2006 Python Software Foundation.\n\ +Copyright (c) 2001-2007 Python Software Foundation.\n\ All Rights Reserved.\n\ \n\ Copyright (c) 2000 BeOpen.com.\n\ Modified: python/branches/release25-maint/README ============================================================================== --- python/branches/release25-maint/README (original) +++ python/branches/release25-maint/README Sat Jan 6 05:50:44 2007 @@ -1,7 +1,8 @@ This is Python version 2.5 ========================== -Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software +Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. From buildbot at python.org Sat Jan 6 06:28:25 2007 From: buildbot at python.org (buildbot at python.org) Date: Sat, 06 Jan 2007 05:28:25 +0000 Subject: [Python-checkins] buildbot warnings in x86 gentoo 2.5 Message-ID: <20070106052826.0FC9E1E4002@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/164 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: anthony.baxter 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') 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') 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') 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') 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_urllib2net sincerely, -The Buildbot From amk at amk.ca Sat Jan 6 13:52:18 2007 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 6 Jan 2007 07:52:18 -0500 Subject: [Python-checkins] r53274 - peps/trunk/pep-3108.txt In-Reply-To: <200701061408.19551.anthony@interlink.com.au> References: <20070105200320.4C3BD1E4002@bag.python.org> <20070105202815.GA10348@localhost.localdomain> <200701061408.19551.anthony@interlink.com.au> Message-ID: <20070106125218.GA9393@Siri.local> On Sat, Jan 06, 2007 at 02:08:18PM +1100, Anthony Baxter wrote: > Someone volunteered to maintain asyncore on the p3yk list. Josiah Carlson -- who can't access the Pytho bug tracker yet. I'll e-mail him about this so that I can reassign the asyncore bugs and patches to him. --amk From python-checkins at python.org Sat Jan 6 21:54:39 2007 From: python-checkins at python.org (brett.cannon) Date: Sat, 6 Jan 2007 21:54:39 +0100 (CET) Subject: [Python-checkins] r53290 - peps/trunk/pep-3108.txt Message-ID: <20070106205439.C72781E4002@bag.python.org> Author: brett.cannon Date: Sat Jan 6 21:54:39 2007 New Revision: 53290 Modified: peps/trunk/pep-3108.txt Log: Remove some hard-to-follow wording with a much more straight-forward one. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Sat Jan 6 21:54:39 2007 @@ -290,7 +290,7 @@ * ihooks - + Documented except for saying that module might be obsolete. + + Undocumented. + For use with rexec which has been turned off since Python 2.3. * imageop From brett at python.org Sat Jan 6 22:02:24 2007 From: brett at python.org (Brett Cannon) Date: Sat, 6 Jan 2007 13:02:24 -0800 Subject: [Python-checkins] r53274 - peps/trunk/pep-3108.txt In-Reply-To: <20070105202815.GA10348@localhost.localdomain> References: <20070105200320.4C3BD1E4002@bag.python.org> <20070105202815.GA10348@localhost.localdomain> Message-ID: On 1/5/07, A.M. Kuchling wrote: > > On Fri, Jan 05, 2007 at 09:03:20PM +0100, brett.cannon wrote: > > Author: brett.cannon > > Date: Fri Jan 5 21:03:19 2007 > > New Revision: 53274 > > > > Modified: > > peps/trunk/pep-3108.txt > > Log: > > Add sndhdr to the audio package suggestion. > > Not to pick on sndhdr, but the stdlib reorganization seems to be > losing its purpose. Sure, for any module X you can probably find > someone who's using it, but the point of the reorganization is to > remove modules that aren't being *maintained*. For example, asyncore > is now listed as being kept, but no one is fixing bugs in asyncore or > adding new features, so why do we want to continue dragging the module > onward? If you have any suggestions, Andrew, on something to drop that is not on the list, please let me know. I obviously don't know single-handedly what is and is not being actively maintained. Plus everything that has been saved from the list someone has spoken up about as needing and thus I expect they will help maintain it. -Brett -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-checkins/attachments/20070106/f947ef95/attachment.html From nnorwitz at gmail.com Sat Jan 6 22:20:40 2007 From: nnorwitz at gmail.com (Neal Norwitz) Date: Sat, 6 Jan 2007 13:20:40 -0800 Subject: [Python-checkins] r53274 - peps/trunk/pep-3108.txt In-Reply-To: <20070106125218.GA9393@Siri.local> References: <20070105200320.4C3BD1E4002@bag.python.org> <20070105202815.GA10348@localhost.localdomain> <200701061408.19551.anthony@interlink.com.au> <20070106125218.GA9393@Siri.local> Message-ID: I've added Josiah to the SF trackers. I didn't add him as a committer yet b/c I don't have his ssh key AFAIK. n On 1/6/07, A.M. Kuchling wrote: > On Sat, Jan 06, 2007 at 02:08:18PM +1100, Anthony Baxter wrote: > > Someone volunteered to maintain asyncore on the p3yk list. > > Josiah Carlson -- who can't access the Pytho bug tracker yet. I'll > e-mail him about this so that I can reassign the asyncore bugs and > patches to him. > > --amk > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From python-checkins at python.org Sat Jan 6 22:24:36 2007 From: python-checkins at python.org (neal.norwitz) Date: Sat, 6 Jan 2007 22:24:36 +0100 (CET) Subject: [Python-checkins] r53291 - python/trunk/Misc/developers.txt Message-ID: <20070106212436.3AE2C1E4002@bag.python.org> Author: neal.norwitz Date: Sat Jan 6 22:24:35 2007 New Revision: 53291 Modified: python/trunk/Misc/developers.txt Log: Add Josiah to SF for maintaining asyncore/asynchat Modified: python/trunk/Misc/developers.txt ============================================================================== --- python/trunk/Misc/developers.txt (original) +++ python/trunk/Misc/developers.txt Sat Jan 6 22:24:35 2007 @@ -17,6 +17,9 @@ Permissions History ------------------- +- Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python + project 06 Jan 2007, by NCN, as a tracker tech. He will maintain asyncore. + - Collin Winter was given SVN access on 05 Jan 2007 by NCN, for PEP update access. From python-checkins at python.org Sun Jan 7 00:12:26 2007 From: python-checkins at python.org (brett.cannon) Date: Sun, 7 Jan 2007 00:12:26 +0100 (CET) Subject: [Python-checkins] r53292 - peps/trunk/pep-3108.txt Message-ID: <20070106231226.A661A1E4002@bag.python.org> Author: brett.cannon Date: Sun Jan 7 00:12:26 2007 New Revision: 53292 Modified: peps/trunk/pep-3108.txt Log: Add more package suggestions. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Sun Jan 7 00:12:26 2007 @@ -504,24 +504,26 @@ Packages are often used to group together modules that have a similar theme but do not have any direct relationship or dependency upon each other. For Python 3.0 obvious groupings could be done since renaming -of various modules is already occurring. Below is a list sectioned -off into what types of obvious groupings there seem to be. No name -for the suggested package (if not already existent) is being proposed. - -Some other suggestions beyond the ones listed here are available at -http://wiki.python.org/moin/CodingProjectIdeas/StandardLibrary/RestructuredStandardLibrary -. +of various modules is already occurring. Below is a list of possible +packages (pre-existing or new) that could be created. In order to be +considered the package must contain three or more modules in order to +not overdue the introduction of new packages and to keep the stdlib +shallow. No specific package name is proposed, just what modules +could go into the package. * collections + heapq + Queue + sets - + UserDist + + UserDist (?) + + UserList (?) + +* Python implementations of built-in data types + + + UserDict + UserList - + What to do with UserString? - Have a package for Python implementations of built-in types - instead of putting the User* modules into 'collections'? + + UserString * Platform-specific @@ -594,14 +596,41 @@ + webbrowser + wsgiref -* HTTP servers +* Servers - + BaseHTTPServer - + CGIHTTPServer - + DocXMLRPCServer - + SimpleHTTPServer - + SimpleXMLRPCServer - + wsgiref + + HTTP + + - BaseHTTPServer + - CGIHTTPServer + - DocXMLRPCServer + - SimpleHTTPServer + - SimpleXMLRPCServer + - wsgiref + + + Socket + + - asynchat + - asyncore + - SocketServer + +* Bytecode + + + codeop + + compiler + + py_compile + + compileall + +* Compression + + + bz2 + + gzip + + zlib + +* Date and time + + + calendar + + datetime + + time Renaming of modules maintained outside of the stdlib From python-checkins at python.org Sun Jan 7 09:53:46 2007 From: python-checkins at python.org (peter.astrand) Date: Sun, 7 Jan 2007 09:53:46 +0100 (CET) Subject: [Python-checkins] r53293 - python/trunk/Lib/subprocess.py Message-ID: <20070107085346.A5AB81E4003@bag.python.org> Author: peter.astrand Date: Sun Jan 7 09:53:46 2007 New Revision: 53293 Modified: python/trunk/Lib/subprocess.py Log: Re-implemented fix for #1531862 once again, in a way that works with Python 2.2. Fixes bug #1603424. Modified: python/trunk/Lib/subprocess.py ============================================================================== --- python/trunk/Lib/subprocess.py (original) +++ python/trunk/Lib/subprocess.py Sun Jan 7 09:53:46 2007 @@ -1004,8 +1004,12 @@ # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)): - if fd: os.close(fd) + if p2cread and p2cread not in (0,): + os.close(p2cread) + if c2pwrite and c2pwrite not in (p2cread, 1): + os.close(c2pwrite) + if errwrite and errwrite not in (p2cread, c2pwrite, 2): + os.close(errwrite) # Close all other fds, if asked for if close_fds: From python-checkins at python.org Sun Jan 7 10:00:11 2007 From: python-checkins at python.org (peter.astrand) Date: Sun, 7 Jan 2007 10:00:11 +0100 (CET) Subject: [Python-checkins] r53294 - python/branches/release25-maint/Lib/subprocess.py Message-ID: <20070107090011.974851E4003@bag.python.org> Author: peter.astrand Date: Sun Jan 7 10:00:11 2007 New Revision: 53294 Modified: python/branches/release25-maint/Lib/subprocess.py Log: Re-implemented fix for #1531862 once again, in a way that works with Python 2.2. Fixes bug #1603424. Modified: python/branches/release25-maint/Lib/subprocess.py ============================================================================== --- python/branches/release25-maint/Lib/subprocess.py (original) +++ python/branches/release25-maint/Lib/subprocess.py Sun Jan 7 10:00:11 2007 @@ -1004,8 +1004,12 @@ # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)): - if fd: os.close(fd) + if p2cread and p2cread not in (0,): + os.close(p2cread) + if c2pwrite and c2pwrite not in (p2cread, 1): + os.close(c2pwrite) + if errwrite and errwrite not in (p2cread, c2pwrite, 2): + os.close(errwrite) # Close all other fds, if asked for if close_fds: From python-checkins at python.org Sun Jan 7 15:34:17 2007 From: python-checkins at python.org (peter.astrand) Date: Sun, 7 Jan 2007 15:34:17 +0100 (CET) Subject: [Python-checkins] r53295 - python/trunk/Lib/subprocess.py Message-ID: <20070107143417.386F31E4003@bag.python.org> Author: peter.astrand Date: Sun Jan 7 15:34:16 2007 New Revision: 53295 Modified: python/trunk/Lib/subprocess.py Log: Avoid O(N**2) bottleneck in _communicate_(). Fixes #1598181. Modified: python/trunk/Lib/subprocess.py ============================================================================== --- python/trunk/Lib/subprocess.py (original) +++ python/trunk/Lib/subprocess.py Sun Jan 7 15:34:16 2007 @@ -1111,6 +1111,7 @@ read_set.append(self.stderr) stderr = [] + input_offset = 0 while read_set or write_set: rlist, wlist, xlist = select.select(read_set, write_set, []) @@ -1118,9 +1119,9 @@ # When select has indicated that the file is writable, # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 - bytes_written = os.write(self.stdin.fileno(), input[:512]) - input = input[bytes_written:] - if not input: + bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) + input_offset += bytes_written + if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) From python-checkins at python.org Mon Jan 8 10:36:18 2007 From: python-checkins at python.org (vinay.sajip) Date: Mon, 8 Jan 2007 10:36:18 +0100 (CET) Subject: [Python-checkins] r53296 - python/branches/release25-maint/Doc/lib/liblogging.tex Message-ID: <20070108093618.425961E4005@bag.python.org> Author: vinay.sajip Date: Mon Jan 8 10:36:17 2007 New Revision: 53296 Modified: python/branches/release25-maint/Doc/lib/liblogging.tex Log: Added relativeCreated to Formatter doc (has been in the system for a long time - was unaccountably left out of the docs and not noticed until now). Documentation clarified to mention optional parameters. Documentation omitted the additional parameter to LogRecord.__init__ which was added in 2.5. (See SF #1569622). Modified: python/branches/release25-maint/Doc/lib/liblogging.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/liblogging.tex (original) +++ python/branches/release25-maint/Doc/lib/liblogging.tex Mon Jan 8 10:36:17 2007 @@ -530,8 +530,8 @@ \method{filter()}. \end{methoddesc} -\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info, - func, extra} +\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info + \optional{, func, extra}} This is a factory method which can be overridden in subclasses to create specialized \class{LogRecord} instances. \versionchanged[\var{func} and \var{extra} were added]{2.5} @@ -1399,6 +1399,9 @@ (if available).} \lineii{\%(created)f} {Time when the \class{LogRecord} was created (as returned by \function{time.time()}).} +\lineii{\%(relativeCreated)d} {Time in milliseconds when the LogRecord was + created, relative to the time the logging module was + loaded.} \lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord} was created. By default this is of the form ``2003-07-08 16:49:45,896'' (the numbers after the @@ -1481,7 +1484,7 @@ information to be logged. \begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args, - exc_info} + exc_info \optional{, func}} Returns an instance of \class{LogRecord} initialized with interesting information. The \var{name} is the logger name; \var{lvl} is the numeric level; \var{pathname} is the absolute pathname of the source @@ -1491,7 +1494,9 @@ which, together with \var{msg}, makes up the user message; and \var{exc_info} is the exception tuple obtained by calling \function{sys.exc_info() }(or \constant{None}, if no exception information -is available). +is available). The \var{func} is the name of the function from which the +logging call was made. If not specified, it defaults to \var{None}. +\versionchanged[\var{func} was added]{2.5} \end{classdesc} \begin{methoddesc}{getMessage}{} From python-checkins at python.org Mon Jan 8 11:11:59 2007 From: python-checkins at python.org (vinay.sajip) Date: Mon, 8 Jan 2007 11:11:59 +0100 (CET) Subject: [Python-checkins] r53297 - python/branches/release25-maint/Lib/logging/handlers.py Message-ID: <20070108101159.2A1F81E4005@bag.python.org> Author: vinay.sajip Date: Mon Jan 8 11:11:58 2007 New Revision: 53297 Modified: python/branches/release25-maint/Lib/logging/handlers.py Log: Backported change from trunk: Made SysLogHandler more resilient in the face of syslogd failures. Modified: python/branches/release25-maint/Lib/logging/handlers.py ============================================================================== --- python/branches/release25-maint/Lib/logging/handlers.py (original) +++ python/branches/release25-maint/Lib/logging/handlers.py Mon Jan 8 11:11:58 2007 @@ -586,11 +586,11 @@ self.address = address self.facility = facility if type(address) == types.StringType: - self._connect_unixsocket(address) self.unixsocket = 1 + self._connect_unixsocket(address) else: - self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.unixsocket = 0 + self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.formatter = None From python-checkins at python.org Mon Jan 8 11:12:29 2007 From: python-checkins at python.org (vinay.sajip) Date: Mon, 8 Jan 2007 11:12:29 +0100 (CET) Subject: [Python-checkins] r53298 - python/branches/release25-maint/Lib/logging/__init__.py Message-ID: <20070108101229.CE1331E4005@bag.python.org> Author: vinay.sajip Date: Mon Jan 8 11:12:29 2007 New Revision: 53298 Modified: python/branches/release25-maint/Lib/logging/__init__.py Log: Backported changes from trunk: Made func argument in LogRecord.__init__ optional. Improved performance of _fixupChildren. 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 Mon Jan 8 11:12:29 2007 @@ -214,7 +214,7 @@ information to be logged. """ def __init__(self, name, level, pathname, lineno, - msg, args, exc_info, func): + msg, args, exc_info, func=None): """ Initialize a logging record with interesting information. """ @@ -910,9 +910,12 @@ Ensure that children of the placeholder ph are connected to the specified logger. """ - #for c in ph.loggers: + name = alogger.name + namelen = len(name) for c in ph.loggerMap.keys(): - if string.find(c.parent.name, alogger.name) <> 0: + #The if means ... if not c.parent.name.startswith(nm) + #if string.find(c.parent.name, nm) <> 0: + if c.parent.name[:namelen] != name: alogger.parent = c.parent c.parent = alogger From buildbot at python.org Mon Jan 8 11:28:45 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 08 Jan 2007 10:28:45 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP 2.5 Message-ID: <20070108102845.292C31E4005@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/69 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: vinay.sajip Build had warnings: warnings failed slave lost sincerely, -The Buildbot From thomas at python.org Mon Jan 8 12:19:57 2007 From: thomas at python.org (Thomas Wouters) Date: Mon, 8 Jan 2007 03:19:57 -0800 Subject: [Python-checkins] r53254 - in python/branches/release25-maint: Doc/lib/libbsddb.tex Lib/bsddb/dbobj.py Lib/bsddb/test/test_1413192.py Misc/NEWS Modules/_bsddb.c setup.py In-Reply-To: <20070105020908.5A4CE1E4002@bag.python.org> References: <20070105020908.5A4CE1E4002@bag.python.org> Message-ID: <9e804ac0701080319i3ff2b455s502ed433d01e12e8@mail.gmail.com> On 1/4/07, gregory.p.smith wrote: > > Author: gregory.p.smith > Date: Fri Jan 5 03:09:06 2007 > New Revision: 53254 > > Modified: > python/branches/release25-maint/Doc/lib/libbsddb.tex > python/branches/release25-maint/Lib/bsddb/dbobj.py > python/branches/release25-maint/Lib/bsddb/test/test_1413192.py > python/branches/release25-maint/Misc/NEWS > python/branches/release25-maint/Modules/_bsddb.c > python/branches/release25-maint/setup.py > Log: > support linking the _bsddb extension module against BerkeleyDB 4.5 > [backport of r53252] I'm not entirely sure this should be backported, it smells somewhat like a feature (but I'll happily hush if you and the 2.5.1 releasemanager are sure it should be in.) Also, I wonder if this change should be part of this backport: > Modified: python/branches/release25-maint/setup.py > > ============================================================================== > --- python/branches/release25-maint/setup.py (original) > +++ python/branches/release25-maint/setup.py Fri Jan 5 03:09:06 2007 > @@ -631,7 +631,7 @@ > db_inc_paths.append('/pkg/db-4.%d/include' % x) > db_inc_paths.append('/opt/db-4.%d/include' % x) > # 3.x minor number specific paths > - for x in (2,3): > + for x in (3,): > db_inc_paths.append('/usr/include/db3%d' % x) > db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x) > db_inc_paths.append('/usr/local/include/db3%d' % x) > _______________________________________________ > 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/20070108/5e8adfe4/attachment.html From python-checkins at python.org Mon Jan 8 19:05:55 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 8 Jan 2007 19:05:55 +0100 (CET) Subject: [Python-checkins] r53299 - in python/branches/release25-maint: Lib/test/test_deque.py Misc/NEWS Modules/collectionsmodule.c Message-ID: <20070108180555.0179B1E400E@bag.python.org> Author: raymond.hettinger Date: Mon Jan 8 19:05:53 2007 New Revision: 53299 Modified: python/branches/release25-maint/Lib/test/test_deque.py python/branches/release25-maint/Misc/NEWS python/branches/release25-maint/Modules/collectionsmodule.c Log: Fix zero-length corner case for iterating over a mutating deque. Modified: python/branches/release25-maint/Lib/test/test_deque.py ============================================================================== --- python/branches/release25-maint/Lib/test/test_deque.py (original) +++ python/branches/release25-maint/Lib/test/test_deque.py Mon Jan 8 19:05:53 2007 @@ -396,6 +396,12 @@ d.pop() self.assertRaises(RuntimeError, it.next) + def test_runtime_error_on_empty_deque(self): + d = deque() + it = iter(d) + d.append(10) + self.assertRaises(RuntimeError, it.next) + class Deque(deque): pass Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Mon Jan 8 19:05:53 2007 @@ -129,6 +129,9 @@ - Added support for linking the bsddb module against BerkeleyDB 4.5.x. +- Modifying an empty deque during iteration now raises RuntimeError + instead of StopIteration. + Library ------- Modified: python/branches/release25-maint/Modules/collectionsmodule.c ============================================================================== --- python/branches/release25-maint/Modules/collectionsmodule.c (original) +++ python/branches/release25-maint/Modules/collectionsmodule.c Mon Jan 8 19:05:53 2007 @@ -911,15 +911,14 @@ { PyObject *item; - if (it->counter == 0) - return NULL; - if (it->deque->state != it->state) { it->counter = 0; PyErr_SetString(PyExc_RuntimeError, "deque mutated during iteration"); return NULL; } + if (it->counter == 0) + return NULL; assert (!(it->b == it->deque->rightblock && it->index > it->deque->rightindex)); From python-checkins at python.org Mon Jan 8 19:09:21 2007 From: python-checkins at python.org (raymond.hettinger) Date: Mon, 8 Jan 2007 19:09:21 +0100 (CET) Subject: [Python-checkins] r53300 - in python/trunk: Lib/test/test_deque.py Modules/collectionsmodule.c Message-ID: <20070108180921.3C7591E4017@bag.python.org> Author: raymond.hettinger Date: Mon Jan 8 19:09:20 2007 New Revision: 53300 Modified: python/trunk/Lib/test/test_deque.py python/trunk/Modules/collectionsmodule.c Log: Fix zero-length corner case for iterating over a mutating deque. Modified: python/trunk/Lib/test/test_deque.py ============================================================================== --- python/trunk/Lib/test/test_deque.py (original) +++ python/trunk/Lib/test/test_deque.py Mon Jan 8 19:09:20 2007 @@ -396,6 +396,12 @@ d.pop() self.assertRaises(RuntimeError, it.next) + def test_runtime_error_on_empty_deque(self): + d = deque() + it = iter(d) + d.append(10) + self.assertRaises(RuntimeError, it.next) + class Deque(deque): pass Modified: python/trunk/Modules/collectionsmodule.c ============================================================================== --- python/trunk/Modules/collectionsmodule.c (original) +++ python/trunk/Modules/collectionsmodule.c Mon Jan 8 19:09:20 2007 @@ -911,15 +911,14 @@ { PyObject *item; - if (it->counter == 0) - return NULL; - if (it->deque->state != it->state) { it->counter = 0; PyErr_SetString(PyExc_RuntimeError, "deque mutated during iteration"); return NULL; } + if (it->counter == 0) + return NULL; assert (!(it->b == it->deque->rightblock && it->index > it->deque->rightindex)); From python-checkins at python.org Mon Jan 8 19:50:34 2007 From: python-checkins at python.org (vinay.sajip) Date: Mon, 8 Jan 2007 19:50:34 +0100 (CET) Subject: [Python-checkins] r53301 - python/trunk/Lib/logging/handlers.py Message-ID: <20070108185034.25AAF1E4013@bag.python.org> Author: vinay.sajip Date: Mon Jan 8 19:50:32 2007 New Revision: 53301 Modified: python/trunk/Lib/logging/handlers.py Log: Bare except clause removed from SMTPHandler.emit(). Now, only ImportError is trapped. Bare except clause removed from SocketHandler.createSocket(). Now, only socket.error is trapped. (SF #411881) Modified: python/trunk/Lib/logging/handlers.py ============================================================================== --- python/trunk/Lib/logging/handlers.py (original) +++ python/trunk/Lib/logging/handlers.py Mon Jan 8 19:50:32 2007 @@ -343,7 +343,7 @@ try: self.sock = self.makeSocket() self.retryTime = None # next time, no delay before trying - except: + except socket.error: #Creation failed, so set the retry time and return. if self.retryTime is None: self.retryPeriod = self.retryStart @@ -734,7 +734,7 @@ import smtplib try: from email.Utils import formatdate - except: + except ImportError: formatdate = self.date_time port = self.mailport if not port: From python-checkins at python.org Mon Jan 8 19:51:46 2007 From: python-checkins at python.org (vinay.sajip) Date: Mon, 8 Jan 2007 19:51:46 +0100 (CET) Subject: [Python-checkins] r53302 - python/trunk/Lib/logging/__init__.py Message-ID: <20070108185146.7A24D1E4013@bag.python.org> Author: vinay.sajip Date: Mon Jan 8 19:51:46 2007 New Revision: 53302 Modified: python/trunk/Lib/logging/__init__.py Log: Bare except clause removed from LogRecord.__init__. Now, only ValueError, TypeError and AttributeError are trapped. (SF #411881) Modified: python/trunk/Lib/logging/__init__.py ============================================================================== --- python/trunk/Lib/logging/__init__.py (original) +++ python/trunk/Lib/logging/__init__.py Mon Jan 8 19:51:46 2007 @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.4.9.9" -__date__ = "06 February 2006" +__version__ = "0.5.0.0" +__date__ = "08 January 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -243,7 +243,7 @@ try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] - except: + except (TypeError, ValueError, AttributeError): self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info From python-checkins at python.org Mon Jan 8 19:52:36 2007 From: python-checkins at python.org (vinay.sajip) Date: Mon, 8 Jan 2007 19:52:36 +0100 (CET) Subject: [Python-checkins] r53303 - python/trunk/Misc/NEWS Message-ID: <20070108185236.00F4F1E400B@bag.python.org> Author: vinay.sajip Date: Mon Jan 8 19:52:36 2007 New Revision: 53303 Modified: python/trunk/Misc/NEWS Log: Added entries about removal of some bare except clauses from logging. Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon Jan 8 19:52:36 2007 @@ -109,6 +109,15 @@ Library ------- +- Bug #411881: logging.handlers: bare except clause removed from + SMTPHandler.emit. Now, only ImportError is trapped. + +- Bug #411881: logging.handlers: bare except clause removed from + SocketHandler.createSocket. Now, only socket.error is trapped. + +- Bug #411881: logging: bare except clause removed from LogRecord.__init__. + Now, only ValueError, TypeError and AttributeError are trapped. + - Patch #1504073: Fix tarfile.open() for mode "r" with a fileobj argument. - Patch #1182394 from Shane Holloway: speed up HMAC.hexdigest. From greg at electricrain.com Mon Jan 8 20:11:44 2007 From: greg at electricrain.com (Gregory P. Smith) Date: Mon, 8 Jan 2007 11:11:44 -0800 Subject: [Python-checkins] r53254 - in python/branches/release25-maint: Doc/lib/libbsddb.tex Lib/bsddb/dbobj.py Lib/bsddb/test/test_1413192.py Misc/NEWS Modules/_bsddb.c setup.py In-Reply-To: <9e804ac0701080319i3ff2b455s502ed433d01e12e8@mail.gmail.com> References: <20070105020908.5A4CE1E4002@bag.python.org> <9e804ac0701080319i3ff2b455s502ed433d01e12e8@mail.gmail.com> Message-ID: <20070108191143.GN24758@electricrain.com> On Mon, Jan 08, 2007 at 03:19:57AM -0800, Thomas Wouters wrote: > On 1/4/07, gregory.p.smith wrote: > > > >Author: gregory.p.smith > >Date: Fri Jan 5 03:09:06 2007 > >New Revision: 53254 > > > >Modified: > > python/branches/release25-maint/Doc/lib/libbsddb.tex > > python/branches/release25-maint/Lib/bsddb/dbobj.py > > python/branches/release25-maint/Lib/bsddb/test/test_1413192.py > > python/branches/release25-maint/Misc/NEWS > > python/branches/release25-maint/Modules/_bsddb.c > > python/branches/release25-maint/setup.py > >Log: > >support linking the _bsddb extension module against BerkeleyDB 4.5 > >[backport of r53252] > > > I'm not entirely sure this should be backported, it smells somewhat like a > feature (but I'll happily hush if you and the 2.5.1 releasemanager are sure > it should be in.) It doesn't add or modify any API, just lets it link against a more recent version of the library. I've backported support for linking with later BerkeleyDB versions to previous python subreleases (2.3 and 2.4) in the past. If anyone objects to this being in 2.5 feel free to remove it, i won't complain. I don't think it matters either way. > Also, I wonder if this change should be part of this backport: > > >Modified: python/branches/release25-maint/setup.py > > > >============================================================================== > >--- python/branches/release25-maint/setup.py (original) > >+++ python/branches/release25-maint/setup.py Fri Jan 5 03:09:06 2007 > >@@ -631,7 +631,7 @@ > > db_inc_paths.append('/pkg/db-4.%d/include' % x) > > db_inc_paths.append('/opt/db-4.%d/include' % x) > > # 3.x minor number specific paths > >- for x in (2,3): > >+ for x in (3,): > > db_inc_paths.append('/usr/include/db3%d' % x) > > db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x) > > db_inc_paths.append('/usr/local/include/db3%d' % x) The code ~10 lines above this that was already in the tree prevents berkeleydb 3.2 from ever being considered in the first place so this change is effectively a no-op. I probably should have left that out but it won't matter. From jimjjewett at gmail.com Mon Jan 8 22:05:47 2007 From: jimjjewett at gmail.com (Jim Jewett) Date: Mon, 8 Jan 2007 16:05:47 -0500 Subject: [Python-checkins] r53280 - sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/mock_importer.py sandbox/trunk/import_in_py/test_importer.py In-Reply-To: <20070105215940.B4F2A1E4002@bag.python.org> References: <20070105215940.B4F2A1E4002@bag.python.org> Message-ID: Comments inline... my apologies for not finding a better way to reduce the context On 1/5/07, brett.cannon wrote: > Author: brett.cannon > Date: Fri Jan 5 22:59:39 2007 > New Revision: 53280 > Log: > Tighten up API to just what needs to be publicly exposed by adding underscores > to various functions and methods. > Modified: sandbox/trunk/import_in_py/importer.py ============================================================================== > --- sandbox/trunk/import_in_py/importer.py (original) > +++ sandbox/trunk/import_in_py/importer.py Fri Jan 5 22:59:39 2007 > @@ -30,38 +28,39 @@ ... > * warnings and stack level. ... > + 'warnings' assumes that the import code does not show up in the call > stack. > - + Because import now in Python, import does show up in the call stack. > - + Trick of specifying that going back two levels will cause the warning > - to be raised in the caller for an import statement no longer holds true. > + + Because import now implemented in Python, import does show up in the > + call stack. > + + Trick of specifying going back in the call stack two levels so warning > + shows up in the caller will cause the warning no longer holds true. > + Possible fixes > - Special module deprecation function. > - - Code in warnings.warn to handle import case. > + - Code in warnings.warn to handle special import case. Note that this is similar to what the logging module does. It might make sense to just skip anything registered as "internal" or "part of debugging", so the wheel wouldn't have to be reinvented each time. > @@ -101,7 +100,7 @@ ... > -def case_ok(directory, file_name): > +def _case_ok(directory, file_name): > """Verify that file_name (as found in 'directory') has the proper case. Why is this internal? Because other code should use os.path.normcase? > @@ -114,8 +113,6 @@ > """ > if sys.platform not in ('win32', 'mac', 'riscos', 'darwin', 'cygwin', > 'os2emx') or os.environ.get('PYTHONCASEOK'): > - # Platform is case-sensitive so existence check already handle > - # case-sensitivity. And why is this comment removed? There may be other case-insensitive platforms in the future. > @@ -551,7 +548,7 @@ ... > - def search_meta_path(self, name, path=None): > + def _search_meta_path(self, name, path=None): > """Check the importers on sys.meta_path for a loader along with the > extended meta path sequence stored within this instance. And why is this internal? Unless the context that didn't get touched by the patch makes it obvious, this seems like the sort of thing other importers might want to do. Same questions for sys_path_importer, import_module, import_full_module, resolve_name, and class_resolve_name > Modified: sandbox/trunk/import_in_py/mock_importer.py ============================================================================== > --- sandbox/trunk/import_in_py/mock_importer.py (original) > +++ sandbox/trunk/import_in_py/mock_importer.py Fri Jan 5 22:59:39 2007 > @@ -2,8 +2,7 @@ > import marshal > import imp Should that become _imp, as your code takes over the import job? From anthony at interlink.com.au Mon Jan 8 22:12:57 2007 From: anthony at interlink.com.au (Anthony Baxter) Date: Tue, 9 Jan 2007 08:12:57 +1100 Subject: [Python-checkins] r53254 - in python/branches/release25-maint: Doc/lib/libbsddb.tex Lib/bsddb/dbobj.py Lib/bsddb/test/test_1413192.py Misc/NEWS Modules/_bsddb.c setup.py In-Reply-To: <20070108191143.GN24758@electricrain.com> References: <20070105020908.5A4CE1E4002@bag.python.org> <9e804ac0701080319i3ff2b455s502ed433d01e12e8@mail.gmail.com> <20070108191143.GN24758@electricrain.com> Message-ID: <200701090813.00188.anthony@interlink.com.au> On Tuesday 09 January 2007 06:11, Gregory P. Smith wrote: > > >support linking the _bsddb extension module against BerkeleyDB > > > 4.5 [backport of r53252] > > > > I'm not entirely sure this should be backported, it smells > > somewhat like a feature (but I'll happily hush if you and the > > 2.5.1 releasemanager are sure it should be in.) > > It doesn't add or modify any API, just lets it link against a > more recent version of the library. I've backported support for > linking with later BerkeleyDB versions to previous python > subreleases (2.3 and 2.4) in the past. If anyone objects to this > being in 2.5 feel free to remove it, i won't complain. I don't > think it matters either way. It's a marginal call as to whether it's a "new feature" or not - but in this case, I think practicality beats purity ;-) Plus, as Greg notes, we've done this before in 2.3 and 2.4. -- Anthony Baxter It's never too late to have a happy childhood. From buildbot at python.org Mon Jan 8 22:16:19 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 08 Jan 2007 21:16:19 +0000 Subject: [Python-checkins] buildbot failure in x86 OpenBSD trunk Message-ID: <20070108211619.E1E201E4005@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/1474 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: raymond.hettinger,vinay.sajip BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Mon Jan 8 22:16:20 2007 From: buildbot at python.org (buildbot at python.org) Date: Mon, 08 Jan 2007 21:16:20 +0000 Subject: [Python-checkins] buildbot failure in x86 OpenBSD 2.5 Message-ID: <20070108211620.C4CF21E4005@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/148 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: raymond.hettinger BUILD FAILED: failed svn sincerely, -The Buildbot From brett at python.org Mon Jan 8 23:36:48 2007 From: brett at python.org (Brett Cannon) Date: Mon, 8 Jan 2007 14:36:48 -0800 Subject: [Python-checkins] r53280 - sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/mock_importer.py sandbox/trunk/import_in_py/test_importer.py In-Reply-To: References: <20070105215940.B4F2A1E4002@bag.python.org> Message-ID: On 1/8/07, Jim Jewett wrote: > > Comments inline... my apologies for not finding a better way to reduce > the context > > On 1/5/07, brett.cannon wrote: > > Author: brett.cannon > > Date: Fri Jan 5 22:59:39 2007 > > New Revision: 53280 > > > Log: > > Tighten up API to just what needs to be publicly exposed by adding > underscores > > to various functions and methods. > > > Modified: sandbox/trunk/import_in_py/importer.py > > ============================================================================== > > --- sandbox/trunk/import_in_py/importer.py (original) > > +++ sandbox/trunk/import_in_py/importer.py Fri Jan 5 22:59:39 2007 > > @@ -30,38 +28,39 @@ > ... > > * warnings and stack level. > ... > > + 'warnings' assumes that the import code does not show up in the > call > > stack. > > - + Because import now in Python, import does show up in the call > stack. > > - + Trick of specifying that going back two levels will cause the > warning > > - to be raised in the caller for an import statement no longer > holds true. > > + + Because import now implemented in Python, import does show up in > the > > + call stack. > > + + Trick of specifying going back in the call stack two levels so > warning > > + shows up in the caller will cause the warning no longer holds > true. > > + Possible fixes > > - Special module deprecation function. > > - - Code in warnings.warn to handle import case. > > + - Code in warnings.warn to handle special import case. > > Note that this is similar to what the logging module does. Ah, OK. Wasn't aware of that. It might make sense to just skip anything registered as "internal" or > "part of debugging", so the wheel wouldn't have to be reinvented each > time. Probably. > @@ -101,7 +100,7 @@ > ... > > > -def case_ok(directory, file_name): > > +def _case_ok(directory, file_name): > > """Verify that file_name (as found in 'directory') has the proper > case. > > Why is this internal? Because other code should use os.path.normcase? No, os.path.normcase doesn't do what this function does as I need a way to verify that a path, with a specific case exists. I made it internal since I don't see an initial need to expose it and I have not worried about its interface. Plus I am hoping to expose imp's C function case_ok to take over since that will have much better performance. > @@ -114,8 +113,6 @@ > > """ > > if sys.platform not in ('win32', 'mac', 'riscos', 'darwin', > 'cygwin', > > 'os2emx') or os.environ.get('PYTHONCASEOK'): > > - # Platform is case-sensitive so existence check already handle > > - # case-sensitivity. > > And why is this comment removed? There may be other case-insensitive > platforms in the future. Right. The comment was removed because it didn't directly apply with the PYTHONCASEOK check. > @@ -551,7 +548,7 @@ > ... > > - def search_meta_path(self, name, path=None): > > + def _search_meta_path(self, name, path=None): > > """Check the importers on sys.meta_path for a loader along with > the > > extended meta path sequence stored within this instance. > > And why is this internal? Unless the context that didn't get touched > by the patch makes it obvious, this seems like the sort of thing other > importers might want to do. > > Same questions for sys_path_importer, > import_module, > import_full_module, > resolve_name, and class_resolve_name Just trying to keep the initial API small. They can be exposed at a later date if it turns out people want the methods exposed. But I don't want to start off with a large API that will need to be continually supported in the future, especially if the code gets tweaked. > Modified: sandbox/trunk/import_in_py/mock_importer.py > > ============================================================================== > > --- sandbox/trunk/import_in_py/mock_importer.py (original) > > +++ sandbox/trunk/import_in_py/mock_importer.py Fri Jan 5 22:59:39 2007 > > @@ -2,8 +2,7 @@ > > import marshal > > import imp > > Should that become _imp, as your code takes over the import job? > Possibly, but let's get the code into the stdlib first. =) -Brett -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-checkins/attachments/20070108/a659c5c6/attachment.htm From python-checkins at python.org Tue Jan 9 15:50:28 2007 From: python-checkins at python.org (vinay.sajip) Date: Tue, 9 Jan 2007 15:50:28 +0100 (CET) Subject: [Python-checkins] r53304 - python/trunk/Lib/logging/__init__.py Message-ID: <20070109145028.BD93B1E400A@bag.python.org> Author: vinay.sajip Date: Tue Jan 9 15:50:28 2007 New Revision: 53304 Modified: python/trunk/Lib/logging/__init__.py Log: 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". Modified: python/trunk/Lib/logging/__init__.py ============================================================================== --- python/trunk/Lib/logging/__init__.py (original) +++ python/trunk/Lib/logging/__init__.py Tue Jan 9 15:50:28 2007 @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.5.0.0" -__date__ = "08 January 2007" +__version__ = "0.5.0.1" +__date__ = "09 January 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -764,17 +764,15 @@ """ Open the specified file and use it as the stream for logging. """ - if codecs is None: - encoding = None - if encoding is None: - stream = open(filename, mode) - else: - stream = codecs.open(filename, mode, encoding) - StreamHandler.__init__(self, stream) #keep the absolute path, otherwise derived classes which use this #may come a cropper when the current directory changes + if codecs is None: + encoding = None self.baseFilename = os.path.abspath(filename) self.mode = mode + self.encoding = encoding + stream = self._open() + StreamHandler.__init__(self, stream) def close(self): """ @@ -784,6 +782,13 @@ self.stream.close() StreamHandler.close(self) + def _open(self): + 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 #--------------------------------------------------------------------------- From python-checkins at python.org Tue Jan 9 15:51:36 2007 From: python-checkins at python.org (vinay.sajip) Date: Tue, 9 Jan 2007 15:51:36 +0100 (CET) Subject: [Python-checkins] r53305 - python/trunk/Misc/NEWS Message-ID: <20070109145136.BC4BA1E4006@bag.python.org> Author: vinay.sajip Date: Tue Jan 9 15:51:36 2007 New Revision: 53305 Modified: python/trunk/Misc/NEWS Log: Added entry about addition of _open() method to logging.FileHandler. Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue Jan 9 15:51:36 2007 @@ -109,6 +109,10 @@ Library ------- +- Bug #1627575: logging: 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". + - Bug #411881: logging.handlers: bare except clause removed from SMTPHandler.emit. Now, only ImportError is trapped. From python-checkins at python.org Tue Jan 9 15:54:56 2007 From: python-checkins at python.org (vinay.sajip) Date: Tue, 9 Jan 2007 15:54:56 +0100 (CET) Subject: [Python-checkins] r53306 - python/trunk/Lib/logging/__init__.py Message-ID: <20070109145456.E79111E4006@bag.python.org> Author: vinay.sajip Date: Tue Jan 9 15:54:56 2007 New Revision: 53306 Modified: python/trunk/Lib/logging/__init__.py Log: Added a docstring Modified: python/trunk/Lib/logging/__init__.py ============================================================================== --- python/trunk/Lib/logging/__init__.py (original) +++ python/trunk/Lib/logging/__init__.py Tue Jan 9 15:54:56 2007 @@ -783,6 +783,10 @@ 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: From buildbot at python.org Tue Jan 9 16:00:58 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 09 Jan 2007 15:00:58 +0000 Subject: [Python-checkins] buildbot failure in S-390 Debian trunk Message-ID: <20070109150058.62DC01E400C@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/587 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: vinay.sajip BUILD FAILED: failed svn sincerely, -The Buildbot From buildbot at python.org Tue Jan 9 17:15:10 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 09 Jan 2007 16:15:10 +0000 Subject: [Python-checkins] buildbot warnings in hppa Ubuntu dapper trunk Message-ID: <20070109161511.1D4351E400F@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/0 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_posix ====================================================================== ERROR: testNoArgFunctions (test.test_posix.PosixTester) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pybot/buildarea/trunk.klose-ubuntu-hppa/build/Lib/test/test_posix.py", line 40, in testNoArgFunctions posix_func() OSError: Load averages are unobtainable sincerely, -The Buildbot From buildbot at python.org Tue Jan 9 17:50:16 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 09 Jan 2007 16:50:16 +0000 Subject: [Python-checkins] buildbot warnings in x86 W2k trunk Message-ID: <20070109165016.B3CD81E4006@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/0 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: 2 tests failed: test_dumbdbm test_uu ====================================================================== FAIL: test_dumbdbm_creation_mode (test.test_dumbdbm.DumbDBMTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\trentm\data\buildbot\python-slave\trunk.mick-windows\build\lib\test\test_dumbdbm.py", line 55, in test_dumbdbm_creation_mode self.assertEqual(stat.S_IMODE(st.st_mode), 0635) AssertionError: 438 != 413 ====================================================================== FAIL: test_encode (test.test_uu.UUFileTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\trentm\data\buildbot\python-slave\trunk.mick-windows\build\lib\test\test_uu.py", line 137, in test_encode self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) AssertionError: 'begin 644 @testi\nM5&AE(\'-M;V]T:"US8V%L960@<\'ET:&]N(&-R97!T(&]V97(@=&AE(\'-L965P\n):6YG(&1O9PT*\n \nend\n' != 'begin 644 @testi\nM5&AE(\'-M;V]T:"US8V%L960@<\'ET:&]N(&-R97!T(&]V97(@=&AE(\'-L965P\n(:6YG(&1O9PH \n \nend\n' sincerely, -The Buildbot From buildbot at python.org Tue Jan 9 18:06:21 2007 From: buildbot at python.org (buildbot at python.org) Date: Tue, 09 Jan 2007 17:06:21 +0000 Subject: [Python-checkins] buildbot warnings in x86 cygwin trunk Message-ID: <20070109170621.00D801E4006@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/0 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: sincerely, -The Buildbot From python-checkins at python.org Tue Jan 9 18:59:35 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 18:59:35 +0100 (CET) Subject: [Python-checkins] r53307 - sandbox/trunk/setuptools/README.txt Message-ID: <20070109175935.661191E4006@bag.python.org> Author: phillip.eby Date: Tue Jan 9 18:59:34 2007 New Revision: 53307 Modified: sandbox/trunk/setuptools/README.txt Log: Formatting fixes for README Modified: sandbox/trunk/setuptools/README.txt ============================================================================== --- sandbox/trunk/setuptools/README.txt (original) +++ sandbox/trunk/setuptools/README.txt Tue Jan 9 18:59:34 2007 @@ -65,19 +65,19 @@ the `EasyInstall manual`_ for detailed instructions, especially `the section on custom installation locations`_. -.. _The EasyInstall user's guide and reference manual: http://peak.telecommunity.com/DevCenter/EasyInstall +.. _EasyInstall manual: http://peak.telecommunity.com/DevCenter/EasyInstall .. _the section on custom installation locations: http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations Cygwin Note ----------- -If you are trying to install setuptools for the *Windows* version of Python (as -opposed to the Cygwin version that lives in ``/usr/bin``), you must make sure -that an appropriate executable (``python2.3``, ``python2.4``, or ``python2.5``) -is on your **Cygwin** ``PATH`` when invoking the egg. For example, doing the -following at a Cygwin bash prompt will install setuptools for the *Windows* -Python found at ``C:\\Python24``:: +If you are trying to install setuptools for the **Windows** version of Python +(as opposed to the Cygwin version that lives in ``/usr/bin``), you must make +sure that an appropriate executable (``python2.3``, ``python2.4``, or +``python2.5``) is on your **Cygwin** ``PATH`` when invoking the egg. For +example, doing the following at a Cygwin bash prompt will install setuptools +for the **Windows** Python found at ``C:\\Python24``:: ln -s /cygdrive/c/Python24/python.exe python2.4 PATH=.:$PATH sh setuptools-0.6c4-py2.4.egg From python-checkins at python.org Tue Jan 9 19:00:58 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 19:00:58 +0100 (CET) Subject: [Python-checkins] r53308 - sandbox/branches/setuptools-0.6/README.txt Message-ID: <20070109180058.4BB981E4007@bag.python.org> Author: phillip.eby Date: Tue Jan 9 19:00:57 2007 New Revision: 53308 Modified: sandbox/branches/setuptools-0.6/README.txt Log: README formatting fix (backport from trunk) Modified: sandbox/branches/setuptools-0.6/README.txt ============================================================================== --- sandbox/branches/setuptools-0.6/README.txt (original) +++ sandbox/branches/setuptools-0.6/README.txt Tue Jan 9 19:00:57 2007 @@ -65,19 +65,19 @@ the `EasyInstall manual`_ for detailed instructions, especially `the section on custom installation locations`_. -.. _The EasyInstall user's guide and reference manual: http://peak.telecommunity.com/DevCenter/EasyInstall +.. _EasyInstall manual: http://peak.telecommunity.com/DevCenter/EasyInstall .. _the section on custom installation locations: http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations Cygwin Note ----------- -If you are trying to install setuptools for the *Windows* version of Python (as -opposed to the Cygwin version that lives in ``/usr/bin``), you must make sure -that an appropriate executable (``python2.3``, ``python2.4``, or ``python2.5``) -is on your **Cygwin** ``PATH`` when invoking the egg. For example, doing the -following at a Cygwin bash prompt will install setuptools for the *Windows* -Python found at ``C:\\Python24``:: +If you are trying to install setuptools for the **Windows** version of Python +(as opposed to the Cygwin version that lives in ``/usr/bin``), you must make +sure that an appropriate executable (``python2.3``, ``python2.4``, or +``python2.5``) is on your **Cygwin** ``PATH`` when invoking the egg. For +example, doing the following at a Cygwin bash prompt will install setuptools +for the **Windows** Python found at ``C:\\Python24``:: ln -s /cygdrive/c/Python24/python.exe python2.4 PATH=.:$PATH sh setuptools-0.6c4-py2.4.egg From python-checkins at python.org Tue Jan 9 19:08:31 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 19:08:31 +0100 (CET) Subject: [Python-checkins] r53309 - sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py Message-ID: <20070109180831.DB83D1E4006@bag.python.org> Author: phillip.eby Date: Tue Jan 9 19:08:31 2007 New Revision: 53309 Modified: sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py Log: Don't double-upload .exe files under Python 2.5. :( Modified: sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py (original) +++ sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py Tue Jan 9 19:08:31 2007 @@ -2,24 +2,24 @@ import os class bdist_wininst(_bdist_wininst): + if sys.version<'2.5': + def create_exe(self, arcname, fullname, bitmap=None): - def create_exe(self, arcname, fullname, bitmap=None): + _bdist_wininst.create_exe(self, arcname, fullname, bitmap) - _bdist_wininst.create_exe(self, arcname, fullname, bitmap) - - if self.target_version: - installer_name = os.path.join(self.dist_dir, - "%s.win32-py%s.exe" % - (fullname, self.target_version)) - pyversion = self.target_version - else: - installer_name = os.path.join(self.dist_dir, - "%s.win32.exe" % fullname) - pyversion = 'any' - - getattr(self.distribution,'dist_files',[]).append( - ('bdist_wininst', pyversion, installer_name) - ) + if self.target_version: + installer_name = os.path.join(self.dist_dir, + "%s.win32-py%s.exe" % + (fullname, self.target_version)) + pyversion = self.target_version + else: + installer_name = os.path.join(self.dist_dir, + "%s.win32.exe" % fullname) + pyversion = 'any' + + getattr(self.distribution,'dist_files',[]).append( + ('bdist_wininst', pyversion, installer_name) + ) def reinitialize_command (self, command, reinit_subcommands=0): cmd = self.distribution.reinitialize_command( From python-checkins at python.org Tue Jan 9 19:09:12 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 19:09:12 +0100 (CET) Subject: [Python-checkins] r53310 - sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py Message-ID: <20070109180912.B349C1E4007@bag.python.org> Author: phillip.eby Date: Tue Jan 9 19:09:12 2007 New Revision: 53310 Modified: sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py Log: Don't double-upload .exe files under Python 2.5. :( (backport from trunk) Modified: sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py Tue Jan 9 19:09:12 2007 @@ -2,24 +2,24 @@ import os class bdist_wininst(_bdist_wininst): + if sys.version<'2.5': + def create_exe(self, arcname, fullname, bitmap=None): - def create_exe(self, arcname, fullname, bitmap=None): + _bdist_wininst.create_exe(self, arcname, fullname, bitmap) - _bdist_wininst.create_exe(self, arcname, fullname, bitmap) - - if self.target_version: - installer_name = os.path.join(self.dist_dir, - "%s.win32-py%s.exe" % - (fullname, self.target_version)) - pyversion = self.target_version - else: - installer_name = os.path.join(self.dist_dir, - "%s.win32.exe" % fullname) - pyversion = 'any' - - getattr(self.distribution,'dist_files',[]).append( - ('bdist_wininst', pyversion, installer_name) - ) + if self.target_version: + installer_name = os.path.join(self.dist_dir, + "%s.win32-py%s.exe" % + (fullname, self.target_version)) + pyversion = self.target_version + else: + installer_name = os.path.join(self.dist_dir, + "%s.win32.exe" % fullname) + pyversion = 'any' + + getattr(self.distribution,'dist_files',[]).append( + ('bdist_wininst', pyversion, installer_name) + ) def reinitialize_command (self, command, reinit_subcommands=0): cmd = self.distribution.reinitialize_command( From python-checkins at python.org Tue Jan 9 19:11:11 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 19:11:11 +0100 (CET) Subject: [Python-checkins] r53311 - sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py Message-ID: <20070109181111.6A5E11E4006@bag.python.org> Author: phillip.eby Date: Tue Jan 9 19:11:10 2007 New Revision: 53311 Modified: sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py Log: Argh. Modified: sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py Tue Jan 9 19:11:10 2007 @@ -1,5 +1,5 @@ from distutils.command.bdist_wininst import bdist_wininst as _bdist_wininst -import os +import os, sys class bdist_wininst(_bdist_wininst): if sys.version<'2.5': From python-checkins at python.org Tue Jan 9 19:14:32 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 19:14:32 +0100 (CET) Subject: [Python-checkins] r53312 - sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py Message-ID: <20070109181432.EE48A1E400A@bag.python.org> Author: phillip.eby Date: Tue Jan 9 19:14:32 2007 New Revision: 53312 Modified: sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py Log: Backport from branch. Modified: sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py (original) +++ sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py Tue Jan 9 19:14:32 2007 @@ -1,5 +1,5 @@ from distutils.command.bdist_wininst import bdist_wininst as _bdist_wininst -import os +import os, sys class bdist_wininst(_bdist_wininst): if sys.version<'2.5': From python-checkins at python.org Tue Jan 9 19:15:24 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 19:15:24 +0100 (CET) Subject: [Python-checkins] r53313 - sandbox/branches/setuptools-0.6/ez_setup.py Message-ID: <20070109181524.5C45B1E400A@bag.python.org> Author: phillip.eby Date: Tue Jan 9 19:15:23 2007 New Revision: 53313 Modified: sandbox/branches/setuptools-0.6/ez_setup.py Log: MD5's for setuptools 0.6c4. Modified: sandbox/branches/setuptools-0.6/ez_setup.py ============================================================================== --- sandbox/branches/setuptools-0.6/ez_setup.py (original) +++ sandbox/branches/setuptools-0.6/ez_setup.py Tue Jan 9 19:15:23 2007 @@ -33,6 +33,9 @@ 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', + 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', + 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', + 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', } import sys, os From python-checkins at python.org Tue Jan 9 19:21:36 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 19:21:36 +0100 (CET) Subject: [Python-checkins] r53314 - sandbox/trunk/setuptools/setuptools/command/bdist_rpm.py Message-ID: <20070109182136.7C63F1E4006@bag.python.org> Author: phillip.eby Date: Tue Jan 9 19:21:36 2007 New Revision: 53314 Modified: sandbox/trunk/setuptools/setuptools/command/bdist_rpm.py Log: Argh, again. Modified: sandbox/trunk/setuptools/setuptools/command/bdist_rpm.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/bdist_rpm.py (original) +++ sandbox/trunk/setuptools/setuptools/command/bdist_rpm.py Tue Jan 9 19:21:36 2007 @@ -18,7 +18,7 @@ _bdist_rpm.move_file(self, src, dst, level) if dst==self.dist_dir and src.endswith('.rpm'): getattr(self.distribution,'dist_files',[]).append( - ('bdist_egg', + ('bdist_rpm', src.endswith('.src.rpm') and 'any' or sys.version[:3], os.path.join(dst, os.path.basename(src))) ) From python-checkins at python.org Tue Jan 9 19:57:24 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 19:57:24 +0100 (CET) Subject: [Python-checkins] r53315 - sandbox/trunk/setuptools/setuptools/command/easy_install.py Message-ID: <20070109185724.765B71E4006@bag.python.org> Author: phillip.eby Date: Tue Jan 9 19:57:23 2007 New Revision: 53315 Modified: sandbox/trunk/setuptools/setuptools/command/easy_install.py Log: Fix not making Cygwin .dll's executable when installing in non-zip-safe mode. 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 Tue Jan 9 19:57:23 2007 @@ -983,16 +983,22 @@ return dst # only unpack-and-compile skips files for dry run def unpack_and_compile(self, egg_path, destination): - to_compile = [] + to_compile = []; to_chmod = [] def pf(src,dst): if dst.endswith('.py') and not src.startswith('EGG-INFO/'): to_compile.append(dst) - self.unpack_progress(src,dst) + self.unpack_progress(src,dst); to_chmod.append(dst) return not self.dry_run and dst or None unpack_archive(egg_path, destination, pf) self.byte_compile(to_compile) + if not self.dry_run: + flags = stat.S_IXGRP|stat.S_IXGRP + for f in to_chmod: + mode = ((os.stat(f)[stat.ST_MODE]) | 0555) & 07777 + log.debug("changing mode of %s to %o", f, mode) + os.chmod(f, mode) def byte_compile(self, to_compile): @@ -1017,12 +1023,6 @@ - - - - - - def no_default_version_msg(self): return """bad install directory or PYTHONPATH From python-checkins at python.org Tue Jan 9 20:19:34 2007 From: python-checkins at python.org (thomas.heller) Date: Tue, 9 Jan 2007 20:19:34 +0100 (CET) Subject: [Python-checkins] r53316 - python/trunk/Lib/ctypes/__init__.py Message-ID: <20070109191934.5290B1E4006@bag.python.org> Author: thomas.heller Date: Tue Jan 9 20:19:33 2007 New Revision: 53316 Modified: python/trunk/Lib/ctypes/__init__.py Log: Verify the sizes of the basic ctypes data types against the struct module. Will backport to release25-maint. Modified: python/trunk/Lib/ctypes/__init__.py ============================================================================== --- python/trunk/Lib/ctypes/__init__.py (original) +++ python/trunk/Lib/ctypes/__init__.py Tue Jan 9 20:19:33 2007 @@ -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 = {} From python-checkins at python.org Tue Jan 9 20:21:07 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 20:21:07 +0100 (CET) Subject: [Python-checkins] r53317 - in sandbox/branches/setuptools-0.6: EasyInstall.txt ez_setup.py release.sh setup.py setuptools.txt setuptools/__init__.py setuptools/command/bdist_rpm.py setuptools/command/easy_install.py version version.dat Message-ID: <20070109192107.1CD4A1E4006@bag.python.org> Author: phillip.eby Date: Tue Jan 9 20:21:05 2007 New Revision: 53317 Modified: sandbox/branches/setuptools-0.6/EasyInstall.txt sandbox/branches/setuptools-0.6/ez_setup.py sandbox/branches/setuptools-0.6/release.sh sandbox/branches/setuptools-0.6/setup.py sandbox/branches/setuptools-0.6/setuptools.txt sandbox/branches/setuptools-0.6/setuptools/__init__.py sandbox/branches/setuptools-0.6/setuptools/command/bdist_rpm.py sandbox/branches/setuptools-0.6/setuptools/command/easy_install.py sandbox/branches/setuptools-0.6/version sandbox/branches/setuptools-0.6/version.dat Log: Bump version to 0.6c5, and backport bdist_rpm and cygwin dll fixes Modified: sandbox/branches/setuptools-0.6/EasyInstall.txt ============================================================================== --- sandbox/branches/setuptools-0.6/EasyInstall.txt (original) +++ sandbox/branches/setuptools-0.6/EasyInstall.txt Tue Jan 9 20:21:05 2007 @@ -1194,6 +1194,10 @@ Release Notes/Change History ============================ +0.6c5 + * Fixed ``.dll`` files on Cygwin not having executable permisions when an egg + is installed unzipped. + 0.6c4 * Added support for HTTP "Basic" authentication using ``http://user:pass at host`` URLs. If a password-protected page contains links to the same host (and Modified: sandbox/branches/setuptools-0.6/ez_setup.py ============================================================================== --- sandbox/branches/setuptools-0.6/ez_setup.py (original) +++ sandbox/branches/setuptools-0.6/ez_setup.py Tue Jan 9 20:21:05 2007 @@ -14,7 +14,7 @@ This file can also be run as a script to install or upgrade setuptools. """ import sys -DEFAULT_VERSION = "0.6c4" +DEFAULT_VERSION = "0.6c5" DEFAULT_URL = "http://cheeseshop.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { Modified: sandbox/branches/setuptools-0.6/release.sh ============================================================================== --- sandbox/branches/setuptools-0.6/release.sh (original) +++ sandbox/branches/setuptools-0.6/release.sh Tue Jan 9 20:21:05 2007 @@ -7,7 +7,7 @@ # If your initials aren't PJE, don't run it. :) # -export VERSION="0.6c4" +export VERSION="0.6c5" python2.3 setup.py -q release source --target-version=2.3 upload && \ python2.4 setup.py -q release binary --target-version=2.4 upload && \ Modified: sandbox/branches/setuptools-0.6/setup.py ============================================================================== --- sandbox/branches/setuptools-0.6/setup.py (original) +++ sandbox/branches/setuptools-0.6/setup.py Tue Jan 9 20:21:05 2007 @@ -7,7 +7,7 @@ execfile(convert_path('setuptools/command/__init__.py'), d) SETUP_COMMANDS = d['__all__'] -VERSION = "0.6c4" +VERSION = "0.6c5" from setuptools import setup, find_packages import sys Modified: sandbox/branches/setuptools-0.6/setuptools.txt ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools.txt (original) +++ sandbox/branches/setuptools-0.6/setuptools.txt Tue Jan 9 20:21:05 2007 @@ -2600,6 +2600,10 @@ Release Notes/Change History ---------------------------- +0.6c5 + * Fix uploaded ``bdist_rpm`` packages being described as ``bdist_egg`` + packages under Python versions less than 2.5. + 0.6c4 * Overhauled Windows script wrapping to support ``bdist_wininst`` better. Modified: sandbox/branches/setuptools-0.6/setuptools/__init__.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/__init__.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/__init__.py Tue Jan 9 20:21:05 2007 @@ -7,7 +7,7 @@ from distutils.util import convert_path import os.path -__version__ = '0.6c4' +__version__ = '0.6c5' __all__ = [ 'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require', 'find_packages' Modified: sandbox/branches/setuptools-0.6/setuptools/command/bdist_rpm.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/bdist_rpm.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/bdist_rpm.py Tue Jan 9 20:21:05 2007 @@ -18,7 +18,7 @@ _bdist_rpm.move_file(self, src, dst, level) if dst==self.dist_dir and src.endswith('.rpm'): getattr(self.distribution,'dist_files',[]).append( - ('bdist_egg', + ('bdist_rpm', src.endswith('.src.rpm') and 'any' or get_python_version(), os.path.join(dst, os.path.basename(src))) ) 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 Tue Jan 9 20:21:05 2007 @@ -983,16 +983,22 @@ return dst # only unpack-and-compile skips files for dry run def unpack_and_compile(self, egg_path, destination): - to_compile = [] + to_compile = []; to_chmod = [] def pf(src,dst): if dst.endswith('.py') and not src.startswith('EGG-INFO/'): to_compile.append(dst) - self.unpack_progress(src,dst) + self.unpack_progress(src,dst); to_chmod.append(dst) return not self.dry_run and dst or None unpack_archive(egg_path, destination, pf) self.byte_compile(to_compile) + if not self.dry_run: + flags = stat.S_IXGRP|stat.S_IXGRP + for f in to_chmod: + mode = ((os.stat(f)[stat.ST_MODE]) | 0555) & 07777 + log.debug("changing mode of %s to %o", f, mode) + os.chmod(f, mode) def byte_compile(self, to_compile): @@ -1017,12 +1023,6 @@ - - - - - - def no_default_version_msg(self): return """bad install directory or PYTHONPATH Modified: sandbox/branches/setuptools-0.6/version ============================================================================== --- sandbox/branches/setuptools-0.6/version (original) +++ sandbox/branches/setuptools-0.6/version Tue Jan 9 20:21:05 2007 @@ -1,4 +1,4 @@ -#!/usr/local/bin/invoke /usr/local/bin/c6peak version-config +#!/usr/local/bin/invoke /usr/bin/peak version-config # This is a PEAK 'version' tool configuration file, that's # also executable. PJE uses it to bump version numbers in Modified: sandbox/branches/setuptools-0.6/version.dat ============================================================================== --- sandbox/branches/setuptools-0.6/version.dat (original) +++ sandbox/branches/setuptools-0.6/version.dat Tue Jan 9 20:21:05 2007 @@ -1,6 +1,6 @@ [setuptools] status = 'release candidate' major = 0 -build = 4 +build = 5 minor = 6 From python-checkins at python.org Tue Jan 9 20:22:42 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 20:22:42 +0100 (CET) Subject: [Python-checkins] r53318 - sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py Message-ID: <20070109192242.EB8031E4007@bag.python.org> Author: phillip.eby Date: Tue Jan 9 20:22:42 2007 New Revision: 53318 Modified: sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py Log: Workaround for Python 2.5 distutils bug: when bdist_wininst files are uploaded, they are marked as suitable for "any" Python version, even if an explicit --target-version was specified. (This needs to be fixed in the distutils too.) Modified: sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py ============================================================================== --- sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py (original) +++ sandbox/trunk/setuptools/setuptools/command/bdist_wininst.py Tue Jan 9 20:22:42 2007 @@ -2,24 +2,27 @@ import os, sys class bdist_wininst(_bdist_wininst): - if sys.version<'2.5': - def create_exe(self, arcname, fullname, bitmap=None): - _bdist_wininst.create_exe(self, arcname, fullname, bitmap) + def create_exe(self, arcname, fullname, bitmap=None): + _bdist_wininst.create_exe(self, arcname, fullname, bitmap) + dist_files = getattr(self.distribution, 'dist_files', []) + + if self.target_version: + installer_name = os.path.join(self.dist_dir, + "%s.win32-py%s.exe" % + (fullname, self.target_version)) + pyversion = self.target_version + + # fix 2.5 bdist_wininst ignoring --target-version spec + bad = ('bdist_wininst','any',installer_name) + if bad in dist_files: + dist_files.remove(bad) + else: + installer_name = os.path.join(self.dist_dir, + "%s.win32.exe" % fullname) + pyversion = 'any' - if self.target_version: - installer_name = os.path.join(self.dist_dir, - "%s.win32-py%s.exe" % - (fullname, self.target_version)) - pyversion = self.target_version - else: - installer_name = os.path.join(self.dist_dir, - "%s.win32.exe" % fullname) - pyversion = 'any' - - getattr(self.distribution,'dist_files',[]).append( - ('bdist_wininst', pyversion, installer_name) - ) + dist_files.append(('bdist_wininst', pyversion, installer_name)) def reinitialize_command (self, command, reinit_subcommands=0): cmd = self.distribution.reinitialize_command( From python-checkins at python.org Tue Jan 9 20:28:06 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 20:28:06 +0100 (CET) Subject: [Python-checkins] r53319 - in sandbox/branches/setuptools-0.6: setuptools.txt setuptools/command/bdist_wininst.py Message-ID: <20070109192806.7B6881E4007@bag.python.org> Author: phillip.eby Date: Tue Jan 9 20:28:05 2007 New Revision: 53319 Modified: sandbox/branches/setuptools-0.6/setuptools.txt sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py Log: Fix uploaded ``bdist_wininst`` packages being described as suitable for "any" version by Python 2.5, even if a ``--target-version`` was specified. (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 Tue Jan 9 20:28:05 2007 @@ -2604,8 +2604,10 @@ * Fix uploaded ``bdist_rpm`` packages being described as ``bdist_egg`` packages under Python versions less than 2.5. -0.6c4 + * Fix uploaded ``bdist_wininst`` packages being described as suitable for + "any" version by Python 2.5, even if a ``--target-version`` was specified. +0.6c4 * Overhauled Windows script wrapping to support ``bdist_wininst`` better. Scripts installed with ``bdist_wininst`` will always use ``#!python.exe`` or ``#!pythonw.exe`` as the executable name (even when built on non-Windows Modified: sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/bdist_wininst.py Tue Jan 9 20:28:05 2007 @@ -2,24 +2,27 @@ import os, sys class bdist_wininst(_bdist_wininst): - if sys.version<'2.5': - def create_exe(self, arcname, fullname, bitmap=None): - _bdist_wininst.create_exe(self, arcname, fullname, bitmap) + def create_exe(self, arcname, fullname, bitmap=None): + _bdist_wininst.create_exe(self, arcname, fullname, bitmap) + dist_files = getattr(self.distribution, 'dist_files', []) + + if self.target_version: + installer_name = os.path.join(self.dist_dir, + "%s.win32-py%s.exe" % + (fullname, self.target_version)) + pyversion = self.target_version + + # fix 2.5 bdist_wininst ignoring --target-version spec + bad = ('bdist_wininst','any',installer_name) + if bad in dist_files: + dist_files.remove(bad) + else: + installer_name = os.path.join(self.dist_dir, + "%s.win32.exe" % fullname) + pyversion = 'any' - if self.target_version: - installer_name = os.path.join(self.dist_dir, - "%s.win32-py%s.exe" % - (fullname, self.target_version)) - pyversion = self.target_version - else: - installer_name = os.path.join(self.dist_dir, - "%s.win32.exe" % fullname) - pyversion = 'any' - - getattr(self.distribution,'dist_files',[]).append( - ('bdist_wininst', pyversion, installer_name) - ) + dist_files.append(('bdist_wininst', pyversion, installer_name)) def reinitialize_command (self, command, reinit_subcommands=0): cmd = self.distribution.reinitialize_command( From python-checkins at python.org Tue Jan 9 20:35:21 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 20:35:21 +0100 (CET) Subject: [Python-checkins] r53320 - sandbox/branches/setuptools-0.6/ez_setup.py Message-ID: <20070109193521.D5F791E4007@bag.python.org> Author: phillip.eby Date: Tue Jan 9 20:35:20 2007 New Revision: 53320 Modified: sandbox/branches/setuptools-0.6/ez_setup.py Log: MD5's for 0.6c5 Modified: sandbox/branches/setuptools-0.6/ez_setup.py ============================================================================== --- sandbox/branches/setuptools-0.6/ez_setup.py (original) +++ sandbox/branches/setuptools-0.6/ez_setup.py Tue Jan 9 20:35:20 2007 @@ -36,6 +36,9 @@ 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', + 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', + 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', + 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', } import sys, os From python-checkins at python.org Tue Jan 9 20:52:31 2007 From: python-checkins at python.org (thomas.heller) Date: Tue, 9 Jan 2007 20:52:31 +0100 (CET) Subject: [Python-checkins] r53321 - python/branches/release25-maint/Lib/ctypes python/branches/release25-maint/Lib/ctypes/__init__.py Message-ID: <20070109195231.D59901E4007@bag.python.org> Author: thomas.heller Date: Tue Jan 9 20:52:31 2007 New Revision: 53321 Modified: python/branches/release25-maint/Lib/ctypes/ (props changed) python/branches/release25-maint/Lib/ctypes/__init__.py Log: Merged revisions 53316 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk/Lib/ctypes ........ r53316 | thomas.heller | 2007-01-09 20:19:33 +0100 (Di, 09 Jan 2007) | 4 lines Verify the sizes of the basic ctypes data types against the struct module. Backport from trunk. ........ Modified: python/branches/release25-maint/Lib/ctypes/__init__.py ============================================================================== --- python/branches/release25-maint/Lib/ctypes/__init__.py (original) +++ python/branches/release25-maint/Lib/ctypes/__init__.py Tue Jan 9 20:52:31 2007 @@ -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 = {} From python-checkins at python.org Tue Jan 9 20:57:46 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 9 Jan 2007 20:57:46 +0100 (CET) Subject: [Python-checkins] r53322 - sandbox/trunk/import_in_py/importer.py Message-ID: <20070109195746.878B81E4007@bag.python.org> Author: brett.cannon Date: Tue Jan 9 20:57:46 2007 New Revision: 53322 Modified: sandbox/trunk/import_in_py/importer.py Log: Clarify an 'if' statement in _case_ok. Modified: sandbox/trunk/import_in_py/importer.py ============================================================================== --- sandbox/trunk/import_in_py/importer.py (original) +++ sandbox/trunk/import_in_py/importer.py Tue Jan 9 20:57:46 2007 @@ -140,6 +140,10 @@ check can be part of case check and thus cut down on stat calls? """ + # If platform is not case-sensitive *or* the environment variable + # PYTHONCASEOK is defined, then os.path.exists already handled the case by + # either doing a case-sensitive check or from the user saying he does not + # want case-sensitivity, respectively. if sys.platform not in ('win32', 'mac', 'riscos', 'darwin', 'cygwin', 'os2emx') or os.environ.get('PYTHONCASEOK'): return True From python-checkins at python.org Tue Jan 9 21:59:18 2007 From: python-checkins at python.org (guido.van.rossum) Date: Tue, 9 Jan 2007 21:59:18 +0100 (CET) Subject: [Python-checkins] r53323 - in sandbox/trunk/2to3: example.py fixes/basefix.py fixes/fix_except.py refactor.py Message-ID: <20070109205918.872641E4007@bag.python.org> Author: guido.van.rossum Date: Tue Jan 9 21:59:17 2007 New Revision: 53323 Added: sandbox/trunk/2to3/fixes/fix_except.py (contents, props changed) Modified: sandbox/trunk/2to3/example.py sandbox/trunk/2to3/fixes/basefix.py sandbox/trunk/2to3/refactor.py Log: Changes by Collin Winter, with some mods: - fixer for except clause - framework for issuing warnings from fixers Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Tue Jan 9 21:59:17 2007 @@ -159,4 +159,47 @@ # x = `1, 2 + `3, 4`` +def except_examples(): + try: + pass + except Exception, e: + pass + # + try: + pass + except (RuntimeError, ImportError), e: + pass + # + # These should not be touched + # + try: + pass + except Exception, (a, b): + pass + # + try: + pass + except Exception, d[5]: + pass + # + try: + pass + except Exception, a.foo: + pass + # + try: + pass + except Exception, a().foo: + pass + # + try: + pass + except Exception: + pass + # + try: + pass + except (RuntimeError, ImportError): + pass + # This is the last line. Modified: sandbox/trunk/2to3/fixes/basefix.py ============================================================================== --- sandbox/trunk/2to3/fixes/basefix.py (original) +++ sandbox/trunk/2to3/fixes/basefix.py Tue Jan 9 21:59:17 2007 @@ -3,6 +3,9 @@ """Base class for fixers (optional, but recommended).""" +# Python imports +import logging + # Local imports import patcomp import pygram @@ -21,6 +24,8 @@ PATTERN = None # Subclass *must* override with a string literal pattern = None # Compiled pattern, set by compile_pattern() options = None # Options object passed to initializer + filename = None # The filename (set by set_filename) + logger = None # A logger (set by set_filename) # Shortcut for access to Python grammar symbols syms = pygram.python_symbols @@ -42,6 +47,14 @@ """ self.pattern = patcomp.PatternCompiler().compile_pattern(self.PATTERN) + def set_filename(self, filename): + """Set the filename, and a logger derived from it. + + The main refactoring tool should call this. + """ + self.filename = filename + self.logger = logging.getLogger(filename) + def match(self, node): """Returns match for a given parse tree node. Added: sandbox/trunk/2to3/fixes/fix_except.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/fix_except.py Tue Jan 9 21:59:17 2007 @@ -0,0 +1,46 @@ +"""Fixer for except statements with named exceptions.""" + +# Python imports +import token + +# Local imports +import pytree +from fixes import basefix + +def get_lineno(node): + while not isinstance(node, pytree.Leaf): + if not node.children: + return + node = node.children[0] + return node.lineno + +class FixExcept(basefix.BaseFix): + + PATTERN = """ + except_clause< 'except' a=any ',' b=any > + """ + + def transform(self, node): + syms = self.syms + results = self.match(node) + assert results + + a = results["a"].clone() + b = results["b"].clone() + + if b.type != token.NAME: + lineno = get_lineno(node) + self.logger.warning("At line %s, unable to transform: %s" % + (lineno, node)) + return node + + as_leaf = pytree.Leaf(token.NAME, "as") + as_leaf.set_prefix(' ') + + new = pytree.Node(syms.except_clause, + [pytree.Leaf(token.NAME, "except"), + pytree.Node(syms.test, [a]), + as_leaf, + pytree.Node(syms.test, [b])]) + new.set_prefix(node.get_prefix()) + return new Modified: sandbox/trunk/2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/refactor.py (original) +++ sandbox/trunk/2to3/refactor.py Tue Jan 9 21:59:17 2007 @@ -17,6 +17,7 @@ import sys import difflib import optparse +import logging # Local imports import pytree @@ -25,6 +26,7 @@ import fixes import pygram +logging.basicConfig(format='%(name)s: %(message)s', level=logging.INFO) def main(args=None): """Main program. @@ -90,8 +92,10 @@ """ self.options = options self.errors = 0 + self.logger = logging.getLogger("RefactoringTool") self.driver = driver.Driver(pygram.python_grammar, - convert=pytree.convert) + convert=pytree.convert, + logger=self.logger) self.fixers = self.get_fixers() self.files = [] # List of files that were or should be modified @@ -129,13 +133,13 @@ def log_error(self, msg, *args): """Increments error count and log a message.""" self.errors += 1 - self.log_message(msg, *args) + self.logger.error(msg, *args) def log_message(self, msg, *args): """Hook to log a message.""" if args: msg = msg % args - print >>sys.stderr, msg + self.logger.info(msg) def refactor_args(self, args): """Refactors files and directories from an argument list.""" @@ -180,15 +184,17 @@ return if self.options.verbose: self.log_message("Refactoring %s", filename) - if self.refactor_tree(tree): + if self.refactor_tree(tree, filename): self.write_tree(tree, filename) elif self.options.verbose: self.log_message("No changes in %s", filename) finally: f.close() - def refactor_tree(self, tree): + def refactor_tree(self, tree, filename): """Refactors a parse tree.""" + for fixer in self.fixers: + fixer.set_filename(filename) changes = 0 for node in tree.post_order(): for fixer in self.fixers: From python-checkins at python.org Tue Jan 9 23:07:19 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 9 Jan 2007 23:07:19 +0100 (CET) Subject: [Python-checkins] r53324 - peps/trunk/pep-3108.txt Message-ID: <20070109220719.B67F01E4007@bag.python.org> Author: brett.cannon Date: Tue Jan 9 23:07:19 2007 New Revision: 53324 Modified: peps/trunk/pep-3108.txt Log: Flesh out platform-specific package suggestions. ALso add some comments on other packages. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Tue Jan 9 23:07:19 2007 @@ -511,7 +511,7 @@ shallow. No specific package name is proposed, just what modules could go into the package. -* collections +* 'collections' package + heapq + Queue @@ -527,8 +527,32 @@ * Platform-specific - + All platform-specific modules should be placed in a package - representing the platform. + + windows + + - _winreg + - msilib + - msvcrt + - winsound + + + unix + + - crypt + - dbm + - fcntl + - fpectl + - gdbm + - grp + - nis + - pipes + - pwd + - readline (?) + - resource + - spwd + - syslog + - termios (?) + - tty (?) + + - mac (all Mac-specific modules) * Profiling @@ -537,7 +561,7 @@ + hotshot + pstats -* email +* 'email' package + imaplib + mailbox @@ -572,7 +596,8 @@ + SimpleXMLRPCServer + xmlrpclib -* Internet +* Internet (leaving out all questionable modules leads to a Web + grouping) + BaseHTTPServer + cgi @@ -617,6 +642,7 @@ + codeop + compiler + + dis + py_compile + compileall @@ -626,7 +652,7 @@ + gzip + zlib -* Date and time +* Date & time + calendar + datetime From python-checkins at python.org Tue Jan 9 23:23:02 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 23:23:02 +0100 (CET) Subject: [Python-checkins] r53325 - sandbox/branches/setuptools-0.6/setuptools/command/bdist_rpm.py Message-ID: <20070109222302.6C0DD1E4007@bag.python.org> Author: phillip.eby Date: Tue Jan 9 23:23:01 2007 New Revision: 53325 Modified: sandbox/branches/setuptools-0.6/setuptools/command/bdist_rpm.py Log: Fix missing backport of import fix for bdist_rpm building non-source rpms. Modified: sandbox/branches/setuptools-0.6/setuptools/command/bdist_rpm.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/command/bdist_rpm.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/command/bdist_rpm.py Tue Jan 9 23:23:01 2007 @@ -19,7 +19,7 @@ if dst==self.dist_dir and src.endswith('.rpm'): getattr(self.distribution,'dist_files',[]).append( ('bdist_rpm', - src.endswith('.src.rpm') and 'any' or get_python_version(), + src.endswith('.src.rpm') and 'any' or sys.version[:3], os.path.join(dst, os.path.basename(src))) ) From python-checkins at python.org Tue Jan 9 23:23:58 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 23:23:58 +0100 (CET) Subject: [Python-checkins] r53326 - in sandbox/branches/setuptools-0.6: ez_setup.py release.sh setup.py setuptools/__init__.py version.dat Message-ID: <20070109222358.B7E461E4007@bag.python.org> Author: phillip.eby Date: Tue Jan 9 23:23:58 2007 New Revision: 53326 Modified: sandbox/branches/setuptools-0.6/ez_setup.py sandbox/branches/setuptools-0.6/release.sh sandbox/branches/setuptools-0.6/setup.py sandbox/branches/setuptools-0.6/setuptools/__init__.py sandbox/branches/setuptools-0.6/version.dat Log: Bump to 0.6c6. :( Modified: sandbox/branches/setuptools-0.6/ez_setup.py ============================================================================== --- sandbox/branches/setuptools-0.6/ez_setup.py (original) +++ sandbox/branches/setuptools-0.6/ez_setup.py Tue Jan 9 23:23:58 2007 @@ -14,7 +14,7 @@ This file can also be run as a script to install or upgrade setuptools. """ import sys -DEFAULT_VERSION = "0.6c5" +DEFAULT_VERSION = "0.6c6" DEFAULT_URL = "http://cheeseshop.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { Modified: sandbox/branches/setuptools-0.6/release.sh ============================================================================== --- sandbox/branches/setuptools-0.6/release.sh (original) +++ sandbox/branches/setuptools-0.6/release.sh Tue Jan 9 23:23:58 2007 @@ -7,7 +7,7 @@ # If your initials aren't PJE, don't run it. :) # -export VERSION="0.6c5" +export VERSION="0.6c6" python2.3 setup.py -q release source --target-version=2.3 upload && \ python2.4 setup.py -q release binary --target-version=2.4 upload && \ Modified: sandbox/branches/setuptools-0.6/setup.py ============================================================================== --- sandbox/branches/setuptools-0.6/setup.py (original) +++ sandbox/branches/setuptools-0.6/setup.py Tue Jan 9 23:23:58 2007 @@ -7,7 +7,7 @@ execfile(convert_path('setuptools/command/__init__.py'), d) SETUP_COMMANDS = d['__all__'] -VERSION = "0.6c5" +VERSION = "0.6c6" from setuptools import setup, find_packages import sys Modified: sandbox/branches/setuptools-0.6/setuptools/__init__.py ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools/__init__.py (original) +++ sandbox/branches/setuptools-0.6/setuptools/__init__.py Tue Jan 9 23:23:58 2007 @@ -7,7 +7,7 @@ from distutils.util import convert_path import os.path -__version__ = '0.6c5' +__version__ = '0.6c6' __all__ = [ 'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require', 'find_packages' Modified: sandbox/branches/setuptools-0.6/version.dat ============================================================================== --- sandbox/branches/setuptools-0.6/version.dat (original) +++ sandbox/branches/setuptools-0.6/version.dat Tue Jan 9 23:23:58 2007 @@ -1,6 +1,6 @@ [setuptools] status = 'release candidate' major = 0 -build = 5 +build = 6 minor = 6 From python-checkins at python.org Tue Jan 9 23:24:14 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 9 Jan 2007 23:24:14 +0100 (CET) Subject: [Python-checkins] r53327 - peps/trunk/pep-3108.txt Message-ID: <20070109222414.904861E4007@bag.python.org> Author: brett.cannon Date: Tue Jan 9 23:24:14 2007 New Revision: 53327 Modified: peps/trunk/pep-3108.txt Log: Add 'sets' to the suggested package of Python implemented built-in types. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Tue Jan 9 23:24:14 2007 @@ -521,6 +521,7 @@ * Python implementations of built-in data types + + sets + UserDict + UserList + UserString From python-checkins at python.org Tue Jan 9 23:24:44 2007 From: python-checkins at python.org (phillip.eby) Date: Tue, 9 Jan 2007 23:24:44 +0100 (CET) Subject: [Python-checkins] r53328 - sandbox/branches/setuptools-0.6/setuptools.txt Message-ID: <20070109222444.242001E4007@bag.python.org> Author: phillip.eby Date: Tue Jan 9 23:24:43 2007 New Revision: 53328 Modified: sandbox/branches/setuptools-0.6/setuptools.txt Log: Update release notes. Modified: sandbox/branches/setuptools-0.6/setuptools.txt ============================================================================== --- sandbox/branches/setuptools-0.6/setuptools.txt (original) +++ sandbox/branches/setuptools-0.6/setuptools.txt Tue Jan 9 23:24:43 2007 @@ -2600,6 +2600,9 @@ Release Notes/Change History ---------------------------- +0.6c6 + * Fix not building binary RPMs correctly. + 0.6c5 * Fix uploaded ``bdist_rpm`` packages being described as ``bdist_egg`` packages under Python versions less than 2.5. From python-checkins at python.org Tue Jan 9 23:28:17 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 9 Jan 2007 23:28:17 +0100 (CET) Subject: [Python-checkins] r53329 - in python/branches/bcannon-objcap: Demo/parser/unparse.py Doc/README Doc/api/concrete.tex Doc/api/exceptions.tex Doc/api/newtypes.tex Doc/dist/dist.tex Doc/ext/extending.tex Doc/howto/functional.rst Doc/howto/regex.tex Doc/inst/inst.tex Doc/lib/libasyncore.tex Doc/lib/libatexit.tex Doc/lib/libbase64.tex Doc/lib/libbsddb.tex Doc/lib/libbz2.tex Doc/lib/libcfgparser.tex Doc/lib/libcommands.tex Doc/lib/libcsv.tex Doc/lib/libctypes.tex Doc/lib/libdatetime.tex Doc/lib/libfpectl.tex Doc/lib/libfuncs.tex Doc/lib/libgetopt.tex Doc/lib/libheapq.tex Doc/lib/libhttplib.tex Doc/lib/libimp.tex Doc/lib/libitertools.tex Doc/lib/liblogging.tex Doc/lib/libmmap.tex Doc/lib/libmsilib.tex Doc/lib/libos.tex Doc/lib/libpickle.tex Doc/lib/libpopen2.tex Doc/lib/libsimplexmlrpc.tex Doc/lib/libsmtplib.tex Doc/lib/libsocket.tex Doc/lib/libsqlite3.tex Doc/lib/libstdtypes.tex Doc/lib/libstring.tex Doc/lib/libsubprocess.tex Doc/lib/libtarfile.tex Doc/lib/libtempfile.tex Doc/lib/libtest.tex Doc/lib/liburlparse.tex Doc/lib/libwsgiref.tex Doc/lib/libxmlrpclib.tex Doc/lib/tkinter.tex Doc/mac/toolbox.tex Doc/ref/ref3.tex Doc/tools/py2texi.el Doc/tut/tut.tex Doc/whatsnew/whatsnew25.tex Doc/whatsnew/whatsnew26.tex Include/abstract.h Include/modsupport.h Include/pyport.h LICENSE Lib/CGIHTTPServer.py Lib/ConfigParser.py Lib/Queue.py Lib/SimpleHTTPServer.py Lib/StringIO.py Lib/_strptime.py Lib/atexit.py Lib/base64.py Lib/bsddb/dbobj.py Lib/bsddb/test/test_1413192.py Lib/bsddb/test/test_associate.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_dbobj.py Lib/bsddb/test/test_dbshelve.py Lib/bsddb/test/test_dbtables.py Lib/bsddb/test/test_env_close.py Lib/bsddb/test/test_join.py Lib/bsddb/test/test_lock.py Lib/bsddb/test/test_misc.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_thread.py Lib/cgi.py Lib/codecs.py Lib/colorsys.py Lib/compiler/pycodegen.py Lib/cookielib.py Lib/ctypes/__init__.py Lib/ctypes/test/__init__.py Lib/ctypes/test/test_callbacks.py Lib/ctypes/test/test_structures.py Lib/difflib.py Lib/distutils/command/bdist_rpm.py Lib/distutils/command/build_ext.py Lib/distutils/command/install_egg_info.py Lib/distutils/command/register.py Lib/distutils/command/wininst-8.exe Lib/distutils/sysconfig.py Lib/distutils/unixccompiler.py Lib/dumbdbm.py Lib/email/utils.py Lib/encodings/__init__.py Lib/encodings/bz2_codec.py Lib/encodings/utf_8_sig.py Lib/encodings/zlib_codec.py Lib/ftplib.py Lib/functools.py Lib/gzip.py Lib/hashlib.py Lib/heapq.py Lib/hmac.py Lib/httplib.py Lib/idlelib/AutoCompleteWindow.py Lib/idlelib/CodeContext.py Lib/idlelib/EditorWindow.py Lib/idlelib/NEWS.txt Lib/idlelib/PyShell.py Lib/idlelib/ScriptBinding.py Lib/inspect.py Lib/lib-tk/Tix.py Lib/lib-tk/Tkinter.py Lib/lib-tk/tkMessageBox.py Lib/lib-tk/tkSimpleDialog.py Lib/lib-tk/turtle.py Lib/logging/__init__.py Lib/logging/config.py Lib/logging/handlers.py Lib/mailbox.py Lib/modulefinder.py Lib/os.py Lib/posixpath.py Lib/pstats.py Lib/pty.py Lib/pyclbr.py Lib/pydoc.py Lib/random.py Lib/smtplib.py Lib/sre_parse.py Lib/subprocess.py Lib/tarfile.py Lib/test/README Lib/test/list_tests.py Lib/test/output/test_MimeWriter Lib/test/output/test_cgi Lib/test/output/test_cookie Lib/test/output/test_global Lib/test/output/test_grammar Lib/test/output/test_httplib Lib/test/output/test_math Lib/test/output/test_mmap Lib/test/output/test_nis Lib/test/output/test_opcodes Lib/test/output/test_openpty Lib/test/output/test_poll Lib/test/output/test_regex Lib/test/output/test_scope Lib/test/output/test_types Lib/test/output/test_xdrlib Lib/test/outstanding_bugs.py Lib/test/test_MimeWriter.py Lib/test/test_StringIO.py Lib/test/test___future__.py Lib/test/test_binascii.py Lib/test/test_bufio.py Lib/test/test_builtin.py Lib/test/test_cfgparser.py Lib/test/test_cgi.py Lib/test/test_class.py Lib/test/test_codecs.py Lib/test/test_compile.py Lib/test/test_cookie.py Lib/test/test_datetime.py Lib/test/test_deque.py Lib/test/test_descr.py Lib/test/test_dict.py Lib/test/test_dumbdbm.py Lib/test/test_exceptions.py Lib/test/test_format.py Lib/test/test_functools.py Lib/test/test_global.py Lib/test/test_grammar.py Lib/test/test_gzip.py Lib/test/test_heapq.py Lib/test/test_httplib.py Lib/test/test_imp.py Lib/test/test_import.py Lib/test/test_long.py Lib/test/test_mailbox.py Lib/test/test_math.py Lib/test/test_mmap.py Lib/test/test_modulefinder.py Lib/test/test_multibytecodec.py Lib/test/test_new.py Lib/test/test_nis.py Lib/test/test_opcodes.py Lib/test/test_openpty.py Lib/test/test_os.py Lib/test/test_peepholer.py Lib/test/test_poll.py Lib/test/test_pty.py Lib/test/test_pyclbr.py Lib/test/test_random.py Lib/test/test_repr.py Lib/test/test_scope.py Lib/test/test_set.py Lib/test/test_sha.py Lib/test/test_struct.py Lib/test/test_structmembers.py Lib/test/test_support.py Lib/test/test_syntax.py Lib/test/test_tarfile.py Lib/test/test_types.py Lib/test/test_uu.py Lib/test/test_weakref.py Lib/test/test_xdrlib.py Lib/test/test_xmlrpc.py Lib/threading.py Lib/tokenize.py Lib/urllib.py Lib/urllib2.py Lib/uu.py Lib/webbrowser.py Lib/xdrlib.py Lib/xmlrpclib.py Mac/BuildScript/build-installer.py Mac/BuildScript/scripts/postflight.documentation Mac/BuildScript/scripts/postflight.patch-profile Mac/PythonLauncher/FileSettings.m Makefile.pre.in Misc/ACKS Misc/NEWS Misc/SpecialBuilds.txt Misc/developers.txt Modules/_bsddb.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c Modules/_ctypes/libffi/src/x86/sysv.S Modules/_ctypes/stgdict.c Modules/_sre.c Modules/_ssl.c Modules/_testcapimodule.c Modules/audioop.c Modules/binascii.c Modules/bz2module.c Modules/cPickle.c Modules/cStringIO.c Modules/cjkcodecs/_codecs_iso2022.c Modules/collectionsmodule.c Modules/datetimemodule.c Modules/dbmmodule.c Modules/gcmodule.c Modules/linuxaudiodev.c Modules/main.c Modules/mathmodule.c Modules/ossaudiodev.c Modules/posixmodule.c Modules/socketmodule.c Modules/socketmodule.h Modules/threadmodule.c Modules/timemodule.c Modules/unicodedata.c Objects/abstract.c Objects/classobject.c Objects/dictnotes.txt Objects/dictobject.c Objects/exceptions.c Objects/fileobject.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/obmalloc.c Objects/setobject.c Objects/stringobject.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodeobject.c PC/VC6/_bsddb.dsp PC/VC6/_ctypes.dsp PC/VC6/_ctypes_test.dsp PC/VC6/_elementtree.dsp PC/VC6/_socket.dsp PC/VC6/_sqlite3.dsp PC/VC6/_ssl.dsp PC/VC6/_ssl.mak PC/VC6/_testcapi.dsp PC/VC6/_tkinter.dsp PC/VC6/bz2.dsp PC/VC6/make_versioninfo.dsp PC/VC6/pcbuild.dsw PC/VC6/pyexpat.dsp PC/VC6/python.dsp PC/VC6/pythoncore.dsp PC/VC6/pythonw.dsp PC/VC6/readme.txt PC/VC6/select.dsp PC/VC6/unicodedata.dsp PC/VC6/w9xpopen.dsp PC/VC6/winsound.dsp PC/VC6/zlib.dsp PC/_msi.c PC/bdist_wininst/wininst-8.sln PC/bdist_wininst/wininst-8.vcproj PC/pyconfig.h PC/python_nt.rc PCbuild/python20.wse PCbuild/pythoncore.vcproj PCbuild8/python20.wse Parser/tokenizer.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/compile.c Python/errors.c Python/getargs.c Python/getcopyright.c Python/import.c Python/marshal.c Python/modsupport.c Python/mystrtoul.c Python/peephole.c Python/structmember.c Python/sysmodule.c README Tools/msi/uuids.py Tools/scripts/findnocoding.py Tools/scripts/pysource.py configure configure.in pyconfig.h.in setup.py Message-ID: <20070109222817.7C3341E4007@bag.python.org> Author: brett.cannon Date: Tue Jan 9 23:27:11 2007 New Revision: 53329 Added: python/branches/bcannon-objcap/Lib/distutils/command/wininst-8.exe - copied unchanged from r53316, python/trunk/Lib/distutils/command/wininst-8.exe python/branches/bcannon-objcap/Lib/test/test_modulefinder.py - copied unchanged from r53316, python/trunk/Lib/test/test_modulefinder.py python/branches/bcannon-objcap/Lib/test/test_structmembers.py - copied unchanged from r53316, python/trunk/Lib/test/test_structmembers.py python/branches/bcannon-objcap/PC/VC6/_ctypes.dsp - copied unchanged from r53316, python/trunk/PC/VC6/_ctypes.dsp python/branches/bcannon-objcap/PC/VC6/_ctypes_test.dsp - copied unchanged from r53316, python/trunk/PC/VC6/_ctypes_test.dsp python/branches/bcannon-objcap/PC/VC6/_elementtree.dsp - copied unchanged from r53316, python/trunk/PC/VC6/_elementtree.dsp python/branches/bcannon-objcap/PC/VC6/_sqlite3.dsp - copied unchanged from r53316, python/trunk/PC/VC6/_sqlite3.dsp python/branches/bcannon-objcap/PC/bdist_wininst/wininst-8.sln - copied unchanged from r53316, python/trunk/PC/bdist_wininst/wininst-8.sln python/branches/bcannon-objcap/PC/bdist_wininst/wininst-8.vcproj - copied unchanged from r53316, python/trunk/PC/bdist_wininst/wininst-8.vcproj Removed: python/branches/bcannon-objcap/Lib/test/output/test_MimeWriter python/branches/bcannon-objcap/Lib/test/output/test_cgi python/branches/bcannon-objcap/Lib/test/output/test_cookie python/branches/bcannon-objcap/Lib/test/output/test_global python/branches/bcannon-objcap/Lib/test/output/test_grammar python/branches/bcannon-objcap/Lib/test/output/test_httplib python/branches/bcannon-objcap/Lib/test/output/test_math python/branches/bcannon-objcap/Lib/test/output/test_mmap python/branches/bcannon-objcap/Lib/test/output/test_nis python/branches/bcannon-objcap/Lib/test/output/test_opcodes python/branches/bcannon-objcap/Lib/test/output/test_openpty python/branches/bcannon-objcap/Lib/test/output/test_poll python/branches/bcannon-objcap/Lib/test/output/test_regex python/branches/bcannon-objcap/Lib/test/output/test_scope python/branches/bcannon-objcap/Lib/test/output/test_types python/branches/bcannon-objcap/Lib/test/output/test_xdrlib python/branches/bcannon-objcap/PC/VC6/zlib.dsp Modified: python/branches/bcannon-objcap/ (props changed) python/branches/bcannon-objcap/Demo/parser/unparse.py python/branches/bcannon-objcap/Doc/README python/branches/bcannon-objcap/Doc/api/concrete.tex python/branches/bcannon-objcap/Doc/api/exceptions.tex python/branches/bcannon-objcap/Doc/api/newtypes.tex python/branches/bcannon-objcap/Doc/dist/dist.tex python/branches/bcannon-objcap/Doc/ext/extending.tex python/branches/bcannon-objcap/Doc/howto/functional.rst python/branches/bcannon-objcap/Doc/howto/regex.tex python/branches/bcannon-objcap/Doc/inst/inst.tex python/branches/bcannon-objcap/Doc/lib/libasyncore.tex python/branches/bcannon-objcap/Doc/lib/libatexit.tex python/branches/bcannon-objcap/Doc/lib/libbase64.tex python/branches/bcannon-objcap/Doc/lib/libbsddb.tex python/branches/bcannon-objcap/Doc/lib/libbz2.tex python/branches/bcannon-objcap/Doc/lib/libcfgparser.tex python/branches/bcannon-objcap/Doc/lib/libcommands.tex python/branches/bcannon-objcap/Doc/lib/libcsv.tex python/branches/bcannon-objcap/Doc/lib/libctypes.tex python/branches/bcannon-objcap/Doc/lib/libdatetime.tex python/branches/bcannon-objcap/Doc/lib/libfpectl.tex python/branches/bcannon-objcap/Doc/lib/libfuncs.tex python/branches/bcannon-objcap/Doc/lib/libgetopt.tex python/branches/bcannon-objcap/Doc/lib/libheapq.tex python/branches/bcannon-objcap/Doc/lib/libhttplib.tex python/branches/bcannon-objcap/Doc/lib/libimp.tex python/branches/bcannon-objcap/Doc/lib/libitertools.tex python/branches/bcannon-objcap/Doc/lib/liblogging.tex python/branches/bcannon-objcap/Doc/lib/libmmap.tex python/branches/bcannon-objcap/Doc/lib/libmsilib.tex python/branches/bcannon-objcap/Doc/lib/libos.tex python/branches/bcannon-objcap/Doc/lib/libpickle.tex python/branches/bcannon-objcap/Doc/lib/libpopen2.tex python/branches/bcannon-objcap/Doc/lib/libsimplexmlrpc.tex python/branches/bcannon-objcap/Doc/lib/libsmtplib.tex python/branches/bcannon-objcap/Doc/lib/libsocket.tex python/branches/bcannon-objcap/Doc/lib/libsqlite3.tex python/branches/bcannon-objcap/Doc/lib/libstdtypes.tex python/branches/bcannon-objcap/Doc/lib/libstring.tex python/branches/bcannon-objcap/Doc/lib/libsubprocess.tex python/branches/bcannon-objcap/Doc/lib/libtarfile.tex python/branches/bcannon-objcap/Doc/lib/libtempfile.tex python/branches/bcannon-objcap/Doc/lib/libtest.tex python/branches/bcannon-objcap/Doc/lib/liburlparse.tex python/branches/bcannon-objcap/Doc/lib/libwsgiref.tex python/branches/bcannon-objcap/Doc/lib/libxmlrpclib.tex python/branches/bcannon-objcap/Doc/lib/tkinter.tex python/branches/bcannon-objcap/Doc/mac/toolbox.tex python/branches/bcannon-objcap/Doc/ref/ref3.tex python/branches/bcannon-objcap/Doc/tools/py2texi.el python/branches/bcannon-objcap/Doc/tut/tut.tex python/branches/bcannon-objcap/Doc/whatsnew/whatsnew25.tex python/branches/bcannon-objcap/Doc/whatsnew/whatsnew26.tex (contents, props changed) python/branches/bcannon-objcap/Include/abstract.h python/branches/bcannon-objcap/Include/modsupport.h python/branches/bcannon-objcap/Include/pyport.h python/branches/bcannon-objcap/LICENSE python/branches/bcannon-objcap/Lib/CGIHTTPServer.py python/branches/bcannon-objcap/Lib/ConfigParser.py python/branches/bcannon-objcap/Lib/Queue.py python/branches/bcannon-objcap/Lib/SimpleHTTPServer.py python/branches/bcannon-objcap/Lib/StringIO.py python/branches/bcannon-objcap/Lib/_strptime.py python/branches/bcannon-objcap/Lib/atexit.py python/branches/bcannon-objcap/Lib/base64.py python/branches/bcannon-objcap/Lib/bsddb/dbobj.py python/branches/bcannon-objcap/Lib/bsddb/test/test_1413192.py python/branches/bcannon-objcap/Lib/bsddb/test/test_associate.py python/branches/bcannon-objcap/Lib/bsddb/test/test_basics.py python/branches/bcannon-objcap/Lib/bsddb/test/test_dbobj.py python/branches/bcannon-objcap/Lib/bsddb/test/test_dbshelve.py python/branches/bcannon-objcap/Lib/bsddb/test/test_dbtables.py python/branches/bcannon-objcap/Lib/bsddb/test/test_env_close.py python/branches/bcannon-objcap/Lib/bsddb/test/test_join.py python/branches/bcannon-objcap/Lib/bsddb/test/test_lock.py python/branches/bcannon-objcap/Lib/bsddb/test/test_misc.py python/branches/bcannon-objcap/Lib/bsddb/test/test_recno.py python/branches/bcannon-objcap/Lib/bsddb/test/test_thread.py python/branches/bcannon-objcap/Lib/cgi.py python/branches/bcannon-objcap/Lib/codecs.py python/branches/bcannon-objcap/Lib/colorsys.py python/branches/bcannon-objcap/Lib/compiler/pycodegen.py python/branches/bcannon-objcap/Lib/cookielib.py python/branches/bcannon-objcap/Lib/ctypes/__init__.py python/branches/bcannon-objcap/Lib/ctypes/test/__init__.py python/branches/bcannon-objcap/Lib/ctypes/test/test_callbacks.py python/branches/bcannon-objcap/Lib/ctypes/test/test_structures.py python/branches/bcannon-objcap/Lib/difflib.py python/branches/bcannon-objcap/Lib/distutils/command/bdist_rpm.py python/branches/bcannon-objcap/Lib/distutils/command/build_ext.py python/branches/bcannon-objcap/Lib/distutils/command/install_egg_info.py python/branches/bcannon-objcap/Lib/distutils/command/register.py python/branches/bcannon-objcap/Lib/distutils/sysconfig.py python/branches/bcannon-objcap/Lib/distutils/unixccompiler.py python/branches/bcannon-objcap/Lib/dumbdbm.py python/branches/bcannon-objcap/Lib/email/utils.py python/branches/bcannon-objcap/Lib/encodings/__init__.py python/branches/bcannon-objcap/Lib/encodings/bz2_codec.py python/branches/bcannon-objcap/Lib/encodings/utf_8_sig.py python/branches/bcannon-objcap/Lib/encodings/zlib_codec.py python/branches/bcannon-objcap/Lib/ftplib.py python/branches/bcannon-objcap/Lib/functools.py python/branches/bcannon-objcap/Lib/gzip.py python/branches/bcannon-objcap/Lib/hashlib.py python/branches/bcannon-objcap/Lib/heapq.py python/branches/bcannon-objcap/Lib/hmac.py python/branches/bcannon-objcap/Lib/httplib.py python/branches/bcannon-objcap/Lib/idlelib/AutoCompleteWindow.py python/branches/bcannon-objcap/Lib/idlelib/CodeContext.py python/branches/bcannon-objcap/Lib/idlelib/EditorWindow.py python/branches/bcannon-objcap/Lib/idlelib/NEWS.txt python/branches/bcannon-objcap/Lib/idlelib/PyShell.py python/branches/bcannon-objcap/Lib/idlelib/ScriptBinding.py python/branches/bcannon-objcap/Lib/inspect.py python/branches/bcannon-objcap/Lib/lib-tk/Tix.py python/branches/bcannon-objcap/Lib/lib-tk/Tkinter.py python/branches/bcannon-objcap/Lib/lib-tk/tkMessageBox.py python/branches/bcannon-objcap/Lib/lib-tk/tkSimpleDialog.py python/branches/bcannon-objcap/Lib/lib-tk/turtle.py python/branches/bcannon-objcap/Lib/logging/__init__.py python/branches/bcannon-objcap/Lib/logging/config.py python/branches/bcannon-objcap/Lib/logging/handlers.py python/branches/bcannon-objcap/Lib/mailbox.py python/branches/bcannon-objcap/Lib/modulefinder.py python/branches/bcannon-objcap/Lib/os.py python/branches/bcannon-objcap/Lib/posixpath.py python/branches/bcannon-objcap/Lib/pstats.py python/branches/bcannon-objcap/Lib/pty.py python/branches/bcannon-objcap/Lib/pyclbr.py python/branches/bcannon-objcap/Lib/pydoc.py python/branches/bcannon-objcap/Lib/random.py python/branches/bcannon-objcap/Lib/smtplib.py python/branches/bcannon-objcap/Lib/sre_parse.py python/branches/bcannon-objcap/Lib/subprocess.py python/branches/bcannon-objcap/Lib/tarfile.py python/branches/bcannon-objcap/Lib/test/README python/branches/bcannon-objcap/Lib/test/list_tests.py python/branches/bcannon-objcap/Lib/test/outstanding_bugs.py python/branches/bcannon-objcap/Lib/test/test_MimeWriter.py python/branches/bcannon-objcap/Lib/test/test_StringIO.py python/branches/bcannon-objcap/Lib/test/test___future__.py python/branches/bcannon-objcap/Lib/test/test_binascii.py python/branches/bcannon-objcap/Lib/test/test_bufio.py python/branches/bcannon-objcap/Lib/test/test_builtin.py python/branches/bcannon-objcap/Lib/test/test_cfgparser.py python/branches/bcannon-objcap/Lib/test/test_cgi.py python/branches/bcannon-objcap/Lib/test/test_class.py python/branches/bcannon-objcap/Lib/test/test_codecs.py python/branches/bcannon-objcap/Lib/test/test_compile.py python/branches/bcannon-objcap/Lib/test/test_cookie.py python/branches/bcannon-objcap/Lib/test/test_datetime.py python/branches/bcannon-objcap/Lib/test/test_deque.py python/branches/bcannon-objcap/Lib/test/test_descr.py python/branches/bcannon-objcap/Lib/test/test_dict.py python/branches/bcannon-objcap/Lib/test/test_dumbdbm.py python/branches/bcannon-objcap/Lib/test/test_exceptions.py python/branches/bcannon-objcap/Lib/test/test_format.py python/branches/bcannon-objcap/Lib/test/test_functools.py python/branches/bcannon-objcap/Lib/test/test_global.py python/branches/bcannon-objcap/Lib/test/test_grammar.py python/branches/bcannon-objcap/Lib/test/test_gzip.py python/branches/bcannon-objcap/Lib/test/test_heapq.py python/branches/bcannon-objcap/Lib/test/test_httplib.py python/branches/bcannon-objcap/Lib/test/test_imp.py python/branches/bcannon-objcap/Lib/test/test_import.py python/branches/bcannon-objcap/Lib/test/test_long.py python/branches/bcannon-objcap/Lib/test/test_mailbox.py python/branches/bcannon-objcap/Lib/test/test_math.py python/branches/bcannon-objcap/Lib/test/test_mmap.py python/branches/bcannon-objcap/Lib/test/test_multibytecodec.py python/branches/bcannon-objcap/Lib/test/test_new.py python/branches/bcannon-objcap/Lib/test/test_nis.py python/branches/bcannon-objcap/Lib/test/test_opcodes.py python/branches/bcannon-objcap/Lib/test/test_openpty.py python/branches/bcannon-objcap/Lib/test/test_os.py python/branches/bcannon-objcap/Lib/test/test_peepholer.py python/branches/bcannon-objcap/Lib/test/test_poll.py python/branches/bcannon-objcap/Lib/test/test_pty.py python/branches/bcannon-objcap/Lib/test/test_pyclbr.py python/branches/bcannon-objcap/Lib/test/test_random.py python/branches/bcannon-objcap/Lib/test/test_repr.py python/branches/bcannon-objcap/Lib/test/test_scope.py python/branches/bcannon-objcap/Lib/test/test_set.py python/branches/bcannon-objcap/Lib/test/test_sha.py python/branches/bcannon-objcap/Lib/test/test_struct.py python/branches/bcannon-objcap/Lib/test/test_support.py python/branches/bcannon-objcap/Lib/test/test_syntax.py python/branches/bcannon-objcap/Lib/test/test_tarfile.py python/branches/bcannon-objcap/Lib/test/test_types.py python/branches/bcannon-objcap/Lib/test/test_uu.py python/branches/bcannon-objcap/Lib/test/test_weakref.py python/branches/bcannon-objcap/Lib/test/test_xdrlib.py python/branches/bcannon-objcap/Lib/test/test_xmlrpc.py python/branches/bcannon-objcap/Lib/threading.py python/branches/bcannon-objcap/Lib/tokenize.py python/branches/bcannon-objcap/Lib/urllib.py python/branches/bcannon-objcap/Lib/urllib2.py python/branches/bcannon-objcap/Lib/uu.py python/branches/bcannon-objcap/Lib/webbrowser.py python/branches/bcannon-objcap/Lib/xdrlib.py python/branches/bcannon-objcap/Lib/xmlrpclib.py python/branches/bcannon-objcap/Mac/BuildScript/build-installer.py python/branches/bcannon-objcap/Mac/BuildScript/scripts/postflight.documentation python/branches/bcannon-objcap/Mac/BuildScript/scripts/postflight.patch-profile python/branches/bcannon-objcap/Mac/PythonLauncher/FileSettings.m python/branches/bcannon-objcap/Makefile.pre.in python/branches/bcannon-objcap/Misc/ACKS python/branches/bcannon-objcap/Misc/NEWS python/branches/bcannon-objcap/Misc/SpecialBuilds.txt python/branches/bcannon-objcap/Misc/developers.txt python/branches/bcannon-objcap/Modules/_bsddb.c python/branches/bcannon-objcap/Modules/_ctypes/callbacks.c python/branches/bcannon-objcap/Modules/_ctypes/callproc.c python/branches/bcannon-objcap/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c python/branches/bcannon-objcap/Modules/_ctypes/libffi/src/x86/sysv.S python/branches/bcannon-objcap/Modules/_ctypes/stgdict.c python/branches/bcannon-objcap/Modules/_sre.c python/branches/bcannon-objcap/Modules/_ssl.c python/branches/bcannon-objcap/Modules/_testcapimodule.c python/branches/bcannon-objcap/Modules/audioop.c python/branches/bcannon-objcap/Modules/binascii.c python/branches/bcannon-objcap/Modules/bz2module.c python/branches/bcannon-objcap/Modules/cPickle.c python/branches/bcannon-objcap/Modules/cStringIO.c python/branches/bcannon-objcap/Modules/cjkcodecs/_codecs_iso2022.c python/branches/bcannon-objcap/Modules/collectionsmodule.c python/branches/bcannon-objcap/Modules/datetimemodule.c python/branches/bcannon-objcap/Modules/dbmmodule.c python/branches/bcannon-objcap/Modules/gcmodule.c python/branches/bcannon-objcap/Modules/linuxaudiodev.c python/branches/bcannon-objcap/Modules/main.c python/branches/bcannon-objcap/Modules/mathmodule.c python/branches/bcannon-objcap/Modules/ossaudiodev.c python/branches/bcannon-objcap/Modules/posixmodule.c python/branches/bcannon-objcap/Modules/socketmodule.c python/branches/bcannon-objcap/Modules/socketmodule.h python/branches/bcannon-objcap/Modules/threadmodule.c python/branches/bcannon-objcap/Modules/timemodule.c python/branches/bcannon-objcap/Modules/unicodedata.c python/branches/bcannon-objcap/Objects/abstract.c python/branches/bcannon-objcap/Objects/classobject.c python/branches/bcannon-objcap/Objects/dictnotes.txt python/branches/bcannon-objcap/Objects/dictobject.c python/branches/bcannon-objcap/Objects/exceptions.c python/branches/bcannon-objcap/Objects/fileobject.c python/branches/bcannon-objcap/Objects/intobject.c python/branches/bcannon-objcap/Objects/listobject.c python/branches/bcannon-objcap/Objects/longobject.c python/branches/bcannon-objcap/Objects/obmalloc.c python/branches/bcannon-objcap/Objects/setobject.c python/branches/bcannon-objcap/Objects/stringobject.c python/branches/bcannon-objcap/Objects/tupleobject.c python/branches/bcannon-objcap/Objects/typeobject.c python/branches/bcannon-objcap/Objects/unicodeobject.c python/branches/bcannon-objcap/PC/VC6/_bsddb.dsp (contents, props changed) python/branches/bcannon-objcap/PC/VC6/_socket.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/_ssl.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/_ssl.mak python/branches/bcannon-objcap/PC/VC6/_testcapi.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/_tkinter.dsp (contents, props changed) python/branches/bcannon-objcap/PC/VC6/bz2.dsp (contents, props changed) python/branches/bcannon-objcap/PC/VC6/make_versioninfo.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/pcbuild.dsw (contents, props changed) python/branches/bcannon-objcap/PC/VC6/pyexpat.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/python.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/pythoncore.dsp (contents, props changed) python/branches/bcannon-objcap/PC/VC6/pythonw.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/readme.txt python/branches/bcannon-objcap/PC/VC6/select.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/unicodedata.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/w9xpopen.dsp (props changed) python/branches/bcannon-objcap/PC/VC6/winsound.dsp (props changed) python/branches/bcannon-objcap/PC/_msi.c python/branches/bcannon-objcap/PC/pyconfig.h python/branches/bcannon-objcap/PC/python_nt.rc python/branches/bcannon-objcap/PCbuild/python20.wse python/branches/bcannon-objcap/PCbuild/pythoncore.vcproj python/branches/bcannon-objcap/PCbuild8/python20.wse python/branches/bcannon-objcap/Parser/tokenizer.c python/branches/bcannon-objcap/Python/ast.c python/branches/bcannon-objcap/Python/bltinmodule.c python/branches/bcannon-objcap/Python/ceval.c python/branches/bcannon-objcap/Python/compile.c python/branches/bcannon-objcap/Python/errors.c python/branches/bcannon-objcap/Python/getargs.c python/branches/bcannon-objcap/Python/getcopyright.c python/branches/bcannon-objcap/Python/import.c python/branches/bcannon-objcap/Python/marshal.c python/branches/bcannon-objcap/Python/modsupport.c python/branches/bcannon-objcap/Python/mystrtoul.c python/branches/bcannon-objcap/Python/peephole.c python/branches/bcannon-objcap/Python/structmember.c python/branches/bcannon-objcap/Python/sysmodule.c python/branches/bcannon-objcap/README python/branches/bcannon-objcap/Tools/msi/uuids.py python/branches/bcannon-objcap/Tools/scripts/findnocoding.py python/branches/bcannon-objcap/Tools/scripts/pysource.py python/branches/bcannon-objcap/configure python/branches/bcannon-objcap/configure.in python/branches/bcannon-objcap/pyconfig.h.in python/branches/bcannon-objcap/setup.py Log: Merged revisions 52005-53323 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r52011 | brett.cannon | 2006-09-26 16:38:24 -0700 (Tue, 26 Sep 2006) | 2 lines Make the error message for when the time data and format do not match clearer. ........ r52014 | andrew.kuchling | 2006-09-27 09:37:30 -0700 (Wed, 27 Sep 2006) | 1 line Add news item for rev. 51815 ........ r52018 | andrew.kuchling | 2006-09-27 12:23:05 -0700 (Wed, 27 Sep 2006) | 1 line Make examples do error checking on Py_InitModule ........ r52032 | brett.cannon | 2006-09-28 15:10:14 -0700 (Thu, 28 Sep 2006) | 2 lines Very minor grammatical fix in a comment. ........ r52048 | george.yoshida | 2006-09-29 22:14:02 -0700 (Fri, 29 Sep 2006) | 4 lines SF bug #1567976 : fix typo Will backport to 2.5. ........ r52051 | gregory.p.smith | 2006-09-29 23:08:20 -0700 (Fri, 29 Sep 2006) | 2 lines wording change ........ r52053 | georg.brandl | 2006-09-30 00:24:48 -0700 (Sat, 30 Sep 2006) | 2 lines Bug #1567375: a minor logical glitch in example description. ........ r52056 | georg.brandl | 2006-09-30 00:31:57 -0700 (Sat, 30 Sep 2006) | 3 lines Bug #1565661: in webbrowser, split() the command for the default GNOME browser in case it is a command with args. ........ r52058 | georg.brandl | 2006-09-30 01:43:30 -0700 (Sat, 30 Sep 2006) | 4 lines Patch #1567691: super() and new.instancemethod() now don't accept keyword arguments any more (previously they accepted them, but didn't use them). ........ r52061 | georg.brandl | 2006-09-30 02:03:42 -0700 (Sat, 30 Sep 2006) | 3 lines Bug #1566800: make sure that EnvironmentError can be called with any number of arguments, as was the case in Python 2.4. ........ r52063 | georg.brandl | 2006-09-30 02:06:45 -0700 (Sat, 30 Sep 2006) | 2 lines Bug #1566663: remove obsolete example from datetime docs. ........ r52065 | georg.brandl | 2006-09-30 02:13:21 -0700 (Sat, 30 Sep 2006) | 3 lines Bug #1566602: correct failure of posixpath unittest when $HOME ends with a slash. ........ r52068 | georg.brandl | 2006-09-30 03:58:01 -0700 (Sat, 30 Sep 2006) | 3 lines Bug #1457823: cgi.(Sv)FormContentDict's constructor now takes keep_blank_values and strict_parsing keyword arguments. ........ r52069 | georg.brandl | 2006-09-30 04:06:47 -0700 (Sat, 30 Sep 2006) | 3 lines Bug #1560617: in pyclbr, return full module name not only for classes, but also for functions. ........ r52072 | georg.brandl | 2006-09-30 04:17:34 -0700 (Sat, 30 Sep 2006) | 3 lines Bug #1556784: allow format strings longer than 127 characters in datetime's strftime function. ........ r52075 | georg.brandl | 2006-09-30 04:22:28 -0700 (Sat, 30 Sep 2006) | 3 lines Bug #1446043: correctly raise a LookupError if an encoding name given to encodings.search_function() contains a dot. ........ r52078 | georg.brandl | 2006-09-30 05:02:57 -0700 (Sat, 30 Sep 2006) | 3 lines Bug #1546052: clarify that PyString_FromString(AndSize) copies the string pointed to by its parameter. ........ r52080 | georg.brandl | 2006-09-30 05:16:03 -0700 (Sat, 30 Sep 2006) | 3 lines Convert test_import to unittest. ........ r52083 | kurt.kaiser | 2006-10-01 14:16:45 -0700 (Sun, 01 Oct 2006) | 5 lines Some syntax errors were being caught by tokenize during the tabnanny check, resulting in obscure error messages. Do the syntax check first. Bug 1562716, 1562719 ........ r52084 | kurt.kaiser | 2006-10-01 14:54:37 -0700 (Sun, 01 Oct 2006) | 3 lines Add comment explaining that error msgs may be due to user code when running w/o subprocess. ........ r52086 | martin.v.loewis | 2006-10-02 07:55:51 -0700 (Mon, 02 Oct 2006) | 3 lines Fix test for uintptr_t. Fixes #1568842. Will backport. ........ r52089 | martin.v.loewis | 2006-10-02 08:20:37 -0700 (Mon, 02 Oct 2006) | 3 lines Guard uintptr_t test with HAVE_STDINT_H, test for stdint.h. Will backport. ........ r52100 | vinay.sajip | 2006-10-03 11:02:37 -0700 (Tue, 03 Oct 2006) | 1 line Documentation omitted the additional parameter to LogRecord.__init__ which was added in 2.5. (See SF #1569622). ........ r52101 | vinay.sajip | 2006-10-03 11:20:26 -0700 (Tue, 03 Oct 2006) | 1 line Documentation clarified to mention optional parameters. ........ r52102 | vinay.sajip | 2006-10-03 11:21:56 -0700 (Tue, 03 Oct 2006) | 1 line Modified LogRecord.__init__ to make the func parameter optional. (See SF #1569622). ........ r52121 | brett.cannon | 2006-10-03 14:58:55 -0700 (Tue, 03 Oct 2006) | 2 lines Fix minor typo in a comment. ........ r52123 | brett.cannon | 2006-10-03 16:23:14 -0700 (Tue, 03 Oct 2006) | 2 lines Convert test_imp over to unittest. ........ r52128 | barry.warsaw | 2006-10-03 19:06:36 -0700 (Tue, 03 Oct 2006) | 3 lines decode_rfc2231(): As Christian Robottom Reis points out, it makes no sense to test for parts > 3 when we use .split(..., 2). ........ r52129 | jeremy.hylton | 2006-10-03 19:24:52 -0700 (Tue, 03 Oct 2006) | 9 lines Fix for SF bug 1569998: break permitted inside try. The compiler was checking that there was something on the fblock stack, but not that there was a loop on the stack. Fixed that and added a test for the specific syntax error. Bug fix candidate. ........ r52130 | martin.v.loewis | 2006-10-03 22:47:34 -0700 (Tue, 03 Oct 2006) | 4 lines Fix integer negation and absolute value to not rely on undefined behaviour of the C compiler anymore. Will backport to 2.5 and 2.4. ........ r52135 | martin.v.loewis | 2006-10-04 02:21:20 -0700 (Wed, 04 Oct 2006) | 1 line Forward port r52134: Add uuids for 2.4.4. ........ r52137 | armin.rigo | 2006-10-04 03:23:57 -0700 (Wed, 04 Oct 2006) | 3 lines Compilation problem caused by conflicting typedefs for uint32_t (unsigned long vs. unsigned int). ........ r52139 | armin.rigo | 2006-10-04 05:17:45 -0700 (Wed, 04 Oct 2006) | 23 lines Forward-port of r52136,52138: a review of overflow-detecting code. * unified the way intobject, longobject and mystrtoul handle values around -sys.maxint-1. * in general, trying to entierely avoid overflows in any computation involving signed ints or longs is extremely involved. Fixed a few simple cases where a compiler might be too clever (but that's all guesswork). * more overflow checks against bad data in marshal.c. * 2.5 specific: fixed a number of places that were still confusing int and Py_ssize_t. Some of them could potentially have caused "real-world" breakage. * list.pop(x): fixing overflow issues on x was messy. I just reverted to PyArg_ParseTuple("n"), which does the right thing. (An obscure test was trying to give a Decimal to list.pop()... doesn't make sense any more IMHO) * trying to write a few tests... ........ r52147 | andrew.kuchling | 2006-10-04 06:42:43 -0700 (Wed, 04 Oct 2006) | 6 lines Cause a PyObject_Malloc() failure to trigger a MemoryError, and then add 'if (PyErr_Occurred())' checks to various places so that NULL is returned properly. 2.4 backport candidate. ........ r52148 | martin.v.loewis | 2006-10-04 08:25:28 -0700 (Wed, 04 Oct 2006) | 1 line Add MSVC8 project files to create wininst-8.exe. ........ r52196 | brett.cannon | 2006-10-05 15:02:31 -0700 (Thu, 05 Oct 2006) | 7 lines Clarify what "re-initialization" means for init_builtin() and init_dynamic(). Also remove warning about re-initialization as possibly raising an execption as both call _PyImport_FindExtension() which pulls any module that was already imported from the Python process' extension cache and just copies the __dict__ into the module stored in sys.modules. ........ r52200 | fred.drake | 2006-10-05 17:03:45 -0700 (Thu, 05 Oct 2006) | 3 lines - update links - remove Sleepycat name now that they have been bought ........ r52204 | andrew.kuchling | 2006-10-06 03:41:01 -0700 (Fri, 06 Oct 2006) | 1 line Case fix ........ r52208 | georg.brandl | 2006-10-06 05:46:08 -0700 (Fri, 06 Oct 2006) | 3 lines Fix name. ........ r52211 | andrew.kuchling | 2006-10-06 06:18:26 -0700 (Fri, 06 Oct 2006) | 1 line [Bug #1545341] Allow 'classifier' parameter to be a tuple as well as a list. Will backport. ........ r52212 | armin.rigo | 2006-10-06 09:33:22 -0700 (Fri, 06 Oct 2006) | 4 lines A very minor bug fix: this code looks like it is designed to accept any hue value and do the modulo itself, except it doesn't quite do it in all cases. At least, the "cannot get here" comment was wrong. ........ r52213 | andrew.kuchling | 2006-10-06 11:51:55 -0700 (Fri, 06 Oct 2006) | 1 line Comment grammar ........ r52218 | skip.montanaro | 2006-10-07 04:05:02 -0700 (Sat, 07 Oct 2006) | 6 lines Note that the excel_tab class is registered as the "excel-tab" dialect. Fixes 1572471. Make a similar change for the excel class and clean up references to the Dialects and Formatting Parameters section in a few places. ........ r52221 | georg.brandl | 2006-10-08 00:11:54 -0700 (Sun, 08 Oct 2006) | 3 lines Add missing NEWS entry for rev. 52129. ........ r52223 | hyeshik.chang | 2006-10-08 06:48:34 -0700 (Sun, 08 Oct 2006) | 3 lines Bug #1572832: fix a bug in ISO-2022 codecs which may cause segfault when encoding non-BMP unicode characters. (Submitted by Ray Chason) ........ r52227 | ronald.oussoren | 2006-10-08 10:37:58 -0700 (Sun, 08 Oct 2006) | 4 lines Add version number to the link to the python documentation in /Developer/Documentation/Python, better for users that install multiple versions of python. ........ r52229 | ronald.oussoren | 2006-10-08 10:40:02 -0700 (Sun, 08 Oct 2006) | 2 lines Fix for bug #1570284 ........ r52233 | ronald.oussoren | 2006-10-08 10:49:52 -0700 (Sun, 08 Oct 2006) | 6 lines MacOSX: distutils changes the values of BASECFLAGS and LDFLAGS when using a universal build of python on OSX 10.3 to ensure that those flags can be used to compile code (the universal build uses compiler flags that aren't supported on 10.3). This patches gives the same treatment to CFLAGS, PY_CFLAGS and BLDSHARED. ........ r52236 | ronald.oussoren | 2006-10-08 10:51:46 -0700 (Sun, 08 Oct 2006) | 5 lines MacOSX: The universal build requires that users have the MacOSX10.4u SDK installed to build extensions. This patch makes distutils emit a warning when the compiler should use an SDK but that SDK is not installed, hopefully reducing some confusion. ........ r52238 | ronald.oussoren | 2006-10-08 11:18:26 -0700 (Sun, 08 Oct 2006) | 3 lines MacOSX: add more logic to recognize the correct startup file to patch to the shell profile patching post-install script. ........ r52242 | andrew.kuchling | 2006-10-09 10:10:12 -0700 (Mon, 09 Oct 2006) | 1 line Add news item for rev. 52211 change ........ r52245 | andrew.kuchling | 2006-10-09 11:05:19 -0700 (Mon, 09 Oct 2006) | 1 line Fix wording in comment ........ r52251 | georg.brandl | 2006-10-09 12:03:06 -0700 (Mon, 09 Oct 2006) | 2 lines Patch #1572724: fix typo ('=' instead of '==') in _msi.c. ........ r52255 | barry.warsaw | 2006-10-09 12:43:24 -0700 (Mon, 09 Oct 2006) | 2 lines List gc.get_count() in the module docstring. ........ r52257 | martin.v.loewis | 2006-10-09 13:44:25 -0700 (Mon, 09 Oct 2006) | 1 line Bug #1565150: Fix subsecond processing for os.utime on Windows. ........ r52268 | ronald.oussoren | 2006-10-10 00:55:06 -0700 (Tue, 10 Oct 2006) | 2 lines MacOSX: fix permission problem in the generated installer ........ r52293 | georg.brandl | 2006-10-12 00:38:04 -0700 (Thu, 12 Oct 2006) | 2 lines Bug #1575746: fix typo in property() docs. ........ r52295 | georg.brandl | 2006-10-12 00:57:21 -0700 (Thu, 12 Oct 2006) | 3 lines Bug #813342: Start the IDLE subprocess with -Qnew if the parent is started with that option. ........ r52297 | georg.brandl | 2006-10-12 01:22:53 -0700 (Thu, 12 Oct 2006) | 2 lines Bug #1565919: document set types in the Language Reference. ........ r52299 | georg.brandl | 2006-10-12 02:20:33 -0700 (Thu, 12 Oct 2006) | 3 lines Bug #1550524: better heuristics to find correct class definition in inspect.findsource(). ........ r52301 | georg.brandl | 2006-10-12 02:47:12 -0700 (Thu, 12 Oct 2006) | 4 lines Bug #1548891: The cStringIO.StringIO() constructor now encodes unicode arguments with the system default encoding just like the write() method does, instead of converting it to a raw buffer. ........ r52303 | georg.brandl | 2006-10-12 04:14:40 -0700 (Thu, 12 Oct 2006) | 2 lines Bug #1546628: add a note about urlparse.urljoin() and absolute paths. ........ r52305 | georg.brandl | 2006-10-12 04:27:59 -0700 (Thu, 12 Oct 2006) | 3 lines Bug #1545497: when given an explicit base, int() did ignore NULs embedded in the string to convert. ........ r52307 | georg.brandl | 2006-10-12 04:41:11 -0700 (Thu, 12 Oct 2006) | 3 lines Add a note to fpectl docs that it's not built by default (bug #1556261). ........ r52309 | georg.brandl | 2006-10-12 04:46:57 -0700 (Thu, 12 Oct 2006) | 3 lines Bug #1560114: the Mac filesystem does have accurate information about the case of filenames. ........ r52311 | georg.brandl | 2006-10-12 04:59:27 -0700 (Thu, 12 Oct 2006) | 2 lines Small grammar fix, thanks Sjoerd. ........ r52313 | georg.brandl | 2006-10-12 05:03:07 -0700 (Thu, 12 Oct 2006) | 2 lines Fix tarfile depending on buggy int('1\0', base) behavior. ........ r52315 | georg.brandl | 2006-10-12 05:33:07 -0700 (Thu, 12 Oct 2006) | 2 lines Bug #1283491: follow docstring convention wrt. keyword-able args in sum(). ........ r52316 | georg.brandl | 2006-10-12 06:08:16 -0700 (Thu, 12 Oct 2006) | 3 lines Bug #1560179: speed up posixpath.(dir|base)name ........ r52327 | brett.cannon | 2006-10-13 23:36:45 -0700 (Fri, 13 Oct 2006) | 3 lines Clean up the language of a sentence relating to the connect() function and user-defined datatypes. ........ r52332 | neal.norwitz | 2006-10-14 14:33:38 -0700 (Sat, 14 Oct 2006) | 3 lines Update the peephole optimizer to remove more dead code (jumps after returns) and inline jumps to returns. ........ r52333 | martin.v.loewis | 2006-10-15 00:54:40 -0700 (Sun, 15 Oct 2006) | 4 lines Patch #1576954: Update VC6 build directory; remove redundant files in VC7. Will backport to 2.5. ........ r52335 | martin.v.loewis | 2006-10-15 01:43:33 -0700 (Sun, 15 Oct 2006) | 1 line Patch #1576166: Support os.utime for directories on Windows NT+. ........ r52336 | martin.v.loewis | 2006-10-15 01:51:22 -0700 (Sun, 15 Oct 2006) | 2 lines Patch #1577551: Add ctypes and ET build support for VC6. Will backport to 2.5. ........ r52338 | martin.v.loewis | 2006-10-15 02:35:51 -0700 (Sun, 15 Oct 2006) | 1 line Loosen the test for equal time stamps. ........ r52339 | martin.v.loewis | 2006-10-15 02:43:39 -0700 (Sun, 15 Oct 2006) | 2 lines Bug #1567666: Emulate GetFileAttributesExA for Win95. Will backport to 2.5. ........ r52341 | martin.v.loewis | 2006-10-15 04:02:07 -0700 (Sun, 15 Oct 2006) | 2 lines Round to int, because some systems support sub-second time stamps in stat, but not in utime. Also be consistent with modifying only mtime, not atime. ........ r52342 | martin.v.loewis | 2006-10-15 04:57:40 -0700 (Sun, 15 Oct 2006) | 2 lines Set the eol-style for project files to "CRLF". ........ r52343 | martin.v.loewis | 2006-10-15 04:59:56 -0700 (Sun, 15 Oct 2006) | 3 lines Drop binary property on dsp files, set eol-style to CRLF instead. ........ r52344 | martin.v.loewis | 2006-10-15 05:01:43 -0700 (Sun, 15 Oct 2006) | 2 lines Remove binary property, set eol-style to CRLF instead. ........ r52346 | martin.v.loewis | 2006-10-15 07:30:38 -0700 (Sun, 15 Oct 2006) | 2 lines Mention the bdist_msi module. Will backport to 2.5. ........ r52354 | brett.cannon | 2006-10-15 20:09:52 -0700 (Sun, 15 Oct 2006) | 3 lines Fix turtle so that you can launch the demo2 function on its own instead of only when the module is launched as a script. ........ r52356 | martin.v.loewis | 2006-10-17 08:18:06 -0700 (Tue, 17 Oct 2006) | 2 lines Patch #1457736: Update VC6 to use current PCbuild settings. Will backport to 2.5. ........ r52360 | martin.v.loewis | 2006-10-17 11:09:55 -0700 (Tue, 17 Oct 2006) | 2 lines Remove obsolete file. Will backport. ........ r52363 | martin.v.loewis | 2006-10-17 11:59:23 -0700 (Tue, 17 Oct 2006) | 4 lines Forward-port r52358: - Bug #1578513: Cross compilation was broken by a change to configure. Repair so that it's back to how it was in 2.4.3. ........ r52365 | thomas.heller | 2006-10-17 12:30:48 -0700 (Tue, 17 Oct 2006) | 6 lines ctypes callback functions only support 'fundamental' result types. Check this and raise an error when something else is used - before this change ctypes would hang or crash when such a callback was called. This is a partial fix for #1574584. Will backport to release25-maint. ........ r52377 | tim.peters | 2006-10-17 22:06:06 -0700 (Tue, 17 Oct 2006) | 2 lines newIobject(): repaired incorrect cast to quiet MSVC warning. ........ r52378 | tim.peters | 2006-10-17 22:09:12 -0700 (Tue, 17 Oct 2006) | 2 lines Whitespace normalization. ........ r52379 | tim.peters | 2006-10-17 22:10:28 -0700 (Tue, 17 Oct 2006) | 2 lines Add missing svn:eol-style to text files. ........ r52387 | martin.v.loewis | 2006-10-19 03:58:46 -0700 (Thu, 19 Oct 2006) | 3 lines Add check for the PyArg_ParseTuple format, and declare it if it is supported. ........ r52388 | martin.v.loewis | 2006-10-19 04:00:37 -0700 (Thu, 19 Oct 2006) | 3 lines Fix various minor errors in passing arguments to PyArg_ParseTuple. ........ r52389 | martin.v.loewis | 2006-10-19 09:01:37 -0700 (Thu, 19 Oct 2006) | 2 lines Restore CFLAGS after checking for __attribute__ ........ r52390 | andrew.kuchling | 2006-10-19 14:55:55 -0700 (Thu, 19 Oct 2006) | 1 line [Bug #1576348] Fix typo in example ........ r52414 | walter.doerwald | 2006-10-22 01:59:41 -0700 (Sun, 22 Oct 2006) | 2 lines Port test___future__ to unittest. ........ r52415 | ronald.oussoren | 2006-10-22 03:45:18 -0700 (Sun, 22 Oct 2006) | 3 lines Patch #1580674: with this patch os.readlink uses the filesystem encoding to decode unicode objects and returns an unicode object when the argument is one. ........ r52416 | martin.v.loewis | 2006-10-22 03:46:18 -0700 (Sun, 22 Oct 2006) | 3 lines Patch #1580872: Remove duplicate declaration of PyCallable_Check. Will backport to 2.5. ........ r52418 | martin.v.loewis | 2006-10-22 03:55:15 -0700 (Sun, 22 Oct 2006) | 4 lines - Patch #1560695: Add .note.GNU-stack to ctypes' sysv.S so that ctypes isn't considered as requiring executable stacks. Will backport to 2.5. ........ r52420 | martin.v.loewis | 2006-10-22 06:45:13 -0700 (Sun, 22 Oct 2006) | 3 lines Remove passwd.adjunct.byname from list of maps for test_nis. Will backport to 2.5. ........ r52431 | georg.brandl | 2006-10-24 09:54:16 -0700 (Tue, 24 Oct 2006) | 2 lines Patch [ 1583506 ] tarfile.py: 100-char filenames are truncated ........ r52446 | andrew.kuchling | 2006-10-26 12:10:46 -0700 (Thu, 26 Oct 2006) | 1 line [Bug #1579796] Wrong syntax for PyDateTime_IMPORT in documentation. Reported by David Faure. ........ r52449 | andrew.kuchling | 2006-10-26 12:16:46 -0700 (Thu, 26 Oct 2006) | 1 line Typo fix ........ r52452 | martin.v.loewis | 2006-10-26 23:16:31 -0700 (Thu, 26 Oct 2006) | 3 lines Patch #1549049: Rewrite type conversion in structmember. Fixes #1545696 and #1566140. Will backport to 2.5. ........ r52454 | martin.v.loewis | 2006-10-26 23:42:27 -0700 (Thu, 26 Oct 2006) | 2 lines Check for values.h. Will backport. ........ r52456 | martin.v.loewis | 2006-10-27 00:06:52 -0700 (Fri, 27 Oct 2006) | 2 lines Get DBL_MAX from float.h not values.h. Will backport. ........ r52458 | martin.v.loewis | 2006-10-27 00:13:28 -0700 (Fri, 27 Oct 2006) | 2 lines Patch #1567274: Support SMTP over TLS. ........ r52459 | andrew.kuchling | 2006-10-27 04:33:29 -0700 (Fri, 27 Oct 2006) | 1 line Set svn:keywords property ........ r52460 | andrew.kuchling | 2006-10-27 04:36:41 -0700 (Fri, 27 Oct 2006) | 1 line Add item ........ r52461 | andrew.kuchling | 2006-10-27 04:37:01 -0700 (Fri, 27 Oct 2006) | 1 line Some wording changes and markup fixes ........ r52462 | andrew.kuchling | 2006-10-27 05:18:38 -0700 (Fri, 27 Oct 2006) | 1 line [Bug #1585690] Note that line_num was added in Python 2.5 ........ r52464 | andrew.kuchling | 2006-10-27 05:50:38 -0700 (Fri, 27 Oct 2006) | 1 line [Bug #1583946] Reword description of server and issuer ........ r52466 | andrew.kuchling | 2006-10-27 06:06:25 -0700 (Fri, 27 Oct 2006) | 1 line [Bug #1562583] Mention the set_reuse_addr() method ........ r52469 | andrew.kuchling | 2006-10-27 06:22:46 -0700 (Fri, 27 Oct 2006) | 4 lines [Bug #1542016] Report PCALL_POP value. This makes the return value of sys.callstats() match its docstring. Backport candidate. Though it's an API change, this is a pretty obscure portion of the API. ........ r52473 | andrew.kuchling | 2006-10-27 07:53:41 -0700 (Fri, 27 Oct 2006) | 1 line Point users to the subprocess module in the docs for os.system, os.spawn*, os.popen2, and the popen2 and commands modules ........ r52476 | andrew.kuchling | 2006-10-27 09:39:10 -0700 (Fri, 27 Oct 2006) | 1 line [Bug #1576241] Let functools.wraps work with built-in functions ........ r52478 | andrew.kuchling | 2006-10-27 09:55:34 -0700 (Fri, 27 Oct 2006) | 1 line [Bug #1575506] The _singlefileMailbox class was using the wrong file object in its flush() method, causing an error ........ r52480 | andrew.kuchling | 2006-10-27 10:06:16 -0700 (Fri, 27 Oct 2006) | 1 line Clarify docstring ........ r52481 | andrew.kuchling | 2006-10-27 10:11:23 -0700 (Fri, 27 Oct 2006) | 5 lines [Patch #1574068 by Scott Dial] urllib and urllib2 were using base64.encodestring() for encoding authentication data. encodestring() can include newlines for very long input, which produced broken HTTP headers. ........ r52483 | andrew.kuchling | 2006-10-27 11:13:46 -0700 (Fri, 27 Oct 2006) | 1 line Check db_setup_debug for a few print statements; change sqlite_setup_debug to False ........ r52484 | andrew.kuchling | 2006-10-27 11:15:02 -0700 (Fri, 27 Oct 2006) | 1 line [Patch #1503717] Tiny patch from Chris AtLee to stop a lengthy line from being printed ........ r52485 | thomas.heller | 2006-10-27 11:31:36 -0700 (Fri, 27 Oct 2006) | 5 lines WindowsError.str should display the windows error code, not the posix error code; with test. Fixes #1576174. Will backport to release25-maint. ........ r52487 | thomas.heller | 2006-10-27 12:05:53 -0700 (Fri, 27 Oct 2006) | 4 lines Modulefinder now handles absolute and relative imports, including tests. Will backport to release25-maint. ........ r52488 | georg.brandl | 2006-10-27 13:39:43 -0700 (Fri, 27 Oct 2006) | 2 lines Patch #1552024: add decorator support to unparse.py demo script. ........ r52492 | walter.doerwald | 2006-10-28 03:47:12 -0700 (Sat, 28 Oct 2006) | 2 lines Port test_bufio to unittest. ........ r52493 | georg.brandl | 2006-10-28 06:10:17 -0700 (Sat, 28 Oct 2006) | 6 lines Convert test_global, test_scope and test_grammar to unittest. I tried to enclose all tests which must be run at the toplevel (instead of inside a method) in exec statements. ........ r52494 | georg.brandl | 2006-10-28 06:11:41 -0700 (Sat, 28 Oct 2006) | 3 lines Update outstanding bugs test file. ........ r52495 | georg.brandl | 2006-10-28 06:51:49 -0700 (Sat, 28 Oct 2006) | 3 lines Convert test_math to unittest. ........ r52496 | georg.brandl | 2006-10-28 06:56:58 -0700 (Sat, 28 Oct 2006) | 3 lines Convert test_opcodes to unittest. ........ r52497 | georg.brandl | 2006-10-28 09:04:04 -0700 (Sat, 28 Oct 2006) | 2 lines Fix nth() itertool recipe. ........ r52500 | georg.brandl | 2006-10-28 13:25:09 -0700 (Sat, 28 Oct 2006) | 2 lines make test_grammar pass with python -O ........ r52501 | neal.norwitz | 2006-10-28 14:15:30 -0700 (Sat, 28 Oct 2006) | 6 lines Add some asserts. In sysmodule, I think these were to try to silence some warnings from Klokwork. They verify the assumptions of the format of svn version output. The assert in the thread module helped debug a problem on HP-UX. ........ r52502 | neal.norwitz | 2006-10-28 14:16:54 -0700 (Sat, 28 Oct 2006) | 5 lines Fix warnings with HP's C compiler. It doesn't recognize that infinite loops are, um, infinite. These conditions should not be able to happen. Will backport. ........ r52503 | neal.norwitz | 2006-10-28 14:17:51 -0700 (Sat, 28 Oct 2006) | 5 lines Fix crash in test on HP-UX. Apparently, it's not possible to delete a lock if it's held (even by the current thread). Will backport. ........ r52504 | neal.norwitz | 2006-10-28 14:19:07 -0700 (Sat, 28 Oct 2006) | 6 lines Fix bug #1565514, SystemError not raised on too many nested blocks. It seems like this should be a different error than SystemError, but I don't have any great ideas and SystemError was raised in 2.4 and earlier. Will backport. ........ r52505 | neal.norwitz | 2006-10-28 14:20:12 -0700 (Sat, 28 Oct 2006) | 4 lines Prevent crash if alloc of garbage fails. Found by Typo.pl. Will backport. ........ r52506 | neal.norwitz | 2006-10-28 14:21:00 -0700 (Sat, 28 Oct 2006) | 4 lines Don't inline Py_ADDRESS_IN_RANGE with gcc 4+ either. Will backport. ........ r52513 | neal.norwitz | 2006-10-28 14:56:49 -0700 (Sat, 28 Oct 2006) | 2 lines Fix test_modulefinder so it doesn't fail when run after test_distutils. ........ r52514 | neal.norwitz | 2006-10-28 15:12:26 -0700 (Sat, 28 Oct 2006) | 4 lines From SF 1557890, fix problem of using wrong type in example. Will backport. ........ r52517 | georg.brandl | 2006-10-29 01:39:22 -0700 (Sun, 29 Oct 2006) | 4 lines Fix codecs.EncodedFile which did not use file_encoding in 2.5.0, and fix all codecs file wrappers to work correctly with the "with" statement (bug #1586513). ........ r52519 | georg.brandl | 2006-10-29 01:47:08 -0700 (Sun, 29 Oct 2006) | 3 lines Clean up a leftover from old listcomp generation code. ........ r52520 | georg.brandl | 2006-10-29 01:53:06 -0700 (Sun, 29 Oct 2006) | 4 lines Bug #1586448: the compiler module now emits the same bytecode for list comprehensions as the builtin compiler, using the LIST_APPEND opcode. ........ r52521 | georg.brandl | 2006-10-29 01:01:01 -0800 (Sun, 29 Oct 2006) | 3 lines Remove trailing comma. ........ r52522 | georg.brandl | 2006-10-29 01:05:04 -0800 (Sun, 29 Oct 2006) | 3 lines Bug #1357915: allow all sequence types for shell arguments in subprocess. ........ r52524 | georg.brandl | 2006-10-29 01:16:12 -0800 (Sun, 29 Oct 2006) | 3 lines Patch #1583880: fix tarfile's problems with long names and posix/ GNU modes. ........ r52526 | georg.brandl | 2006-10-29 01:18:00 -0800 (Sun, 29 Oct 2006) | 3 lines Test assert if __debug__ is true. ........ r52527 | georg.brandl | 2006-10-29 01:32:16 -0800 (Sun, 29 Oct 2006) | 2 lines Fix the new EncodedFile test to work with big endian platforms. ........ r52529 | georg.brandl | 2006-10-29 06:39:09 -0800 (Sun, 29 Oct 2006) | 2 lines Bug #1586613: fix zlib and bz2 codecs' incremental en/decoders. ........ r52532 | georg.brandl | 2006-10-29 10:01:08 -0800 (Sun, 29 Oct 2006) | 2 lines Bug #1586773: extend hashlib docstring. ........ r52534 | neal.norwitz | 2006-10-29 10:30:10 -0800 (Sun, 29 Oct 2006) | 4 lines Update comments, remove commented out code. Move assembler structure next to assembler code to make it easier to move it to a separate file. ........ r52535 | georg.brandl | 2006-10-29 10:31:42 -0800 (Sun, 29 Oct 2006) | 3 lines Bug #1576657: when setting a KeyError for a tuple key, make sure that the tuple isn't used as the "exception arguments tuple". ........ r52537 | georg.brandl | 2006-10-29 11:13:40 -0800 (Sun, 29 Oct 2006) | 3 lines Convert test_mmap to unittest. ........ r52538 | georg.brandl | 2006-10-29 11:20:45 -0800 (Sun, 29 Oct 2006) | 3 lines Convert test_poll to unittest. ........ r52539 | georg.brandl | 2006-10-29 11:24:43 -0800 (Sun, 29 Oct 2006) | 3 lines Convert test_nis to unittest. ........ r52540 | georg.brandl | 2006-10-29 11:35:03 -0800 (Sun, 29 Oct 2006) | 3 lines Convert test_types to unittest. ........ r52541 | georg.brandl | 2006-10-29 11:51:16 -0800 (Sun, 29 Oct 2006) | 3 lines Convert test_cookie to unittest. ........ r52542 | georg.brandl | 2006-10-29 12:09:12 -0800 (Sun, 29 Oct 2006) | 3 lines Convert test_cgi to unittest. ........ r52543 | georg.brandl | 2006-10-29 12:24:01 -0800 (Sun, 29 Oct 2006) | 3 lines Completely convert test_httplib to unittest. ........ r52544 | georg.brandl | 2006-10-29 12:28:26 -0800 (Sun, 29 Oct 2006) | 2 lines Convert test_MimeWriter to unittest. ........ r52545 | georg.brandl | 2006-10-29 12:31:17 -0800 (Sun, 29 Oct 2006) | 3 lines Convert test_openpty to unittest. ........ r52546 | georg.brandl | 2006-10-29 12:35:12 -0800 (Sun, 29 Oct 2006) | 3 lines Remove leftover test output file. ........ r52547 | georg.brandl | 2006-10-29 13:54:18 -0800 (Sun, 29 Oct 2006) | 3 lines Move the check for openpty to the beginning. ........ r52548 | walter.doerwald | 2006-10-29 14:06:28 -0800 (Sun, 29 Oct 2006) | 2 lines Add tests for basic argument errors. ........ r52549 | walter.doerwald | 2006-10-29 15:02:27 -0800 (Sun, 29 Oct 2006) | 3 lines Add tests for incremental codecs with an errors argument. ........ r52550 | neal.norwitz | 2006-10-29 15:39:03 -0800 (Sun, 29 Oct 2006) | 1 line Fix refleak ........ r52552 | neal.norwitz | 2006-10-29 15:58:36 -0800 (Sun, 29 Oct 2006) | 1 line I'm assuming this is correct, it fixes the tests so they pass again ........ r52555 | vinay.sajip | 2006-10-31 09:32:37 -0800 (Tue, 31 Oct 2006) | 1 line Change to improve speed of _fixupChildren ........ r52556 | vinay.sajip | 2006-10-31 09:34:31 -0800 (Tue, 31 Oct 2006) | 1 line Added relativeCreated to Formatter doc (has been in the system for a long time - was unaccountably left out of the docs and not noticed until now). ........ r52588 | thomas.heller | 2006-11-02 11:48:24 -0800 (Thu, 02 Nov 2006) | 5 lines Replace the XXX marker in the 'Arrays and pointers' reference manual section with a link to the tutorial sections. Will backport to release25-maint. ........ r52592 | thomas.heller | 2006-11-02 12:22:29 -0800 (Thu, 02 Nov 2006) | 6 lines Fix a code example by adding a missing import. Fixes #1557890. Will backport to release25-maint. ........ r52598 | tim.peters | 2006-11-02 18:32:46 -0800 (Thu, 02 Nov 2006) | 2 lines Whitespace normalization. ........ r52619 | martin.v.loewis | 2006-11-04 10:14:06 -0800 (Sat, 04 Nov 2006) | 4 lines - Patch #1060577: Extract list of RPM files from spec file in bdist_rpm Will backport to 2.5. ........ r52621 | neal.norwitz | 2006-11-04 11:25:22 -0800 (Sat, 04 Nov 2006) | 4 lines Bug #1588287: fix invalid assertion for `1,2` in debug builds. Will backport ........ r52630 | andrew.kuchling | 2006-11-05 13:04:37 -0800 (Sun, 05 Nov 2006) | 1 line Update link ........ r52631 | skip.montanaro | 2006-11-06 06:34:52 -0800 (Mon, 06 Nov 2006) | 1 line note that user can control directory location even if default dir is used ........ r52644 | ronald.oussoren | 2006-11-07 07:53:38 -0800 (Tue, 07 Nov 2006) | 2 lines Fix a number of typos in strings and comments (sf#1589070) ........ r52647 | ronald.oussoren | 2006-11-07 08:00:34 -0800 (Tue, 07 Nov 2006) | 2 lines Whitespace changes to make the source more compliant with PEP8 (SF#1589070) ........ r52651 | thomas.heller | 2006-11-07 10:01:18 -0800 (Tue, 07 Nov 2006) | 3 lines Fix markup. Will backport to release25-maint. ........ r52653 | thomas.heller | 2006-11-07 10:20:47 -0800 (Tue, 07 Nov 2006) | 3 lines Fix grammatical error as well. Will backport to release25-maint. ........ r52657 | andrew.kuchling | 2006-11-07 12:39:16 -0800 (Tue, 07 Nov 2006) | 1 line Add missing word ........ r52662 | martin.v.loewis | 2006-11-07 22:46:37 -0800 (Tue, 07 Nov 2006) | 4 lines Correctly forward exception in instance_contains(). Fixes #1591996. Patch contributed by Neal Norwitz. Will backport. ........ r52664 | martin.v.loewis | 2006-11-07 22:48:36 -0800 (Tue, 07 Nov 2006) | 2 lines News entry for 52662. ........ r52665 | martin.v.loewis | 2006-11-07 23:35:55 -0800 (Tue, 07 Nov 2006) | 2 lines Patch #1351744: Add askyesnocancel helper for tkMessageBox. ........ r52666 | georg.brandl | 2006-11-07 23:45:59 -0800 (Tue, 07 Nov 2006) | 2 lines Patch #1592072: fix docs for return value of PyErr_CheckSignals. ........ r52668 | georg.brandl | 2006-11-08 02:04:29 -0800 (Wed, 08 Nov 2006) | 3 lines Bug #1592533: rename variable in heapq doc example, to avoid shadowing "sorted". ........ r52671 | andrew.kuchling | 2006-11-08 05:35:34 -0800 (Wed, 08 Nov 2006) | 1 line Add section on the functional module ........ r52672 | andrew.kuchling | 2006-11-08 06:14:30 -0800 (Wed, 08 Nov 2006) | 1 line Add section on operator module; make a few edits ........ r52673 | andrew.kuchling | 2006-11-08 06:24:03 -0800 (Wed, 08 Nov 2006) | 1 line Add table of contents; this required fixing a few headings. Some more smalle edits. ........ r52674 | andrew.kuchling | 2006-11-08 06:30:14 -0800 (Wed, 08 Nov 2006) | 1 line More edits ........ r52686 | martin.v.loewis | 2006-11-09 03:06:03 -0800 (Thu, 09 Nov 2006) | 3 lines Patch #838546: Make terminal become controlling in pty.fork(). Will backport to 2.5. ........ r52688 | martin.v.loewis | 2006-11-09 03:27:32 -0800 (Thu, 09 Nov 2006) | 2 lines Patch #1592250: Add elidge argument to Tkinter.Text.search. ........ r52690 | andrew.kuchling | 2006-11-09 05:27:07 -0800 (Thu, 09 Nov 2006) | 7 lines [Bug #1569790] mailbox.Maildir.get_folder() loses factory information Both the Maildir and MH classes had this bug; the patch fixes both classes and adds a test. Will backport to 25-maint. ........ r52692 | andrew.kuchling | 2006-11-09 05:51:14 -0800 (Thu, 09 Nov 2006) | 1 line [Patch #1514544 by David Watson] use fsync() to ensure data is really on disk ........ r52695 | walter.doerwald | 2006-11-09 08:23:26 -0800 (Thu, 09 Nov 2006) | 2 lines Replace C++ comment with C comment (fixes SF bug #1593525). ........ r52712 | andrew.kuchling | 2006-11-09 13:16:46 -0800 (Thu, 09 Nov 2006) | 11 lines [Patch #1514543] mailbox (Maildir): avoid losing messages on name clash Two changes: Where possible, use link()/remove() to move files into a directory; this makes it easier to avoid overwriting an existing file. Use _create_carefully() to create files in tmp/, which uses O_EXCL. Backport candidate. ........ r52716 | phillip.eby | 2006-11-09 16:33:36 -0800 (Thu, 09 Nov 2006) | 4 lines Fix SF#1566719: not creating site-packages (or other target directory) when installing .egg-info for a project that contains no modules or packages, while using --root (as in bdist_rpm). ........ r52719 | andrew.kuchling | 2006-11-10 05:14:01 -0800 (Fri, 10 Nov 2006) | 1 line Reword entry ........ r52725 | andrew.kuchling | 2006-11-10 06:39:01 -0800 (Fri, 10 Nov 2006) | 1 line [Feature request #1542920] Link to wsgi.org ........ r52731 | georg.brandl | 2006-11-11 10:29:11 -0800 (Sat, 11 Nov 2006) | 2 lines Bug #1594742: wrong word in stringobject doc. ........ r52733 | georg.brandl | 2006-11-11 10:32:47 -0800 (Sat, 11 Nov 2006) | 2 lines Bug #1594758: wording improvement for dict.update() docs. ........ r52736 | martin.v.loewis | 2006-11-12 02:32:47 -0800 (Sun, 12 Nov 2006) | 3 lines Patch #1065257: Support passing open files as body in HTTPConnection.request(). ........ r52737 | martin.v.loewis | 2006-11-12 02:41:39 -0800 (Sun, 12 Nov 2006) | 2 lines Patch #1355023: support whence argument for GzipFile.seek. ........ r52738 | martin.v.loewis | 2006-11-12 10:24:26 -0800 (Sun, 12 Nov 2006) | 2 lines Bug #1067760: Deprecate passing floats to file.seek. ........ r52739 | martin.v.loewis | 2006-11-12 10:48:13 -0800 (Sun, 12 Nov 2006) | 3 lines Patch #1359217: Ignore 2xx response before 150 response. Will backport to 2.5. ........ r52741 | martin.v.loewis | 2006-11-12 10:56:03 -0800 (Sun, 12 Nov 2006) | 4 lines Patch #1360200: Use unmangled_version RPM spec field to deal with file name mangling. Will backport to 2.5. ........ r52753 | walter.doerwald | 2006-11-15 08:23:46 -0800 (Wed, 15 Nov 2006) | 2 lines Fix typo. ........ r52754 | georg.brandl | 2006-11-15 09:42:03 -0800 (Wed, 15 Nov 2006) | 2 lines Bug #1594809: add a note to README regarding PYTHONPATH and make install. ........ r52762 | georg.brandl | 2006-11-16 07:05:14 -0800 (Thu, 16 Nov 2006) | 2 lines Bug #1597576: mention that the new base64 api has been introduced in py2.4. ........ r52764 | georg.brandl | 2006-11-16 08:50:59 -0800 (Thu, 16 Nov 2006) | 3 lines Bug #1597824: return the registered function from atexit.register() to facilitate usage as a decorator. ........ r52765 | georg.brandl | 2006-11-16 09:08:45 -0800 (Thu, 16 Nov 2006) | 4 lines Bug #1588217: don't parse "= " as a soft line break in binascii's a2b_qp() function, instead leave it in the string as quopri.decode() does. ........ r52776 | andrew.kuchling | 2006-11-17 05:30:25 -0800 (Fri, 17 Nov 2006) | 17 lines Remove file-locking in MH.pack() method. This change looks massive but it's mostly a re-indenting after removing some try...finally blocks. Also adds a test case that does a pack() while the mailbox is locked; this test would have turned up bugs in the original code on some platforms. In both nmh and GNU Mailutils' implementation of MH-format mailboxes, no locking is done of individual message files when renaming them. The original mailbox.py code did do locking, which meant that message files had to be opened. This code was buggy on certain platforms (found through reading the code); there were code paths that closed the file object and then called _unlock_file() on it. Will backport to 25-maint once I see how the buildbots react to this patch. ........ r52780 | martin.v.loewis | 2006-11-18 10:00:23 -0800 (Sat, 18 Nov 2006) | 5 lines Patch #1538878: Don't make tkSimpleDialog dialogs transient if the parent window is withdrawn. This mirrors what dialog.tcl does. Will backport to 2.5. ........ r52782 | martin.v.loewis | 2006-11-18 10:05:35 -0800 (Sat, 18 Nov 2006) | 4 lines Patch #1594554: Always close a tkSimpleDialog on ok(), even if an exception occurs. Will backport to 2.5. ........ r52784 | martin.v.loewis | 2006-11-18 10:42:11 -0800 (Sat, 18 Nov 2006) | 3 lines Patch #1472877: Fix Tix subwidget name resolution. Will backport to 2.5. ........ r52786 | andrew.kuchling | 2006-11-18 14:17:33 -0800 (Sat, 18 Nov 2006) | 1 line Expand checking in test_sha ........ r52787 | georg.brandl | 2006-11-19 00:48:30 -0800 (Sun, 19 Nov 2006) | 3 lines Patch [ 1586791 ] better error msgs for some TypeErrors ........ r52788 | martin.v.loewis | 2006-11-19 02:41:41 -0800 (Sun, 19 Nov 2006) | 4 lines Make cStringIO.truncate raise IOError for negative arguments (even for -1). Fixes the last bit of #1359365. ........ r52789 | andrew.kuchling | 2006-11-19 10:40:01 -0800 (Sun, 19 Nov 2006) | 1 line Add a test case of data w/ bytes > 127 ........ r52790 | martin.v.loewis | 2006-11-19 10:51:54 -0800 (Sun, 19 Nov 2006) | 3 lines Patch #1070046: Marshal new-style objects like InstanceType in xmlrpclib. ........ r52792 | neal.norwitz | 2006-11-19 13:26:53 -0800 (Sun, 19 Nov 2006) | 4 lines Speed up function calls into the math module by using METH_O. There should be no functional changes. However, the error msgs are slightly different. Also verified that the module dict is not NULL on init. ........ r52794 | george.yoshida | 2006-11-19 18:24:48 -0800 (Sun, 19 Nov 2006) | 2 lines markup fix ........ r52795 | georg.brandl | 2006-11-19 23:12:58 -0800 (Sun, 19 Nov 2006) | 3 lines Further markup fix. ........ r52800 | andrew.kuchling | 2006-11-20 05:39:37 -0800 (Mon, 20 Nov 2006) | 2 lines Jython compatibility fix: if uu.decode() opened its output file, be sure to close it. ........ r52811 | neal.norwitz | 2006-11-20 21:26:22 -0800 (Mon, 20 Nov 2006) | 9 lines Bug #1599782: Fix segfault on bsddb.db.DB().type(). The problem is that _DB_get_type() can't be called without the GIL because it calls a bunch of PyErr_* APIs when an error occurs. There were no other cases in this file that it was called without the GIL. Removing the BEGIN/END THREAD around _DB_get_type() made everything work. Will backport. ........ r52814 | neal.norwitz | 2006-11-20 21:51:51 -0800 (Mon, 20 Nov 2006) | 1 line Oops, convert tabs to spaces ........ r52815 | neal.norwitz | 2006-11-20 22:23:44 -0800 (Mon, 20 Nov 2006) | 1 line Fix SF #1599879, socket.gethostname should ref getfqdn directly. ........ r52817 | martin.v.loewis | 2006-11-21 10:20:25 -0800 (Tue, 21 Nov 2006) | 4 lines Conditionalize definition of _CRT_SECURE_NO_DEPRECATE and _CRT_NONSTDC_NO_DEPRECATE. Will backport. ........ r52821 | martin.v.loewis | 2006-11-22 00:50:02 -0800 (Wed, 22 Nov 2006) | 4 lines Patch #1362975: Rework CodeContext indentation algorithm to avoid hard-coding pixel widths. Also make the text's scrollbar a child of the text frame, not the top widget. ........ r52826 | walter.doerwald | 2006-11-22 21:03:56 -0800 (Wed, 22 Nov 2006) | 3 lines Change decode() so that it works with a buffer (i.e. unicode(..., 'utf-8-sig')) SF bug #1601501. ........ r52833 | georg.brandl | 2006-11-23 01:55:07 -0800 (Thu, 23 Nov 2006) | 2 lines Bug #1601630: little improvement to getopt docs ........ r52835 | michael.hudson | 2006-11-23 05:54:04 -0800 (Thu, 23 Nov 2006) | 3 lines a test for an error condition not covered by existing tests (noticed this when writing the equivalent code for pypy) ........ r52839 | raymond.hettinger | 2006-11-23 13:06:03 -0800 (Thu, 23 Nov 2006) | 1 line Fix and/add typo ........ r52840 | raymond.hettinger | 2006-11-23 13:35:19 -0800 (Thu, 23 Nov 2006) | 1 line ... and the number of the counting shall be three. ........ r52841 | thomas.heller | 2006-11-24 10:45:39 -0800 (Fri, 24 Nov 2006) | 1 line Fix bug #1598620: A ctypes structure cannot contain itself. ........ r52843 | martin.v.loewis | 2006-11-25 07:39:19 -0800 (Sat, 25 Nov 2006) | 3 lines Disable _XOPEN_SOURCE on NetBSD 1.x. Will backport to 2.5 ........ r52845 | georg.brandl | 2006-11-26 11:27:47 -0800 (Sun, 26 Nov 2006) | 2 lines Bug #1603321: make pstats.Stats accept Unicode file paths. ........ r52850 | georg.brandl | 2006-11-27 10:46:21 -0800 (Mon, 27 Nov 2006) | 2 lines Bug #1603789: grammatical error in Tkinter docs. ........ r52855 | thomas.heller | 2006-11-28 12:21:54 -0800 (Tue, 28 Nov 2006) | 7 lines Fix #1563807: _ctypes built on AIX fails with ld ffi error. The contents of ffi_darwin.c must be compiled unless __APPLE__ is defined and __ppc__ is not. Will backport. ........ r52862 | armin.rigo | 2006-11-29 13:59:22 -0800 (Wed, 29 Nov 2006) | 3 lines Forgot a case where the locals can now be a general mapping instead of just a dictionary. (backporting...) ........ r52872 | guido.van.rossum | 2006-11-30 11:23:13 -0800 (Thu, 30 Nov 2006) | 2 lines Update version. ........ r52890 | walter.doerwald | 2006-12-01 08:59:47 -0800 (Fri, 01 Dec 2006) | 3 lines Move xdrlib tests from the module into a separate test script, port the tests to unittest and add a few new tests. ........ r52900 | raymond.hettinger | 2006-12-01 18:00:39 -0800 (Fri, 01 Dec 2006) | 1 line Add name to credits (for untokenize). ........ r52905 | martin.v.loewis | 2006-12-03 01:54:46 -0800 (Sun, 03 Dec 2006) | 2 lines Move IDLE news into NEWS.txt. ........ r52906 | martin.v.loewis | 2006-12-03 03:23:45 -0800 (Sun, 03 Dec 2006) | 4 lines Patch #1544279: Improve thread-safety of the socket module by moving the sock_addr_t storage out of the socket object. Will backport to 2.5. ........ r52908 | martin.v.loewis | 2006-12-03 04:01:53 -0800 (Sun, 03 Dec 2006) | 3 lines Patch #1371075: Make ConfigParser accept optional dict type for ordering, sorting, etc. ........ r52910 | matthias.klose | 2006-12-03 09:16:41 -0800 (Sun, 03 Dec 2006) | 2 lines - Fix build failure on kfreebsd and on the hurd. ........ r52915 | george.yoshida | 2006-12-04 03:41:54 -0800 (Mon, 04 Dec 2006) | 2 lines fix a versionchanged tag ........ r52917 | george.yoshida | 2006-12-04 21:39:50 -0800 (Mon, 04 Dec 2006) | 3 lines Fix pickle doc typo Patch #1608758 ........ r52938 | georg.brandl | 2006-12-06 14:21:18 -0800 (Wed, 06 Dec 2006) | 2 lines Patch #1610437: fix a tarfile bug with long filename headers. ........ r52945 | brett.cannon | 2006-12-06 15:38:48 -0800 (Wed, 06 Dec 2006) | 3 lines Fix a bad assumption that all objects assigned to '__loader__' on a module will have a '_files' attribute. ........ r52951 | georg.brandl | 2006-12-07 01:30:06 -0800 (Thu, 07 Dec 2006) | 3 lines RFE #1592899: mention string.maketrans() in docs for str.translate, remove reference to the old regex module in the former's doc. ........ r52962 | raymond.hettinger | 2006-12-07 19:17:18 -0800 (Thu, 07 Dec 2006) | 1 line Eliminate two redundant calls to PyObject_Hash(). ........ r52963 | raymond.hettinger | 2006-12-07 20:24:33 -0800 (Thu, 07 Dec 2006) | 3 lines Port Armin's fix for a dict resize vulnerability (svn revision 46589, sf bug 1456209). ........ r52964 | raymond.hettinger | 2006-12-07 20:57:50 -0800 (Thu, 07 Dec 2006) | 4 lines Port Georg's dictobject.c fix keys that were tuples got unpacked on the way to setting a KeyError (svn revision 52535, sf bug 1576657). ........ r52966 | raymond.hettinger | 2006-12-08 09:35:25 -0800 (Fri, 08 Dec 2006) | 2 lines Add test for SF bug 1576657 ........ r52970 | georg.brandl | 2006-12-08 12:46:11 -0800 (Fri, 08 Dec 2006) | 3 lines #1577756: svnversion doesn't react to LANG=C, use LC_ALL=C to force English output. ........ r52972 | georg.brandl | 2006-12-09 01:08:29 -0800 (Sat, 09 Dec 2006) | 3 lines Patch #1608267: fix a race condition in os.makedirs() is the directory to be created is already there. ........ r52975 | matthias.klose | 2006-12-09 04:15:27 -0800 (Sat, 09 Dec 2006) | 2 lines - Fix the build of the library reference in info format. ........ r52994 | neal.norwitz | 2006-12-10 17:01:06 -0800 (Sun, 10 Dec 2006) | 1 line Fix a typo ........ r52996 | georg.brandl | 2006-12-10 23:56:33 -0800 (Sun, 10 Dec 2006) | 2 lines Move errno imports back to individual functions. ........ r52998 | vinay.sajip | 2006-12-11 06:07:16 -0800 (Mon, 11 Dec 2006) | 1 line Patch by Jeremy Katz (SF #1609407) ........ r53000 | vinay.sajip | 2006-12-11 06:26:23 -0800 (Mon, 11 Dec 2006) | 1 line Patch by "cuppatea" (SF #1503765) ........ r53012 | walter.doerwald | 2006-12-12 13:55:31 -0800 (Tue, 12 Dec 2006) | 2 lines Fix typo. ........ r53023 | brett.cannon | 2006-12-13 14:31:37 -0800 (Wed, 13 Dec 2006) | 2 lines Remove an unneeded import of 'warnings'. ........ r53025 | brett.cannon | 2006-12-13 15:02:38 -0800 (Wed, 13 Dec 2006) | 2 lines Remove unneeded imports of 'warnings'. ........ r53026 | brett.cannon | 2006-12-13 15:09:53 -0800 (Wed, 13 Dec 2006) | 4 lines Add test.test_support.guard_warnings_filter . This function returns a context manager that protects warnings.filter from being modified once the context is exited. ........ r53029 | george.yoshida | 2006-12-13 18:22:44 -0800 (Wed, 13 Dec 2006) | 2 lines Note that guard_warnings_filter was added in 2.6 ........ r53031 | vinay.sajip | 2006-12-14 00:53:55 -0800 (Thu, 14 Dec 2006) | 1 line Added news on recent changes to logging ........ r53032 | andrew.kuchling | 2006-12-14 10:57:53 -0800 (Thu, 14 Dec 2006) | 1 line [Patch #1599256 from David Watson] check that os.fsync is available before using it ........ r53042 | kurt.kaiser | 2006-12-14 21:13:11 -0800 (Thu, 14 Dec 2006) | 6 lines 1. Avoid hang when encountering a duplicate in a completion list. Bug 1571112. 2. Duplicate some old entries from Python's NEWS to IDLE's NEWS.txt M AutoCompleteWindow.py M NEWS.txt ........ r53048 | andrew.kuchling | 2006-12-18 09:12:31 -0800 (Mon, 18 Dec 2006) | 1 line [Bug #1618083] Add missing word; make a few grammar fixes ........ r53050 | andrew.kuchling | 2006-12-18 09:16:05 -0800 (Mon, 18 Dec 2006) | 1 line Bump version ........ r53051 | andrew.kuchling | 2006-12-18 09:22:07 -0800 (Mon, 18 Dec 2006) | 1 line [Bug #1616726] Fix description of generator.close(); if you raise some random exception, the exception is raised and doesn't trigger a RuntimeError ........ r53052 | andrew.kuchling | 2006-12-18 09:38:14 -0800 (Mon, 18 Dec 2006) | 1 line Describe new methods in Queue module ........ r53053 | andrew.kuchling | 2006-12-18 11:22:24 -0800 (Mon, 18 Dec 2006) | 1 line [Patch #1615868 by Lars Gustaebel] Use Py_off_t to fix BZ2File.seek() for offsets > 2Gb ........ r53057 | andrew.kuchling | 2006-12-18 13:29:07 -0800 (Mon, 18 Dec 2006) | 1 line Fix markup ........ r53063 | thomas.wouters | 2006-12-19 00:17:50 -0800 (Tue, 19 Dec 2006) | 5 lines Make sre's SubPattern objects accept slice objects like it already accepts simple slices. ........ r53065 | andrew.kuchling | 2006-12-19 06:13:05 -0800 (Tue, 19 Dec 2006) | 6 lines [Patch #1618455 by Ben Maurer] Improve speed of HMAC by using str.translate() instead of a more general XOR that has to construct a list. Slightly modified from Maurer's patch: the _strxor() function is no longer necessary at all. ........ r53066 | andrew.kuchling | 2006-12-19 06:28:23 -0800 (Tue, 19 Dec 2006) | 9 lines [Bug #1613651] Document socket.recv_into, socket.recvfrom_into Also, the text for recvfrom told you to read recv() for an explanation of the 'flags' argument, but recv() just pointed you at the man page. Copied the man-page text to recvfrom(), recvfrom_into, recv_into to avoid the pointless redirection. I don't have LaTeX on this machine; hope my markup is OK. ........ r53067 | andrew.kuchling | 2006-12-19 06:29:04 -0800 (Tue, 19 Dec 2006) | 1 line Comment typo ........ r53068 | andrew.kuchling | 2006-12-19 07:11:41 -0800 (Tue, 19 Dec 2006) | 1 line [Patch #1617413 from Dug Song] Fix HTTP Basic authentication via HTTPS ........ r53071 | andrew.kuchling | 2006-12-19 07:18:12 -0800 (Tue, 19 Dec 2006) | 1 line [Patch #1600491 from Jim Jewett] Describe how to build help files on Windows ........ r53073 | andrew.kuchling | 2006-12-19 07:43:10 -0800 (Tue, 19 Dec 2006) | 6 lines [Patch #1587139 by kxroberto] Protect lock acquisition/release with try...finally to ensure the lock is always released. This could use the 'with' statement, but the patch uses 'finally'. 2.5 backport candidate. ........ r53074 | vinay.sajip | 2006-12-19 10:29:11 -0800 (Tue, 19 Dec 2006) | 1 line Updated documentation for findCaller() to indicate that a 3-tuple is now returned, rather than a 2-tuple. ........ r53090 | georg.brandl | 2006-12-19 14:06:46 -0800 (Tue, 19 Dec 2006) | 3 lines Patch #1484695: The tarfile module now raises a HeaderError exception if a buffer given to frombuf() is invalid. ........ r53099 | raymond.hettinger | 2006-12-19 22:42:06 -0800 (Tue, 19 Dec 2006) | 5 lines Bug #1590891: random.randrange don't return correct value for big number Needs to be backported. ........ r53106 | georg.brandl | 2006-12-20 03:55:16 -0800 (Wed, 20 Dec 2006) | 3 lines Testcase for patch #1484695. ........ r53110 | andrew.kuchling | 2006-12-20 11:48:20 -0800 (Wed, 20 Dec 2006) | 17 lines [Apply length-checking.diff from bug #1599254] Add length checking to single-file mailbox formats: before doing a flush() on a mailbox, seek to the end and verify its length is unchanged, raising ExternalClashError if the file's length has changed. This fix avoids potential data loss if some other process appends to the mailbox file after the table of contents has been generated; instead of overwriting the modified file, you'll get the exception. I also noticed that the self._lookup() call in self.flush() wasn't necessary (everything that sets self._pending to True also calls self.lookup()), and replaced it by an assertion. 2.5 backport candidate. ........ r53112 | andrew.kuchling | 2006-12-20 11:57:10 -0800 (Wed, 20 Dec 2006) | 1 line [Bug #1619674] Make sum() use the term iterable, not sequence ........ r53113 | andrew.kuchling | 2006-12-20 11:58:11 -0800 (Wed, 20 Dec 2006) | 1 line Two grammar fixes ........ r53115 | andrew.kuchling | 2006-12-20 12:11:12 -0800 (Wed, 20 Dec 2006) | 5 lines Some other built-in functions are described with 'sequence' arguments that should really be 'iterable'; this commit changes them. Did I miss any? Did I introduce any errors? ........ r53117 | andrew.kuchling | 2006-12-20 12:20:42 -0800 (Wed, 20 Dec 2006) | 1 line [Bug #1619680] in_dll() arguments are documented in the wrong order ........ r53120 | neal.norwitz | 2006-12-20 20:38:00 -0800 (Wed, 20 Dec 2006) | 1 line Lars asked for permission on on python-dev for work on tarfile.py ........ r53125 | andrew.kuchling | 2006-12-21 05:40:29 -0800 (Thu, 21 Dec 2006) | 1 line Mention the os.SEEK_* constants ........ r53129 | walter.doerwald | 2006-12-21 10:06:30 -0800 (Thu, 21 Dec 2006) | 2 lines Fix typo. ........ r53131 | thomas.heller | 2006-12-21 10:30:56 -0800 (Thu, 21 Dec 2006) | 3 lines Fix wrong markup of an argument in a method signature. Will backport. ........ r53137 | andrew.kuchling | 2006-12-21 16:50:56 -0800 (Thu, 21 Dec 2006) | 1 line Typo fix ........ r53139 | andrew.kuchling | 2006-12-22 05:25:02 -0800 (Fri, 22 Dec 2006) | 1 line [Bug #737202; fix from Titus Brown] Make CGIHTTPServer work for scripts in sub-directories ........ r53141 | andrew.kuchling | 2006-12-22 07:04:45 -0800 (Fri, 22 Dec 2006) | 6 lines [Bug #802128] Make the mode argument of dumbdbm actually work the way it's described, and add a test for it. 2.5 bugfix candidate, maybe; arguably this patch changes the API of dumbdbm and shouldn't be added in a point-release. ........ r53142 | andrew.kuchling | 2006-12-22 07:16:58 -0800 (Fri, 22 Dec 2006) | 6 lines [Bug #802128 continued] Modify mode depending on the process umask. Is there really no other way to read the umask than to set it? Hope this works on Windows... ........ r53145 | andrew.kuchling | 2006-12-22 08:43:26 -0800 (Fri, 22 Dec 2006) | 1 line [Bug #776202] Apply Walter Doerwald's patch to use text mode for encoded files ........ r53146 | andrew.kuchling | 2006-12-22 10:41:42 -0800 (Fri, 22 Dec 2006) | 9 lines [Patch #783050 from Patrick Lynch] The emulation of forkpty() is incorrect; the master should close the slave fd. Added a test to test_pty.py that reads from the master_fd after doing a pty.fork(); without the fix it hangs forever instead of raising an exception. () 2.5 backport candidate. ........ r53147 | andrew.kuchling | 2006-12-22 11:06:16 -0800 (Fri, 22 Dec 2006) | 1 line [Patch #827559 from Chris Gonnerman] Make SimpleHTTPServer redirect when a directory URL is missing the trailing slash; this lets relative links work. ........ r53149 | andrew.kuchling | 2006-12-22 11:21:27 -0800 (Fri, 22 Dec 2006) | 1 line Darn; this test works when you run test_pty.py directly, but fails when regrtest runs it (the os.read() raises os.error). I can't figure out the cause, so am commenting out the test. ........ r53150 | andrew.kuchling | 2006-12-22 13:48:19 -0800 (Fri, 22 Dec 2006) | 1 line Frak; this test also fails ........ r53153 | lars.gustaebel | 2006-12-23 08:40:13 -0800 (Sat, 23 Dec 2006) | 5 lines Patch #1230446: tarfile.py: fix ExFileObject so that read() and tell() work correctly together with readline(). Will backport to 2.5. ........ r53155 | lars.gustaebel | 2006-12-23 09:57:23 -0800 (Sat, 23 Dec 2006) | 5 lines Patch #1262036: Prevent TarFiles from being added to themselves under certain conditions. Will backport to 2.5. ........ r53159 | andrew.kuchling | 2006-12-26 19:25:31 -0800 (Tue, 26 Dec 2006) | 4 lines [Part of patch #1182394] Move the HMAC blocksize to be a class-level constant; this allows changing it in a subclass. To accommodate this, copy() now uses __class__. Also add some text to a comment. ........ r53160 | andrew.kuchling | 2006-12-26 19:31:24 -0800 (Tue, 26 Dec 2006) | 1 line [Rest of patch #1182394] Add ._current() method so that we can use the written-in-C .hexdigest() method ........ r53161 | lars.gustaebel | 2006-12-27 02:30:46 -0800 (Wed, 27 Dec 2006) | 4 lines Patch #1504073: Fix tarfile.open() for mode "r" with a fileobj argument. Will backport to 2.5. ........ r53165 | neal.norwitz | 2006-12-27 20:39:20 -0800 (Wed, 27 Dec 2006) | 1 line Remove a stray (old) macro name left around (I guess) ........ r53188 | neal.norwitz | 2006-12-28 19:01:53 -0800 (Thu, 28 Dec 2006) | 1 line SF bug #1623890, fix argument name in docstring ........ r53200 | raymond.hettinger | 2006-12-29 20:01:17 -0800 (Fri, 29 Dec 2006) | 1 line For sets with cyclical reprs, emit an ellipsis instead of infinitely recursing. ........ r53232 | brett.cannon | 2007-01-03 16:23:49 -0800 (Wed, 03 Jan 2007) | 3 lines Add EnvironmentVarGuard to test.test_support. Provides a context manager to temporarily set or unset environment variables. ........ r53235 | neal.norwitz | 2007-01-03 22:25:31 -0800 (Wed, 03 Jan 2007) | 1 line SF #1627373, fix typo in CarbonEvt. ........ r53244 | raymond.hettinger | 2007-01-04 09:53:34 -0800 (Thu, 04 Jan 2007) | 1 line Fix stability of heapq's nlargest() and nsmallest(). ........ r53249 | martin.v.loewis | 2007-01-04 13:06:12 -0800 (Thu, 04 Jan 2007) | 3 lines Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, to avoid relying on atexit. Will backport to 2.5. ........ r53252 | gregory.p.smith | 2007-01-04 17:59:42 -0800 (Thu, 04 Jan 2007) | 3 lines Support linking of the bsddb module against BerkeleyDB 4.5.x (will backport to 2.5) ........ r53253 | gregory.p.smith | 2007-01-04 18:06:17 -0800 (Thu, 04 Jan 2007) | 2 lines bump module version to match supported berkeleydb version ........ r53255 | neal.norwitz | 2007-01-04 21:25:22 -0800 (Thu, 04 Jan 2007) | 6 lines Prevent crash on shutdown which can occur if we are finalizing and the module dict has been cleared already and some object raises a warning (like in a __del__). Will backport. ........ r53258 | gregory.p.smith | 2007-01-04 23:21:35 -0800 (Thu, 04 Jan 2007) | 2 lines typo fix ........ r53260 | neal.norwitz | 2007-01-05 00:06:43 -0800 (Fri, 05 Jan 2007) | 1 line Add Collin Winter for access to update PEP 3107 ........ r53262 | andrew.kuchling | 2007-01-05 06:22:17 -0800 (Fri, 05 Jan 2007) | 1 line [Bug #1622533] Make docstrings raw strings because they contain control characters (\0, \1) ........ r53264 | andrew.kuchling | 2007-01-05 07:51:24 -0800 (Fri, 05 Jan 2007) | 1 line [Patch #1520904] Fix bsddb tests to write to the temp directory instead of the Lib/bsddb/test directory ........ r53279 | brett.cannon | 2007-01-05 13:45:09 -0800 (Fri, 05 Jan 2007) | 3 lines Silence a warning from gcc 4.0.1 by specifying a function's parameter list is 'void' instead of just a set of empty parentheses. ........ r53285 | raymond.hettinger | 2007-01-05 17:14:41 -0800 (Fri, 05 Jan 2007) | 2 lines SF# 1409443: Expand comment to cover the interaction between f->f_lasti and the PREDICT macros. ........ r53286 | anthony.baxter | 2007-01-05 20:45:54 -0800 (Fri, 05 Jan 2007) | 1 line update to (c) years to include 2007 ........ r53291 | neal.norwitz | 2007-01-06 13:24:35 -0800 (Sat, 06 Jan 2007) | 1 line Add Josiah to SF for maintaining asyncore/asynchat ........ r53293 | peter.astrand | 2007-01-07 00:53:46 -0800 (Sun, 07 Jan 2007) | 1 line Re-implemented fix for #1531862 once again, in a way that works with Python 2.2. Fixes bug #1603424. ........ r53295 | peter.astrand | 2007-01-07 06:34:16 -0800 (Sun, 07 Jan 2007) | 1 line Avoid O(N**2) bottleneck in _communicate_(). Fixes #1598181. ........ r53300 | raymond.hettinger | 2007-01-08 10:09:20 -0800 (Mon, 08 Jan 2007) | 1 line Fix zero-length corner case for iterating over a mutating deque. ........ r53301 | vinay.sajip | 2007-01-08 10:50:32 -0800 (Mon, 08 Jan 2007) | 4 lines Bare except clause removed from SMTPHandler.emit(). Now, only ImportError is trapped. Bare except clause removed from SocketHandler.createSocket(). Now, only socket.error is trapped. (SF #411881) ........ r53302 | vinay.sajip | 2007-01-08 10:51:46 -0800 (Mon, 08 Jan 2007) | 2 lines Bare except clause removed from LogRecord.__init__. Now, only ValueError, TypeError and AttributeError are trapped. (SF #411881) ........ r53303 | vinay.sajip | 2007-01-08 10:52:36 -0800 (Mon, 08 Jan 2007) | 1 line Added entries about removal of some bare except clauses from logging. ........ r53304 | vinay.sajip | 2007-01-09 06:50:28 -0800 (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 06:51:36 -0800 (Tue, 09 Jan 2007) | 1 line Added entry about addition of _open() method to logging.FileHandler. ........ r53306 | vinay.sajip | 2007-01-09 06:54:56 -0800 (Tue, 09 Jan 2007) | 1 line Added a docstring ........ r53316 | thomas.heller | 2007-01-09 11:19:33 -0800 (Tue, 09 Jan 2007) | 4 lines Verify the sizes of the basic ctypes data types against the struct module. Will backport to release25-maint. . Modified: python/branches/bcannon-objcap/Demo/parser/unparse.py ============================================================================== --- python/branches/bcannon-objcap/Demo/parser/unparse.py (original) +++ python/branches/bcannon-objcap/Demo/parser/unparse.py Tue Jan 9 23:27:11 2007 @@ -223,6 +223,9 @@ def _FunctionDef(self, t): self.write("\n") + for deco in t.decorators: + self.fill("@") + self.dispatch(deco) self.fill("def "+t.name + "(") self.dispatch(t.args) self.write(")") Modified: python/branches/bcannon-objcap/Doc/README ============================================================================== --- python/branches/bcannon-objcap/Doc/README (original) +++ python/branches/bcannon-objcap/Doc/README Tue Jan 9 23:27:11 2007 @@ -229,7 +229,7 @@ as long as you don't change or remove the copyright notice: ---------------------------------------------------------------------- -Copyright (c) 2000-2006 Python Software Foundation. +Copyright (c) 2000-2007 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/branches/bcannon-objcap/Doc/api/concrete.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/api/concrete.tex (original) +++ python/branches/bcannon-objcap/Doc/api/concrete.tex Tue Jan 9 23:27:11 2007 @@ -602,15 +602,15 @@ \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v} - Return a new string object with the value \var{v} on success, and - \NULL{} on failure. The parameter \var{v} must not be \NULL{}; it - will not be checked. + Return a new string object with a copy of the string \var{v} as value + on success, and \NULL{} on failure. The parameter \var{v} must not be + \NULL{}; it will not be checked. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v, Py_ssize_t len} - Return a new string object with the value \var{v} and length - \var{len} on success, and \NULL{} on failure. If \var{v} is + Return a new string object with a copy of the string \var{v} as value + and length \var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{}, the contents of the string are uninitialized. \end{cfuncdesc} @@ -2879,10 +2879,10 @@ Various date and time objects are supplied by the \module{datetime} module. Before using any of these functions, the header file \file{datetime.h} must be included in your source (note that this is -not include by \file{Python.h}), and macro \cfunction{PyDateTime_IMPORT()} -must be invoked. The macro arranges to put a pointer to a C structure -in a static variable \code{PyDateTimeAPI}, which is used by the following -macros. +not included by \file{Python.h}), and the macro +\cfunction{PyDateTime_IMPORT} must be invoked. The macro puts a +pointer to a C structure into a static variable, +\code{PyDateTimeAPI}, that is used by the following macros. Type-check macros: @@ -3080,9 +3080,9 @@ \cfunction{PyObject_IsTrue()}, \cfunction{PyObject_Print()}, and \cfunction{PyObject_GetIter()}) or the abstract number protocol (including -\cfunction{PyNumber_Add()}, \cfunction{PyNumber_Subtract()}, +\cfunction{PyNumber_And()}, \cfunction{PyNumber_Subtract()}, \cfunction{PyNumber_Or()}, \cfunction{PyNumber_Xor()}, -\cfunction{PyNumber_InPlaceAdd()}, \cfunction{PyNumber_InPlaceSubtract()}, +\cfunction{PyNumber_InPlaceAnd()}, \cfunction{PyNumber_InPlaceSubtract()}, \cfunction{PyNumber_InPlaceOr()}, and \cfunction{PyNumber_InPlaceXor()}). \begin{ctypedesc}{PySetObject} Modified: python/branches/bcannon-objcap/Doc/api/exceptions.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/api/exceptions.tex (original) +++ python/branches/bcannon-objcap/Doc/api/exceptions.tex Tue Jan 9 23:27:11 2007 @@ -328,7 +328,7 @@ default effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the \withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}} \exception{KeyboardInterrupt} exception. If an exception is raised - the error indicator is set and the function returns \code{1}; + the error indicator is set and the function returns \code{-1}; otherwise the function returns \code{0}. The error indicator may or may not be cleared if it was previously set. \end{cfuncdesc} Modified: python/branches/bcannon-objcap/Doc/api/newtypes.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/api/newtypes.tex (original) +++ python/branches/bcannon-objcap/Doc/api/newtypes.tex Tue Jan 9 23:27:11 2007 @@ -103,8 +103,6 @@ the value for the \var{methods} argument]{2.3} \end{cfuncdesc} -DL_IMPORT - \begin{cvardesc}{PyObject}{_Py_NoneStruct} Object which is visible in Python as \code{None}. This should only be accessed using the \code{Py_None} macro, which evaluates to a Modified: python/branches/bcannon-objcap/Doc/dist/dist.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/dist/dist.tex (original) +++ python/branches/bcannon-objcap/Doc/dist/dist.tex Tue Jan 9 23:27:11 2007 @@ -3607,6 +3607,11 @@ % todo +\section{\module{distutils.command.bdist_msi} --- Build a Microsoft Installer binary package} +\declaremodule[distutils.command.bdistmsi]{standard}{distutils.command.bdist_msi} +\modulesynopsis{Build a binary distribution as a Windows MSI file} + +% todo \section{\module{distutils.command.bdist_rpm} --- Build a binary distribution as a Redhat RPM and SRPM} \declaremodule[distutils.command.bdistrpm]{standard}{distutils.command.bdist_rpm} Modified: python/branches/bcannon-objcap/Doc/ext/extending.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/ext/extending.tex (original) +++ python/branches/bcannon-objcap/Doc/ext/extending.tex Tue Jan 9 23:27:11 2007 @@ -221,6 +221,8 @@ PyObject *m; m = Py_InitModule("spam", SpamMethods); + if (m == NULL) + return; SpamError = PyErr_NewException("spam.error", NULL, NULL); Py_INCREF(SpamError); @@ -365,9 +367,9 @@ created module based upon the table (an array of \ctype{PyMethodDef} structures) that was passed as its second argument. \cfunction{Py_InitModule()} returns a pointer to the module object -that it creates (which is unused here). It aborts with a fatal error -if the module could not be initialized satisfactorily, so the caller -doesn't need to check for errors. +that it creates (which is unused here). It may abort with a fatal error +for certain errors, or return \NULL{} if the module could not be +initialized satisfactorily. When embedding Python, the \cfunction{initspam()} function is not called automatically unless there's an entry in the @@ -1276,6 +1278,8 @@ PyObject *c_api_object; m = Py_InitModule("spam", SpamMethods); + if (m == NULL) + return; /* Initialize the C API pointer array */ PySpam_API[PySpam_System_NUM] = (void *)PySpam_System; @@ -1362,7 +1366,9 @@ { PyObject *m; - Py_InitModule("client", ClientMethods); + m = Py_InitModule("client", ClientMethods); + if (m == NULL) + return; if (import_spam() < 0) return; /* additional initialization can happen here */ Modified: python/branches/bcannon-objcap/Doc/howto/functional.rst ============================================================================== --- python/branches/bcannon-objcap/Doc/howto/functional.rst (original) +++ python/branches/bcannon-objcap/Doc/howto/functional.rst Tue Jan 9 23:27:11 2007 @@ -1,7 +1,7 @@ Functional Programming HOWTO ================================ -**Version 0.21** +**Version 0.30** (This is a first draft. Please send comments/error reports/suggestions to amk at amk.ca. This URL is probably not going to @@ -15,6 +15,8 @@ such as ``itertools`` and ``functools``. +.. contents:: + Introduction ---------------------- @@ -339,11 +341,11 @@ Generator expressions and list comprehensions ---------------------------------------------------- -Two common operations on a stream are 1) performing some operation for -every element, 2) selecting a subset of elements that meet some -condition. For example, given a list of strings, you might want to -strip off trailing whitespace from each line or extract all the -strings containing a given substring. +Two common operations on an iterator's output are 1) performing some +operation for every element, 2) selecting a subset of elements that +meet some condition. For example, given a list of strings, you might +want to strip off trailing whitespace from each line or extract all +the strings containing a given substring. List comprehensions and generator expressions (short form: "listcomps" and "genexps") are a concise notation for such operations, borrowed @@ -658,7 +660,7 @@ Two Python's built-in functions, ``map()`` and ``filter()``, are somewhat obsolete; they duplicate the features of list comprehensions -and return actual lists instead of iterators. +but return actual lists instead of iterators. ``map(f, iterA, iterB, ...)`` returns a list containing ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``. @@ -675,7 +677,7 @@ As shown above, you can achieve the same effect with a list comprehension. The ``itertools.imap()`` function does the same thing -but can handle infinite iterators; it'll be discussed in the section on +but can handle infinite iterators; it'll be discussed later, in the section on the ``itertools`` module. ``filter(predicate, iter)`` returns a list @@ -705,7 +707,7 @@ ``reduce(func, iter, [initial_value])`` doesn't have a counterpart in the ``itertools`` module because it cumulatively performs an operation on all the iterable's elements and therefore can't be applied to -infinite ones. ``func`` must be a function that takes two elements +infinite iterables. ``func`` must be a function that takes two elements and returns a single value. ``reduce()`` takes the first two elements A and B returned by the iterator and calculates ``func(A, B)``. It then requests the third element, C, calculates ``func(func(A, B), @@ -821,7 +823,7 @@ If the function you need doesn't exist, you need to write it. One way to write small functions is to use the ``lambda`` statement. ``lambda`` takes a number of parameters and an expression combining these parameters, -and creates a small function that returns the value of the expression: +and creates a small function that returns the value of the expression:: lowercase = lambda x: x.lower() @@ -842,14 +844,15 @@ return x + y Which alternative is preferable? That's a style question; my usual -view is to avoid using ``lambda``. +course is to avoid using ``lambda``. -``lambda`` is quite limited in the functions it can define. The -result has to be computable as a single expression, which means you -can't have multiway ``if... elif... else`` comparisons or -``try... except`` statements. If you try to do too much in a -``lambda`` statement, you'll end up with an overly complicated -expression that's hard to read. Quick, what's the following code doing? +One reason for my preference is that ``lambda`` is quite limited in +the functions it can define. The result has to be computable as a +single expression, which means you can't have multiway +``if... elif... else`` comparisons or ``try... except`` statements. +If you try to do too much in a ``lambda`` statement, you'll end up +with an overly complicated expression that's hard to read. Quick, +what's the following code doing? :: @@ -886,8 +889,8 @@ 4) Convert the lambda to a def statement, using that name. 5) Remove the comment. -I really like these rules, but you're free to disagree that this style -is better. +I really like these rules, but you're free to disagree that this +lambda-free style is better. The itertools module @@ -897,6 +900,16 @@ as well as functions for combining several iterators. This section will introduce the module's contents by showing small examples. +The module's functions fall into a few broad classes: + +* Functions that create a new iterator based on an existing iterator. +* Functions for treating an iterator's elements as function arguments. +* Functions for selecting portions of an iterator's output. +* A function for grouping an iterator's output. + +Creating new iterators +'''''''''''''''''''''' + ``itertools.count(n)`` returns an infinite stream of integers, increasing by 1 each time. You can optionally supply the starting number, which defaults to 0:: @@ -941,6 +954,12 @@ itertools.izip(['a', 'b', 'c'], (1, 2, 3)) => ('a', 1), ('b', 2), ('c', 3) +It's similiar to the built-in ``zip()`` function, but doesn't +construct an in-memory list and exhaust all the input iterators before +returning; instead tuples are constructed and returned only if they're +requested. (The technical term for this behaviour is +`lazy evaluation `__.) + This iterator is intended to be used with iterables that are all of the same length. If the iterables are of different lengths, the resulting stream will be the same length as the shortest iterable. @@ -956,9 +975,10 @@ element. ``itertools.islice(iter, [start], stop, [step])`` returns a stream -that's a slice of the iterator. It can return the first ``stop`` +that's a slice of the iterator. With a single ``stop`` argument, +it will return the first ``stop`` elements. If you supply a starting index, you'll get ``stop-start`` -elements, and if you supply a value for ``step` elements will be +elements, and if you supply a value for ``step`, elements will be skipped accordingly. Unlike Python's string and list slicing, you can't use negative values for ``start``, ``stop``, or ``step``. @@ -990,6 +1010,9 @@ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... +Calling functions on elements +''''''''''''''''''''''''''''' + Two functions are used for calling other functions on the contents of an iterable. @@ -1018,6 +1041,10 @@ => /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby + +Selecting elements +'''''''''''''''''' + Another group of functions chooses a subset of an iterator's elements based on a predicate. @@ -1064,6 +1091,9 @@ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ... +Grouping elements +''''''''''''''''' + The last function I'll discuss, ``itertools.groupby(iter, key_func=None)``, is the most complicated. ``key_func(elem)`` is a function that can compute a key value for each element returned by the @@ -1109,15 +1139,16 @@ ---------------------------------------------- The ``functools`` module in Python 2.5 contains some higher-order -functions. A **higher-order function** takes functions as input and -returns new functions. The most useful tool in this module is the -``partial()`` function. +functions. A **higher-order function** takes one or more functions as +input and returns a new function. The most useful tool in this module +is the ``partial()`` function. For programs written in a functional style, you'll sometimes want to construct variants of existing functions that have some of the parameters filled in. Consider a Python function ``f(a, b, c)``; you -may wish to create a new function ``g(b, c)`` that was equivalent to -``f(1, b, c)``. This is called "partial function application". +may wish to create a new function ``g(b, c)`` that's equivalent to +``f(1, b, c)``; you're filling in a value for one of ``f()``'s parameters. +This is called "partial function application". The constructor for ``partial`` takes the arguments ``(function, arg1, arg2, ... kwarg1=value1, kwarg2=value2)``. The resulting object is @@ -1136,9 +1167,165 @@ server_log = functools.partial(log, subsystem='server') server_log('Unable to open socket') -There are also third-party modules, such as Collin Winter's -`functional package `__, -that are intended for use in functional-style programs. + +The operator module +------------------- + +The ``operator`` module was mentioned earlier. It contains a set of +functions corresponding to Python's operators. These functions +are often useful in functional-style code because they save you +from writing trivial functions that perform a single operation. + +Some of the functions in this module are: + +* Math operations: ``add()``, ``sub()``, ``mul()``, ``div()``, ``floordiv()``, + ``abs()``, ... +* Logical operations: ``not_()``, ``truth()``. +* Bitwise operations: ``and_()``, ``or_()``, ``invert()``. +* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``. +* Object identity: ``is_()``, ``is_not()``. + +Consult `the operator module's documentation `__ for a complete +list. + + + +The functional module +--------------------- + +Collin Winter's `functional module `__ +provides a number of more +advanced tools for functional programming. It also reimplements +several Python built-ins, trying to make them more intuitive to those +used to functional programming in other languages. + +This section contains an introduction to some of the most important +functions in ``functional``; full documentation can be found at `the +project's website `__. + +``compose(outer, inner, unpack=False)`` + +The ``compose()`` function implements function composition. +In other words, it returns a wrapper around the ``outer`` and ``inner`` callables, such +that the return value from ``inner`` is fed directly to ``outer``. That is, + +:: + + >>> def add(a, b): + ... return a + b + ... + >>> def double(a): + ... return 2 * a + ... + >>> compose(double, add)(5, 6) + 22 + +is equivalent to + +:: + + >>> double(add(5, 6)) + 22 + +The ``unpack`` keyword is provided to work around the fact that Python functions are not always +`fully curried `__. +By default, it is expected that the ``inner`` function will return a single object and that the ``outer`` +function will take a single argument. Setting the ``unpack`` argument causes ``compose`` to expect a +tuple from ``inner`` which will be expanded before being passed to ``outer``. Put simply, + +:: + + compose(f, g)(5, 6) + +is equivalent to:: + + f(g(5, 6)) + +while + +:: + + compose(f, g, unpack=True)(5, 6) + +is equivalent to:: + + f(*g(5, 6)) + +Even though ``compose()`` only accepts two functions, it's trivial to +build up a version that will compose any number of functions. We'll +use ``reduce()``, ``compose()`` and ``partial()`` (the last of which +is provided by both ``functional`` and ``functools``). + +:: + + from functional import compose, partial + + multi_compose = partial(reduce, compose) + + +We can also use ``map()``, ``compose()`` and ``partial()`` to craft a +version of ``"".join(...)`` that converts its arguments to string:: + + from functional import compose, partial + + join = compose("".join, partial(map, str)) + + +``flip(func)`` + +``flip()`` wraps the callable in ``func`` and +causes it to receive its non-keyword arguments in reverse order. + +:: + + >>> def triple(a, b, c): + ... return (a, b, c) + ... + >>> triple(5, 6, 7) + (5, 6, 7) + >>> + >>> flipped_triple = flip(triple) + >>> flipped_triple(5, 6, 7) + (7, 6, 5) + +``foldl(func, start, iterable)`` + +``foldl()`` takes a binary function, a starting value (usually some kind of 'zero'), and an iterable. +The function is applied to the starting value and the first element of the list, then the result of +that and the second element of the list, then the result of that and the third element of the list, +and so on. + +This means that a call such as:: + + foldl(f, 0, [1, 2, 3]) + +is equivalent to:: + + f(f(f(0, 1), 2), 3) + + +``foldl()`` is roughly equivalent to the following recursive function:: + + def foldl(func, start, seq): + if len(seq) == 0: + return start + + return foldl(func, func(start, seq[0]), seq[1:]) + +Speaking of equivalence, the above ``foldl`` call can be expressed in terms of the built-in ``reduce`` like +so:: + + reduce(f, [1, 2, 3], 0) + + +We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to +write a cleaner, more aesthetically-pleasing version of Python's +``"".join(...)`` idiom:: + + from functional import foldl, partial + from operator import concat + + join = partial(foldl, concat, "") Revision History and Acknowledgements @@ -1159,6 +1346,10 @@ Version 0.21: Added more references suggested on the tutor mailing list. +Version 0.30: Adds a section on the ``functional`` module written by +Collin Winter; adds short section on the operator module; a few other +edits. + References -------------------- @@ -1185,6 +1376,8 @@ http://en.wikipedia.org/wiki/Coroutine: Entry for coroutines. +http://en.wikipedia.org/wiki/Currying: +Entry for the concept of currying. Python-specific ''''''''''''''''''''''''''' @@ -1205,10 +1398,10 @@ ''''''''''''''''''''''''''' http://docs.python.org/lib/module-itertools.html: -Documentation ``for the itertools`` module. +Documentation for the ``itertools`` module. http://docs.python.org/lib/module-operator.html: -Documentation ``for the operator`` module. +Documentation for the ``operator`` module. http://www.python.org/dev/peps/pep-0289/: PEP 289: "Generator Expressions" Modified: python/branches/bcannon-objcap/Doc/howto/regex.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/howto/regex.tex (original) +++ python/branches/bcannon-objcap/Doc/howto/regex.tex Tue Jan 9 23:27:11 2007 @@ -367,7 +367,7 @@ strings, and displays whether the RE matches or fails. \file{redemo.py} can be quite useful when trying to debug a complicated RE. Phil Schwartz's -\ulink{Kodos}{http://kodos.sourceforge.net} is also an interactive +\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. Modified: python/branches/bcannon-objcap/Doc/inst/inst.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/inst/inst.tex (original) +++ python/branches/bcannon-objcap/Doc/inst/inst.tex Tue Jan 9 23:27:11 2007 @@ -632,7 +632,7 @@ installation base directory when you run the setup script. For example, \begin{verbatim} -python setup.py --install-base=/tmp +python setup.py install --install-base=/tmp \end{verbatim} would install pure modules to \filevar{/tmp/python/lib} in the first Modified: python/branches/bcannon-objcap/Doc/lib/libasyncore.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libasyncore.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libasyncore.tex Tue Jan 9 23:27:11 2007 @@ -198,9 +198,11 @@ \end{methoddesc} \begin{methoddesc}{bind}{address} - Bind the socket to \var{address}. The socket must not already - be bound. (The format of \var{address} depends on the address - family --- see above.) + Bind the socket to \var{address}. The socket must not already be + bound. (The format of \var{address} depends on the address family + --- see above.) To mark the socket as re-usable (setting the + \constant{SO_REUSEADDR} option), call the \class{dispatcher} + object's \method{set_reuse_addr()} method. \end{methoddesc} \begin{methoddesc}{accept}{} Modified: python/branches/bcannon-objcap/Doc/lib/libatexit.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libatexit.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libatexit.tex Tue Jan 9 23:27:11 2007 @@ -44,6 +44,10 @@ traceback is printed (unless \exception{SystemExit} is raised) and the exception information is saved. After all exit handlers have had a chance to run the last exception to be raised is re-raised. + +\versionchanged[This function now returns \var{func} which makes it + possible to use it as a decorator without binding the + original name to \code{None}]{2.6} \end{funcdesc} @@ -92,3 +96,15 @@ # or: atexit.register(goodbye, adjective='nice', name='Donny') \end{verbatim} + +Usage as a decorator: + +\begin{verbatim} +import atexit + + at atexit.register +def goodbye(): + print "You are now leaving the Python sector." +\end{verbatim} + +This obviously only works with functions that don't take arguments. Modified: python/branches/bcannon-objcap/Doc/lib/libbase64.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libbase64.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libbase64.tex Tue Jan 9 23:27:11 2007 @@ -21,7 +21,7 @@ decoding to and from file-like objects as well as strings, but only using the Base64 standard alphabet. -The modern interface provides: +The modern interface, which was introduced in Python 2.4, provides: \begin{funcdesc}{b64encode}{s\optional{, altchars}} Encode a string use Base64. Modified: python/branches/bcannon-objcap/Doc/lib/libbsddb.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libbsddb.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libbsddb.tex Tue Jan 9 23:27:11 2007 @@ -16,24 +16,26 @@ \function{pickle.dumps()}. The \module{bsddb} module requires a Berkeley DB library version from -3.3 thru 4.4. +3.3 thru 4.5. \begin{seealso} - \seeurl{http://pybsddb.sourceforge.net/}{The website with documentation - for the \module{bsddb.db} python Berkeley DB interface that closely mirrors - the Sleepycat object oriented interface provided in Berkeley DB 3 and 4.} - \seeurl{http://www.sleepycat.com/}{Sleepycat Software produces the - Berkeley DB library.} + \seeurl{http://pybsddb.sourceforge.net/} + {The website with documentation for the \module{bsddb.db} + Python Berkeley DB interface that closely mirrors the object + oriented interface provided in Berkeley DB 3 and 4.} + + \seeurl{http://www.oracle.com/database/berkeley-db/} + {The Berkeley DB library.} \end{seealso} A more modern DB, DBEnv and DBSequence object interface is available in the -\module{bsddb.db} module which closely matches the Sleepycat Berkeley DB C API +\module{bsddb.db} module which closely matches the Berkeley DB C API documented at the above URLs. Additional features provided by the \module{bsddb.db} API include fine tuning, transactions, logging, and multiprocess concurrent database access. The following is a description of the legacy \module{bsddb} interface -compatible with the old python bsddb module. Starting in Python 2.5 this +compatible with the old Python bsddb module. Starting in Python 2.5 this interface should be safe for multithreaded access. The \module{bsddb.db} API is recommended for threading users as it provides better control. Modified: python/branches/bcannon-objcap/Doc/lib/libbz2.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libbz2.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libbz2.tex Tue Jan 9 23:27:11 2007 @@ -90,10 +90,10 @@ \begin{methoddesc}[BZ2File]{seek}{offset\optional{, whence}} Move to new file position. Argument \var{offset} is a byte count. Optional -argument \var{whence} defaults to \code{0} (offset from start of file, -offset should be \code{>= 0}); other values are \code{1} (move relative to -current position, positive or negative), and \code{2} (move relative to end -of file, usually negative, although many platforms allow seeking beyond +argument \var{whence} defaults to \code{os.SEEK_SET} or \code{0} (offset from start of file; +offset should be \code{>= 0}); other values are \code{os.SEEK_CUR} or \code{1} (move relative to +current position; offset can be positive or negative), and \code{os.SEEK_END} or \code{2} (move relative to end +of file; offset is usually negative, although many platforms allow seeking beyond the end of a file). Note that seeking of bz2 files is emulated, and depending on the parameters Modified: python/branches/bcannon-objcap/Doc/lib/libcfgparser.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libcfgparser.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libcfgparser.tex Tue Jan 9 23:27:11 2007 @@ -48,11 +48,20 @@ may be passed into the \method{get()} method which will override all others. -\begin{classdesc}{RawConfigParser}{\optional{defaults}} +Sections are normally stored in a builtin dictionary. An alternative +dictionary type can be passed to the \class{ConfigParser} constructor. +For example, if a dictionary type is passed that sorts its keys, +the sections will be sorted on write-back, as will be the keys within +each section. + +\begin{classdesc}{RawConfigParser}{\optional{defaults\optional{, dict_type}}} The basic configuration object. When \var{defaults} is given, it is -initialized into the dictionary of intrinsic defaults. This class -does not support the magical interpolation behavior. +initialized into the dictionary of intrinsic defaults. When \var{dict_type} +is given, it will be used to create the dictionary objects for the list +of sections, for the options within a section, and for the default values. +This class does not support the magical interpolation behavior. \versionadded{2.3} +\versionchanged[\var{dict_type} was added]{2.6} \end{classdesc} \begin{classdesc}{ConfigParser}{\optional{defaults}} Modified: python/branches/bcannon-objcap/Doc/lib/libcommands.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libcommands.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libcommands.tex Tue Jan 9 23:27:11 2007 @@ -12,6 +12,11 @@ return any output generated by the command and, optionally, the exit status. +The \module{subprocess} module provides more powerful facilities for +spawning new processes and retrieving their results. Using the +\module{subprocess} module is preferable to using the \module{commands} +module. + The \module{commands} module defines the following functions: @@ -51,3 +56,7 @@ >>> commands.getstatus('/bin/ls') '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls' \end{verbatim} + +\begin{seealso} + \seemodule{subprocess}{Module for spawning and managing subprocesses.} +\end{seealso} Modified: python/branches/bcannon-objcap/Doc/lib/libcsv.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libcsv.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libcsv.tex Tue Jan 9 23:27:11 2007 @@ -64,9 +64,9 @@ class or one of the strings returned by the \function{list_dialects} function. The other optional {}\var{fmtparam} keyword arguments can be given to override individual formatting parameters in the current -dialect. For more information about the dialect and formatting +dialect. For full details about the dialect and formatting parameters, see section~\ref{csv-fmt-params}, ``Dialects and Formatting -Parameters'' for details of these parameters. +Parameters''. All data read are returned as strings. No automatic data type conversion is performed. @@ -96,10 +96,10 @@ of a subclass of the \class{Dialect} class or one of the strings returned by the \function{list_dialects} function. The other optional {}\var{fmtparam} keyword arguments can be given to override individual -formatting parameters in the current dialect. For more information +formatting parameters in the current dialect. For full details about the dialect and formatting parameters, see -section~\ref{csv-fmt-params}, ``Dialects and Formatting Parameters'' for -details of these parameters. To make it as easy as possible to +section~\ref{csv-fmt-params}, ``Dialects and Formatting Parameters''. +To make it as easy as possible to interface with modules which implement the DB API, the value \constant{None} is written as the empty string. While this isn't a reversible transformation, it makes it easier to dump SQL NULL data values @@ -113,9 +113,8 @@ or Unicode object. The dialect can be specified either by passing a sub-class of \class{Dialect}, or by \var{fmtparam} keyword arguments, or both, with keyword arguments overriding parameters of the dialect. -For more information about the dialect and formatting parameters, see -section~\ref{csv-fmt-params}, ``Dialects and Formatting Parameters'' -for details of these parameters. +For full details about the dialect and formatting parameters, see +section~\ref{csv-fmt-params}, ``Dialects and Formatting Parameters''. \end{funcdesc} \begin{funcdesc}{unregister_dialect}{name} @@ -197,12 +196,13 @@ \begin{classdesc}{excel}{} The \class{excel} class defines the usual properties of an Excel-generated -CSV file. +CSV file. It is registered with the dialect name \code{'excel'}. \end{classdesc} \begin{classdesc}{excel_tab}{} The \class{excel_tab} class defines the usual properties of an -Excel-generated TAB-delimited file. +Excel-generated TAB-delimited file. It is registered with the dialect name +\code{'excel-tab'}. \end{classdesc} \begin{classdesc}{Sniffer}{} @@ -345,6 +345,7 @@ \begin{memberdesc}[csv reader]{line_num} The number of lines read from the source iterator. This is not the same as the number of records returned, as records can span multiple lines. + \versionadded{2.5} \end{memberdesc} Modified: python/branches/bcannon-objcap/Doc/lib/libctypes.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libctypes.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libctypes.tex Tue Jan 9 23:27:11 2007 @@ -1821,7 +1821,7 @@ \begin{quote} \begin{verbatim}>>> from ctypes import c_int, WINFUNCTYPE, windll >>> from ctypes.wintypes import HWND, LPCSTR, UINT ->>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, c_uint) +>>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT) >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0) >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags) >>>\end{verbatim} @@ -1848,7 +1848,7 @@ Here is the wrapping with \code{ctypes}: \begin{quote} -\begin{verbatim}>>> from ctypes import POINTER, WINFUNCTYPE, windll +\begin{verbatim}>>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError >>> from ctypes.wintypes import BOOL, HWND, RECT >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT)) >>> paramflags = (1, "hwnd"), (2, "lprect") @@ -2085,10 +2085,10 @@ the type. Some types accept other objects as well. \end{methoddesc} -\begin{methoddesc}{in_dll}{name, library} +\begin{methoddesc}{in_dll}{library, name} This method returns a ctypes type instance exported by a shared library. \var{name} is the name of the symbol that exports the data, -\code{library} is the loaded shared library. +\var{library} is the loaded shared library. \end{methoddesc} Common instance variables of ctypes data types: @@ -2299,12 +2299,10 @@ or error information for a function or method call. \end{classdesc*} -\code{py{\_}object} : classdesc* -\begin{quote} - -Represents the C \code{PyObject *} datatype. Calling this with an -without an argument creates a \code{NULL} \code{PyObject *} pointer. -\end{quote} +\begin{classdesc*}{py_object} +Represents the C \code{PyObject *} datatype. Calling this without an +argument creates a \code{NULL} \code{PyObject *} pointer. +\end{classdesc*} The \code{ctypes.wintypes} module provides quite some other Windows specific data types, for example \code{HWND}, \code{WPARAM}, or \code{DWORD}. @@ -2440,5 +2438,6 @@ \subsubsection{Arrays and pointers\label{ctypes-arrays-pointers}} -XXX +Not yet written - please see section~\ref{ctypes-pointers}, pointers and +section~\ref{ctypes-arrays}, arrays in the tutorial. Modified: python/branches/bcannon-objcap/Doc/lib/libdatetime.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libdatetime.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libdatetime.tex Tue Jan 9 23:27:11 2007 @@ -1421,19 +1421,21 @@ varies across platforms. Regardless of platform, years before 1900 cannot be used. -\subsection{Examples} - -\subsubsection{Creating Datetime Objects from Formatted Strings} - -The \class{datetime} class does not directly support parsing formatted time -strings. You can use \function{time.strptime} to do the parsing and create -a \class{datetime} object from the tuple it returns: - -\begin{verbatim} ->>> s = "2005-12-06T12:13:14" ->>> from datetime import datetime ->>> from time import strptime ->>> datetime(*strptime(s, "%Y-%m-%dT%H:%M:%S")[0:6]) -datetime.datetime(2005, 12, 6, 12, 13, 14) -\end{verbatim} - +%%% This example is obsolete, since strptime is now supported by datetime. +% +% \subsection{Examples} +% +% \subsubsection{Creating Datetime Objects from Formatted Strings} +% +% The \class{datetime} class does not directly support parsing formatted time +% strings. You can use \function{time.strptime} to do the parsing and create +% a \class{datetime} object from the tuple it returns: +% +% \begin{verbatim} +% >>> s = "2005-12-06T12:13:14" +% >>> from datetime import datetime +% >>> from time import strptime +% >>> datetime(*strptime(s, "%Y-%m-%dT%H:%M:%S")[0:6]) +% datetime.datetime(2005, 12, 6, 12, 13, 14) +% \end{verbatim} +% Modified: python/branches/bcannon-objcap/Doc/lib/libfpectl.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libfpectl.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libfpectl.tex Tue Jan 9 23:27:11 2007 @@ -7,6 +7,11 @@ \sectionauthor{Lee Busby}{busby1 at llnl.gov} \modulesynopsis{Provide control for floating point exception handling.} +\note{The \module{fpectl} module is not built by default, and its usage + is discouraged and may be dangerous except in the hands of + experts. See also the section \ref{fpectl-limitations} on + limitations for more details.} + Most computers carry out floating point operations\index{IEEE-754} in conformance with the so-called IEEE-754 standard. On any real computer, @@ -95,7 +100,7 @@ \end{verbatim} -\subsection{Limitations and other considerations} +\subsection{Limitations and other considerations \label{fpectl-limitations}} Setting up a given processor to trap IEEE-754 floating point errors currently requires custom code on a per-architecture basis. Modified: python/branches/bcannon-objcap/Doc/lib/libfuncs.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libfuncs.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libfuncs.tex Tue Jan 9 23:27:11 2007 @@ -237,11 +237,11 @@ \code{del \var{x}.\var{foobar}}. \end{funcdesc} -\begin{funcdesc}{dict}{\optional{mapping-or-sequence}} +\begin{funcdesc}{dict}{\optional{arg}} Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. - If the positional argument is a mapping object, return a dictionary + If the positional argument \var{arg} is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. Otherwise the positional argument must be a sequence, a container that supports iteration, or an iterator object. The elements of the argument @@ -414,18 +414,18 @@ \versionadded{2.2} \end{funcdesc} -\begin{funcdesc}{filter}{function, list} - Construct a list from those elements of \var{list} for which - \var{function} returns true. \var{list} may be either a sequence, a - container which supports iteration, or an iterator, If \var{list} +\begin{funcdesc}{filter}{function, iterable} + Construct a list from those elements of \var{iterable} for which + \var{function} returns true. \var{iterable} may be either a sequence, a + container which supports iteration, or an iterator, If \var{iterable} is a string or a tuple, the result also has that type; otherwise it is always a list. If \var{function} is \code{None}, the identity function is assumed, that is, all elements of - \var{list} that are false are removed. + \var{iterable} that are false are removed. - Note that \code{filter(function, \var{list})} is equivalent to - \code{[item for item in \var{list} if function(item)]} if function is - not \code{None} and \code{[item for item in \var{list} if item]} if + Note that \code{filter(function, \var{iterable})} is equivalent to + \code{[item for item in \var{iterable} if function(item)]} if function is + not \code{None} and \code{[item for item in \var{iterable} if item]} if function is \code{None}. \end{funcdesc} @@ -591,12 +591,12 @@ may be a sequence (string, tuple or list) or a mapping (dictionary). \end{funcdesc} -\begin{funcdesc}{list}{\optional{sequence}} +\begin{funcdesc}{list}{\optional{iterable}} Return a list whose items are the same and in the same order as - \var{sequence}'s items. \var{sequence} may be either a sequence, a + \var{iterable}'s items. \var{iterable} may be either a sequence, a container that supports iteration, or an iterator object. If - \var{sequence} is already a list, a copy is made and returned, - similar to \code{\var{sequence}[:]}. For instance, + \var{iterable} is already a list, a copy is made and returned, + similar to \code{\var{iterable}[:]}. For instance, \code{list('abc')} returns \code{['a', 'b', 'c']} and \code{list( (1, 2, 3) )} returns \code{[1, 2, 3]}. If no argument is given, returns a new empty list, \code{[]}. @@ -622,22 +622,22 @@ are given, returns \code{0L}. \end{funcdesc} -\begin{funcdesc}{map}{function, list, ...} - Apply \var{function} to every item of \var{list} and return a list - of the results. If additional \var{list} arguments are passed, +\begin{funcdesc}{map}{function, iterable, ...} + Apply \var{function} to every item of \var{iterable} and return a list + of the results. If additional \var{iterable} arguments are passed, \var{function} must take that many arguments and is applied to the - items of all lists in parallel; if a list is shorter than another it + items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with \code{None} items. If \var{function} is \code{None}, the identity function is assumed; if there are - multiple list arguments, \function{map()} returns a list consisting - of tuples containing the corresponding items from all lists (a kind - of transpose operation). The \var{list} arguments may be any kind - of sequence; the result is always a list. + multiple arguments, \function{map()} returns a list consisting + of tuples containing the corresponding items from all iterables (a kind + of transpose operation). The \var{iterable} arguments may be a sequence + or any iterable object; the result is always a list. \end{funcdesc} -\begin{funcdesc}{max}{s\optional{, args...}\optional{key}} - With a single argument \var{s}, return the largest item of a - non-empty sequence (such as a string, tuple or list). With more +\begin{funcdesc}{max}{iterable\optional{, args...}\optional{key}} + With a single argument \var{iterable}, return the largest item of a + non-empty iterable (such as a string, tuple or list). With more than one argument, return the largest of the arguments. The optional \var{key} argument specifies a one-argument ordering @@ -647,16 +647,16 @@ \versionchanged[Added support for the optional \var{key} argument]{2.5} \end{funcdesc} -\begin{funcdesc}{min}{s\optional{, args...}\optional{key}} - With a single argument \var{s}, return the smallest item of a - non-empty sequence (such as a string, tuple or list). With more +\begin{funcdesc}{min}{iterable\optional{, args...}\optional{key}} + With a single argument \var{iterable}, return the smallest item of a + non-empty iterable (such as a string, tuple or list). With more than one argument, return the smallest of the arguments. The optional \var{key} argument specifies a one-argument ordering function like that used for \method{list.sort()}. The \var{key} argument, if supplied, must be in keyword form (for example, \samp{min(a,b,c,key=func)}). - \versionchanged[Added support for the optional \var{key} argument]{2.5} + \versionchanged[Added support for the optional \var{key} argument]{2.5} \end{funcdesc} \begin{funcdesc}{object}{} @@ -791,7 +791,7 @@ \begin{verbatim} class C(object): - def __init__(self): self.__x = None + def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x @@ -871,17 +871,17 @@ line editing and history features. \end{funcdesc} -\begin{funcdesc}{reduce}{function, sequence\optional{, initializer}} +\begin{funcdesc}{reduce}{function, iterable\optional{, initializer}} Apply \var{function} of two arguments cumulatively to the items of - \var{sequence}, from left to right, so as to reduce the sequence to + \var{iterable}, from left to right, so as to reduce the iterable to a single value. For example, \code{reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])} calculates \code{((((1+2)+3)+4)+5)}. The left argument, \var{x}, is the accumulated value and the right argument, \var{y}, - is the update value from the \var{sequence}. If the optional + is the update value from the \var{iterable}. If the optional \var{initializer} is present, it is placed before the items of the - sequence in the calculation, and serves as a default when the - sequence is empty. If \var{initializer} is not given and - \var{sequence} contains only one item, the first item is returned. + iterable in the calculation, and serves as a default when the + iterable is empty. If \var{initializer} is not given and + \var{iterable} contains only one item, the first item is returned. \end{funcdesc} \begin{funcdesc}{reload}{module} @@ -1087,11 +1087,11 @@ string, \code{''}. \end{funcdesc} -\begin{funcdesc}{sum}{sequence\optional{, start}} - Sums \var{start} and the items of a \var{sequence}, from left to - right, and returns the total. \var{start} defaults to \code{0}. - The \var{sequence}'s items are normally numbers, and are not allowed - to be strings. The fast, correct way to concatenate sequence of +\begin{funcdesc}{sum}{iterable\optional{, start}} + Sums \var{start} and the items of an \var{iterable} from left to + right and returns the total. \var{start} defaults to \code{0}. + The \var{iterable}'s items are normally numbers, and are not allowed + to be strings. The fast, correct way to concatenate a sequence of strings is by calling \code{''.join(\var{sequence})}. Note that \code{sum(range(\var{n}), \var{m})} is equivalent to \code{reduce(operator.add, range(\var{n}), \var{m})} @@ -1121,11 +1121,11 @@ \versionadded{2.2} \end{funcdesc} -\begin{funcdesc}{tuple}{\optional{sequence}} +\begin{funcdesc}{tuple}{\optional{iterable}} Return a tuple whose items are the same and in the same order as - \var{sequence}'s items. \var{sequence} may be a sequence, a + \var{iterable}'s items. \var{iterable} may be a sequence, a container that supports iteration, or an iterator object. - If \var{sequence} is already a tuple, it + If \var{iterable} is already a tuple, it is returned unchanged. For instance, \code{tuple('abc')} returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns \code{(1, 2, 3)}. If no argument is given, returns a new empty Modified: python/branches/bcannon-objcap/Doc/lib/libgetopt.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libgetopt.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libgetopt.tex Tue Jan 9 23:27:11 2007 @@ -126,8 +126,9 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) - except getopt.GetoptError: + except getopt.GetoptError, err: # print help information and exit: + print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) output = None @@ -135,11 +136,13 @@ for o, a in opts: if o == "-v": verbose = True - if o in ("-h", "--help"): + elif o in ("-h", "--help"): usage() sys.exit() - if o in ("-o", "--output"): + elif o in ("-o", "--output"): output = a + else: + assert False, "unhandled option" # ... if __name__ == "__main__": Modified: python/branches/bcannon-objcap/Doc/lib/libheapq.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libheapq.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libheapq.tex Tue Jan 9 23:27:11 2007 @@ -76,14 +76,14 @@ >>> for item in data: ... heappush(heap, item) ... ->>> sorted = [] +>>> ordered = [] >>> while heap: -... sorted.append(heappop(heap)) +... ordered.append(heappop(heap)) ... ->>> print sorted +>>> print ordered [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> data.sort() ->>> print data == sorted +>>> print data == ordered True >>> \end{verbatim} Modified: python/branches/bcannon-objcap/Doc/lib/libhttplib.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libhttplib.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libhttplib.tex Tue Jan 9 23:27:11 2007 @@ -304,9 +304,14 @@ This will send a request to the server using the HTTP request method \var{method} and the selector \var{url}. If the \var{body} argument is present, it should be a string of data to send after the headers are finished. +Alternatively, it may be an open file object, in which case the +contents of the file is sent; this file object should support +\code{fileno()} and \code{read()} methods. The header Content-Length is automatically set to the correct value. The \var{headers} argument should be a mapping of extra HTTP headers to send with the request. + +\versionchanged[\var{body} can be a file object]{2.6} \end{methoddesc} \begin{methoddesc}{getresponse}{} Modified: python/branches/bcannon-objcap/Doc/lib/libimp.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libimp.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libimp.tex Tue Jan 9 23:27:11 2007 @@ -161,10 +161,10 @@ \begin{funcdesc}{init_builtin}{name} Initialize the built-in module called \var{name} and return its module -object. If the module was already initialized, it will be initialized -\emph{again}. A few modules cannot be initialized twice --- attempting -to initialize these again will raise an \exception{ImportError} -exception. If there is no +object along with storing it in \code{sys.modules}. If the module was already +initialized, it will be initialized \emph{again}. Re-initialization involves +the copying of the built-in module's \code{__dict__} from the cached +module over the module's entry in \code{sys.modules}. If there is no built-in module called \var{name}, \code{None} is returned. \end{funcdesc} @@ -208,14 +208,15 @@ \begin{funcdesc}{load_dynamic}{name, pathname\optional{, file}} Load and initialize a module implemented as a dynamically loadable shared library and return its module object. If the module was -already initialized, it will be initialized \emph{again}. Some modules -don't like that and may raise an exception. The \var{pathname} -argument must point to the shared library. The \var{name} argument is -used to construct the name of the initialization function: an external -C function called \samp{init\var{name}()} in the shared library is -called. The optional \var{file} argument is ignored. (Note: using -shared libraries is highly system dependent, and not all systems -support it.) +already initialized, it will be initialized \emph{again}. +Re-initialization involves copying the \code{__dict__} attribute of the cached +instance of the module over the value used in the module cached in +\code{sys.modules}. The \var{pathname} argument must point to the shared +library. The \var{name} argument is used to construct the name of the +initialization function: an external C function called +\samp{init\var{name}()} in the shared library is called. The optional +\var{file} argument is ignored. (Note: using shared libraries is highly +system dependent, and not all systems support it.) \end{funcdesc} \begin{funcdesc}{load_source}{name, pathname\optional{, file}} Modified: python/branches/bcannon-objcap/Doc/lib/libitertools.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libitertools.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libitertools.tex Tue Jan 9 23:27:11 2007 @@ -474,8 +474,8 @@ return izip(mapping.iterkeys(), mapping.itervalues()) def nth(iterable, n): - "Returns the nth item" - return list(islice(iterable, n, n+1)) + "Returns the nth item or raise IndexError" + return list(islice(iterable, n, n+1))[0] def all(seq, pred=None): "Returns True if pred(x) is true for every element in the iterable" Modified: python/branches/bcannon-objcap/Doc/lib/liblogging.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/liblogging.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/liblogging.tex Tue Jan 9 23:27:11 2007 @@ -516,8 +516,10 @@ \end{methoddesc} \begin{methoddesc}{findCaller}{} -Finds the caller's source filename and line number. Returns the filename -and line number as a 2-element tuple. +Finds the caller's source filename and line number. Returns the filename, +line number and function name as a 3-element tuple. +\versionchanged[The function name was added. In earlier versions, the +filename and line number were returned as a 2-element tuple.]{2.5} \end{methoddesc} \begin{methoddesc}{handle}{record} @@ -528,8 +530,8 @@ \method{filter()}. \end{methoddesc} -\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info, - func, extra} +\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info + \optional{, func, extra}} This is a factory method which can be overridden in subclasses to create specialized \class{LogRecord} instances. \versionchanged[\var{func} and \var{extra} were added]{2.5} @@ -1397,6 +1399,9 @@ (if available).} \lineii{\%(created)f} {Time when the \class{LogRecord} was created (as returned by \function{time.time()}).} +\lineii{\%(relativeCreated)d} {Time in milliseconds when the LogRecord was + created, relative to the time the logging module was + loaded.} \lineii{\%(asctime)s} {Human-readable time when the \class{LogRecord} was created. By default this is of the form ``2003-07-08 16:49:45,896'' (the numbers after the @@ -1479,7 +1484,7 @@ information to be logged. \begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args, - exc_info} + exc_info \optional{, func}} Returns an instance of \class{LogRecord} initialized with interesting information. The \var{name} is the logger name; \var{lvl} is the numeric level; \var{pathname} is the absolute pathname of the source @@ -1489,7 +1494,9 @@ which, together with \var{msg}, makes up the user message; and \var{exc_info} is the exception tuple obtained by calling \function{sys.exc_info() }(or \constant{None}, if no exception information -is available). +is available). The \var{func} is the name of the function from which the +logging call was made. If not specified, it defaults to \var{None}. +\versionchanged[\var{func} was added]{2.5} \end{classdesc} \begin{methoddesc}{getMessage}{} Modified: python/branches/bcannon-objcap/Doc/lib/libmmap.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libmmap.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libmmap.tex Tue Jan 9 23:27:11 2007 @@ -140,8 +140,9 @@ \begin{methoddesc}{seek}{pos\optional{, whence}} Set the file's current position. \var{whence} argument is optional - and defaults to \code{0} (absolute file positioning); other values - are \code{1} (seek relative to the current position) and \code{2} + and defaults to \code{os.SEEK_SET} or \code{0} (absolute file + positioning); other values are \code{os.SEEK_CUR} or \code{1} (seek + relative to the current position) and \code{os.SEEK_END} or \code{2} (seek relative to the file's end). \end{methoddesc} Modified: python/branches/bcannon-objcap/Doc/lib/libmsilib.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libmsilib.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libmsilib.tex Tue Jan 9 23:27:11 2007 @@ -344,8 +344,8 @@ \subsection{Features\label{features}} \begin{classdesc}{Feature}{database, id, title, desc, display\optional{, - level=1\optional{, parent\optional\{, directory\optional{, - attributes=0}}}} + level=1\optional{, parent\optional{, directory\optional{, + attributes=0}}}}} Add a new record to the \code{Feature} table, using the values \var{id}, \var{parent.id}, \var{title}, \var{desc}, \var{display}, Modified: python/branches/bcannon-objcap/Doc/lib/libos.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libos.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libos.tex Tue Jan 9 23:27:11 2007 @@ -361,6 +361,10 @@ errors), \code{None} is returned. Availability: Macintosh, \UNIX, Windows. +The \module{subprocess} module provides more powerful facilities for +spawning new processes and retrieving their results; using that module +is preferable to using this function. + \versionchanged[This function worked unreliably under Windows in earlier versions of Python. This was due to the use of the \cfunction{_popen()} function from the libraries provided with @@ -375,8 +379,13 @@ Availability: Macintosh, \UNIX, Windows. \end{funcdesc} +There are a number of different \function{popen*()} functions that +provide slightly different ways to create subprocesses. Note that the +\module{subprocess} module is easier to use and more powerful; +consider using that module before writing code using the +lower-level \function{popen*()} functions. -For each of the following \function{popen()} variants, if \var{bufsize} is +For each of the \function{popen*()} variants, if \var{bufsize} is specified, it specifies the buffer size for the I/O pipes. \var{mode}, if provided, should be the string \code{'b'} or \code{'t'}; on Windows this is needed to determine whether the file @@ -920,6 +929,8 @@ points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using \code{os.path.join(os.path.dirname(\var{path}), \var{result})}. +\versionchanged [If the \var{path} is a Unicode object the result will also +be a Unicode object]{2.6} Availability: Macintosh, \UNIX. \end{funcdesc} @@ -1545,7 +1556,13 @@ \funcline{spawnve}{mode, path, args, env} \funcline{spawnvp}{mode, file, args} \funcline{spawnvpe}{mode, file, args, env} -Execute the program \var{path} in a new process. If \var{mode} is +Execute the program \var{path} in a new process. + +(Note that the \module{subprocess} module provides more powerful +facilities for spawning new processes and retrieving their results; +using that module is preferable to using these functions.) + +If \var{mode} is \constant{P_NOWAIT}, this function returns the process ID of the new process; if \var{mode} is \constant{P_WAIT}, returns the process's exit code if it exits normally, or \code{-\var{signal}}, where @@ -1682,6 +1699,10 @@ a non-native shell, consult your shell documentation. Availability: Macintosh, \UNIX, Windows. + +The \module{subprocess} module provides more powerful facilities for +spawning new processes and retrieving their results; using that module +is preferable to using this function. \end{funcdesc} \begin{funcdesc}{times}{} Modified: python/branches/bcannon-objcap/Doc/lib/libpickle.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libpickle.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libpickle.tex Tue Jan 9 23:27:11 2007 @@ -519,7 +519,7 @@ version of the object. The next element of the tuple will provide arguments for this callable, and later elements provide additional state information that will subsequently be used to fully reconstruct -the pickled date. +the pickled data. In the unpickling environment this object must be either a class, a callable registered as a ``safe constructor'' (see below), or it must Modified: python/branches/bcannon-objcap/Doc/lib/libpopen2.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libpopen2.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libpopen2.tex Tue Jan 9 23:27:11 2007 @@ -11,10 +11,10 @@ input/output/error pipes and obtain their return codes under \UNIX{} and Windows. -Note that starting with Python 2.0, this functionality is available -using functions from the \refmodule{os} module which have the same -names as the factory functions here, but the order of the return -values is more intuitive in the \refmodule{os} module variants. +The \module{subprocess} module provides more powerful facilities for +spawning new processes and retrieving their results. Using the +\module{subprocess} module is preferable to using the \module{popen2} +module. The primary interface offered by this module is a trio of factory functions. For each of these, if \var{bufsize} is specified, @@ -184,3 +184,7 @@ separate threads to read each of the individual files provided by whichever \function{popen*()} function or \class{Popen*} class was used. + +\begin{seealso} + \seemodule{subprocess}{Module for spawning and managing subprocesses.} +\end{seealso} Modified: python/branches/bcannon-objcap/Doc/lib/libsimplexmlrpc.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libsimplexmlrpc.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libsimplexmlrpc.tex Tue Jan 9 23:27:11 2007 @@ -15,7 +15,7 @@ \begin{classdesc}{SimpleXMLRPCServer}{addr\optional{, requestHandler\optional{, - logRequests\optional{allow_none\optional{, encoding}}}}} + logRequests\optional{, allow_none\optional{, encoding}}}}} Create a new server instance. This class provides methods for registration of functions that can be called by Modified: python/branches/bcannon-objcap/Doc/lib/libsmtplib.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libsmtplib.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libsmtplib.tex Tue Jan 9 23:27:11 2007 @@ -28,6 +28,18 @@ included below. \end{classdesc} +\begin{classdesc}{SMTP_SSL}{\optional{host\optional{, port\optional{, + local_hostname\optional{, + keyfile\optional{, + certfile}}}}}} +A \class{SMTP_SSL} instance behaves exactly the same as instances of \class{SMTP}. +\class{SMTP_SSL} should be used for situations where SSL is required from +the beginning of the connection and using \method{starttls()} is not appropriate. +If \var{host} is not specified, the local host is used. If \var{port} is +omitted, the standard SMTP-over-SSL port (465) is used. \var{keyfile} and \var{certfile} +are also optional, and can contain a PEM formatted private key and +certificate chain file for the SSL connection. +\end{classdesc} A nice selection of exceptions is defined as well: Modified: python/branches/bcannon-objcap/Doc/lib/libsocket.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libsocket.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libsocket.tex Tue Jan 9 23:27:11 2007 @@ -241,8 +241,8 @@ This operation assumes that there is a valid address-to-host mapping for the host, and the assumption does not always hold. Note: \function{gethostname()} doesn't always return the fully qualified -domain name; use \code{gethostbyaddr(gethostname())} -(see below). +domain name; use \code{getfqdn()} +(see above). \end{funcdesc} \begin{funcdesc}{gethostbyaddr}{ip_address} @@ -569,11 +569,32 @@ Receive data from the socket. The return value is a pair \code{(\var{string}, \var{address})} where \var{string} is a string representing the data received and \var{address} is the address of the -socket sending the data. The optional \var{flags} argument has the -same meaning as for \method{recv()} above. +socket sending the data. See the \UNIX{} manual page +\manpage{recv}{2} for the meaning of the optional argument +\var{flags}; it defaults to zero. (The format of \var{address} depends on the address family --- see above.) \end{methoddesc} +\begin{methoddesc}[socket]{recvfrom_into}{buffer\optional{, nbytes\optional{, flags}}} +Receive data from the socket, writing it into \var{buffer} instead of +creating a new string. The return value is a pair +\code{(\var{nbytes}, \var{address})} where \var{nbytes} is the number +of bytes received and \var{address} is the address of the socket +sending the data. See the \UNIX{} manual page +\manpage{recv}{2} for the meaning of the optional argument +\var{flags}; it defaults to zero. (The format of \var{address} +depends on the address family --- see above.) +\end{methoddesc} + +\begin{methoddesc}[socket]{recv_into}{buffer\optional{, nbytes\optional{, flags}}} +Receive up to \var{nbytes} bytes from the socket, +storing the data into a buffer rather than creating a new string. +If \var{nbytes} is not specified (or 0), +receive up to the size available in the given buffer. +See the \UNIX{} manual page \manpage{recv}{2} for the meaning of the +optional argument \var{flags}; it defaults to zero. +\end{methoddesc} + \begin{methoddesc}[socket]{send}{string\optional{, flags}} Send data to the socket. The socket must be connected to a remote socket. The optional \var{flags} argument has the same meaning as for @@ -712,14 +733,15 @@ \end{methoddesc} \begin{methoddesc}{server}{} -Returns a string containing the ASN.1 distinguished name identifying the -server's certificate. (See below for an example -showing what distinguished names look like.) +Returns a string describing the server's certificate. +Useful for debugging purposes; do not parse the content of this string +because its format can't be parsed unambiguously. \end{methoddesc} \begin{methoddesc}{issuer}{} -Returns a string containing the ASN.1 distinguished name identifying the -issuer of the server's certificate. +Returns a string describing the issuer of the server's certificate. +Useful for debugging purposes; do not parse the content of this string +because its format can't be parsed unambiguously. \end{methoddesc} \subsection{Example \label{socket-example}} Modified: python/branches/bcannon-objcap/Doc/lib/libsqlite3.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libsqlite3.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libsqlite3.tex Tue Jan 9 23:27:11 2007 @@ -150,7 +150,7 @@ property of \class{Connection} objects in section~\ref{sqlite3-Connection-IsolationLevel}. SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If -you want to use other types, like you have to add support for them yourself. +you want to use other types you must add support for them yourself. The \var{detect_types} parameter and the using custom \strong{converters} registered with the module-level \function{register_converter} function allow you to easily do that. @@ -187,12 +187,12 @@ \end{funcdesc} \begin{funcdesc}{complete_statement}{sql} -Returns \constant{True} if the string \var{sql} one or more complete SQL -statements terminated by semicolons. It does not verify if the SQL is -syntactically correct, only if there are no unclosed string literals and if the +Returns \constant{True} if the string \var{sql} contains one or more complete SQL +statements terminated by semicolons. It does not verify that the SQL is +syntactically correct, only that there are no unclosed string literals and the statement is terminated by a semicolon. -This can be used to build a shell for SQLite, like in the following example: +This can be used to build a shell for SQLite, as in the following example: \verbatiminput{sqlite3/complete_statement.py} \end{funcdesc} Modified: python/branches/bcannon-objcap/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libstdtypes.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libstdtypes.tex Tue Jan 9 23:27:11 2007 @@ -834,7 +834,7 @@ start\optional{, end}}} Return \code{True} if string starts with the \var{prefix}, otherwise return \code{False}. \var{prefix} can also be a tuple of -suffixes to look for. With optional \var{start}, test string beginning at +prefixes to look for. With optional \var{start}, test string beginning at that position. With optional \var{end}, stop comparing string at that position. @@ -876,6 +876,9 @@ characters have been mapped through the given translation table, which must be a string of length 256. +You can use the \function{maketrans()} helper function in the +\refmodule{string} module to create a translation table. + For Unicode objects, the \method{translate()} method does not accept the optional \var{deletechars} argument. Instead, it returns a copy of the \var{s} where all characters have been mapped @@ -1424,7 +1427,8 @@ {(3)} \lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(3)} \lineiii{\var{a}.update(\optional{\var{b}})} - {updates (and overwrites) key/value pairs from \var{b}} + {updates \var{a} with key/value pairs from \var{b}, overwriting + existing keys, returns \code{None}} {(9)} \lineiii{\var{a}.fromkeys(\var{seq}\optional{, \var{value}})} {Creates a new dictionary with keys from \var{seq} and values set to \var{value}} @@ -1674,9 +1678,12 @@ \begin{methoddesc}[file]{seek}{offset\optional{, whence}} Set the file's current position, like \code{stdio}'s \cfunction{fseek()}. - The \var{whence} argument is optional and defaults to \code{0} - (absolute file positioning); other values are \code{1} (seek - relative to the current position) and \code{2} (seek relative to the + The \var{whence} argument is optional and defaults to + \code{os.SEEK_SET} or \code{0} + (absolute file positioning); other values are \code{os.SEEK_CUR} or \code{1} + (seek + relative to the current position) and \code{os.SEEK_END} or \code{2} + (seek relative to the file's end). There is no return value. Note that if the file is opened for appending (mode \code{'a'} or \code{'a+'}), any \method{seek()} operations will be undone at the next write. If the @@ -1688,6 +1695,7 @@ behavior. Note that not all file objects are seekable. + \versionchanged{Passing float values as offset has been deprecated}[2.6] \end{methoddesc} \begin{methoddesc}[file]{tell}{} Modified: python/branches/bcannon-objcap/Doc/lib/libstring.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libstring.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libstring.tex Tue Jan 9 23:27:11 2007 @@ -220,7 +220,7 @@ \begin{funcdesc}{maketrans}{from, to} Return a translation table suitable for passing to - \function{translate()} or \function{regex.compile()}, that will map + \function{translate()}, that will map each character in \var{from} into the character at the same position in \var{to}; \var{from} and \var{to} must have the same length. Modified: python/branches/bcannon-objcap/Doc/lib/libsubprocess.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libsubprocess.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libsubprocess.tex Tue Jan 9 23:27:11 2007 @@ -12,9 +12,6 @@ codes. This module intends to replace several other, older modules and functions, such as: -% XXX Should add pointers to this module to at least the popen2 -% and commands sections. - \begin{verbatim} os.system os.spawn* Modified: python/branches/bcannon-objcap/Doc/lib/libtarfile.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libtarfile.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libtarfile.tex Tue Jan 9 23:27:11 2007 @@ -124,6 +124,11 @@ only if \member{TarFile.errorlevel}\code{ == 2}. \end{excdesc} +\begin{excdesc}{HeaderError} + Is raised by \method{frombuf()} if the buffer it gets is invalid. + \versionadded{2.6} +\end{excdesc} + \begin{seealso} \seemodule{zipfile}{Documentation of the \refmodule{zipfile} standard module.} @@ -332,6 +337,8 @@ \begin{methoddesc}{frombuf}{} Create and return a \class{TarInfo} object from a string buffer. + \versionadded[Raises \exception{HeaderError} if the buffer is + invalid.]{2.6} \end{methoddesc} \begin{methoddesc}{tobuf}{posix} Modified: python/branches/bcannon-objcap/Doc/lib/libtempfile.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libtempfile.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libtempfile.tex Tue Jan 9 23:27:11 2007 @@ -86,7 +86,12 @@ prefix; otherwise, a default prefix is used. If \var{dir} is specified, the file will be created in that directory; -otherwise, a default directory is used. +otherwise, a default directory is used. The default directory is chosen +from a platform-dependent list, but the user of the application can control +the directory location by setting the \var{TMPDIR}, \var{TEMP} or \var{TMP} +environment variables. There is thus no guarantee that the generated +filename will have any nice properties, such as not requiring quoting when +passed to external commands via \code{os.popen()}. If \var{text} is specified, it indicates whether to open the file in binary mode (the default) or text mode. On some platforms, this makes Modified: python/branches/bcannon-objcap/Doc/lib/libtest.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libtest.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libtest.tex Tue Jan 9 23:27:11 2007 @@ -263,6 +263,12 @@ This does not equal a failure since it could be the path to the file. \end{funcdesc} +\begin{funcdesc}{guard_warnings_filter}{} +Returns a context manager that guards the \module{warnings} module's +filter settings. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{run_unittest}{*classes} Execute \class{unittest.TestCase} subclasses passed to the function. The function scans the classes for methods starting with the prefix @@ -275,4 +281,22 @@ The optional argument \var{testclass} accepts one of the test classes in the suite so as to print out more detailed information on where the testing suite originated from. + +The \module{test.test_support} module defines the following classes: + +\begin{classdesc}{EnvironmentVarGuard}{} +Class used to temporarily set or unset environment variables. Instances can be +used as a context manager. +\versionadded{2.6} +\end{classdesc} + +\begin{methoddesc}{set}{envvar, value} +Temporarily set the environment variable \code{envvar} to the value of +\code{value}. +\end{methoddesc} + +\begin{methoddesc}{unset}{envvar} +Temporarily unset the environment variable \code{envvar}. +\end{methoddesc} + \end{funcdesc} Modified: python/branches/bcannon-objcap/Doc/lib/liburlparse.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/liburlparse.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/liburlparse.tex Tue Jan 9 23:27:11 2007 @@ -89,7 +89,7 @@ \begin{funcdesc}{urlunparse}{parts} Construct a URL from a tuple as returned by \code{urlparse()}. -The \var{parts} argument be any six-item iterable. +The \var{parts} argument can be any six-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). @@ -133,7 +133,7 @@ \begin{funcdesc}{urlunsplit}{parts} Combine the elements of a tuple as returned by \function{urlsplit()} into a complete URL as a string. -The \var{parts} argument be any five-item iterable. +The \var{parts} argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). @@ -142,7 +142,7 @@ \begin{funcdesc}{urljoin}{base, url\optional{, allow_fragments}} Construct a full (``absolute'') URL by combining a ``base URL'' -(\var{base}) with a ``relative URL'' (\var{url}). Informally, this +(\var{base}) with another URL (\var{url}). Informally, this uses components of the base URL, in particular the addressing scheme, the network location and (part of) the path, to provide missing components in the relative URL. For example: @@ -155,6 +155,20 @@ The \var{allow_fragments} argument has the same meaning and default as for \function{urlparse()}. + +\note{If \var{url} is an absolute URL (that is, starting with \code{//} + or \code{scheme://}, the \var{url}'s host name and/or scheme + will be present in the result. For example:} + +\begin{verbatim} +>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', +... '//www.python.org/%7Eguido') +'http://www.python.org/%7Eguido' +\end{verbatim} + +If you do not want that behavior, preprocess +the \var{url} with \function{urlsplit()} and \function{urlunsplit()}, +removing possible \em{scheme} and \em{netloc} parts. \end{funcdesc} \begin{funcdesc}{urldefrag}{url} Modified: python/branches/bcannon-objcap/Doc/lib/libwsgiref.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libwsgiref.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libwsgiref.tex Tue Jan 9 23:27:11 2007 @@ -26,8 +26,9 @@ WSGI specification (\pep{333}). % XXX If you're just trying to write a web application... -% XXX should create a URL on python.org to point people to. +See \url{http://www.wsgi.org} for more information about WSGI, +and links to tutorials and other resources. Modified: python/branches/bcannon-objcap/Doc/lib/libxmlrpclib.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/libxmlrpclib.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/libxmlrpclib.tex Tue Jan 9 23:27:11 2007 @@ -68,7 +68,10 @@ \lineii{arrays}{Any Python sequence type containing conformable elements. Arrays are returned as lists} \lineii{structures}{A Python dictionary. Keys must be strings, - values may be any conformable type.} + values may be any conformable type. Objects + of user-defined classes can be passed in; + only their \var{__dict__} attribute is + transmitted.} \lineii{dates}{in seconds since the epoch (pass in an instance of the \class{DateTime} class) or a \class{\refmodule{datetime}.datetime}, @@ -100,6 +103,10 @@ compatibility. New code should use \class{ServerProxy}. \versionchanged[The \var{use_datetime} flag was added]{2.5} + +\versionchanged[Instances of new-style classes can be passed in +if they have an \var{__dict__} attribute and don't have a base class +that is marshalled in a special way]{2.6} \end{classdesc} Modified: python/branches/bcannon-objcap/Doc/lib/tkinter.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/lib/tkinter.tex (original) +++ python/branches/bcannon-objcap/Doc/lib/tkinter.tex Tue Jan 9 23:27:11 2007 @@ -318,7 +318,7 @@ \item[\var{options}] configure the widget's appearance and in some cases, its behavior. The options come in the form of a list of flags and values. -Flags are proceeded by a `-', like \UNIX{} shell command flags, and +Flags are preceded by a `-', like \UNIX{} shell command flags, and values are put in quotes if they are more than one word. \end{description} Modified: python/branches/bcannon-objcap/Doc/mac/toolbox.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/mac/toolbox.tex (original) +++ python/branches/bcannon-objcap/Doc/mac/toolbox.tex Tue Jan 9 23:27:11 2007 @@ -65,7 +65,7 @@ \modulesynopsis{Interface to the Component Manager.} \section{\module{Carbon.CarbonEvt} --- Carbon Event Manager} -\declaremodule{standard}{Carbon.CaronEvt} +\declaremodule{standard}{Carbon.CarbonEvt} \platform{Mac} \modulesynopsis{Interface to the Carbon Event Manager.} Modified: python/branches/bcannon-objcap/Doc/ref/ref3.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/ref/ref3.tex (original) +++ python/branches/bcannon-objcap/Doc/ref/ref3.tex Tue Jan 9 23:27:11 2007 @@ -379,6 +379,41 @@ \end{description} % Sequences + +\item[Set types] +These represent unordered, finite sets of unique, immutable objects. +As such, they cannot be indexed by any subscript. However, they can be +iterated over, and the built-in function \function{len()} returns the +number of items in a set. Common uses for sets are +fast membership testing, removing duplicates from a sequence, and +computing mathematical operations such as intersection, union, difference, +and symmetric difference. +\bifuncindex{len} +\obindex{set type} + +For set elements, the same immutability rules apply as for dictionary +keys. Note that numeric types obey the normal rules for numeric +comparison: if two numbers compare equal (e.g., \code{1} and +\code{1.0}), only one of them can be contained in a set. + +There are currently two intrinsic set types: + +\begin{description} + +\item[Sets] +These\obindex{set} represent a mutable set. They are created by the +built-in \function{set()} constructor and can be modified afterwards +by several methods, such as \method{add()}. + +\item[Frozen sets] +These\obindex{frozenset} represent an immutable set. They are created by +the built-in \function{frozenset()} constructor. As a frozenset is +immutable and hashable, it can be used again as an element of another set, +or as a dictionary key. + +\end{description} % Set types + + \item[Mappings] These represent finite sets of objects indexed by arbitrary index sets. The subscript notation \code{a[k]} selects the item indexed Modified: python/branches/bcannon-objcap/Doc/tools/py2texi.el ============================================================================== --- python/branches/bcannon-objcap/Doc/tools/py2texi.el (original) +++ python/branches/bcannon-objcap/Doc/tools/py2texi.el Tue Jan 9 23:27:11 2007 @@ -1,5 +1,6 @@ ;;; py2texi.el -- Conversion of Python LaTeX documentation to Texinfo +;; Copyright (C) 2006 Jeroen Dekkers ;; Copyright (C) 1998, 1999, 2001, 2002 Milan Zamazal ;; Author: Milan Zamazal @@ -168,6 +169,7 @@ "@end table\n") ("productionlist" 0 "\n at table @code\n" "@end table\n") ("quotation" 0 "@quotation" "@end quotation") + ("quote" 0 "@quotation" "@end quotation") ("seealso" 0 "See also:\n at table @emph\n" "@end table\n") ("seealso*" 0 "@table @emph\n" "@end table\n") ("sloppypar" 0 "" "") @@ -246,11 +248,12 @@ ("env" 1 "@code{\\1}") ("EOF" 0 "@code{EOF}") ("email" 1 "@email{\\1}") + ("em" 1 "@emph{\\1}") ("emph" 1 "@emph{\\1}") ("envvar" 1 "@env{\\1}") ("exception" 1 "@code{\\1}") ("exindex" 1 (progn (setq obindex t) "@obindex{\\1}")) - ("fi" 0 (concat "@end " last-if)) + ("fi" 0 (if (equal last-if "ifx") "" (concat "@end " last-if))) ("file" 1 "@file{\\1}") ("filenq" 1 "@file{\\1}") ("filevar" 1 "@file{@var{\\1}}") @@ -262,6 +265,7 @@ ("grammartoken" 1 "@code{\\1}") ("guilabel" 1 "@strong{\\1}") ("hline" 0 "") + ("ifx" 0 (progn (setq last-if "ifx") "")) ("ifhtml" 0 (concat "@" (setq last-if "ifinfo"))) ("iftexi" 0 (concat "@" (setq last-if "ifinfo"))) ("index" 1 (progn (setq cindex t) "@cindex{\\1}")) @@ -284,6 +288,7 @@ ("lineiii" 3 "@item \\1 @tab \\2 @tab \\3") ("lineiv" 4 "@item \\1 @tab \\2 @tab \\3 @tab \\4") ("linev" 5 "@item \\1 @tab \\2 @tab \\3 @tab \\4 @tab \\5") + ("locallinewidth" 0 "") ("localmoduletable" 0 "") ("longprogramopt" 1 "@option{--\\1}") ("macro" 1 "@code{@backslash{}\\1}") @@ -307,6 +312,7 @@ ("moreargs" 0 "@dots{}") ("n" 0 "@backslash{}n") ("newcommand" 2 "") + ("newlength" 1 "") ("newsgroup" 1 "@samp{\\1}") ("nodename" 1 (save-excursion @@ -322,6 +328,7 @@ ("opindex" 1 (progn (setq cindex t) "@cindex{\\1}")) ("option" 1 "@option{\\1}") ("optional" 1 "[\\1]") + ("paragraph" 1 "@subsubheading \\1") ("pep" 1 (progn (setq cindex t) "PEP@ \\1 at cindex PEP \\1\n")) ("pi" 0 "pi") ("platform" 1 "") @@ -363,6 +370,7 @@ ("seetitle" 1 "@cite{\\1}") ("seeurl" 2 "\n at table @url\n at item \\1\n\\2\n at end table\n") ("setindexsubitem" 1 (progn (setq cindex t) "@cindex \\1")) + ("setlength" 2 "") ("setreleaseinfo" 1 (progn (setq py2texi-releaseinfo ""))) ("setshortversion" 1 (progn (setq py2texi-python-short-version (match-string 1 string)) "")) @@ -382,8 +390,8 @@ ("textasciicircum" 0 "^") ("textbackslash" 0 "@backslash{}") ("textbar" 0 "|") - ; Some common versions of Texinfo don't support @euro yet: - ; ("texteuro" 0 "@euro{}") + ("textbf" 1 "@strong{\\1}") + ("texteuro" 0 "@euro{}") ; Unfortunately, this alternate spelling doesn't actually apply to ; the usage found in Python Tutorial, which actually requires a ; Euro symbol to make sense, so this is commented out as well. @@ -394,6 +402,7 @@ ("textrm" 1 "\\1") ("texttt" 1 "@code{\\1}") ("textunderscore" 0 "_") + ("tilde" 0 "~") ("title" 1 (progn (setq title (match-string 1 string)) "@settitle \\1")) ("today" 0 "@today{}") ("token" 1 "@code{\\1}") @@ -402,6 +411,7 @@ ("u" 0 "@backslash{}u") ("ulink" 2 "\\1") ("UNIX" 0 "UNIX") + ("undefined" 0 "") ("unspecified" 0 "@dots{}") ("url" 1 "@url{\\1}") ("usepackage" 1 "") @@ -534,15 +544,20 @@ beg end) (py2texi-search-safe "\\\\begin{\\(verbatim\\|displaymath\\)}" - (replace-match "@example") - (setq beg (copy-marker (point) nil)) - (re-search-forward "\\\\end{\\(verbatim\\|displaymath\\)}") - (setq end (copy-marker (match-beginning 0) nil)) - (replace-match "@end example") - (py2texi-texinfo-escape beg end) - (put-text-property (- beg (length "@example")) - (+ end (length "@end example")) - 'py2texi-protected t)) + (when (save-excursion + ; Make sure we aren't looking at a commented out version + ; of a verbatim environment + (beginning-of-line) + (not (looking-at "%"))) + (replace-match "@example ") + (setq beg (copy-marker (point) nil)) + (re-search-forward "\\\\end{\\(verbatim\\|displaymath\\)}") + (setq end (copy-marker (match-beginning 0) nil)) + (replace-match "@end example") + (py2texi-texinfo-escape beg end) + (put-text-property (- beg (length "@example ")) + (+ end (length "@end example")) + 'py2texi-protected t))) (py2texi-search-safe "\\\\verb\\([^a-z]\\)" (setq delimiter (match-string 1)) (replace-match "@code{") @@ -883,6 +898,10 @@ (defun py2texi-fix-braces () "Escape braces for Texinfo." + (py2texi-search "{@{}" + (replace-match "@{")) + (py2texi-search "{@}}" + (replace-match "@}")) (let (string) (py2texi-search "{" (unless (or (py2texi-protected) Modified: python/branches/bcannon-objcap/Doc/tut/tut.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/tut/tut.tex (original) +++ python/branches/bcannon-objcap/Doc/tut/tut.tex Tue Jan 9 23:27:11 2007 @@ -2855,7 +2855,7 @@ *}? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. Unfortunately, this operation does not work very -well on Mac and Windows platforms, where the filesystem does not +well on Windows platforms, where the filesystem does not always have accurate information about the case of a filename! On these platforms, there is no guaranteed way to know whether a file \file{ECHO.PY} should be imported as a module \module{echo}, @@ -3060,6 +3060,7 @@ 8 64 512 9 81 729 10 100 1000 + >>> for x in range(1,11): ... print '%2d %3d %4d' % (x, x*x, x*x*x) ... @@ -3075,8 +3076,9 @@ 10 100 1000 \end{verbatim} -(Note that one space between each column was added by the way -\keyword{print} works: it always adds spaces between its arguments.) +(Note that in the first example, one space between each column was +added by the way \keyword{print} works: it always adds spaces between +its arguments.) This example demonstrates the \method{rjust()} method of string objects, which right-justifies a string in a field of a given width by padding @@ -3539,7 +3541,7 @@ But use of \code{.args} is discouraged. Instead, the preferred use is to pass a single argument to an exception (which can be a tuple if multiple arguments -are needed) and have it bound to the \code{message} attribute. One my also +are needed) and have it bound to the \code{message} attribute. One may also instantiate an exception first before raising it and add any attributes to it as desired. Modified: python/branches/bcannon-objcap/Doc/whatsnew/whatsnew25.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/whatsnew/whatsnew25.tex (original) +++ python/branches/bcannon-objcap/Doc/whatsnew/whatsnew25.tex Tue Jan 9 23:27:11 2007 @@ -5,7 +5,7 @@ % Fix XXX comments \title{What's New in Python 2.5} -\release{1.0} +\release{1.01} \author{A.M. Kuchling} \authoraddress{\email{amk at amk.ca}} @@ -540,7 +540,7 @@ StopIteration \end{verbatim} -\keyword{yield} will usually return \constant{None}, you +\keyword{yield} will usually return \constant{None}, so you should always check for this case. Don't just use its value in expressions unless you're sure that the \method{send()} method will be the only method used to resume your generator function. @@ -556,13 +556,14 @@ where the generator's execution is paused. \item \method{close()} raises a new \exception{GeneratorExit} - exception inside the generator to terminate the iteration. - On receiving this - exception, the generator's code must either raise - \exception{GeneratorExit} or \exception{StopIteration}; catching the - exception and doing anything else is illegal and will trigger - a \exception{RuntimeError}. \method{close()} will also be called by - Python's garbage collector when the generator is garbage-collected. + exception inside the generator to terminate the iteration. On + receiving this exception, the generator's code must either raise + \exception{GeneratorExit} or \exception{StopIteration}. Catching + the \exception{GeneratorExit} exception and returning a value is + illegal and will trigger a \exception{RuntimeError}; if the function + raises some other exception, that exception is propagated to the + caller. \method{close()} will also be called by Python's garbage + collector when the generator is garbage-collected. If you need to run cleanup code when a \exception{GeneratorExit} occurs, I suggest using a \code{try: ... finally:} suite instead of @@ -1663,6 +1664,13 @@ \item The \module{pyexpat} module now uses version 2.0 of the Expat parser. (Contributed by Trent Mick.) +\item The \class{Queue} class provided by the \module{Queue} module +gained two new methods. \method{join()} blocks until all items in +the queue have been retrieved and all processing work on the items +have been completed. Worker threads call the other new method, +\method{task_done()}, to signal that processing for an item has been +completed. (Contributed by Raymond Hettinger.) + \item The old \module{regex} and \module{regsub} modules, which have been deprecated ever since Python 2.0, have finally been deleted. Other deleted modules: \module{statcache}, \module{tzparse}, Modified: python/branches/bcannon-objcap/Doc/whatsnew/whatsnew26.tex ============================================================================== --- python/branches/bcannon-objcap/Doc/whatsnew/whatsnew26.tex (original) +++ python/branches/bcannon-objcap/Doc/whatsnew/whatsnew26.tex Tue Jan 9 23:27:11 2007 @@ -1,6 +1,6 @@ \documentclass{howto} \usepackage{distutils} -% $Id: whatsnew25.tex 37952 2004-12-03 13:54:09Z akuchling $ +% $Id$ \title{What's New in Python 2.6} @@ -67,7 +67,10 @@ \begin{itemize} -\item Descriptions go here. +\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} +class. (Contributed by Monty Taylor.) \end{itemize} Modified: python/branches/bcannon-objcap/Include/abstract.h ============================================================================== --- python/branches/bcannon-objcap/Include/abstract.h (original) +++ python/branches/bcannon-objcap/Include/abstract.h Tue Jan 9 23:27:11 2007 @@ -288,9 +288,10 @@ */ + /* Declared elsewhere + PyAPI_FUNC(int) PyCallable_Check(PyObject *o); - /* Determine if the object, o, is callable. Return 1 if the object is callable and 0 otherwise. Modified: python/branches/bcannon-objcap/Include/modsupport.h ============================================================================== --- python/branches/bcannon-objcap/Include/modsupport.h (original) +++ python/branches/bcannon-objcap/Include/modsupport.h Tue Jan 9 23:27:11 2007 @@ -24,7 +24,7 @@ #endif PyAPI_FUNC(int) PyArg_Parse(PyObject *, const char *, ...); -PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...); +PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...) Py_FORMAT_PARSETUPLE(PyArg_ParseTuple, 2, 3); PyAPI_FUNC(int) PyArg_ParseTupleAndKeywords(PyObject *, PyObject *, const char *, char **, ...); PyAPI_FUNC(int) PyArg_UnpackTuple(PyObject *, const char *, Py_ssize_t, Py_ssize_t, ...); Modified: python/branches/bcannon-objcap/Include/pyport.h ============================================================================== --- python/branches/bcannon-objcap/Include/pyport.h (original) +++ python/branches/bcannon-objcap/Include/pyport.h Tue Jan 9 23:27:11 2007 @@ -3,6 +3,10 @@ #include "pyconfig.h" /* include for defines */ +#ifdef HAVE_STDINT_H +#include +#endif + /************************************************************************** Symbols and macros to supply platform-independent interfaces to basic C language & library operations whose spellings vary across platforms. @@ -745,6 +749,15 @@ #define Py_GCC_ATTRIBUTE(x) __attribute__(x) #endif +/* + * Add PyArg_ParseTuple format where available. + */ +#ifdef HAVE_ATTRIBUTE_FORMAT_PARSETUPLE +#define Py_FORMAT_PARSETUPLE(func,p1,p2) __attribute__((format(func,p1,p2))) +#else +#define Py_FORMAT_PARSETUPLE(func,p1,p2) +#endif + /* Eliminate end-of-loop code not reached warnings from SunPro C * when using do{...}while(0) macros */ Modified: python/branches/bcannon-objcap/LICENSE ============================================================================== --- python/branches/bcannon-objcap/LICENSE (original) +++ python/branches/bcannon-objcap/LICENSE Tue Jan 9 23:27:11 2007 @@ -88,9 +88,9 @@ prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) -2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights -Reserved" are retained in Python alone or in any derivative version -prepared by Licensee. +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make Modified: python/branches/bcannon-objcap/Lib/CGIHTTPServer.py ============================================================================== --- python/branches/bcannon-objcap/Lib/CGIHTTPServer.py (original) +++ python/branches/bcannon-objcap/Lib/CGIHTTPServer.py Tue Jan 9 23:27:11 2007 @@ -105,17 +105,36 @@ def run_cgi(self): """Execute a CGI script.""" + path = self.path dir, rest = self.cgi_info + + i = path.find('/', len(dir) + 1) + while i >= 0: + nextdir = path[:i] + nextrest = path[i+1:] + + scriptdir = self.translate_path(nextdir) + if os.path.isdir(scriptdir): + dir, rest = nextdir, nextrest + i = path.find('/', len(dir) + 1) + else: + break + + # find an explicit query string, if present. i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' + + # dissect the part after the directory name into a script name & + # a possible additional path, to be stored in PATH_INFO. i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' + scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): Modified: python/branches/bcannon-objcap/Lib/ConfigParser.py ============================================================================== --- python/branches/bcannon-objcap/Lib/ConfigParser.py (original) +++ python/branches/bcannon-objcap/Lib/ConfigParser.py Tue Jan 9 23:27:11 2007 @@ -199,11 +199,11 @@ self.line = line - class RawConfigParser: - def __init__(self, defaults=None): - self._sections = {} - self._defaults = {} + def __init__(self, defaults=None, dict_type=dict): + self._dict = dict_type + self._sections = self._dict() + self._defaults = self._dict() if defaults: for key, value in defaults.items(): self._defaults[self.optionxform(key)] = value @@ -224,7 +224,7 @@ """ if section in self._sections: raise DuplicateSectionError(section) - self._sections[section] = {} + self._sections[section] = self._dict() def has_section(self, section): """Indicate whether the named section is present in the configuration. @@ -307,7 +307,7 @@ except KeyError: if section != DEFAULTSECT: raise NoSectionError(section) - d2 = {} + d2 = self._dict() d = self._defaults.copy() d.update(d2) if "__name__" in d: @@ -453,7 +453,8 @@ elif sectname == DEFAULTSECT: cursect = self._defaults else: - cursect = {'__name__': sectname} + cursect = self._dict() + cursect['__name__'] = sectname self._sections[sectname] = cursect # So sections can't start with a continuation line optname = None Modified: python/branches/bcannon-objcap/Lib/Queue.py ============================================================================== --- python/branches/bcannon-objcap/Lib/Queue.py (original) +++ python/branches/bcannon-objcap/Lib/Queue.py Tue Jan 9 23:27:11 2007 @@ -26,7 +26,7 @@ self._init(maxsize) # mutex must be held whenever the queue is mutating. All methods # that acquire mutex must release it before returning. mutex - # is shared between the two conditions, so acquiring and + # is shared between the three conditions, so acquiring and # releasing the conditions also acquires and releases mutex. self.mutex = threading.Lock() # Notify not_empty whenever an item is added to the queue; a Modified: python/branches/bcannon-objcap/Lib/SimpleHTTPServer.py ============================================================================== --- python/branches/bcannon-objcap/Lib/SimpleHTTPServer.py (original) +++ python/branches/bcannon-objcap/Lib/SimpleHTTPServer.py Tue Jan 9 23:27:11 2007 @@ -66,6 +66,12 @@ path = self.translate_path(self.path) f = None if os.path.isdir(path): + if not self.path.endswith('/'): + # redirect browser - doing basically what apache does + self.send_response(301) + self.send_header("Location", self.path + "/") + self.end_headers() + return None for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): Modified: python/branches/bcannon-objcap/Lib/StringIO.py ============================================================================== --- python/branches/bcannon-objcap/Lib/StringIO.py (original) +++ python/branches/bcannon-objcap/Lib/StringIO.py Tue Jan 9 23:27:11 2007 @@ -137,7 +137,7 @@ return r def readline(self, length=None): - """Read one entire line from the file. + r"""Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is Modified: python/branches/bcannon-objcap/Lib/_strptime.py ============================================================================== --- python/branches/bcannon-objcap/Lib/_strptime.py (original) +++ python/branches/bcannon-objcap/Lib/_strptime.py Tue Jan 9 23:27:11 2007 @@ -306,7 +306,7 @@ _cache_lock.release() found = format_regex.match(data_string) if not found: - raise ValueError("time data did not match format: data=%s fmt=%s" % + raise ValueError("time data %r does not match format %r" % (data_string, format)) if len(data_string) != found.end(): raise ValueError("unconverted data remains: %s" % Modified: python/branches/bcannon-objcap/Lib/atexit.py ============================================================================== --- python/branches/bcannon-objcap/Lib/atexit.py (original) +++ python/branches/bcannon-objcap/Lib/atexit.py Tue Jan 9 23:27:11 2007 @@ -40,8 +40,11 @@ func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func + + func is returned to facilitate usage as a decorator. """ _exithandlers.append((func, targs, kargs)) + return func if hasattr(sys, "exitfunc"): # Assume it's another registered exit function - append it to our list Modified: python/branches/bcannon-objcap/Lib/base64.py ============================================================================== --- python/branches/bcannon-objcap/Lib/base64.py (original) +++ python/branches/bcannon-objcap/Lib/base64.py Tue Jan 9 23:27:11 2007 @@ -308,7 +308,7 @@ def encodestring(s): - """Encode a string.""" + """Encode a string into multiple lines of base-64 data.""" pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i : i + MAXBINSIZE] Modified: python/branches/bcannon-objcap/Lib/bsddb/dbobj.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/dbobj.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/dbobj.py Tue Jan 9 23:27:11 2007 @@ -55,8 +55,9 @@ return apply(self._cobj.set_lg_max, args, kwargs) def set_lk_detect(self, *args, **kwargs): return apply(self._cobj.set_lk_detect, args, kwargs) - def set_lk_max(self, *args, **kwargs): - return apply(self._cobj.set_lk_max, args, kwargs) + if db.version() < (4,5): + def set_lk_max(self, *args, **kwargs): + return apply(self._cobj.set_lk_max, args, kwargs) def set_lk_max_locks(self, *args, **kwargs): return apply(self._cobj.set_lk_max_locks, args, kwargs) def set_lk_max_lockers(self, *args, **kwargs): Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_1413192.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_1413192.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_1413192.py Tue Jan 9 23:27:11 2007 @@ -14,7 +14,7 @@ env_name = '.' env = db.DBEnv() -env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN) +env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN | db.DB_INIT_MPOOL) the_txn = env.txn_begin() map = db.DB(env) Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_associate.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_associate.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_associate.py Tue Jan 9 23:27:11 2007 @@ -91,7 +91,7 @@ class AssociateErrorTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_basics.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_basics.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_basics.py Tue Jan 9 23:27:11 2007 @@ -54,7 +54,7 @@ def setUp(self): if self.useEnv: - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: shutil.rmtree(homeDir) Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_dbobj.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_dbobj.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_dbobj.py Tue Jan 9 23:27:11 2007 @@ -2,6 +2,7 @@ import sys, os, string import unittest import glob +import tempfile try: # For Pythons w/distutils pybsddb @@ -19,7 +20,7 @@ db_name = 'test-dbobj.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass @@ -69,6 +70,10 @@ self.db.close() self.env.close() + def test03_dbobj_type_before_open(self): + # Ensure this doesn't cause a segfault. + self.assertRaises(db.DBInvalidArgError, db.DB().type) + #---------------------------------------------------------------------- def test_suite(): Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_dbshelve.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_dbshelve.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_dbshelve.py Tue Jan 9 23:27:11 2007 @@ -231,7 +231,7 @@ class BasicEnvShelveTestCase(DBShelveTestCase): def do_open(self): self.homeDir = homeDir = os.path.join( - os.path.dirname(sys.argv[0]), 'db_home') + tempfile.gettempdir(), 'db_home') try: os.mkdir(homeDir) except os.error: pass self.env = db.DBEnv() Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_dbtables.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_dbtables.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_dbtables.py Tue Jan 9 23:27:11 2007 @@ -26,6 +26,7 @@ pickle = cPickle except ImportError: import pickle +import tempfile import unittest from test_all import verbose @@ -46,7 +47,7 @@ db_name = 'test-table.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_env_close.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_env_close.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_env_close.py Tue Jan 9 23:27:11 2007 @@ -33,7 +33,7 @@ class DBEnvClosedEarlyCrash(unittest.TestCase): def setUp(self): - self.homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + self.homeDir = os.path.join(tempfile.gettempdir(), 'db_home') try: os.mkdir(self.homeDir) except os.error: pass tempfile.tempdir = self.homeDir Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_join.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_join.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_join.py Tue Jan 9 23:27:11 2007 @@ -49,7 +49,7 @@ def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_lock.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_lock.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_lock.py Tue Jan 9 23:27:11 2007 @@ -30,7 +30,7 @@ class LockingTestCase(unittest.TestCase): def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_misc.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_misc.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_misc.py Tue Jan 9 23:27:11 2007 @@ -4,6 +4,7 @@ import os import sys import unittest +import tempfile try: # For Pythons w/distutils pybsddb @@ -17,7 +18,7 @@ class MiscTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_recno.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_recno.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_recno.py Tue Jan 9 23:27:11 2007 @@ -203,10 +203,10 @@ just a line in the file, but you can set a different record delimiter if needed. """ - source = os.path.join(os.path.dirname(sys.argv[0]), - 'db_home/test_recno.txt') - if not os.path.isdir('db_home'): - os.mkdir('db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') + source = os.path.join(homeDir, 'test_recno.txt') + if not os.path.isdir(homeDir): + os.mkdir(homeDir) f = open(source, 'w') # create the file f.close() Modified: python/branches/bcannon-objcap/Lib/bsddb/test/test_thread.py ============================================================================== --- python/branches/bcannon-objcap/Lib/bsddb/test/test_thread.py (original) +++ python/branches/bcannon-objcap/Lib/bsddb/test/test_thread.py Tue Jan 9 23:27:11 2007 @@ -53,7 +53,7 @@ if verbose: dbutils._deadlock_VerboseFile = sys.stdout - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/bcannon-objcap/Lib/cgi.py ============================================================================== --- python/branches/bcannon-objcap/Lib/cgi.py (original) +++ python/branches/bcannon-objcap/Lib/cgi.py Tue Jan 9 23:27:11 2007 @@ -807,8 +807,10 @@ form.dict == {key: [val, val, ...], ...} """ - def __init__(self, environ=os.environ): - self.dict = self.data = parse(environ=environ) + def __init__(self, environ=os.environ, keep_blank_values=0, strict_parsing=0): + self.dict = self.data = parse(environ=environ, + keep_blank_values=keep_blank_values, + strict_parsing=strict_parsing) self.query_string = environ['QUERY_STRING'] Modified: python/branches/bcannon-objcap/Lib/codecs.py ============================================================================== --- python/branches/bcannon-objcap/Lib/codecs.py (original) +++ python/branches/bcannon-objcap/Lib/codecs.py Tue Jan 9 23:27:11 2007 @@ -329,6 +329,12 @@ """ return getattr(self.stream, name) + def __enter__(self): + return self + + def __exit__(self, type, value, tb): + self.stream.close() + ### class StreamReader(Codec): @@ -568,6 +574,12 @@ """ return getattr(self.stream, name) + def __enter__(self): + return self + + def __exit__(self, type, value, tb): + self.stream.close() + ### class StreamReaderWriter: @@ -641,6 +653,14 @@ """ return getattr(self.stream, name) + # these are needed to make "with codecs.open(...)" work properly + + def __enter__(self): + return self + + def __exit__(self, type, value, tb): + self.stream.close() + ### class StreamRecoder: @@ -751,6 +771,12 @@ """ return getattr(self.stream, name) + def __enter__(self): + return self + + def __exit__(self, type, value, tb): + self.stream.close() + ### Shortcuts def open(filename, mode='rb', encoding=None, errors='strict', buffering=1): @@ -824,9 +850,10 @@ """ if file_encoding is None: file_encoding = data_encoding - info = lookup(data_encoding) - sr = StreamRecoder(file, info.encode, info.decode, - info.streamreader, info.streamwriter, errors) + data_info = lookup(data_encoding) + file_info = lookup(file_encoding) + sr = StreamRecoder(file, data_info.encode, data_info.decode, + file_info.streamreader, file_info.streamwriter, errors) # Add attributes to simplify introspection sr.data_encoding = data_encoding sr.file_encoding = file_encoding Modified: python/branches/bcannon-objcap/Lib/colorsys.py ============================================================================== --- python/branches/bcannon-objcap/Lib/colorsys.py (original) +++ python/branches/bcannon-objcap/Lib/colorsys.py Tue Jan 9 23:27:11 2007 @@ -117,7 +117,8 @@ p = v*(1.0 - s) q = v*(1.0 - s*f) t = v*(1.0 - s*(1.0-f)) - if i%6 == 0: return v, t, p + i = i%6 + if i == 0: return v, t, p if i == 1: return q, v, p if i == 2: return p, v, t if i == 3: return p, q, v Modified: python/branches/bcannon-objcap/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/bcannon-objcap/Lib/compiler/pycodegen.py (original) +++ python/branches/bcannon-objcap/Lib/compiler/pycodegen.py Tue Jan 9 23:27:11 2007 @@ -573,12 +573,11 @@ def visitListComp(self, node): self.set_lineno(node) # setup list - append = "$append%d" % self.__list_count + tmpname = "$list%d" % self.__list_count self.__list_count = self.__list_count + 1 self.emit('BUILD_LIST', 0) self.emit('DUP_TOP') - self.emit('LOAD_ATTR', 'append') - self._implicitNameOp('STORE', append) + self._implicitNameOp('STORE', tmpname) stack = [] for i, for_ in zip(range(len(node.quals)), node.quals): @@ -590,10 +589,9 @@ self.visit(if_, cont) stack.insert(0, (start, cont, anchor)) - self._implicitNameOp('LOAD', append) + self._implicitNameOp('LOAD', tmpname) self.visit(node.expr) - self.emit('CALL_FUNCTION', 1) - self.emit('POP_TOP') + self.emit('LIST_APPEND') for start, cont, anchor in stack: if cont: @@ -604,7 +602,7 @@ self.nextBlock(skip_one) self.emit('JUMP_ABSOLUTE', start) self.startBlock(anchor) - self._implicitNameOp('DELETE', append) + self._implicitNameOp('DELETE', tmpname) self.__list_count = self.__list_count - 1 Modified: python/branches/bcannon-objcap/Lib/cookielib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/cookielib.py (original) +++ python/branches/bcannon-objcap/Lib/cookielib.py Tue Jan 9 23:27:11 2007 @@ -1316,26 +1316,28 @@ """ _debug("add_cookie_header") self._cookies_lock.acquire() + try: - self._policy._now = self._now = int(time.time()) - - cookies = self._cookies_for_request(request) + self._policy._now = self._now = int(time.time()) - attrs = self._cookie_attrs(cookies) - if attrs: - if not request.has_header("Cookie"): - request.add_unredirected_header( - "Cookie", "; ".join(attrs)) - - # if necessary, advertise that we know RFC 2965 - if (self._policy.rfc2965 and not self._policy.hide_cookie2 and - not request.has_header("Cookie2")): - for cookie in cookies: - if cookie.version != 1: - request.add_unredirected_header("Cookie2", '$Version="1"') - break + cookies = self._cookies_for_request(request) - self._cookies_lock.release() + attrs = self._cookie_attrs(cookies) + if attrs: + if not request.has_header("Cookie"): + request.add_unredirected_header( + "Cookie", "; ".join(attrs)) + + # if necessary, advertise that we know RFC 2965 + if (self._policy.rfc2965 and not self._policy.hide_cookie2 and + not request.has_header("Cookie2")): + for cookie in cookies: + if cookie.version != 1: + request.add_unredirected_header("Cookie2", '$Version="1"') + break + + finally: + self._cookies_lock.release() self.clear_expired_cookies() @@ -1602,12 +1604,15 @@ def set_cookie_if_ok(self, cookie, request): """Set a cookie if policy says it's OK to do so.""" self._cookies_lock.acquire() - self._policy._now = self._now = int(time.time()) + try: + self._policy._now = self._now = int(time.time()) - if self._policy.set_ok(cookie, request): - self.set_cookie(cookie) + if self._policy.set_ok(cookie, request): + self.set_cookie(cookie) + - self._cookies_lock.release() + finally: + self._cookies_lock.release() def set_cookie(self, cookie): """Set a cookie, without checking whether or not it should be set.""" @@ -1626,13 +1631,15 @@ """Extract cookies from response, where allowable given the request.""" _debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() - self._policy._now = self._now = int(time.time()) + try: + self._policy._now = self._now = int(time.time()) - for cookie in self.make_cookies(response, request): - if self._policy.set_ok(cookie, request): - _debug(" setting cookie: %s", cookie) - self.set_cookie(cookie) - self._cookies_lock.release() + for cookie in self.make_cookies(response, request): + if self._policy.set_ok(cookie, request): + _debug(" setting cookie: %s", cookie) + self.set_cookie(cookie) + finally: + self._cookies_lock.release() def clear(self, domain=None, path=None, name=None): """Clear some cookies. @@ -1669,10 +1676,12 @@ """ self._cookies_lock.acquire() - for cookie in self: - if cookie.discard: - self.clear(cookie.domain, cookie.path, cookie.name) - self._cookies_lock.release() + try: + for cookie in self: + if cookie.discard: + self.clear(cookie.domain, cookie.path, cookie.name) + finally: + self._cookies_lock.release() def clear_expired_cookies(self): """Discard all expired cookies. @@ -1685,11 +1694,13 @@ """ self._cookies_lock.acquire() - now = time.time() - for cookie in self: - if cookie.is_expired(now): - self.clear(cookie.domain, cookie.path, cookie.name) - self._cookies_lock.release() + try: + now = time.time() + for cookie in self: + if cookie.is_expired(now): + self.clear(cookie.domain, cookie.path, cookie.name) + finally: + self._cookies_lock.release() def __iter__(self): return deepvalues(self._cookies) @@ -1761,16 +1772,18 @@ else: raise ValueError(MISSING_FILENAME_TEXT) self._cookies_lock.acquire() - - old_state = copy.deepcopy(self._cookies) - self._cookies = {} try: - self.load(filename, ignore_discard, ignore_expires) - except (LoadError, IOError): - self._cookies = old_state - raise - self._cookies_lock.release() + old_state = copy.deepcopy(self._cookies) + self._cookies = {} + try: + self.load(filename, ignore_discard, ignore_expires) + except (LoadError, IOError): + self._cookies = old_state + raise + + finally: + self._cookies_lock.release() from _LWPCookieJar import LWPCookieJar, lwp_cookie_str from _MozillaCookieJar import MozillaCookieJar Modified: python/branches/bcannon-objcap/Lib/ctypes/__init__.py ============================================================================== --- python/branches/bcannon-objcap/Lib/ctypes/__init__.py (original) +++ python/branches/bcannon-objcap/Lib/ctypes/__init__.py Tue Jan 9 23:27:11 2007 @@ -133,6 +133,18 @@ from _ctypes import sizeof, byref, addressof, alignment, resize from _ctypes import _SimpleCData +def _check_size(typ, typecode=None): + # Check if sizeof(ctypes_type) against struct.calcsize. This + # should protect somewhat against a misconfigured libffi. + from struct import calcsize + if typecode is None: + # Most _type_ codes are the same as used in struct + typecode = typ._type_ + actual, required = sizeof(typ), calcsize(typecode) + if actual != required: + raise SystemError("sizeof(%s) wrong: %d instead of %d" % \ + (typ, actual, required)) + class py_object(_SimpleCData): _type_ = "O" def __repr__(self): @@ -140,18 +152,23 @@ return super(py_object, self).__repr__() except ValueError: return "%s()" % type(self).__name__ +_check_size(py_object, "P") class c_short(_SimpleCData): _type_ = "h" +_check_size(c_short) class c_ushort(_SimpleCData): _type_ = "H" +_check_size(c_ushort) class c_long(_SimpleCData): _type_ = "l" +_check_size(c_long) class c_ulong(_SimpleCData): _type_ = "L" +_check_size(c_ulong) if _calcsize("i") == _calcsize("l"): # if int and long have the same size, make c_int an alias for c_long @@ -160,15 +177,19 @@ else: class c_int(_SimpleCData): _type_ = "i" + _check_size(c_int) class c_uint(_SimpleCData): _type_ = "I" + _check_size(c_uint) class c_float(_SimpleCData): _type_ = "f" +_check_size(c_float) class c_double(_SimpleCData): _type_ = "d" +_check_size(c_double) if _calcsize("l") == _calcsize("q"): # if long and long long have the same size, make c_longlong an alias for c_long @@ -177,33 +198,40 @@ else: class c_longlong(_SimpleCData): _type_ = "q" + _check_size(c_longlong) class c_ulonglong(_SimpleCData): _type_ = "Q" ## def from_param(cls, val): ## return ('d', float(val), val) ## from_param = classmethod(from_param) + _check_size(c_ulonglong) class c_ubyte(_SimpleCData): _type_ = "B" c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte # backward compatibility: ##c_uchar = c_ubyte +_check_size(c_ubyte) class c_byte(_SimpleCData): _type_ = "b" c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte +_check_size(c_byte) class c_char(_SimpleCData): _type_ = "c" c_char.__ctype_le__ = c_char.__ctype_be__ = c_char +_check_size(c_char) class c_char_p(_SimpleCData): _type_ = "z" +_check_size(c_char_p, "P") class c_void_p(_SimpleCData): _type_ = "P" c_voidp = c_void_p # backwards compatibility (to a bug) +_check_size(c_void_p) # This cache maps types to pointers to them. _pointer_type_cache = {} Modified: python/branches/bcannon-objcap/Lib/ctypes/test/__init__.py ============================================================================== --- python/branches/bcannon-objcap/Lib/ctypes/test/__init__.py (original) +++ python/branches/bcannon-objcap/Lib/ctypes/test/__init__.py Tue Jan 9 23:27:11 2007 @@ -37,7 +37,8 @@ def find_package_modules(package, mask): import fnmatch - if hasattr(package, "__loader__"): + if (hasattr(package, "__loader__") and + hasattr(package.__loader__, '_files')): path = package.__name__.replace(".", os.path.sep) mask = os.path.join(path, mask) for fnm in package.__loader__._files.iterkeys(): Modified: python/branches/bcannon-objcap/Lib/ctypes/test/test_callbacks.py ============================================================================== --- python/branches/bcannon-objcap/Lib/ctypes/test/test_callbacks.py (original) +++ python/branches/bcannon-objcap/Lib/ctypes/test/test_callbacks.py Tue Jan 9 23:27:11 2007 @@ -101,6 +101,19 @@ after = grc(o) self.failUnlessEqual((after, o), (before, o)) + def test_unsupported_restype_1(self): + # Only "fundamental" result types are supported for callback + # functions, the type must have a non-NULL stgdict->setfunc. + # POINTER(c_double), for example, is not supported. + + prototype = self.functype.im_func(POINTER(c_double)) + # The type is checked when the prototype is called + self.assertRaises(TypeError, prototype, lambda: None) + + def test_unsupported_restype_2(self): + prototype = self.functype.im_func(object) + self.assertRaises(TypeError, prototype, lambda: None) + try: WINFUNCTYPE except NameError: Modified: python/branches/bcannon-objcap/Lib/ctypes/test/test_structures.py ============================================================================== --- python/branches/bcannon-objcap/Lib/ctypes/test/test_structures.py (original) +++ python/branches/bcannon-objcap/Lib/ctypes/test/test_structures.py Tue Jan 9 23:27:11 2007 @@ -381,5 +381,35 @@ s.p = None self.failUnlessEqual(s.x, 12345678) +class TestRecursiveStructure(unittest.TestCase): + def test_contains_itself(self): + class Recursive(Structure): + pass + + try: + Recursive._fields_ = [("next", Recursive)] + except AttributeError, details: + self.failUnless("Structure or union cannot contain itself" in + str(details)) + else: + self.fail("Structure or union cannot contain itself") + + + def test_vice_versa(self): + class First(Structure): + pass + class Second(Structure): + pass + + First._fields_ = [("second", Second)] + + try: + Second._fields_ = [("first", First)] + except AttributeError, details: + self.failUnless("_fields_ is final" in + str(details)) + else: + self.fail("AttributeError not raised") + if __name__ == '__main__': unittest.main() Modified: python/branches/bcannon-objcap/Lib/difflib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/difflib.py (original) +++ python/branches/bcannon-objcap/Lib/difflib.py Tue Jan 9 23:27:11 2007 @@ -1311,7 +1311,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, charjunk=IS_CHARACTER_JUNK): - """Returns generator yielding marked up from/to side by side differences. + r"""Returns generator yielding marked up from/to side by side differences. Arguments: fromlines -- list of text lines to compared to tolines Modified: python/branches/bcannon-objcap/Lib/distutils/command/bdist_rpm.py ============================================================================== --- python/branches/bcannon-objcap/Lib/distutils/command/bdist_rpm.py (original) +++ python/branches/bcannon-objcap/Lib/distutils/command/bdist_rpm.py Tue Jan 9 23:27:11 2007 @@ -337,37 +337,47 @@ if not self.keep_temp: rpm_cmd.append('--clean') rpm_cmd.append(spec_path) + # Determine the binary rpm names that should be built out of this spec + # file + # Note that some of these may not be really built (if the file + # list is empty) + nvr_string = "%{name}-%{version}-%{release}" + src_rpm = nvr_string + ".src.rpm" + non_src_rpm = "%{arch}/" + nvr_string + ".%{arch}.rpm" + q_cmd = r"rpm -q --qf '%s %s\n' --specfile '%s'" % ( + src_rpm, non_src_rpm, spec_path) + + out = os.popen(q_cmd) + binary_rpms = [] + source_rpm = None + while 1: + line = out.readline() + if not line: + break + l = string.split(string.strip(line)) + assert(len(l) == 2) + binary_rpms.append(l[1]) + # The source rpm is named after the first entry in the spec file + if source_rpm is None: + source_rpm = l[0] + + status = out.close() + if status: + raise DistutilsExecError("Failed to execute: %s" % repr(q_cmd)) + self.spawn(rpm_cmd) - # XXX this is a nasty hack -- we really should have a proper way to - # find out the names of the RPM files created; also, this assumes - # that RPM creates exactly one source and one binary RPM. if not self.dry_run: if not self.binary_only: - srpms = glob.glob(os.path.join(rpm_dir['SRPMS'], "*.rpm")) - assert len(srpms) == 1, \ - "unexpected number of SRPM files found: %s" % srpms - dist_file = ('bdist_rpm', 'any', - self._dist_path(srpms[0])) - self.distribution.dist_files.append(dist_file) - self.move_file(srpms[0], self.dist_dir) + srpm = os.path.join(rpm_dir['SRPMS'], source_rpm) + assert(os.path.exists(srpm)) + self.move_file(srpm, self.dist_dir) if not self.source_only: - rpms = glob.glob(os.path.join(rpm_dir['RPMS'], "*/*.rpm")) - debuginfo = glob.glob(os.path.join(rpm_dir['RPMS'], - "*/*debuginfo*.rpm")) - if debuginfo: - rpms.remove(debuginfo[0]) - assert len(rpms) == 1, \ - "unexpected number of RPM files found: %s" % rpms - dist_file = ('bdist_rpm', get_python_version(), - self._dist_path(rpms[0])) - self.distribution.dist_files.append(dist_file) - self.move_file(rpms[0], self.dist_dir) - if debuginfo: - dist_file = ('bdist_rpm', get_python_version(), - self._dist_path(debuginfo[0])) - self.move_file(debuginfo[0], self.dist_dir) + for rpm in binary_rpms: + rpm = os.path.join(rpm_dir['RPMS'], rpm) + if os.path.exists(rpm): + self.move_file(rpm, self.dist_dir) # run() def _dist_path(self, path): @@ -381,6 +391,7 @@ spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), + '%define unmangled_version ' + self.distribution.get_version(), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), @@ -402,9 +413,9 @@ # but only after it has run: and we create the spec file before # running "sdist", in case of --spec-only. if self.use_bzip2: - spec_file.append('Source0: %{name}-%{version}.tar.bz2') + spec_file.append('Source0: %{name}-%{unmangled_version}.tar.bz2') else: - spec_file.append('Source0: %{name}-%{version}.tar.gz') + spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz') spec_file.extend([ 'License: ' + self.distribution.get_license(), @@ -479,7 +490,7 @@ # are just text that we drop in as-is. Hmmm. script_options = [ - ('prep', 'prep_script', "%setup"), + ('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"), ('build', 'build_script', def_build), ('install', 'install_script', ("%s install " Modified: python/branches/bcannon-objcap/Lib/distutils/command/build_ext.py ============================================================================== --- python/branches/bcannon-objcap/Lib/distutils/command/build_ext.py (original) +++ python/branches/bcannon-objcap/Lib/distutils/command/build_ext.py Tue Jan 9 23:27:11 2007 @@ -186,7 +186,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') and + ((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 Modified: python/branches/bcannon-objcap/Lib/distutils/command/install_egg_info.py ============================================================================== --- python/branches/bcannon-objcap/Lib/distutils/command/install_egg_info.py (original) +++ python/branches/bcannon-objcap/Lib/distutils/command/install_egg_info.py Tue Jan 9 23:27:11 2007 @@ -35,6 +35,9 @@ dir_util.remove_tree(target, dry_run=self.dry_run) elif os.path.exists(target): self.execute(os.unlink,(self.target,),"Removing "+target) + elif not os.path.isdir(self.install_dir): + self.execute(os.makedirs, (self.install_dir,), + "Creating "+self.install_dir) log.info("Writing %s", target) if not self.dry_run: f = open(target, 'w') Modified: python/branches/bcannon-objcap/Lib/distutils/command/register.py ============================================================================== --- python/branches/bcannon-objcap/Lib/distutils/command/register.py (original) +++ python/branches/bcannon-objcap/Lib/distutils/command/register.py Tue Jan 9 23:27:11 2007 @@ -251,7 +251,7 @@ body = StringIO.StringIO() for key, value in data.items(): # handle multiple entries for the same name - if type(value) != type([]): + if type(value) not in (type([]), type( () )): value = [value] for value in value: value = unicode(value).encode("utf-8") Modified: python/branches/bcannon-objcap/Lib/distutils/sysconfig.py ============================================================================== --- python/branches/bcannon-objcap/Lib/distutils/sysconfig.py (original) +++ python/branches/bcannon-objcap/Lib/distutils/sysconfig.py Tue Jan 9 23:27:11 2007 @@ -509,7 +509,10 @@ # are in CFLAGS or LDFLAGS and remove them if they are. # This is needed when building extensions on a 10.3 system # using a universal build of python. - for key in ('LDFLAGS', 'BASECFLAGS'): + for key in ('LDFLAGS', 'BASECFLAGS', + # a number of derived variables. These need to be + # patched up as well. + 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): flags = _config_vars[key] flags = re.sub('-arch\s+\w+\s', ' ', flags) flags = re.sub('-isysroot [^ \t]*', ' ', flags) Modified: python/branches/bcannon-objcap/Lib/distutils/unixccompiler.py ============================================================================== --- python/branches/bcannon-objcap/Lib/distutils/unixccompiler.py (original) +++ python/branches/bcannon-objcap/Lib/distutils/unixccompiler.py Tue Jan 9 23:27:11 2007 @@ -82,6 +82,22 @@ except ValueError: pass + # Check if the SDK that is used during compilation actually exists, + # the universal build requires the usage of a universal SDK and not all + # users have that installed by default. + sysroot = None + if '-isysroot' in cc_args: + idx = cc_args.index('-isysroot') + sysroot = cc_args[idx+1] + elif '-isysroot' in compiler_so: + idx = compiler_so.index('-isysroot') + sysroot = compiler_so[idx+1] + + if sysroot and not os.path.isdir(sysroot): + log.warn("Compiling with an SDK that doesn't seem to exist: %s", + sysroot) + log.warn("Please check your Xcode installation") + return compiler_so class UnixCCompiler(CCompiler): Modified: python/branches/bcannon-objcap/Lib/dumbdbm.py ============================================================================== --- python/branches/bcannon-objcap/Lib/dumbdbm.py (original) +++ python/branches/bcannon-objcap/Lib/dumbdbm.py Tue Jan 9 23:27:11 2007 @@ -68,7 +68,8 @@ try: f = _open(self._datfile, 'r') except IOError: - f = _open(self._datfile, 'w', self._mode) + f = _open(self._datfile, 'w') + self._chmod(self._datfile) f.close() self._update() @@ -106,7 +107,8 @@ except self._os.error: pass - f = self._open(self._dirfile, 'w', self._mode) + f = self._open(self._dirfile, 'w') + self._chmod(self._dirfile) for key, pos_and_siz_pair in self._index.iteritems(): f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -152,7 +154,8 @@ # the in-memory index dict, and append one to the directory file. def _addkey(self, key, pos_and_siz_pair): self._index[key] = pos_and_siz_pair - f = _open(self._dirfile, 'a', self._mode) + f = _open(self._dirfile, 'a') + self._chmod(self._dirfile) f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -214,6 +217,9 @@ __del__ = close + def _chmod (self, file): + if hasattr(self._os, 'chmod'): + self._os.chmod(file, self._mode) def open(file, flag=None, mode=0666): @@ -230,4 +236,15 @@ """ # flag argument is currently ignored + + # Modify mode depending on the umask + try: + um = _os.umask(0) + _os.umask(um) + except AttributeError: + pass + else: + # Turn off any bits that are set in the umask + mode = mode & (~um) + return _Database(file, mode) Modified: python/branches/bcannon-objcap/Lib/email/utils.py ============================================================================== --- python/branches/bcannon-objcap/Lib/email/utils.py (original) +++ python/branches/bcannon-objcap/Lib/email/utils.py Tue Jan 9 23:27:11 2007 @@ -235,10 +235,6 @@ parts = s.split(TICK, 2) if len(parts) <= 2: return None, None, s - if len(parts) > 3: - charset, language = parts[:2] - s = TICK.join(parts[2:]) - return charset, language, s return parts Modified: python/branches/bcannon-objcap/Lib/encodings/__init__.py ============================================================================== --- python/branches/bcannon-objcap/Lib/encodings/__init__.py (original) +++ python/branches/bcannon-objcap/Lib/encodings/__init__.py Tue Jan 9 23:27:11 2007 @@ -90,7 +90,7 @@ else: modnames = [norm_encoding] for modname in modnames: - if not modname: + if not modname or '.' in modname: continue try: mod = __import__('encodings.' + modname, Modified: python/branches/bcannon-objcap/Lib/encodings/bz2_codec.py ============================================================================== --- python/branches/bcannon-objcap/Lib/encodings/bz2_codec.py (original) +++ python/branches/bcannon-objcap/Lib/encodings/bz2_codec.py Tue Jan 9 23:27:11 2007 @@ -52,14 +52,35 @@ return bz2_decode(input, errors) class IncrementalEncoder(codecs.IncrementalEncoder): + def __init__(self, errors='strict'): + assert errors == 'strict' + self.errors = errors + self.compressobj = bz2.BZ2Compressor() + def encode(self, input, final=False): - assert self.errors == 'strict' - return bz2.compress(input) + if final: + c = self.compressobj.compress(input) + return c + self.compressobj.flush() + else: + return self.compressobj.compress(input) + + def reset(self): + self.compressobj = bz2.BZ2Compressor() class IncrementalDecoder(codecs.IncrementalDecoder): + def __init__(self, errors='strict'): + assert errors == 'strict' + self.errors = errors + self.decompressobj = bz2.BZ2Decompressor() + def decode(self, input, final=False): - assert self.errors == 'strict' - return bz2.decompress(input) + try: + return self.decompressobj.decompress(input) + except EOFError: + return '' + + def reset(self): + self.decompressobj = bz2.BZ2Decompressor() class StreamWriter(Codec,codecs.StreamWriter): pass Modified: python/branches/bcannon-objcap/Lib/encodings/utf_8_sig.py ============================================================================== --- python/branches/bcannon-objcap/Lib/encodings/utf_8_sig.py (original) +++ python/branches/bcannon-objcap/Lib/encodings/utf_8_sig.py Tue Jan 9 23:27:11 2007 @@ -16,7 +16,7 @@ def decode(input, errors='strict'): prefix = 0 - if input.startswith(codecs.BOM_UTF8): + if input[:3] == codecs.BOM_UTF8: input = input[3:] prefix = 3 (output, consumed) = codecs.utf_8_decode(input, errors, True) Modified: python/branches/bcannon-objcap/Lib/encodings/zlib_codec.py ============================================================================== --- python/branches/bcannon-objcap/Lib/encodings/zlib_codec.py (original) +++ python/branches/bcannon-objcap/Lib/encodings/zlib_codec.py Tue Jan 9 23:27:11 2007 @@ -51,14 +51,36 @@ return zlib_decode(input, errors) class IncrementalEncoder(codecs.IncrementalEncoder): + def __init__(self, errors='strict'): + assert errors == 'strict' + self.errors = errors + self.compressobj = zlib.compressobj() + def encode(self, input, final=False): - assert self.errors == 'strict' - return zlib.compress(input) + if final: + c = self.compressobj.compress(input) + return c + self.compressobj.flush() + else: + return self.compressobj.compress(input) + + def reset(self): + self.compressobj = zlib.compressobj() class IncrementalDecoder(codecs.IncrementalDecoder): + def __init__(self, errors='strict'): + assert errors == 'strict' + self.errors = errors + self.decompressobj = zlib.decompressobj() + def decode(self, input, final=False): - assert self.errors == 'strict' - return zlib.decompress(input) + if final: + c = self.decompressobj.decompress(input) + return c + self.decompressobj.flush() + else: + return self.decompressobj.decompress(input) + + def reset(self): + self.decompressobj = zlib.decompressobj() class StreamWriter(Codec,codecs.StreamWriter): pass Modified: python/branches/bcannon-objcap/Lib/ftplib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/ftplib.py (original) +++ python/branches/bcannon-objcap/Lib/ftplib.py Tue Jan 9 23:27:11 2007 @@ -325,6 +325,14 @@ if rest is not None: self.sendcmd("REST %s" % rest) resp = self.sendcmd(cmd) + # Some servers apparently send a 200 reply to + # a LIST or STOR command, before the 150 reply + # (and way before the 226 reply). This seems to + # be in violation of the protocol (which only allows + # 1xx or error messages for LIST), so we just discard + # this response. + if resp[0] == '2': + resp = self.getresp() if resp[0] != '1': raise error_reply, resp else: @@ -332,6 +340,9 @@ if rest is not None: self.sendcmd("REST %s" % rest) resp = self.sendcmd(cmd) + # See above. + if resp[0] == '2': + resp = self.getresp() if resp[0] != '1': raise error_reply, resp conn, sockaddr = sock.accept() Modified: python/branches/bcannon-objcap/Lib/functools.py ============================================================================== --- python/branches/bcannon-objcap/Lib/functools.py (original) +++ python/branches/bcannon-objcap/Lib/functools.py Tue Jan 9 23:27:11 2007 @@ -25,14 +25,14 @@ assigned is a tuple naming the attributes assigned directly from the wrapped function to the wrapper function (defaults to functools.WRAPPER_ASSIGNMENTS) - updated is a tuple naming the attributes off the wrapper that + updated is a tuple naming the attributes of the wrapper that are updated with the corresponding attribute from the wrapped function (defaults to functools.WRAPPER_UPDATES) """ for attr in assigned: setattr(wrapper, attr, getattr(wrapped, attr)) for attr in updated: - getattr(wrapper, attr).update(getattr(wrapped, attr)) + getattr(wrapper, attr).update(getattr(wrapped, attr, {})) # Return the wrapper so this can be used as a decorator via partial() return wrapper Modified: python/branches/bcannon-objcap/Lib/gzip.py ============================================================================== --- python/branches/bcannon-objcap/Lib/gzip.py (original) +++ python/branches/bcannon-objcap/Lib/gzip.py Tue Jan 9 23:27:11 2007 @@ -371,7 +371,12 @@ self.extrasize = 0 self.offset = 0 - def seek(self, offset): + def seek(self, offset, whence=0): + if whence: + if whence == 1: + offset = self.offset + offset + else: + raise ValueError('Seek from end not supported') if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') Modified: python/branches/bcannon-objcap/Lib/hashlib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/hashlib.py (original) +++ python/branches/bcannon-objcap/Lib/hashlib.py Tue Jan 9 23:27:11 2007 @@ -18,8 +18,37 @@ More algorithms may be available on your platform but the above are guaranteed to exist. -Choose your hash function wisely. Some have known weaknesses. +Choose your hash function wisely. Some have known collision weaknesses. sha384 and sha512 will be slow on 32 bit platforms. + +Hash objects have these methods: + - update(arg): Update the hash object with the string arg. Repeated calls + are equivalent to a single call with the concatenation of all + the arguments. + - digest(): Return the digest of the strings passed to the update() method + so far. This may contain non-ASCII characters, including + NUL bytes. + - hexdigest(): Like digest() except the digest is returned as a string of + double length, containing only hexadecimal digits. + - copy(): Return a copy (clone) of the hash object. This can be used to + efficiently compute the digests of strings that share a common + initial substring. + +For example, to obtain the digest of the string 'Nobody inspects the +spammish repetition': + + >>> import hashlib + >>> m = hashlib.md5() + >>> m.update("Nobody inspects") + >>> m.update(" the spammish repetition") + >>> m.digest() + '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' + +More condensed: + + >>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest() + 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' + """ Modified: python/branches/bcannon-objcap/Lib/heapq.py ============================================================================== --- python/branches/bcannon-objcap/Lib/heapq.py (original) +++ python/branches/bcannon-objcap/Lib/heapq.py Tue Jan 9 23:27:11 2007 @@ -130,7 +130,7 @@ 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee -from operator import itemgetter +from operator import itemgetter, neg import bisect def heappush(heap, item): @@ -315,8 +315,6 @@ Equivalent to: sorted(iterable, key=key)[:n] """ - if key is None: - return _nsmallest(n, iterable) in1, in2 = tee(iterable) it = izip(imap(key, in1), count(), in2) # decorate result = _nsmallest(n, it) @@ -328,10 +326,8 @@ Equivalent to: sorted(iterable, key=key, reverse=True)[:n] """ - if key is None: - return _nlargest(n, iterable) in1, in2 = tee(iterable) - it = izip(imap(key, in1), count(), in2) # decorate + it = izip(imap(key, in1), imap(neg, count()), in2) # decorate result = _nlargest(n, it) return map(itemgetter(2), result) # undecorate Modified: python/branches/bcannon-objcap/Lib/hmac.py ============================================================================== --- python/branches/bcannon-objcap/Lib/hmac.py (original) +++ python/branches/bcannon-objcap/Lib/hmac.py Tue Jan 9 23:27:11 2007 @@ -3,13 +3,11 @@ Implements the HMAC algorithm as described by RFC 2104. """ -def _strxor(s1, s2): - """Utility method. XOR the two strings s1 and s2 (must have same length). - """ - return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) +trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)]) +trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)]) # The size of the digests returned by HMAC depends on the underlying -# hashing module used. +# hashing module used. Use digest_size from the instance of HMAC instead. digest_size = None # A unique object passed by HMAC.copy() to the HMAC constructor, in order @@ -22,6 +20,7 @@ This supports the API for Cryptographic Hash Functions (PEP 247). """ + blocksize = 64 # 512-bit HMAC; can be changed in subclasses. def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. @@ -49,16 +48,13 @@ self.inner = self.digest_cons() self.digest_size = self.inner.digest_size - blocksize = 64 - ipad = "\x36" * blocksize - opad = "\x5C" * blocksize - + blocksize = self.blocksize if len(key) > blocksize: key = self.digest_cons(key).digest() key = key + chr(0) * (blocksize - len(key)) - self.outer.update(_strxor(key, opad)) - self.inner.update(_strxor(key, ipad)) + self.outer.update(key.translate(trans_5C)) + self.inner.update(key.translate(trans_36)) if msg is not None: self.update(msg) @@ -75,13 +71,22 @@ An update to this copy won't affect the original object. """ - other = HMAC(_secret_backdoor_key) + other = self.__class__(_secret_backdoor_key) other.digest_cons = self.digest_cons other.digest_size = self.digest_size other.inner = self.inner.copy() other.outer = self.outer.copy() return other + def _current(self): + """Return a hash object for the current state. + + To be used only internally with digest() and hexdigest(). + """ + h = self.outer.copy() + h.update(self.inner.digest()) + return h + def digest(self): """Return the hash value of this hashing object. @@ -89,15 +94,14 @@ not altered in any way by this function; you can continue updating the object after calling this function. """ - h = self.outer.copy() - h.update(self.inner.digest()) + h = self._current() return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ - return "".join([hex(ord(x))[2:].zfill(2) - for x in tuple(self.digest())]) + h = self._current() + return h.hexdigest() def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. Modified: python/branches/bcannon-objcap/Lib/httplib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/httplib.py (original) +++ python/branches/bcannon-objcap/Lib/httplib.py Tue Jan 9 23:27:11 2007 @@ -704,7 +704,15 @@ if self.debuglevel > 0: print "send:", repr(str) try: - self.sock.sendall(str) + blocksize=8192 + if hasattr(str,'read') : + if self.debuglevel > 0: print "sendIng a read()able" + data=str.read(blocksize) + while data: + self.sock.sendall(data) + data=str.read(blocksize) + else: + self.sock.sendall(str) except socket.error, v: if v[0] == 32: # Broken pipe self.close() @@ -879,7 +887,21 @@ self.putrequest(method, url, **skips) if body and ('content-length' not in header_names): - self.putheader('Content-Length', str(len(body))) + thelen=None + try: + thelen=str(len(body)) + except TypeError, te: + # If this is a file-like object, try to + # fstat its file descriptor + import os + try: + 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 thelen is not None: + self.putheader('Content-Length',thelen) for hdr, value in headers.iteritems(): self.putheader(hdr, value) self.endheaders() Modified: python/branches/bcannon-objcap/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/branches/bcannon-objcap/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/branches/bcannon-objcap/Lib/idlelib/AutoCompleteWindow.py Tue Jan 9 23:27:11 2007 @@ -118,8 +118,11 @@ i = 0 while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]: i += 1 - while cursel > 0 and selstart[:i] <= self.completions[cursel-1]: + previous_completion = self.completions[cursel - 1] + while cursel > 0 and selstart[:i] <= previous_completion: i += 1 + if selstart == previous_completion: + break # maybe we have a duplicate? newstart = selstart[:i] self._change_start(newstart) Modified: python/branches/bcannon-objcap/Lib/idlelib/CodeContext.py ============================================================================== --- python/branches/bcannon-objcap/Lib/idlelib/CodeContext.py (original) +++ python/branches/bcannon-objcap/Lib/idlelib/CodeContext.py Tue Jan 9 23:27:11 2007 @@ -54,25 +54,68 @@ def toggle_code_context_event(self, event=None): if not self.label: - self.pad_frame = Tkinter.Frame(self.editwin.top, - bg=self.bgcolor, border=2, - relief="sunken") - self.label = Tkinter.Label(self.pad_frame, - text="\n" * (self.context_depth - 1), - anchor="w", justify="left", - font=self.textfont, - bg=self.bgcolor, fg=self.fgcolor, - border=0, - width=1, # Don't request more than we get - ) - self.label.pack(side="top", fill="x", expand=True, - padx=4, pady=0) - self.pad_frame.pack(side="top", fill="x", expand=False, - padx=0, pady=0, - after=self.editwin.status_bar) + # 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. + # + # 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 + 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 + + self.label = Tkinter.Label(self.editwin.top, + text="\n" * (self.context_depth - 1), + 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, + before=self.editwin.text_frame) + else: self.label.destroy() - self.pad_frame.destroy() self.label = None idleConf.SetOption("extensions", "CodeContext", "visible", str(self.label is not None)) Modified: python/branches/bcannon-objcap/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/bcannon-objcap/Lib/idlelib/EditorWindow.py (original) +++ python/branches/bcannon-objcap/Lib/idlelib/EditorWindow.py Tue Jan 9 23:27:11 2007 @@ -102,8 +102,8 @@ self.top.instance_dict = {} self.recent_files_path = os.path.join(idleConf.GetUserCfgDir(), 'recent-files.lst') - self.vbar = vbar = Scrollbar(top, name='vbar') self.text_frame = text_frame = Frame(top) + self.vbar = vbar = Scrollbar(text_frame, name='vbar') self.width = idleConf.GetOption('main','EditorWindow','width') self.text = text = MultiCallCreator(Text)( text_frame, name='text', padx=5, wrap='none', Modified: python/branches/bcannon-objcap/Lib/idlelib/NEWS.txt ============================================================================== --- python/branches/bcannon-objcap/Lib/idlelib/NEWS.txt (original) +++ python/branches/bcannon-objcap/Lib/idlelib/NEWS.txt Tue Jan 9 23:27:11 2007 @@ -3,10 +3,28 @@ *Release date: XX-XXX-200X* +- Avoid hang when encountering a duplicate in a completion list. Bug 1571112. + +- Patch #1362975: Rework CodeContext indentation algorithm to + avoid hard-coding pixel widths. + +- Bug #813342: Start the IDLE subprocess with -Qnew if the parent + is started with that option. + +- Some syntax errors were being caught by tokenize during the tabnanny + check, resulting in obscure error messages. Do the syntax check + first. Bug 1562716, 1562719 + - IDLE's version number takes a big jump to match the version number of the Python release of which it's a part. +What's New in IDLE 1.2? +======================= + +*Release date: 19-SEP-2006* + + What's New in IDLE 1.2c1? ========================= @@ -37,6 +55,13 @@ *Release date: 03-AUG-2006* +- Bug #1525817: Don't truncate short lines in IDLE's tool tips. + +- Bug #1517990: IDLE keybindings on MacOS X now work correctly + +- Bug #1517996: IDLE now longer shows the default Tk menu when a + path browser, class browser or debugger is the frontmost window on MacOS X + - EditorWindow.test() was failing. Bug 1417598 - EditorWindow failed when used stand-alone if sys.ps1 not set. @@ -73,6 +98,8 @@ *Release date: 05-APR-2006* +- Patch #1162825: Support non-ASCII characters in IDLE window titles. + - Source file f.flush() after writing; trying to avoid lossage if user kills GUI. Modified: python/branches/bcannon-objcap/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/bcannon-objcap/Lib/idlelib/PyShell.py (original) +++ python/branches/bcannon-objcap/Lib/idlelib/PyShell.py Tue Jan 9 23:27:11 2007 @@ -351,6 +351,8 @@ def build_subprocess_arglist(self): w = ['-W' + s for s in sys.warnoptions] + if 1/2 > 0: # account for new division + w.append('-Qnew') # Maybe IDLE is installed and is being accessed via sys.path, # or maybe it's not installed and the idle.py script is being # run from the IDLE source directory. @@ -726,6 +728,8 @@ 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()" self.showtraceback() Modified: python/branches/bcannon-objcap/Lib/idlelib/ScriptBinding.py ============================================================================== --- python/branches/bcannon-objcap/Lib/idlelib/ScriptBinding.py (original) +++ python/branches/bcannon-objcap/Lib/idlelib/ScriptBinding.py Tue Jan 9 23:27:11 2007 @@ -57,9 +57,10 @@ filename = self.getfilename() if not filename: return + if not self.checksyntax(filename): + return if not self.tabnanny(filename): return - self.checksyntax(filename) def tabnanny(self, filename): f = open(filename, 'r') @@ -76,9 +77,6 @@ self.editwin.gotoline(nag.get_lineno()) self.errorbox("Tab/space error", indent_message) return False - except IndentationError: - # From tokenize(), let compile() in checksyntax find it again. - pass return True def checksyntax(self, filename): @@ -139,11 +137,11 @@ filename = self.getfilename() if not filename: return - if not self.tabnanny(filename): - return code = self.checksyntax(filename) if not code: return + if not self.tabnanny(filename): + return shell = self.shell interp = shell.interp if PyShell.use_subprocess: Modified: python/branches/bcannon-objcap/Lib/inspect.py ============================================================================== --- python/branches/bcannon-objcap/Lib/inspect.py (original) +++ python/branches/bcannon-objcap/Lib/inspect.py Tue Jan 9 23:27:11 2007 @@ -472,9 +472,24 @@ if isclass(object): name = object.__name__ - pat = re.compile(r'^\s*class\s*' + name + r'\b') + pat = re.compile(r'^(\s*)class\s*' + name + r'\b') + # make some effort to find the best matching class definition: + # use the one with the least indentation, which is the one + # that's most probably not inside a function definition. + candidates = [] for i in range(len(lines)): - if pat.match(lines[i]): return lines, i + match = pat.match(lines[i]) + if match: + # if it's at toplevel, it's already the best one + if lines[i][0] == 'c': + return lines, i + # else add whitespace to candidate list + candidates.append((match.group(1), i)) + if candidates: + # this will sort by whitespace, and by line number, + # less whitespace first + candidates.sort() + return lines, candidates[0][1] else: raise IOError('could not find class definition') Modified: python/branches/bcannon-objcap/Lib/lib-tk/Tix.py ============================================================================== --- python/branches/bcannon-objcap/Lib/lib-tk/Tix.py (original) +++ python/branches/bcannon-objcap/Lib/lib-tk/Tix.py Tue Jan 9 23:27:11 2007 @@ -421,7 +421,7 @@ except: plist = [] - if (not check_intermediate) or len(plist) < 2: + if not check_intermediate: # immediate descendant TixWidget.__init__(self, master, None, None, {'name' : name}) else: @@ -437,6 +437,9 @@ parent = TixSubWidget(parent, plist[i], destroy_physically=0, check_intermediate=0) + # The Tk widget name is in plist, not in name + if plist: + name = plist[-1] TixWidget.__init__(self, parent, None, None, {'name' : name}) self.destroy_physically = destroy_physically Modified: python/branches/bcannon-objcap/Lib/lib-tk/Tkinter.py ============================================================================== --- python/branches/bcannon-objcap/Lib/lib-tk/Tkinter.py (original) +++ python/branches/bcannon-objcap/Lib/lib-tk/Tkinter.py Tue Jan 9 23:27:11 2007 @@ -3017,7 +3017,7 @@ self.tk.call(self._w, 'scan', 'dragto', x, y) def search(self, pattern, index, stopindex=None, forwards=None, backwards=None, exact=None, - regexp=None, nocase=None, count=None): + regexp=None, nocase=None, count=None, elide=None): """Search PATTERN beginning from INDEX until STOPINDEX. Return the index of the first character of a match or an empty string.""" args = [self._w, 'search'] @@ -3026,6 +3026,7 @@ if exact: args.append('-exact') if regexp: args.append('-regexp') if nocase: args.append('-nocase') + if elide: args.append('-elide') if count: args.append('-count'); args.append(count) if pattern[0] == '-': args.append('--') args.append(pattern) Modified: python/branches/bcannon-objcap/Lib/lib-tk/tkMessageBox.py ============================================================================== --- python/branches/bcannon-objcap/Lib/lib-tk/tkMessageBox.py (original) +++ python/branches/bcannon-objcap/Lib/lib-tk/tkMessageBox.py Tue Jan 9 23:27:11 2007 @@ -102,6 +102,15 @@ s = _show(title, message, QUESTION, YESNO, **options) return s == YES +def askyesnocancel(title=None, message=None, **options): + "Ask a question; return true if the answer is yes, None if cancelled." + s = _show(title, message, QUESTION, YESNOCANCEL, **options) + # s might be a Tcl index object, so convert it to a string + s = str(s) + if s == CANCEL: + return None + return s == YES + def askretrycancel(title=None, message=None, **options): "Ask if operation should be retried; return true if the answer is yes" s = _show(title, message, WARNING, RETRYCANCEL, **options) @@ -119,4 +128,5 @@ 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/bcannon-objcap/Lib/lib-tk/tkSimpleDialog.py ============================================================================== --- python/branches/bcannon-objcap/Lib/lib-tk/tkSimpleDialog.py (original) +++ python/branches/bcannon-objcap/Lib/lib-tk/tkSimpleDialog.py Tue Jan 9 23:27:11 2007 @@ -46,8 +46,13 @@ title -- the dialog title ''' Toplevel.__init__(self, parent) - self.transient(parent) + # If the master is not viewable, don't + # make the child transient, or else it + # would be opened withdrawn + if parent.winfo_viewable(): + self.transient(parent) + if title: self.title(title) @@ -124,9 +129,10 @@ self.withdraw() self.update_idletasks() - self.apply() - - self.cancel() + try: + self.apply() + finally: + self.cancel() def cancel(self, event=None): Modified: python/branches/bcannon-objcap/Lib/lib-tk/turtle.py ============================================================================== --- python/branches/bcannon-objcap/Lib/lib-tk/turtle.py (original) +++ python/branches/bcannon-objcap/Lib/lib-tk/turtle.py Tue Jan 9 23:27:11 2007 @@ -15,6 +15,7 @@ """ from math import * # Also for export +from time import sleep import Tkinter speeds = ['fastest', 'fast', 'normal', 'slow', 'slowest'] @@ -949,7 +950,6 @@ if __name__ == '__main__': - from time import sleep demo() sleep(3) demo2() Modified: python/branches/bcannon-objcap/Lib/logging/__init__.py ============================================================================== --- python/branches/bcannon-objcap/Lib/logging/__init__.py (original) +++ python/branches/bcannon-objcap/Lib/logging/__init__.py Tue Jan 9 23:27:11 2007 @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.4.9.9" -__date__ = "06 February 2006" +__version__ = "0.5.0.1" +__date__ = "09 January 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -214,7 +214,7 @@ information to be logged. """ def __init__(self, name, level, pathname, lineno, - msg, args, exc_info, func): + msg, args, exc_info, func=None): """ Initialize a logging record with interesting information. """ @@ -243,7 +243,7 @@ try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] - except: + except (TypeError, ValueError, AttributeError): self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info @@ -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 #--------------------------------------------------------------------------- @@ -910,9 +919,12 @@ Ensure that children of the placeholder ph are connected to the specified logger. """ - #for c in ph.loggers: + name = alogger.name + namelen = len(name) for c in ph.loggerMap.keys(): - if string.find(c.parent.name, alogger.name) <> 0: + #The if means ... if not c.parent.name.startswith(nm) + #if string.find(c.parent.name, nm) <> 0: + if c.parent.name[:namelen] != name: alogger.parent = c.parent c.parent = alogger Modified: python/branches/bcannon-objcap/Lib/logging/config.py ============================================================================== --- python/branches/bcannon-objcap/Lib/logging/config.py (original) +++ python/branches/bcannon-objcap/Lib/logging/config.py Tue Jan 9 23:27:11 2007 @@ -110,7 +110,7 @@ flist = string.split(flist, ",") formatters = {} for form in flist: - sectname = "formatter_%s" % form + sectname = "formatter_%s" % string.strip(form) opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) @@ -139,7 +139,7 @@ handlers = {} fixups = [] #for inter-handler references for hand in hlist: - sectname = "handler_%s" % hand + sectname = "handler_%s" % string.strip(hand) klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: @@ -176,6 +176,7 @@ # configure the root first llist = cp.get("loggers", "keys") llist = string.split(llist, ",") + llist = map(lambda x: string.strip(x), llist) llist.remove("root") sectname = "logger_root" root = logging.root @@ -190,7 +191,7 @@ if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: - log.addHandler(handlers[hand]) + log.addHandler(handlers[string.strip(hand)]) #and now the others... #we don't want to lose the existing loggers, @@ -225,7 +226,7 @@ if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: - logger.addHandler(handlers[hand]) + logger.addHandler(handlers[string.strip(hand)]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references Modified: python/branches/bcannon-objcap/Lib/logging/handlers.py ============================================================================== --- python/branches/bcannon-objcap/Lib/logging/handlers.py (original) +++ python/branches/bcannon-objcap/Lib/logging/handlers.py Tue Jan 9 23:27:11 2007 @@ -343,7 +343,7 @@ try: self.sock = self.makeSocket() self.retryTime = None # next time, no delay before trying - except: + except socket.error: #Creation failed, so set the retry time and return. if self.retryTime is None: self.retryPeriod = self.retryStart @@ -586,11 +586,11 @@ self.address = address self.facility = facility if type(address) == types.StringType: - self._connect_unixsocket(address) self.unixsocket = 1 + self._connect_unixsocket(address) else: - self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.unixsocket = 0 + self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.formatter = None @@ -734,7 +734,7 @@ import smtplib try: from email.Utils import formatdate - except: + except ImportError: formatdate = self.date_time port = self.mailport if not port: Modified: python/branches/bcannon-objcap/Lib/mailbox.py ============================================================================== --- python/branches/bcannon-objcap/Lib/mailbox.py (original) +++ python/branches/bcannon-objcap/Lib/mailbox.py Tue Jan 9 23:27:11 2007 @@ -2,6 +2,12 @@ """Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes.""" +# Notes for authors of new mailbox subclasses: +# +# Remember to fsync() changes to disk before closing a modified file +# or returning from a flush() method. See functions _sync_flush() and +# _sync_close(). + import sys import os import time @@ -238,7 +244,7 @@ try: self._dump_message(message, tmp_file) finally: - tmp_file.close() + _sync_close(tmp_file) if isinstance(message, MaildirMessage): subdir = message.get_subdir() suffix = self.colon + message.get_info() @@ -249,7 +255,19 @@ suffix = '' uniq = os.path.basename(tmp_file.name).split(self.colon)[0] dest = os.path.join(self._path, subdir, uniq + suffix) - os.rename(tmp_file.name, dest) + try: + if hasattr(os, 'link'): + os.link(tmp_file.name, dest) + os.remove(tmp_file.name) + else: + os.rename(tmp_file.name, dest) + except OSError, e: + os.remove(tmp_file.name) + if e.errno == errno.EEXIST: + raise ExternalClashError('Name clash with existing message: %s' + % dest) + else: + raise if isinstance(message, MaildirMessage): os.utime(dest, (os.path.getatime(dest), message.get_date())) return uniq @@ -367,12 +385,14 @@ def get_folder(self, folder): """Return a Maildir instance for the named folder.""" - return Maildir(os.path.join(self._path, '.' + folder), create=False) + return Maildir(os.path.join(self._path, '.' + folder), + factory=self._factory, + create=False) def add_folder(self, folder): """Create a folder and return a Maildir instance representing it.""" path = os.path.join(self._path, '.' + folder) - result = Maildir(path) + result = Maildir(path, factory=self._factory) maildirfolder_path = os.path.join(path, 'maildirfolder') if not os.path.exists(maildirfolder_path): os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY)) @@ -423,12 +443,17 @@ except OSError, e: if e.errno == errno.ENOENT: Maildir._count += 1 - return open(path, 'wb+') + try: + return _create_carefully(path) + except OSError, e: + if e.errno != errno.EEXIST: + raise else: raise - else: - raise ExternalClashError('Name clash prevented file creation: %s' % - path) + + # Fall through to here if stat succeeded or open raised EEXIST. + raise ExternalClashError('Name clash prevented file creation: %s' % + path) def _refresh(self): """Update table of contents mapping.""" @@ -488,6 +513,7 @@ self._next_key = 0 self._pending = False # No changes require rewriting the file. self._locked = False + self._file_length = None # Used to record mailbox size def add(self, message): """Add message and return assigned key.""" @@ -541,7 +567,21 @@ """Write any pending changes to disk.""" if not self._pending: return - self._lookup() + + # In order to be writing anything out at all, self._toc must + # already have been generated (and presumably has been modified + # by adding or deleting an item). + assert self._toc is not None + + # Check length of self._file; if it's changed, some other process + # has modified the mailbox since we scanned it. + self._file.seek(0, 2) + cur_len = self._file.tell() + if cur_len != self._file_length: + raise ExternalClashError('Size of mailbox file changed ' + '(expected %i, found %i)' % + (self._file_length, cur_len)) + new_file = _create_temporary(self._path) try: new_toc = {} @@ -563,7 +603,8 @@ new_file.close() os.remove(new_file.name) raise - new_file.close() + _sync_close(new_file) + # self._file is about to get replaced, so no need to sync. self._file.close() try: os.rename(new_file.name, self._path) @@ -578,7 +619,7 @@ self._toc = new_toc self._pending = False if self._locked: - _lock_file(new_file, dotlock=False) + _lock_file(self._file, dotlock=False) def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" @@ -597,7 +638,7 @@ self.flush() if self._locked: self.unlock() - self._file.close() + self._file.close() # Sync has been done by self.flush() above. def _lookup(self, key=None): """Return (start, stop) or raise KeyError.""" @@ -616,6 +657,7 @@ offsets = self._install_message(message) self._post_message_hook(self._file) self._file.flush() + self._file_length = self._file.tell() # Record current length of mailbox return offsets @@ -707,6 +749,7 @@ break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) + self._file_length = self._file.tell() class MMDF(_mboxMMDF): @@ -750,6 +793,8 @@ break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) + self._file.seek(0, 2) + self._file_length = self._file.tell() class MH(Mailbox): @@ -787,7 +832,7 @@ if self._locked: _unlock_file(f) finally: - f.close() + _sync_close(f) return new_key def remove(self, key): @@ -834,7 +879,7 @@ if self._locked: _unlock_file(f) finally: - f.close() + _sync_close(f) def get_message(self, key): """Return a Message representation or raise a KeyError.""" @@ -921,7 +966,7 @@ """Unlock the mailbox if it is locked.""" if self._locked: _unlock_file(self._file) - self._file.close() + _sync_close(self._file) del self._file self._locked = False @@ -944,11 +989,13 @@ def get_folder(self, folder): """Return an MH instance for the named folder.""" - return MH(os.path.join(self._path, folder), create=False) + return MH(os.path.join(self._path, folder), + factory=self._factory, create=False) def add_folder(self, folder): """Create a folder and return an MH instance representing it.""" - return MH(os.path.join(self._path, folder)) + return MH(os.path.join(self._path, folder), + factory=self._factory) def remove_folder(self, folder): """Delete the named folder, which must be empty.""" @@ -1016,7 +1063,7 @@ else: f.write('\n') finally: - f.close() + _sync_close(f) def pack(self): """Re-name messages to eliminate numbering gaps. Invalidates keys.""" @@ -1026,27 +1073,13 @@ for key in self.iterkeys(): if key - 1 != prev: changes.append((key, prev + 1)) - f = open(os.path.join(self._path, str(key)), 'r+') - try: - if self._locked: - _lock_file(f) - try: - if hasattr(os, 'link'): - os.link(os.path.join(self._path, str(key)), - os.path.join(self._path, str(prev + 1))) - if sys.platform == 'os2emx': - # cannot unlink an open file on OS/2 - f.close() - os.unlink(os.path.join(self._path, str(key))) - else: - f.close() - os.rename(os.path.join(self._path, str(key)), - os.path.join(self._path, str(prev + 1))) - finally: - if self._locked: - _unlock_file(f) - finally: - f.close() + if hasattr(os, 'link'): + os.link(os.path.join(self._path, str(key)), + os.path.join(self._path, str(prev + 1))) + os.unlink(os.path.join(self._path, str(key))) + else: + os.rename(os.path.join(self._path, str(key)), + os.path.join(self._path, str(prev + 1))) prev += 1 self._next_key = prev + 1 if len(changes) == 0: @@ -1187,7 +1220,9 @@ self._toc = dict(enumerate(zip(starts, stops))) self._labels = dict(enumerate(label_lists)) self._next_key = len(self._toc) - + self._file.seek(0, 2) + self._file_length = self._file.tell() + def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' % @@ -1870,6 +1905,16 @@ socket.gethostname(), os.getpid())) +def _sync_flush(f): + """Ensure changes to file f are physically on disk.""" + f.flush() + if hasattr(os, 'fsync'): + os.fsync(f.fileno()) + +def _sync_close(f): + """Close file f, ensuring all changes are physically on disk.""" + _sync_flush(f) + f.close() ## Start: classes from the original module (for backward compatibility). Modified: python/branches/bcannon-objcap/Lib/modulefinder.py ============================================================================== --- python/branches/bcannon-objcap/Lib/modulefinder.py (original) +++ python/branches/bcannon-objcap/Lib/modulefinder.py Tue Jan 9 23:27:11 2007 @@ -1,13 +1,14 @@ """Find modules used by a script, using introspection.""" - # This module should be kept compatible with Python 2.2, see PEP 291. +from __future__ import generators import dis import imp import marshal import os import sys import new +import struct if hasattr(sys.__stdout__, "newlines"): READ_MODE = "U" # universal line endings @@ -15,11 +16,12 @@ # remain compatible with Python < 2.3 READ_MODE = "r" -LOAD_CONST = dis.opname.index('LOAD_CONST') -IMPORT_NAME = dis.opname.index('IMPORT_NAME') -STORE_NAME = dis.opname.index('STORE_NAME') -STORE_GLOBAL = dis.opname.index('STORE_GLOBAL') +LOAD_CONST = chr(dis.opname.index('LOAD_CONST')) +IMPORT_NAME = chr(dis.opname.index('IMPORT_NAME')) +STORE_NAME = chr(dis.opname.index('STORE_NAME')) +STORE_GLOBAL = chr(dis.opname.index('STORE_GLOBAL')) STORE_OPS = [STORE_NAME, STORE_GLOBAL] +HAVE_ARGUMENT = chr(dis.HAVE_ARGUMENT) # Modulefinder does a good job at simulating Python's, but it can not # handle __path__ modifications packages make at runtime. Therefore there @@ -118,9 +120,9 @@ stuff = (ext, "r", imp.PY_SOURCE) self.load_module(name, fp, pathname, stuff) - def import_hook(self, name, caller=None, fromlist=None): - self.msg(3, "import_hook", name, caller, fromlist) - parent = self.determine_parent(caller) + def import_hook(self, name, caller=None, fromlist=None, level=-1): + self.msg(3, "import_hook", name, caller, fromlist, level) + parent = self.determine_parent(caller, level=level) q, tail = self.find_head_package(parent, name) m = self.load_tail(q, tail) if not fromlist: @@ -129,12 +131,26 @@ self.ensure_fromlist(m, fromlist) return None - def determine_parent(self, caller): - self.msgin(4, "determine_parent", caller) - if not caller: + def determine_parent(self, caller, level=-1): + self.msgin(4, "determine_parent", caller, level) + if not caller or level == 0: self.msgout(4, "determine_parent -> None") return None pname = caller.__name__ + if level >= 1: # relative import + if caller.__path__: + level -= 1 + if level == 0: + parent = self.modules[pname] + assert parent is caller + self.msgout(4, "determine_parent ->", parent) + return parent + if pname.count(".") < level: + raise ImportError, "relative importpath too deep" + pname = ".".join(pname.split(".")[:-level]) + parent = self.modules[pname] + self.msgout(4, "determine_parent ->", parent) + return parent if caller.__path__: parent = self.modules[pname] assert caller is parent @@ -294,13 +310,13 @@ self.badmodules[name] = {} self.badmodules[name][caller.__name__] = 1 - def _safe_import_hook(self, name, caller, fromlist): + def _safe_import_hook(self, name, caller, fromlist, level=-1): # wrapper for self.import_hook() that won't raise ImportError if name in self.badmodules: self._add_badmodule(name, caller) return try: - self.import_hook(name, caller) + self.import_hook(name, caller, level=level) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) self._add_badmodule(name, caller) @@ -311,38 +327,87 @@ self._add_badmodule(sub, caller) continue try: - self.import_hook(name, caller, [sub]) + self.import_hook(name, caller, [sub], level=level) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = name + "." + sub self._add_badmodule(fullname, caller) + def scan_opcodes(self, co, + unpack = struct.unpack): + # Scan the code, and yield 'interesting' opcode combinations + # Version for Python 2.4 and older + code = co.co_code + names = co.co_names + consts = co.co_consts + while code: + c = code[0] + if c in STORE_OPS: + oparg, = unpack('= HAVE_ARGUMENT: + code = code[3:] + else: + code = code[1:] + + def scan_opcodes_25(self, co, + unpack = struct.unpack): + # Scan the code, and yield 'interesting' opcode combinations + # Python 2.5 version (has absolute and relative imports) + code = co.co_code + names = co.co_names + consts = co.co_consts + LOAD_LOAD_AND_IMPORT = LOAD_CONST + LOAD_CONST + IMPORT_NAME + while code: + c = code[0] + if c in STORE_OPS: + oparg, = unpack('= HAVE_ARGUMENT: + code = code[3:] + else: + code = code[1:] + def scan_code(self, co, m): code = co.co_code - n = len(code) - i = 0 - fromlist = None - while i < n: - c = code[i] - i = i+1 - op = ord(c) - if op >= dis.HAVE_ARGUMENT: - oparg = ord(code[i]) + ord(code[i+1])*256 - i = i+2 - if op == LOAD_CONST: - # An IMPORT_NAME is always preceded by a LOAD_CONST, it's - # a tuple of "from" names, or None for a regular import. - # The tuple may contain "*" for "from import *" - fromlist = co.co_consts[oparg] - elif op == IMPORT_NAME: - assert fromlist is None or type(fromlist) is tuple - name = co.co_names[oparg] + if sys.version_info >= (2, 5): + scanner = self.scan_opcodes_25 + else: + scanner = self.scan_opcodes + for what, args in scanner(co): + if what == "store": + name, = args + m.globalnames[name] = 1 + elif what in ("import", "absolute_import"): + fromlist, name = args have_star = 0 if fromlist is not None: if "*" in fromlist: have_star = 1 fromlist = [f for f in fromlist if f != "*"] - self._safe_import_hook(name, m, fromlist) + if what == "absolute_import": level = 0 + else: level = -1 + self._safe_import_hook(name, m, fromlist, level=level) if have_star: # We've encountered an "import *". If it is a Python module, # the code has already been parsed and we can suck out the @@ -362,10 +427,17 @@ m.starimports[name] = 1 else: m.starimports[name] = 1 - elif op in STORE_OPS: - # keep track of all global names that are assigned to - name = co.co_names[oparg] - m.globalnames[name] = 1 + elif what == "relative_import": + level, fromlist, name = args + if name: + self._safe_import_hook(name, m, fromlist, level=level) + else: + parent = self.determine_parent(m, level=level) + self._safe_import_hook(parent.__name__, None, fromlist, level=0) + else: + # We don't expect anything else from the generator. + raise RuntimeError(what) + for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m) Modified: python/branches/bcannon-objcap/Lib/os.py ============================================================================== --- python/branches/bcannon-objcap/Lib/os.py (original) +++ python/branches/bcannon-objcap/Lib/os.py Tue Jan 9 23:27:11 2007 @@ -156,11 +156,17 @@ recursive. """ + from errno import EEXIST head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): - makedirs(head, mode) + try: + makedirs(head, mode) + except OSError, e: + # be happy if someone already created the path + if e.errno != EEXIST: + raise if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists return mkdir(name, mode) Modified: python/branches/bcannon-objcap/Lib/posixpath.py ============================================================================== --- python/branches/bcannon-objcap/Lib/posixpath.py (original) +++ python/branches/bcannon-objcap/Lib/posixpath.py Tue Jan 9 23:27:11 2007 @@ -106,18 +106,23 @@ return '', p -# Return the tail (basename) part of a path. +# Return the tail (basename) part of a path, same as split(path)[1]. def basename(p): """Returns the final component of a pathname""" - return split(p)[1] + i = p.rfind('/') + 1 + return p[i:] -# Return the head (dirname) part of a path. +# Return the head (dirname) part of a path, same as split(path)[0]. def dirname(p): """Returns the directory component of a pathname""" - return split(p)[0] + i = p.rfind('/') + 1 + head = p[:i] + if head and head != '/'*len(head): + head = head.rstrip('/') + return head # Is a path a symbolic link? @@ -259,8 +264,7 @@ except KeyError: return path userhome = pwent.pw_dir - if userhome.endswith('/'): - i += 1 + userhome = userhome.rstrip('/') return userhome + path[i:] Modified: python/branches/bcannon-objcap/Lib/pstats.py ============================================================================== --- python/branches/bcannon-objcap/Lib/pstats.py (original) +++ python/branches/bcannon-objcap/Lib/pstats.py Tue Jan 9 23:27:11 2007 @@ -116,7 +116,7 @@ def load_stats(self, arg): if not arg: self.stats = {} - elif type(arg) == type(""): + elif isinstance(arg, basestring): f = open(arg, 'rb') self.stats = marshal.load(f) f.close() Modified: python/branches/bcannon-objcap/Lib/pty.py ============================================================================== --- python/branches/bcannon-objcap/Lib/pty.py (original) +++ python/branches/bcannon-objcap/Lib/pty.py Tue Jan 9 23:27:11 2007 @@ -118,6 +118,12 @@ if (slave_fd > STDERR_FILENO): os.close (slave_fd) + # Explicitly open the tty to make it become a controlling tty. + tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) + os.close(tmp_fd) + else: + os.close(slave_fd) + # Parent and child process. return pid, master_fd Modified: python/branches/bcannon-objcap/Lib/pyclbr.py ============================================================================== --- python/branches/bcannon-objcap/Lib/pyclbr.py (original) +++ python/branches/bcannon-objcap/Lib/pyclbr.py Tue Jan 9 23:27:11 2007 @@ -172,7 +172,7 @@ # else it's a nested def else: # it's a function - dict[meth_name] = Function(module, meth_name, file, lineno) + dict[meth_name] = Function(fullmodule, meth_name, file, lineno) stack.append((None, thisindent)) # Marker for nested fns elif token == 'class': lineno, thisindent = start Modified: python/branches/bcannon-objcap/Lib/pydoc.py ============================================================================== --- python/branches/bcannon-objcap/Lib/pydoc.py (original) +++ python/branches/bcannon-objcap/Lib/pydoc.py Tue Jan 9 23:27:11 2007 @@ -1737,6 +1737,9 @@ Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. + +On the Microsoft Windows operating system, the files can be built by +running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory. ''') return target = self.topics.get(topic, self.keywords.get(topic)) Modified: python/branches/bcannon-objcap/Lib/random.py ============================================================================== --- python/branches/bcannon-objcap/Lib/random.py (original) +++ python/branches/bcannon-objcap/Lib/random.py Tue Jan 9 23:27:11 2007 @@ -205,7 +205,7 @@ raise ValueError, "empty range for randrange()" if n >= maxwidth: - return istart + self._randbelow(n) + return istart + istep*self._randbelow(n) return istart + istep*int(self.random() * n) def randint(self, a, b): Modified: python/branches/bcannon-objcap/Lib/smtplib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/smtplib.py (original) +++ python/branches/bcannon-objcap/Lib/smtplib.py Tue Jan 9 23:27:11 2007 @@ -52,9 +52,10 @@ __all__ = ["SMTPException","SMTPServerDisconnected","SMTPResponseException", "SMTPSenderRefused","SMTPRecipientsRefused","SMTPDataError", "SMTPConnectError","SMTPHeloError","SMTPAuthenticationError", - "quoteaddr","quotedata","SMTP"] + "quoteaddr","quotedata","SMTP","SMTP_SSL"] SMTP_PORT = 25 +SMTP_SSL_PORT = 465 CRLF="\r\n" OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I) @@ -240,6 +241,7 @@ """ self.esmtp_features = {} + self.default_port = SMTP_PORT if host: (code, msg) = self.connect(host, port) if code != 220: @@ -271,6 +273,13 @@ """ self.debuglevel = debuglevel + def _get_socket(self,af, socktype, proto,sa): + # 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) + self.sock.connect(sa) + def connect(self, host='localhost', port = 0): """Connect to a host on a given port. @@ -289,16 +298,14 @@ try: port = int(port) except ValueError: raise socket.error, "nonnumeric port" - if not port: port = SMTP_PORT + if not port: port = self.default_port if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: - self.sock = socket.socket(af, socktype, proto) - if self.debuglevel > 0: print>>stderr, 'connect:', sa - self.sock.connect(sa) + self._get_socket(af,socktype,proto,sa) except socket.error, msg: if self.debuglevel > 0: print>>stderr, 'connect fail:', msg if self.sock: @@ -716,6 +723,28 @@ self.docmd("quit") self.close() +class SMTP_SSL(SMTP): + """ This is a subclass derived from SMTP that connects over an SSL encrypted + socket (to use this class you need a socket module that was compiled with SSL + support). If host is not specified, '' (the local host) is used. If port is + omitted, the standard SMTP-over-SSL port (465) is used. keyfile and certfile + are also optional - they can contain a PEM formatted private key and + certificate chain file for the SSL connection. + """ + def __init__(self, host = '', port = 0, local_hostname = None, + keyfile = None, certfile = None): + self.keyfile = keyfile + self.certfile = certfile + SMTP.__init__(self,host,port,local_hostname) + self.default_port = SMTP_SSL_PORT + + def _get_socket(self,af, socktype, proto,sa): + self.sock = socket.socket(af, socktype, proto) + if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) + self.sock.connect(sa) + sslobj = socket.ssl(self.sock, self.keyfile, self.certfile) + self.sock = SSLFakeSocket(self.sock, sslobj) + self.file = SSLFakeFile(sslobj) # Test the sendmail method, which tests most of the others. # Note: This always sends to localhost. Modified: python/branches/bcannon-objcap/Lib/sre_parse.py ============================================================================== --- python/branches/bcannon-objcap/Lib/sre_parse.py (original) +++ python/branches/bcannon-objcap/Lib/sre_parse.py Tue Jan 9 23:27:11 2007 @@ -134,6 +134,8 @@ def __delitem__(self, index): del self.data[index] def __getitem__(self, index): + if isinstance(index, slice): + return SubPattern(self.pattern, self.data[index]) return self.data[index] def __setitem__(self, index, code): self.data[index] = code Modified: python/branches/bcannon-objcap/Lib/subprocess.py ============================================================================== --- python/branches/bcannon-objcap/Lib/subprocess.py (original) +++ python/branches/bcannon-objcap/Lib/subprocess.py Tue Jan 9 23:27:11 2007 @@ -166,7 +166,7 @@ communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to - terminate. The optional stdin argument should be a string to be + terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. @@ -965,6 +965,8 @@ if isinstance(args, types.StringTypes): args = [args] + else: + args = list(args) if shell: args = ["/bin/sh", "-c"] + args @@ -1002,8 +1004,12 @@ # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)): - if fd: os.close(fd) + if p2cread and p2cread not in (0,): + os.close(p2cread) + if c2pwrite and c2pwrite not in (p2cread, 1): + os.close(c2pwrite) + if errwrite and errwrite not in (p2cread, c2pwrite, 2): + os.close(errwrite) # Close all other fds, if asked for if close_fds: @@ -1105,6 +1111,7 @@ read_set.append(self.stderr) stderr = [] + input_offset = 0 while read_set or write_set: rlist, wlist, xlist = select.select(read_set, write_set, []) @@ -1112,9 +1119,9 @@ # When select has indicated that the file is writable, # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 - bytes_written = os.write(self.stdin.fileno(), input[:512]) - input = input[bytes_written:] - if not input: + bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) + input_offset += bytes_written + if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) Modified: python/branches/bcannon-objcap/Lib/tarfile.py ============================================================================== --- python/branches/bcannon-objcap/Lib/tarfile.py (original) +++ python/branches/bcannon-objcap/Lib/tarfile.py Tue Jan 9 23:27:11 2007 @@ -49,6 +49,7 @@ import errno import time import struct +import copy if sys.platform == 'mac': # This module needs work for MacOS9, especially in the area of pathname @@ -138,7 +139,7 @@ def stn(s, length): """Convert a python string to a null-terminated string buffer. """ - return s[:length-1] + (length - len(s) - 1) * NUL + NUL + return s[:length] + (length - len(s)) * NUL def nti(s): """Convert a number field to a python number. @@ -146,7 +147,10 @@ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0200): - n = int(s.rstrip(NUL) or "0", 8) + try: + n = int(s.rstrip(NUL + " ") or "0", 8) + except ValueError: + raise HeaderError("invalid header") else: n = 0L for i in xrange(len(s) - 1): @@ -281,6 +285,9 @@ class StreamError(TarError): """Exception for unsupported operations on stream-like TarFiles.""" pass +class HeaderError(TarError): + """Exception for invalid headers.""" + pass #--------------------------- # internal stream interface @@ -623,140 +630,194 @@ #------------------------ # Extraction file object #------------------------ -class ExFileObject(object): - """File-like object for reading an archive member. - Is returned by TarFile.extractfile(). Support for - sparse files included. +class _FileInFile(object): + """A thin wrapper around an existing file object that + provides a part of its data as an individual file + object. """ - def __init__(self, tarfile, tarinfo): - self.fileobj = tarfile.fileobj - self.name = tarinfo.name - self.mode = "r" - self.closed = False - self.offset = tarinfo.offset_data - self.size = tarinfo.size - self.pos = 0L - self.linebuffer = "" - if tarinfo.issparse(): - self.sparse = tarinfo.sparse - self.read = self._readsparse - else: - self.read = self._readnormal + def __init__(self, fileobj, offset, size, sparse=None): + self.fileobj = fileobj + self.offset = offset + self.size = size + self.sparse = sparse + self.position = 0 - def __read(self, size): - """Overloadable read method. + def tell(self): + """Return the current file position. """ - return self.fileobj.read(size) - - def readline(self, size=-1): - """Read a line with approx. size. If size is negative, - read a whole line. readline() and read() must not - be mixed up (!). - """ - if size < 0: - size = sys.maxint - - nl = self.linebuffer.find("\n") - if nl >= 0: - nl = min(nl, size) - else: - size -= len(self.linebuffer) - while (nl < 0 and size > 0): - buf = self.read(min(size, 100)) - if not buf: - break - self.linebuffer += buf - size -= len(buf) - nl = self.linebuffer.find("\n") - if nl == -1: - s = self.linebuffer - self.linebuffer = "" - return s - buf = self.linebuffer[:nl] - self.linebuffer = self.linebuffer[nl + 1:] - while buf[-1:] == "\r": - buf = buf[:-1] - return buf + "\n" + return self.position - def readlines(self): - """Return a list with all (following) lines. + def seek(self, position): + """Seek to a position in the file. """ - result = [] - while True: - line = self.readline() - if not line: break - result.append(line) - return result + self.position = position - def _readnormal(self, size=None): - """Read operation for regular files. + def read(self, size=None): + """Read data from the file. """ - if self.closed: - raise ValueError("file is closed") - self.fileobj.seek(self.offset + self.pos) - bytesleft = self.size - self.pos if size is None: - bytestoread = bytesleft + size = self.size - self.position else: - bytestoread = min(size, bytesleft) - self.pos += bytestoread - return self.__read(bytestoread) + size = min(size, self.size - self.position) - def _readsparse(self, size=None): - """Read operation for sparse files. - """ - if self.closed: - raise ValueError("file is closed") + if self.sparse is None: + return self.readnormal(size) + else: + return self.readsparse(size) - if size is None: - size = self.size - self.pos + def readnormal(self, size): + """Read operation for regular files. + """ + self.fileobj.seek(self.offset + self.position) + self.position += size + return self.fileobj.read(size) + def readsparse(self, size): + """Read operation for sparse files. + """ data = [] while size > 0: - buf = self._readsparsesection(size) + buf = self.readsparsesection(size) if not buf: break size -= len(buf) data.append(buf) return "".join(data) - def _readsparsesection(self, size): + def readsparsesection(self, size): """Read a single section of a sparse file. """ - section = self.sparse.find(self.pos) + section = self.sparse.find(self.position) if section is None: return "" - toread = min(size, section.offset + section.size - self.pos) + size = min(size, section.offset + section.size - self.position) + if isinstance(section, _data): - realpos = section.realpos + self.pos - section.offset - self.pos += toread + realpos = section.realpos + self.position - section.offset self.fileobj.seek(self.offset + realpos) - return self.__read(toread) + self.position += size + return self.fileobj.read(size) else: - self.pos += toread - return NUL * toread + self.position += size + return NUL * size +#class _FileInFile + + +class ExFileObject(object): + """File-like object for reading an archive member. + Is returned by TarFile.extractfile(). + """ + blocksize = 1024 + + def __init__(self, tarfile, tarinfo): + self.fileobj = _FileInFile(tarfile.fileobj, + tarinfo.offset_data, + tarinfo.size, + getattr(tarinfo, "sparse", None)) + self.name = tarinfo.name + self.mode = "r" + self.closed = False + self.size = tarinfo.size + + self.position = 0 + self.buffer = "" + + def read(self, size=None): + """Read at most size bytes from the file. If size is not + present or None, read all data until EOF is reached. + """ + if self.closed: + raise ValueError("I/O operation on closed file") + + buf = "" + if self.buffer: + if size is None: + buf = self.buffer + self.buffer = "" + else: + buf = self.buffer[:size] + self.buffer = self.buffer[size:] + + if size is None: + buf += self.fileobj.read() + else: + buf += self.fileobj.read(size - len(buf)) + + self.position += len(buf) + return buf + + def readline(self, size=-1): + """Read one entire line from the file. If size is present + and non-negative, return a string with at most that + size, which may be an incomplete line. + """ + if self.closed: + raise ValueError("I/O operation on closed file") + + if "\n" in self.buffer: + pos = self.buffer.find("\n") + 1 + else: + buffers = [self.buffer] + while True: + buf = self.fileobj.read(self.blocksize) + buffers.append(buf) + if not buf or "\n" in buf: + self.buffer = "".join(buffers) + pos = self.buffer.find("\n") + 1 + if pos == 0: + # no newline found. + pos = len(self.buffer) + break + + if size != -1: + pos = min(size, pos) + + buf = self.buffer[:pos] + self.buffer = self.buffer[pos:] + self.position += len(buf) + return buf + + def readlines(self): + """Return a list with all remaining lines. + """ + result = [] + while True: + line = self.readline() + if not line: break + result.append(line) + return result def tell(self): """Return the current file position. """ - return self.pos + if self.closed: + raise ValueError("I/O operation on closed file") - def seek(self, pos, whence=0): + return self.position + + def seek(self, pos, whence=os.SEEK_SET): """Seek to a position in the file. """ - self.linebuffer = "" - if whence == 0: - self.pos = min(max(pos, 0), self.size) - if whence == 1: + if self.closed: + raise ValueError("I/O operation on closed file") + + if whence == os.SEEK_SET: + self.position = min(max(pos, 0), self.size) + elif whence == os.SEEK_CUR: if pos < 0: - self.pos = max(self.pos + pos, 0) + self.position = max(self.position + pos, 0) else: - self.pos = min(self.pos + pos, self.size) - if whence == 2: - self.pos = max(min(self.size + pos, self.size), 0) + self.position = min(self.position + pos, self.size) + elif whence == os.SEEK_END: + self.position = max(min(self.size + pos, self.size), 0) + else: + raise ValueError("Invalid argument") + + self.buffer = "" + self.fileobj.seek(self.position) def close(self): """Close the file object. @@ -764,20 +825,13 @@ self.closed = True def __iter__(self): - """Get an iterator over the file object. - """ - if self.closed: - raise ValueError("I/O operation on closed file") - return self - - def next(self): - """Get the next item from the file iterator. + """Get an iterator over the file's lines. """ - result = self.readline() - if not result: - raise StopIteration - return result - + while True: + line = self.readline() + if not line: + break + yield line #class ExFileObject #------------------ @@ -795,7 +849,6 @@ """Construct a TarInfo object. name is the optional name of the member. """ - self.name = name # member name (dirnames must end with '/') self.mode = 0666 # file permissions self.uid = 0 # user id @@ -809,8 +862,6 @@ self.gname = "group" # group name self.devmajor = 0 # device major number self.devminor = 0 # device minor number - self.prefix = "" # prefix to filename or information - # about sparse files self.offset = 0 # the tar header starts here self.offset_data = 0 # the file's data starts here @@ -823,9 +874,13 @@ """Construct a TarInfo object from a 512 byte string buffer. """ if len(buf) != BLOCKSIZE: - raise ValueError("truncated header") + raise HeaderError("truncated header") if buf.count(NUL) == BLOCKSIZE: - raise ValueError("empty header") + raise HeaderError("empty header") + + chksum = nti(buf[148:156]) + if chksum not in calc_chksums(buf): + raise HeaderError("bad checksum") tarinfo = cls() tarinfo.buf = buf @@ -835,31 +890,79 @@ tarinfo.gid = nti(buf[116:124]) tarinfo.size = nti(buf[124:136]) tarinfo.mtime = nti(buf[136:148]) - tarinfo.chksum = nti(buf[148:156]) + tarinfo.chksum = chksum tarinfo.type = buf[156:157] tarinfo.linkname = buf[157:257].rstrip(NUL) tarinfo.uname = buf[265:297].rstrip(NUL) tarinfo.gname = buf[297:329].rstrip(NUL) tarinfo.devmajor = nti(buf[329:337]) tarinfo.devminor = nti(buf[337:345]) - tarinfo.prefix = buf[345:500] + prefix = buf[345:500].rstrip(NUL) + + if prefix and not tarinfo.issparse(): + tarinfo.name = prefix + "/" + tarinfo.name - if tarinfo.chksum not in calc_chksums(buf): - raise ValueError("invalid header") return tarinfo def tobuf(self, posix=False): - """Return a tar header block as a 512 byte string. + """Return a tar header as a string of 512 byte blocks. """ + buf = "" + type = self.type + prefix = "" + + if self.name.endswith("/"): + type = DIRTYPE + + if type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): + # Prevent "././@LongLink" from being normalized. + name = self.name + else: + name = normpath(self.name) + + if type == DIRTYPE: + # directories should end with '/' + name += "/" + + linkname = self.linkname + if linkname: + # if linkname is empty we end up with a '.' + linkname = normpath(linkname) + + if posix: + if self.size > MAXSIZE_MEMBER: + raise ValueError("file is too large (>= 8 GB)") + + if len(self.linkname) > LENGTH_LINK: + raise ValueError("linkname is too long (>%d)" % (LENGTH_LINK)) + + if len(name) > LENGTH_NAME: + prefix = name[:LENGTH_PREFIX + 1] + while prefix and prefix[-1] != "/": + prefix = prefix[:-1] + + name = name[len(prefix):] + prefix = prefix[:-1] + + if not prefix or len(name) > LENGTH_NAME: + raise ValueError("name is too long") + + else: + if len(self.linkname) > LENGTH_LINK: + buf += self._create_gnulong(self.linkname, GNUTYPE_LONGLINK) + + if len(name) > LENGTH_NAME: + buf += self._create_gnulong(name, GNUTYPE_LONGNAME) + parts = [ - stn(self.name, 100), + stn(name, 100), itn(self.mode & 07777, 8, posix), itn(self.uid, 8, posix), itn(self.gid, 8, posix), itn(self.size, 12, posix), itn(self.mtime, 12, posix), " ", # checksum field - self.type, + type, stn(self.linkname, 100), stn(MAGIC, 6), stn(VERSION, 2), @@ -867,15 +970,38 @@ stn(self.gname, 32), itn(self.devmajor, 8, posix), itn(self.devminor, 8, posix), - stn(self.prefix, 155) + stn(prefix, 155) ] - buf = struct.pack("%ds" % BLOCKSIZE, "".join(parts)) - chksum = calc_chksums(buf)[0] - buf = buf[:148] + "%06o\0" % chksum + buf[155:] + buf += struct.pack("%ds" % BLOCKSIZE, "".join(parts)) + chksum = calc_chksums(buf[-BLOCKSIZE:])[0] + buf = buf[:-364] + "%06o\0" % chksum + buf[-357:] self.buf = buf return buf + def _create_gnulong(self, name, type): + """Create a GNU longname/longlink header from name. + It consists of an extended tar header, with the length + of the longname as size, followed by data blocks, + which contain the longname as a null terminated string. + """ + name += NUL + + tarinfo = self.__class__() + tarinfo.name = "././@LongLink" + tarinfo.type = type + tarinfo.mode = 0 + tarinfo.size = len(name) + + # create extended header + buf = tarinfo.tobuf() + # create name blocks + buf += name + blocks, remainder = divmod(len(name), BLOCKSIZE) + if remainder > 0: + buf += (BLOCKSIZE - remainder) * NUL + return buf + def isreg(self): return self.type in REGULAR_TYPES def isfile(self): @@ -928,7 +1054,7 @@ can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ - self.name = name + self.name = os.path.abspath(name) if len(mode) > 1 or mode not in "raw": raise ValueError("mode must be 'r', 'a' or 'w'") @@ -940,7 +1066,7 @@ self._extfileobj = False else: if self.name is None and hasattr(fileobj, "name"): - self.name = fileobj.name + self.name = os.path.abspath(fileobj.name) if hasattr(fileobj, "mode"): self.mode = fileobj.mode self._extfileobj = True @@ -1017,9 +1143,13 @@ # Find out which *open() is appropriate for opening the file. for comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) + if fileobj is not None: + saved_pos = fileobj.tell() try: return func(name, "r", fileobj) except (ReadError, CompressionError): + if fileobj is not None: + fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") @@ -1076,24 +1206,12 @@ except (ImportError, AttributeError): raise CompressionError("gzip module is not available") - pre, ext = os.path.splitext(name) - pre = os.path.basename(pre) - if ext == ".tgz": - ext = ".tar" - if ext == ".gz": - ext = "" - tarname = pre + ext - if fileobj is None: fileobj = _open(name, mode + "b") - if mode != "r": - name = tarname - try: - t = cls.taropen(tarname, mode, - gzip.GzipFile(name, mode, compresslevel, fileobj) - ) + t = cls.taropen(name, mode, + gzip.GzipFile(name, mode, compresslevel, fileobj)) except IOError: raise ReadError("not a gzip file") t._extfileobj = False @@ -1112,21 +1230,13 @@ except ImportError: raise CompressionError("bz2 module is not available") - pre, ext = os.path.splitext(name) - pre = os.path.basename(pre) - if ext == ".tbz2": - ext = ".tar" - if ext == ".bz2": - ext = "" - tarname = pre + ext - if fileobj is not None: fileobj = _BZ2Proxy(fileobj, mode) else: fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel) try: - t = cls.taropen(tarname, mode, fileobj) + t = cls.taropen(name, mode, fileobj) except IOError: raise ReadError("not a bzip2 file") t._extfileobj = False @@ -1331,8 +1441,7 @@ arcname = name # Skip if somebody tries to archive the archive... - if self.name is not None \ - and os.path.abspath(name) == os.path.abspath(self.name): + if self.name is not None and os.path.abspath(name) == self.name: self._dbg(2, "tarfile: Skipped %r" % name) return @@ -1379,50 +1488,11 @@ """ self._check("aw") - tarinfo.name = normpath(tarinfo.name) - if tarinfo.isdir(): - # directories should end with '/' - tarinfo.name += "/" - - if tarinfo.linkname: - tarinfo.linkname = normpath(tarinfo.linkname) - - if tarinfo.size > MAXSIZE_MEMBER: - if self.posix: - raise ValueError("file is too large (>= 8 GB)") - else: - self._dbg(2, "tarfile: Created GNU tar largefile header") - - - if len(tarinfo.linkname) > LENGTH_LINK: - if self.posix: - raise ValueError("linkname is too long (>%d)" % (LENGTH_LINK)) - else: - self._create_gnulong(tarinfo.linkname, GNUTYPE_LONGLINK) - tarinfo.linkname = tarinfo.linkname[:LENGTH_LINK -1] - self._dbg(2, "tarfile: Created GNU tar extension LONGLINK") - - if len(tarinfo.name) > LENGTH_NAME: - if self.posix: - prefix = tarinfo.name[:LENGTH_PREFIX + 1] - while prefix and prefix[-1] != "/": - prefix = prefix[:-1] - - name = tarinfo.name[len(prefix):] - prefix = prefix[:-1] - - if not prefix or len(name) > LENGTH_NAME: - raise ValueError("name is too long (>%d)" % (LENGTH_NAME)) - - tarinfo.name = name - tarinfo.prefix = prefix - else: - self._create_gnulong(tarinfo.name, GNUTYPE_LONGNAME) - tarinfo.name = tarinfo.name[:LENGTH_NAME - 1] - self._dbg(2, "tarfile: Created GNU tar extension LONGNAME") + tarinfo = copy.copy(tarinfo) - self.fileobj.write(tarinfo.tobuf(self.posix)) - self.offset += BLOCKSIZE + buf = tarinfo.tobuf(self.posix) + self.fileobj.write(buf) + self.offset += len(buf) # If there's data to follow, append it. if fileobj is not None: @@ -1763,16 +1833,14 @@ tarinfo = self.proc_member(tarinfo) - except ValueError, e: + except HeaderError, e: if self.ignore_zeros: - self._dbg(2, "0x%X: empty or invalid block: %s" % - (self.offset, e)) + self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue else: if self.offset == 0: - raise ReadError("empty, unreadable or compressed " - "file: %s" % e) + raise ReadError(str(e)) return None break @@ -1781,12 +1849,6 @@ if tarinfo.isreg() and tarinfo.name.endswith("/"): tarinfo.type = DIRTYPE - # The prefix field is used for filenames > 100 in - # the POSIX standard. - # name = prefix + '/' + name - tarinfo.name = normpath(os.path.join(tarinfo.prefix.rstrip(NUL), - tarinfo.name)) - # Directory names should have a '/' at the end. if tarinfo.isdir(): tarinfo.name += "/" @@ -1911,10 +1973,6 @@ self.offset += self._block(tarinfo.size) tarinfo.size = origsize - # Clear the prefix field so that it is not used - # as a pathname in next(). - tarinfo.prefix = "" - return tarinfo #-------------------------------------------------------------------------- @@ -1972,31 +2030,6 @@ else: return TarIter(self) - def _create_gnulong(self, name, type): - """Write a GNU longname/longlink member to the TarFile. - It consists of an extended tar header, with the length - of the longname as size, followed by data blocks, - which contain the longname as a null terminated string. - """ - name += NUL - - tarinfo = TarInfo() - tarinfo.name = "././@LongLink" - tarinfo.type = type - tarinfo.mode = 0 - tarinfo.size = len(name) - - # write extended header - self.fileobj.write(tarinfo.tobuf()) - self.offset += BLOCKSIZE - # write name blocks - self.fileobj.write(name) - blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) - if remainder > 0: - self.fileobj.write(NUL * (BLOCKSIZE - remainder)) - blocks += 1 - self.offset += blocks * BLOCKSIZE - def _dbg(self, level, msg): """Write debugging output to sys.stderr. """ Modified: python/branches/bcannon-objcap/Lib/test/README ============================================================================== --- python/branches/bcannon-objcap/Lib/test/README (original) +++ python/branches/bcannon-objcap/Lib/test/README Tue Jan 9 23:27:11 2007 @@ -379,8 +379,8 @@ point numbers when you expect them to only be approximately equal withing a fuzz factor (``test_support.FUZZ``, which defaults to 1e-6). - * ``check_syntax(statement)`` - make sure that the statement is *not* - correct Python syntax. + * ``check_syntax_error(testcase, statement)`` - make sure that the + statement is *not* correct Python syntax. Python and C statement coverage results are currently available at Modified: python/branches/bcannon-objcap/Lib/test/list_tests.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/list_tests.py (original) +++ python/branches/bcannon-objcap/Lib/test/list_tests.py Tue Jan 9 23:27:11 2007 @@ -269,7 +269,6 @@ self.assertRaises(TypeError, a.insert) def test_pop(self): - from decimal import Decimal a = self.type2test([-1, 0, 1]) a.pop() self.assertEqual(a, [-1, 0]) @@ -281,8 +280,6 @@ self.assertRaises(IndexError, a.pop) self.assertRaises(TypeError, a.pop, 42, 42) a = self.type2test([0, 10, 20, 30, 40]) - self.assertEqual(a.pop(Decimal(2)), 20) - self.assertRaises(IndexError, a.pop, Decimal(25)) def test_remove(self): a = self.type2test([0, 0, 1]) Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_MimeWriter ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_MimeWriter Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,110 +0,0 @@ -test_MimeWriter -From: bwarsaw at cnri.reston.va.us -Date: Mon Feb 12 17:21:48 EST 1996 -To: kss-submit at cnri.reston.va.us -MIME-Version: 1.0 -Content-Type: multipart/knowbot; - boundary="801spam999"; - version="0.1" - -This is a multi-part message in MIME format. - ---801spam999 -Content-Type: multipart/knowbot-metadata; - boundary="802spam999" - - ---802spam999 -Content-Type: message/rfc822 -KP-Metadata-Type: simple -KP-Access: read-only - -KPMD-Interpreter: python -KPMD-Interpreter-Version: 1.3 -KPMD-Owner-Name: Barry Warsaw -KPMD-Owner-Rendezvous: bwarsaw at cnri.reston.va.us -KPMD-Home-KSS: kss.cnri.reston.va.us -KPMD-Identifier: hdl://cnri.kss/my_first_knowbot -KPMD-Launch-Date: Mon Feb 12 16:39:03 EST 1996 - ---802spam999 -Content-Type: text/isl -KP-Metadata-Type: complex -KP-Metadata-Key: connection -KP-Access: read-only -KP-Connection-Description: Barry's Big Bass Business -KP-Connection-Id: B4 -KP-Connection-Direction: client - -INTERFACE Seller-1; - -TYPE Seller = OBJECT - DOCUMENTATION "A simple Seller interface to test ILU" - METHODS - price():INTEGER, - END; - ---802spam999 -Content-Type: message/external-body; - access-type="URL"; - URL="hdl://cnri.kss/generic-knowbot" - -Content-Type: text/isl -KP-Metadata-Type: complex -KP-Metadata-Key: generic-interface -KP-Access: read-only -KP-Connection-Description: Generic Interface for All Knowbots -KP-Connection-Id: generic-kp -KP-Connection-Direction: client - - ---802spam999-- - ---801spam999 -Content-Type: multipart/knowbot-code; - boundary="803spam999" - - ---803spam999 -Content-Type: text/plain -KP-Module-Name: BuyerKP - -class Buyer: - def __setup__(self, maxprice): - self._maxprice = maxprice - - def __main__(self, kos): - """Entry point upon arrival at a new KOS.""" - broker = kos.broker() - # B4 == Barry's Big Bass Business :-) - seller = broker.lookup('Seller_1.Seller', 'B4') - if seller: - price = seller.price() - print 'Seller wants $', price, '... ' - if price > self._maxprice: - print 'too much!' - else: - print "I'll take it!" - else: - print 'no seller found here' - ---803spam999-- - ---801spam999 -Content-Type: multipart/knowbot-state; - boundary="804spam999" -KP-Main-Module: main - - ---804spam999 -Content-Type: text/plain -KP-Module-Name: main - -# instantiate a buyer instance and put it in a magic place for the KOS -# to find. -__kp__ = Buyer() -__kp__.__setup__(500) - ---804spam999-- - ---801spam999-- Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_cgi ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_cgi Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,42 +0,0 @@ -test_cgi -'' => [] -'&' => [] -'&&' => [] -'=' => [('', '')] -'=a' => [('', 'a')] -'a' => [('a', '')] -'a=' => [('a', '')] -'a=' => [('a', '')] -'&a=b' => [('a', 'b')] -'a=a+b&b=b+c' => [('a', 'a b'), ('b', 'b c')] -'a=1&a=2' => [('a', '1'), ('a', '2')] -'' -'&' -'&&' -';' -';&;' -'=' -'=&=' -'=;=' -'=a' -'&=a' -'=a&' -'=&a' -'b=a' -'b+=a' -'a=b=a' -'a=+b=a' -'&b=a' -'b&=a' -'a=a+b&b=b+c' -'a=a+b&a=b+a' -'x=1&y=2.0&z=2-3.%2b0' -'x=1;y=2.0&z=2-3.%2b0' -'x=1;y=2.0;z=2-3.%2b0' -'Hbc5161168c542333633315dee1182227:key_store_seqid=400006&cuyer=r&view=bustomer&order_id=0bb2e248638833d48cb7fed300000f1b&expire=964546263&lobale=en-US&kid=130003.300038&ss=env' -'group_id=5470&set=custom&_assigned_to=31392&_status=1&_category=100&SUBMIT=Browse' -Testing log -Testing initlog 1 -Testing log 2 -Test FieldStorage methods that use readline -Test basic FieldStorage multipart parsing Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_cookie ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_cookie Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,32 +0,0 @@ -test_cookie - -Set-Cookie: chips=ahoy -Set-Cookie: vienna=finger - chips 'ahoy' 'ahoy' -Set-Cookie: chips=ahoy - vienna 'finger' 'finger' -Set-Cookie: vienna=finger - -Set-Cookie: keebler="E=mc2; L=\"Loves\"; fudge=\012;" - keebler 'E=mc2; L="Loves"; fudge=\n;' 'E=mc2; L="Loves"; fudge=\n;' -Set-Cookie: keebler="E=mc2; L=\"Loves\"; fudge=\012;" - -Set-Cookie: keebler=E=mc2 - keebler 'E=mc2' 'E=mc2' -Set-Cookie: keebler=E=mc2 -Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme - - - - - - -If anything blows up after this line, it's from Cookie's doctest. Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_global ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_global Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,5 +0,0 @@ -test_global -got SyntaxError as expected -got SyntaxError as expected -got SyntaxError as expected -as expected, no SyntaxError Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_grammar ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_grammar Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,69 +0,0 @@ -test_grammar -1. Parser -1.1 Tokens -1.1.1 Backslashes -1.1.2 Numeric literals -1.1.2.1 Plain integers -1.1.2.2 Long integers -1.1.2.3 Floating point -1.1.3 String literals -1.2 Grammar -single_input -file_input -expr_input -eval_input -funcdef -lambdef -simple_stmt -expr_stmt -print_stmt -1 2 3 -1 2 3 -1 1 1 -extended print_stmt -1 2 3 -1 2 3 -1 1 1 -hello world -del_stmt -pass_stmt -flow_stmt -break_stmt -continue_stmt -continue + try/except ok -continue + try/finally ok -testing continue and break in try/except in loop -return_stmt -yield_stmt -raise_stmt -import_name -import_from -global_stmt -exec_stmt -assert_stmt -if_stmt -while_stmt -for_stmt -try_stmt -suite -test -comparison -binary mask ops -shift ops -additive ops -multiplicative ops -unary ops -selectors - -[1, (1,), (1, 2), (1, 2, 3)] -atoms -classdef -['Apple', 'Banana', 'Coco nut'] -[3, 6, 9, 12, 15] -[3, 4, 5] -[(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')] -[(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), (5, 'Banana'), (5, 'Coconut')] -[[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]] -[False, False, False] -[[1, 2], [3, 4], [5, 6]] -[('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), ('Macdonalds', 'Cheeseburger')] Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_httplib ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_httplib Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,13 +0,0 @@ -test_httplib -reply: 'HTTP/1.1 200 Ok\r\n' -Text -reply: 'HTTP/1.1 400.100 Not Ok\r\n' -BadStatusLine raised as expected -InvalidURL raised as expected -InvalidURL raised as expected -reply: 'HTTP/1.1 200 OK\r\n' -header: Set-Cookie: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme" -header: Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme" -reply: 'HTTP/1.1 200 OK\r\n' -header: Content-Length: 14432 - Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_math ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_math Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,28 +0,0 @@ -test_math -math module, testing with eps 1e-05 -constants -acos -asin -atan -atan2 -ceil -cos -cosh -degrees -exp -fabs -floor -fmod -frexp -hypot -ldexp -log -log10 -modf -pow -radians -sin -sinh -sqrt -tan -tanh Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_mmap ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_mmap Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,38 +0,0 @@ -test_mmap - - Position of foo: 1.0 pages - Length of file: 2.0 pages - Contents of byte 0: '\x00' - Contents of first 3 bytes: '\x00\x00\x00' - - Modifying file's content... - Contents of byte 0: '3' - Contents of first 3 bytes: '3\x00\x00' - Contents of second page: '\x00foobar\x00' - Regex match on mmap (page start, length of match): 1.0 6 - Seek to zeroth byte - Seek to 42nd byte - Seek to last byte - Try to seek to negative position... - Try to seek beyond end of mmap... - Try to seek to negative position... - Attempting resize() - Creating 10 byte test data file. - Opening mmap with access=ACCESS_READ - Ensuring that readonly mmap can't be slice assigned. - Ensuring that readonly mmap can't be item assigned. - Ensuring that readonly mmap can't be write() to. - Ensuring that readonly mmap can't be write_byte() to. - Ensuring that readonly mmap can't be resized. - Opening mmap with size too big - Opening mmap with access=ACCESS_WRITE - Modifying write-through memory map. - Opening mmap with access=ACCESS_COPY - Modifying copy-on-write memory map. - Ensuring copy-on-write maps cannot be resized. - Ensuring invalid access parameter raises exception. - Try opening a bad file descriptor... - Ensuring that passing 0 as map length sets map size to current file size. - Ensuring that passing 0 as map length sets map size to current file size. - anonymous mmap.mmap(-1, PAGESIZE)... - Test passed Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_nis ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_nis Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,2 +0,0 @@ -test_nis -nis.maps() Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_opcodes ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_opcodes Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,6 +0,0 @@ -test_opcodes -2. Opcodes -XXX Not yet fully implemented -2.1 try inside for loop -2.2 raise class exceptions -2.3 comparing function objects Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_openpty ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_openpty Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,2 +0,0 @@ -test_openpty -Ping! Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_poll ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_poll Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,19 +0,0 @@ -test_poll -Running poll test 1 - This is a test. - This is a test. - This is a test. - This is a test. - This is a test. - This is a test. - This is a test. - This is a test. - This is a test. - This is a test. - This is a test. - This is a test. -Poll test 1 complete -Running poll test 2 -Poll test 2 complete -Running poll test 3 -Poll test 3 complete Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_regex ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_regex Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,29 +0,0 @@ -test_regex -no match: -1 -successful search: 6 -caught expected exception -failed awk syntax: -1 -successful awk syntax: 2 -failed awk syntax: -1 -matching with group names and compile() --1 -caught expected exception -matching with group names and symcomp() -7 -801 999 -801 -('801', '999') -('801', '999') -realpat: \([0-9]+\) *\([0-9]+\) -groupindex: {'one': 1, 'two': 2} -not case folded search: -1 -case folded search: 6 -__members__: ['last', 'regs', 'translate', 'groupindex', 'realpat', 'givenpat'] -regs: ((6, 11), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1), (-1, -1)) -last: HELLO WORLD -translate: 256 -givenpat: world -match with pos: -1 -search with pos: 18 -bogus group: ('world', None, None) -no name: caught expected exception Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_scope ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_scope Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,24 +0,0 @@ -test_scope -1. simple nesting -2. extra nesting -3. simple nesting + rebinding -4. nesting with global but no free -5. nesting through class -6. nesting plus free ref to global -7. nearest enclosing scope -8. mixed freevars and cellvars -9. free variable in method -10. recursion -11. unoptimized namespaces -12. lambdas -13. UnboundLocal -14. complex definitions -15. scope of global statements -16. check leaks -17. class and global -18. verify that locals() works -19. var is bound and free in class -20. interaction with trace function -20. eval and exec with free variables -21. list comprehension with local variables -22. eval with free variables Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_types ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_types Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,15 +0,0 @@ -test_types -6. Built-in types -6.1 Truth value testing -6.2 Boolean operations -6.3 Comparisons -6.4 Numeric types (mostly conversions) -6.4.1 32-bit integers -6.4.2 Long integers -6.4.3 Floating point numbers -6.5 Sequence types -6.5.1 Strings -6.5.2 Tuples [see test_tuple.py] -6.5.3 Lists [see test_list.py] -6.6 Mappings == Dictionaries [see test_dict.py] -Buffers Deleted: /python/branches/bcannon-objcap/Lib/test/output/test_xdrlib ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/output/test_xdrlib Tue Jan 9 23:27:11 2007 +++ (empty file) @@ -1,19 +0,0 @@ -test_xdrlib -pack test 0 succeeded -pack test 1 succeeded -pack test 2 succeeded -pack test 3 succeeded -pack test 4 succeeded -pack test 5 succeeded -pack test 6 succeeded -pack test 7 succeeded -pack test 8 succeeded -unpack test 0 succeeded : 9 -unpack test 1 succeeded : True -unpack test 2 succeeded : False -unpack test 3 succeeded : 45 -unpack test 4 succeeded : 1.89999997616 -unpack test 5 succeeded : 1.9 -unpack test 6 succeeded : hello world -unpack test 7 succeeded : [0, 1, 2, 3, 4] -unpack test 8 succeeded : ['what', 'is', 'hapnin', 'doctor'] Modified: python/branches/bcannon-objcap/Lib/test/outstanding_bugs.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/outstanding_bugs.py (original) +++ python/branches/bcannon-objcap/Lib/test/outstanding_bugs.py Tue Jan 9 23:27:11 2007 @@ -9,19 +9,14 @@ import unittest from test import test_support -class TestBug1385040(unittest.TestCase): - def testSyntaxError(self): - import compiler - - # The following snippet gives a SyntaxError in the interpreter - # - # If you compile and exec it, the call foo(7) returns (7, 1) - self.assertRaises(SyntaxError, compiler.compile, - "def foo(a=1, b): return a, b\n\n", "", "exec") +# +# No test cases for outstanding bugs at the moment. +# def test_main(): - test_support.run_unittest(TestBug1385040) + #test_support.run_unittest() + pass if __name__ == "__main__": test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_MimeWriter.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_MimeWriter.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_MimeWriter.py Tue Jan 9 23:27:11 2007 @@ -7,6 +7,8 @@ """ +import unittest, sys, StringIO +from test.test_support import run_unittest from MimeWriter import MimeWriter @@ -77,94 +79,213 @@ ] -def main(): - import sys +OUTPUT = '''\ +From: bwarsaw at cnri.reston.va.us +Date: Mon Feb 12 17:21:48 EST 1996 +To: kss-submit at cnri.reston.va.us +MIME-Version: 1.0 +Content-Type: multipart/knowbot; + boundary="801spam999"; + version="0.1" + +This is a multi-part message in MIME format. + +--801spam999 +Content-Type: multipart/knowbot-metadata; + boundary="802spam999" + + +--802spam999 +Content-Type: message/rfc822 +KP-Metadata-Type: simple +KP-Access: read-only + +KPMD-Interpreter: python +KPMD-Interpreter-Version: 1.3 +KPMD-Owner-Name: Barry Warsaw +KPMD-Owner-Rendezvous: bwarsaw at cnri.reston.va.us +KPMD-Home-KSS: kss.cnri.reston.va.us +KPMD-Identifier: hdl://cnri.kss/my_first_knowbot +KPMD-Launch-Date: Mon Feb 12 16:39:03 EST 1996 + +--802spam999 +Content-Type: text/isl +KP-Metadata-Type: complex +KP-Metadata-Key: connection +KP-Access: read-only +KP-Connection-Description: Barry's Big Bass Business +KP-Connection-Id: B4 +KP-Connection-Direction: client - # Toplevel headers +INTERFACE Seller-1; + +TYPE Seller = OBJECT + DOCUMENTATION "A simple Seller interface to test ILU" + METHODS + price():INTEGER, + END; + +--802spam999 +Content-Type: message/external-body; + access-type="URL"; + URL="hdl://cnri.kss/generic-knowbot" + +Content-Type: text/isl +KP-Metadata-Type: complex +KP-Metadata-Key: generic-interface +KP-Access: read-only +KP-Connection-Description: Generic Interface for All Knowbots +KP-Connection-Id: generic-kp +KP-Connection-Direction: client + + +--802spam999-- + +--801spam999 +Content-Type: multipart/knowbot-code; + boundary="803spam999" + + +--803spam999 +Content-Type: text/plain +KP-Module-Name: BuyerKP + +class Buyer: + def __setup__(self, maxprice): + self._maxprice = maxprice + + def __main__(self, kos): + """Entry point upon arrival at a new KOS.""" + broker = kos.broker() + # B4 == Barry's Big Bass Business :-) + seller = broker.lookup('Seller_1.Seller', 'B4') + if seller: + price = seller.price() + print 'Seller wants $', price, '... ' + if price > self._maxprice: + print 'too much!' + else: + print "I'll take it!" + else: + print 'no seller found here' + +--803spam999-- + +--801spam999 +Content-Type: multipart/knowbot-state; + boundary="804spam999" +KP-Main-Module: main + + +--804spam999 +Content-Type: text/plain +KP-Module-Name: main + +# instantiate a buyer instance and put it in a magic place for the KOS +# to find. +__kp__ = Buyer() +__kp__.__setup__(500) + +--804spam999-- + +--801spam999-- +''' + +class MimewriterTest(unittest.TestCase): + + def test(self): + buf = StringIO.StringIO() + + # Toplevel headers + + toplevel = MimeWriter(buf) + toplevel.addheader("From", "bwarsaw at cnri.reston.va.us") + toplevel.addheader("Date", "Mon Feb 12 17:21:48 EST 1996") + toplevel.addheader("To", "kss-submit at cnri.reston.va.us") + toplevel.addheader("MIME-Version", "1.0") - toplevel = MimeWriter(sys.stdout) - toplevel.addheader("From", "bwarsaw at cnri.reston.va.us") - toplevel.addheader("Date", "Mon Feb 12 17:21:48 EST 1996") - toplevel.addheader("To", "kss-submit at cnri.reston.va.us") - toplevel.addheader("MIME-Version", "1.0") + # Toplevel body parts - # Toplevel body parts + f = toplevel.startmultipartbody("knowbot", "801spam999", + [("version", "0.1")], prefix=0) + f.write("This is a multi-part message in MIME format.\n") - f = toplevel.startmultipartbody("knowbot", "801spam999", - [("version", "0.1")], prefix=0) - f.write("This is a multi-part message in MIME format.\n") + # First toplevel body part: metadata - # First toplevel body part: metadata + md = toplevel.nextpart() + md.startmultipartbody("knowbot-metadata", "802spam999") - md = toplevel.nextpart() - md.startmultipartbody("knowbot-metadata", "802spam999") + # Metadata part 1 - # Metadata part 1 + md1 = md.nextpart() + md1.addheader("KP-Metadata-Type", "simple") + md1.addheader("KP-Access", "read-only") + m = MimeWriter(md1.startbody("message/rfc822")) + for key, value in SIMPLE_METADATA: + m.addheader("KPMD-" + key, value) + m.flushheaders() + del md1 - md1 = md.nextpart() - md1.addheader("KP-Metadata-Type", "simple") - md1.addheader("KP-Access", "read-only") - m = MimeWriter(md1.startbody("message/rfc822")) - for key, value in SIMPLE_METADATA: - m.addheader("KPMD-" + key, value) - m.flushheaders() - del md1 + # Metadata part 2 - # Metadata part 2 + md2 = md.nextpart() + for key, value in COMPLEX_METADATA: + md2.addheader("KP-" + key, value) + f = md2.startbody("text/isl") + f.write(SELLER) + del md2 - md2 = md.nextpart() - for key, value in COMPLEX_METADATA: - md2.addheader("KP-" + key, value) - f = md2.startbody("text/isl") - f.write(SELLER) - del md2 + # Metadata part 3 - # Metadata part 3 + md3 = md.nextpart() + f = md3.startbody("message/external-body", + [("access-type", "URL"), + ("URL", "hdl://cnri.kss/generic-knowbot")]) + m = MimeWriter(f) + for key, value in EXTERNAL_METADATA: + md3.addheader("KP-" + key, value) + md3.startbody("text/isl") + # Phantom body doesn't need to be written - md3 = md.nextpart() - f = md3.startbody("message/external-body", - [("access-type", "URL"), - ("URL", "hdl://cnri.kss/generic-knowbot")]) - m = MimeWriter(f) - for key, value in EXTERNAL_METADATA: - md3.addheader("KP-" + key, value) - md3.startbody("text/isl") - # Phantom body doesn't need to be written + md.lastpart() - md.lastpart() + # Second toplevel body part: code - # Second toplevel body part: code + code = toplevel.nextpart() + code.startmultipartbody("knowbot-code", "803spam999") - code = toplevel.nextpart() - code.startmultipartbody("knowbot-code", "803spam999") + # Code: buyer program source - # Code: buyer program source + buyer = code.nextpart() + buyer.addheader("KP-Module-Name", "BuyerKP") + f = buyer.startbody("text/plain") + f.write(BUYER) - buyer = code.nextpart() - buyer.addheader("KP-Module-Name", "BuyerKP") - f = buyer.startbody("text/plain") - f.write(BUYER) + code.lastpart() - code.lastpart() + # Third toplevel body part: state - # Third toplevel body part: state + state = toplevel.nextpart() + state.addheader("KP-Main-Module", "main") + state.startmultipartbody("knowbot-state", "804spam999") - state = toplevel.nextpart() - state.addheader("KP-Main-Module", "main") - state.startmultipartbody("knowbot-state", "804spam999") + # State: a bunch of assignments - # State: a bunch of assignments + st = state.nextpart() + st.addheader("KP-Module-Name", "main") + f = st.startbody("text/plain") + f.write(STATE) - st = state.nextpart() - st.addheader("KP-Module-Name", "main") - f = st.startbody("text/plain") - f.write(STATE) + state.lastpart() - state.lastpart() + # End toplevel body parts - # End toplevel body parts + toplevel.lastpart() - toplevel.lastpart() + self.assertEqual(buf.getvalue(), OUTPUT) +def test_main(): + run_unittest(MimewriterTest) -main() +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_StringIO.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_StringIO.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_StringIO.py Tue Jan 9 23:27:11 2007 @@ -62,6 +62,7 @@ eq(f.getvalue(), 'abcde') f.write('xyz') eq(f.getvalue(), 'abcdexyz') + self.assertRaises(IOError, f.truncate, -1) f.close() self.assertRaises(ValueError, f.write, 'frobnitz') @@ -120,6 +121,28 @@ class TestcStringIO(TestGenericStringIO): MODULE = cStringIO + def test_unicode(self): + + if not test_support.have_unicode: return + + # The cStringIO module converts Unicode strings to character + # strings when writing them to cStringIO objects. + # Check that this works. + + f = self.MODULE.StringIO() + f.write(unicode(self._line[:5])) + s = f.getvalue() + self.assertEqual(s, 'abcde') + self.assertEqual(type(s), types.StringType) + + f = self.MODULE.StringIO(unicode(self._line[:5])) + s = f.getvalue() + self.assertEqual(s, 'abcde') + self.assertEqual(type(s), types.StringType) + + self.assertRaises(UnicodeEncodeError, self.MODULE.StringIO, + unicode('\xf4', 'latin-1')) + import sys if sys.platform.startswith('java'): # Jython doesn't have a buffer object, so we just do a useless Modified: python/branches/bcannon-objcap/Lib/test/test___future__.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test___future__.py (original) +++ python/branches/bcannon-objcap/Lib/test/test___future__.py Tue Jan 9 23:27:11 2007 @@ -1,59 +1,63 @@ #! /usr/bin/env python -from test.test_support import verbose, verify -from types import TupleType, StringType, IntType +import unittest +from test import test_support import __future__ GOOD_SERIALS = ("alpha", "beta", "candidate", "final") features = __future__.all_feature_names -# Verify that all_feature_names appears correct. -given_feature_names = features[:] -for name in dir(__future__): - obj = getattr(__future__, name, None) - if obj is not None and isinstance(obj, __future__._Feature): - verify(name in given_feature_names, - "%r should have been in all_feature_names" % name) - given_feature_names.remove(name) -verify(len(given_feature_names) == 0, - "all_feature_names has too much: %r" % given_feature_names) -del given_feature_names - -for feature in features: - value = getattr(__future__, feature) - if verbose: - print "Checking __future__ ", feature, "value", value - - optional = value.getOptionalRelease() - mandatory = value.getMandatoryRelease() - - verify(type(optional) is TupleType, "optional isn't tuple") - verify(len(optional) == 5, "optional isn't 5-tuple") - major, minor, micro, level, serial = optional - verify(type(major) is IntType, "optional major isn't int") - verify(type(minor) is IntType, "optional minor isn't int") - verify(type(micro) is IntType, "optional micro isn't int") - verify(isinstance(level, basestring), "optional level isn't string") - verify(level in GOOD_SERIALS, - "optional level string has unknown value") - verify(type(serial) is IntType, "optional serial isn't int") - - verify(type(mandatory) is TupleType or - mandatory is None, "mandatory isn't tuple or None") - if mandatory is not None: - verify(len(mandatory) == 5, "mandatory isn't 5-tuple") - major, minor, micro, level, serial = mandatory - verify(type(major) is IntType, "mandatory major isn't int") - verify(type(minor) is IntType, "mandatory minor isn't int") - verify(type(micro) is IntType, "mandatory micro isn't int") - verify(isinstance(level, basestring), "mandatory level isn't string") - verify(level in GOOD_SERIALS, - "mandatory serial string has unknown value") - verify(type(serial) is IntType, "mandatory serial isn't int") - verify(optional < mandatory, - "optional not less than mandatory, and mandatory not None") - - verify(hasattr(value, "compiler_flag"), - "feature is missing a .compiler_flag attr") - verify(type(getattr(value, "compiler_flag")) is IntType, - ".compiler_flag isn't int") +class FutureTest(unittest.TestCase): + + def test_names(self): + # Verify that all_feature_names appears correct. + given_feature_names = features[:] + for name in dir(__future__): + obj = getattr(__future__, name, None) + if obj is not None and isinstance(obj, __future__._Feature): + self.assert_( + name in given_feature_names, + "%r should have been in all_feature_names" % name + ) + given_feature_names.remove(name) + self.assertEqual(len(given_feature_names), 0, + "all_feature_names has too much: %r" % given_feature_names) + + def test_attributes(self): + for feature in features: + value = getattr(__future__, feature) + + optional = value.getOptionalRelease() + mandatory = value.getMandatoryRelease() + + a = self.assert_ + e = self.assertEqual + def check(t, name): + a(isinstance(t, tuple), "%s isn't tuple" % name) + e(len(t), 5, "%s isn't 5-tuple" % name) + (major, minor, micro, level, serial) = t + a(isinstance(major, int), "%s major isn't int" % name) + a(isinstance(minor, int), "%s minor isn't int" % name) + a(isinstance(micro, int), "%s micro isn't int" % name) + a(isinstance(level, basestring), + "%s level isn't string" % name) + a(level in GOOD_SERIALS, + "%s level string has unknown value" % name) + a(isinstance(serial, int), "%s serial isn't int" % name) + + check(optional, "optional") + if mandatory is not None: + check(mandatory, "mandatory") + a(optional < mandatory, + "optional not less than mandatory, and mandatory not None") + + a(hasattr(value, "compiler_flag"), + "feature is missing a .compiler_flag attr") + a(isinstance(getattr(value, "compiler_flag"), int), + ".compiler_flag isn't int") + +def test_main(): + test_support.run_unittest(FutureTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_binascii.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_binascii.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_binascii.py Tue Jan 9 23:27:11 2007 @@ -134,7 +134,7 @@ pass else: self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError") - self.assertEqual(binascii.a2b_qp("= "), "") + self.assertEqual(binascii.a2b_qp("= "), "= ") self.assertEqual(binascii.a2b_qp("=="), "=") self.assertEqual(binascii.a2b_qp("=AX"), "=AX") self.assertRaises(TypeError, binascii.b2a_qp, foo="bar") Modified: python/branches/bcannon-objcap/Lib/test/test_bufio.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_bufio.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_bufio.py Tue Jan 9 23:27:11 2007 @@ -1,60 +1,66 @@ -from test.test_support import verify, TestFailed, TESTFN +import unittest +from test import test_support # Simple test to ensure that optimizations in fileobject.c deliver # the expected results. For best testing, run this under a debug-build # Python too (to exercise asserts in the C code). -# Repeat string 'pattern' as often as needed to reach total length -# 'length'. Then call try_one with that string, a string one larger -# than that, and a string one smaller than that. The main driver -# feeds this all small sizes and various powers of 2, so we exercise -# all likely stdio buffer sizes, and "off by one" errors on both -# sides. -def drive_one(pattern, length): - q, r = divmod(length, len(pattern)) - teststring = pattern * q + pattern[:r] - verify(len(teststring) == length) - try_one(teststring) - try_one(teststring + "x") - try_one(teststring[:-1]) - -# Write s + "\n" + s to file, then open it and ensure that successive -# .readline()s deliver what we wrote. -def try_one(s): - # Since C doesn't guarantee we can write/read arbitrary bytes in text - # files, use binary mode. - f = open(TESTFN, "wb") - # write once with \n and once without - f.write(s) - f.write("\n") - f.write(s) - f.close() - f = open(TESTFN, "rb") - line = f.readline() - if line != s + "\n": - raise TestFailed("Expected %r got %r" % (s + "\n", line)) - line = f.readline() - if line != s: - raise TestFailed("Expected %r got %r" % (s, line)) - line = f.readline() - if line: - raise TestFailed("Expected EOF but got %r" % line) - f.close() - -# A pattern with prime length, to avoid simple relationships with -# stdio buffer sizes. -primepat = "1234567890\00\01\02\03\04\05\06" - -nullpat = "\0" * 1000 - -try: - for size in range(1, 257) + [512, 1000, 1024, 2048, 4096, 8192, 10000, - 16384, 32768, 65536, 1000000]: - drive_one(primepat, size) - drive_one(nullpat, size) -finally: - try: - import os - os.unlink(TESTFN) - except: - pass +lengths = range(1, 257) + [512, 1000, 1024, 2048, 4096, 8192, 10000, + 16384, 32768, 65536, 1000000] + +class BufferSizeTest(unittest.TestCase): + def try_one(self, s): + # Write s + "\n" + s to file, then open it and ensure that successive + # .readline()s deliver what we wrote. + + # Since C doesn't guarantee we can write/read arbitrary bytes in text + # files, use binary mode. + f = open(test_support.TESTFN, "wb") + try: + # write once with \n and once without + f.write(s) + f.write("\n") + f.write(s) + f.close() + f = open(test_support.TESTFN, "rb") + line = f.readline() + self.assertEqual(line, s + "\n") + line = f.readline() + self.assertEqual(line, s) + line = f.readline() + self.assert_(not line) # Must be at EOF + f.close() + finally: + try: + import os + os.unlink(test_support.TESTFN) + except: + pass + + def drive_one(self, pattern): + for length in lengths: + # Repeat string 'pattern' as often as needed to reach total length + # 'length'. Then call try_one with that string, a string one larger + # than that, and a string one smaller than that. Try this with all + # small sizes and various powers of 2, so we exercise all likely + # stdio buffer sizes, and "off by one" errors on both sides. + q, r = divmod(length, len(pattern)) + teststring = pattern * q + pattern[:r] + self.assertEqual(len(teststring), length) + self.try_one(teststring) + self.try_one(teststring + "x") + self.try_one(teststring[:-1]) + + def test_primepat(self): + # A pattern with prime length, to avoid simple relationships with + # stdio buffer sizes. + self.drive_one("1234567890\00\01\02\03\04\05\06") + + def test_nullpat(self): + self.drive_one("\0" * 1000) + +def test_main(): + test_support.run_unittest(BufferSizeTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_builtin.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_builtin.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_builtin.py Tue Jan 9 23:27:11 2007 @@ -116,6 +116,7 @@ self.assertEqual(abs(0), 0) self.assertEqual(abs(1234), 1234) self.assertEqual(abs(-1234), 1234) + self.assertTrue(abs(-sys.maxint-1) > 0) # float self.assertEqual(abs(0.0), 0.0) self.assertEqual(abs(3.14), 3.14) @@ -155,6 +156,11 @@ S = [10, 20, 30] self.assertEqual(any(x > 42 for x in S), False) + def test_neg(self): + x = -sys.maxint-1 + self.assert_(isinstance(x, int)) + self.assertEqual(-x, sys.maxint+1) + def test_apply(self): def f0(*args): self.assertEqual(args, ()) @@ -701,9 +707,11 @@ pass s = repr(-1-sys.maxint) - self.assertEqual(int(s)+1, -sys.maxint) + x = int(s) + self.assertEqual(x+1, -sys.maxint) + self.assert_(isinstance(x, int)) # should return long - int(s[1:]) + self.assertEqual(int(s[1:]), sys.maxint+1) # should return long x = int(1e100) @@ -721,6 +729,11 @@ self.assertRaises(ValueError, int, '123\0') self.assertRaises(ValueError, int, '53', 40) + # SF bug 1545497: embedded NULs were not detected with + # explicit base + self.assertRaises(ValueError, int, '123\0', 10) + self.assertRaises(ValueError, int, '123\x00 245', 20) + x = int('1' * 600) self.assert_(isinstance(x, long)) Modified: python/branches/bcannon-objcap/Lib/test/test_cfgparser.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_cfgparser.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_cfgparser.py Tue Jan 9 23:27:11 2007 @@ -1,9 +1,29 @@ import ConfigParser import StringIO import unittest +import UserDict from test import test_support +class SortedDict(UserDict.UserDict): + def items(self): + result = self.data.items() + result.sort() + return result + + def keys(self): + result = self.data.keys() + result.sort() + return result + + def values(self): + result = self.items() + return [i[1] for i in values] + + def iteritems(self): return iter(self.items()) + def iterkeys(self): return iter(self.keys()) + __iter__ = iterkeys + def itervalues(self): return iter(self.values()) class TestCaseBase(unittest.TestCase): def newconfig(self, defaults=None): @@ -414,12 +434,36 @@ self.assertRaises(TypeError, cf.set, "sect", "option2", 1.0) self.assertRaises(TypeError, cf.set, "sect", "option2", object()) +class SortedTestCase(RawConfigParserTestCase): + def newconfig(self, defaults=None): + self.cf = self.config_class(defaults=defaults, dict_type=SortedDict) + return self.cf + + def test_sorted(self): + self.fromstring("[b]\n" + "o4=1\n" + "o3=2\n" + "o2=3\n" + "o1=4\n" + "[a]\n" + "k=v\n") + output = StringIO.StringIO() + self.cf.write(output) + self.assertEquals(output.getvalue(), + "[a]\n" + "k = v\n\n" + "[b]\n" + "o1 = 4\n" + "o2 = 3\n" + "o3 = 2\n" + "o4 = 1\n\n") def test_main(): test_support.run_unittest( ConfigParserTestCase, RawConfigParserTestCase, - SafeConfigParserTestCase + SafeConfigParserTestCase, + SortedTestCase ) if __name__ == "__main__": Modified: python/branches/bcannon-objcap/Lib/test/test_cgi.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_cgi.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_cgi.py Tue Jan 9 23:27:11 2007 @@ -1,8 +1,9 @@ -from test.test_support import verify, verbose +from test.test_support import run_unittest import cgi import os import sys import tempfile +import unittest from StringIO import StringIO class HackedSysModule: @@ -129,119 +130,124 @@ def first_second_elts(list): return map(lambda p:(p[0], p[1][0]), list) -def main(): - for orig, expect in parse_qsl_test_cases: - result = cgi.parse_qsl(orig, keep_blank_values=True) - print repr(orig), '=>', result - verify(result == expect, "Error parsing %s" % repr(orig)) - - for orig, expect in parse_strict_test_cases: - # Test basic parsing - print repr(orig) - d = do_test(orig, "GET") - verify(d == expect, "Error parsing %s" % repr(orig)) - d = do_test(orig, "POST") - verify(d == expect, "Error parsing %s" % repr(orig)) - - env = {'QUERY_STRING': orig} - fcd = cgi.FormContentDict(env) - sd = cgi.SvFormContentDict(env) - fs = cgi.FieldStorage(environ=env) - if type(expect) == type({}): - # test dict interface - verify(len(expect) == len(fcd)) - verify(norm(expect.keys()) == norm(fcd.keys())) - verify(norm(expect.values()) == norm(fcd.values())) - verify(norm(expect.items()) == norm(fcd.items())) - verify(fcd.get("nonexistent field", "default") == "default") - verify(len(sd) == len(fs)) - verify(norm(sd.keys()) == norm(fs.keys())) - verify(fs.getvalue("nonexistent field", "default") == "default") - # test individual fields - for key in expect.keys(): - expect_val = expect[key] - verify(fcd.has_key(key)) - verify(norm(fcd[key]) == norm(expect[key])) - verify(fcd.get(key, "default") == fcd[key]) - verify(fs.has_key(key)) - if len(expect_val) > 1: - single_value = 0 - else: - single_value = 1 - try: - val = sd[key] - except IndexError: - verify(not single_value) - verify(fs.getvalue(key) == expect_val) +class CgiTests(unittest.TestCase): + + def test_qsl(self): + for orig, expect in parse_qsl_test_cases: + result = cgi.parse_qsl(orig, keep_blank_values=True) + self.assertEqual(result, expect, "Error parsing %s" % repr(orig)) + + def test_strict(self): + for orig, expect in parse_strict_test_cases: + # Test basic parsing + d = do_test(orig, "GET") + self.assertEqual(d, expect, "Error parsing %s" % repr(orig)) + d = do_test(orig, "POST") + self.assertEqual(d, expect, "Error parsing %s" % repr(orig)) + + env = {'QUERY_STRING': orig} + fcd = cgi.FormContentDict(env) + sd = cgi.SvFormContentDict(env) + fs = cgi.FieldStorage(environ=env) + if type(expect) == type({}): + # test dict interface + self.assertEqual(len(expect), len(fcd)) + self.assertEqual(norm(expect.keys()), norm(fcd.keys())) + self.assertEqual(norm(expect.values()), norm(fcd.values())) + self.assertEqual(norm(expect.items()), norm(fcd.items())) + self.assertEqual(fcd.get("nonexistent field", "default"), "default") + self.assertEqual(len(sd), len(fs)) + self.assertEqual(norm(sd.keys()), norm(fs.keys())) + self.assertEqual(fs.getvalue("nonexistent field", "default"), "default") + # test individual fields + for key in expect.keys(): + expect_val = expect[key] + self.assert_(fcd.has_key(key)) + self.assertEqual(norm(fcd[key]), norm(expect[key])) + self.assertEqual(fcd.get(key, "default"), fcd[key]) + self.assert_(fs.has_key(key)) + if len(expect_val) > 1: + single_value = 0 + else: + single_value = 1 + try: + val = sd[key] + except IndexError: + self.failIf(single_value) + self.assertEqual(fs.getvalue(key), expect_val) + else: + self.assert_(single_value) + self.assertEqual(val, expect_val[0]) + self.assertEqual(fs.getvalue(key), expect_val[0]) + self.assertEqual(norm(sd.getlist(key)), norm(expect_val)) + if single_value: + self.assertEqual(norm(sd.values()), + first_elts(norm(expect.values()))) + self.assertEqual(norm(sd.items()), + first_second_elts(norm(expect.items()))) + + def test_weird_formcontentdict(self): + # Test the weird FormContentDict classes + env = {'QUERY_STRING': "x=1&y=2.0&z=2-3.%2b0&1=1abc"} + expect = {'x': 1, 'y': 2.0, 'z': '2-3.+0', '1': '1abc'} + d = cgi.InterpFormContentDict(env) + for k, v in expect.items(): + self.assertEqual(d[k], v) + for k, v in d.items(): + self.assertEqual(expect[k], v) + self.assertEqual(norm(expect.values()), norm(d.values())) + + def test_log(self): + cgi.log("Testing") + + cgi.logfp = StringIO() + cgi.initlog("%s", "Testing initlog 1") + cgi.log("%s", "Testing log 2") + self.assertEqual(cgi.logfp.getvalue(), "Testing initlog 1\nTesting log 2\n") + if os.path.exists("/dev/null"): + cgi.logfp = None + cgi.logfile = "/dev/null" + cgi.initlog("%s", "Testing log 3") + cgi.log("Testing log 4") + + def test_fieldstorage_readline(self): + # FieldStorage uses readline, which has the capacity to read all + # contents of the input file into memory; we use readline's size argument + # to prevent that for files that do not contain any newlines in + # non-GET/HEAD requests + class TestReadlineFile: + def __init__(self, file): + self.file = file + self.numcalls = 0 + + def readline(self, size=None): + self.numcalls += 1 + if size: + return self.file.readline(size) else: - verify(single_value) - verify(val == expect_val[0]) - verify(fs.getvalue(key) == expect_val[0]) - verify(norm(sd.getlist(key)) == norm(expect_val)) - if single_value: - verify(norm(sd.values()) == \ - first_elts(norm(expect.values()))) - verify(norm(sd.items()) == \ - first_second_elts(norm(expect.items()))) - - # Test the weird FormContentDict classes - env = {'QUERY_STRING': "x=1&y=2.0&z=2-3.%2b0&1=1abc"} - expect = {'x': 1, 'y': 2.0, 'z': '2-3.+0', '1': '1abc'} - d = cgi.InterpFormContentDict(env) - for k, v in expect.items(): - verify(d[k] == v) - for k, v in d.items(): - verify(expect[k] == v) - verify(norm(expect.values()) == norm(d.values())) - - print "Testing log" - cgi.log("Testing") - cgi.logfp = sys.stdout - cgi.initlog("%s", "Testing initlog 1") - cgi.log("%s", "Testing log 2") - if os.path.exists("/dev/null"): - cgi.logfp = None - cgi.logfile = "/dev/null" - cgi.initlog("%s", "Testing log 3") - cgi.log("Testing log 4") - - print "Test FieldStorage methods that use readline" - # FieldStorage uses readline, which has the capacity to read all - # contents of the input file into memory; we use readline's size argument - # to prevent that for files that do not contain any newlines in - # non-GET/HEAD requests - class TestReadlineFile: - def __init__(self, file): - self.file = file - self.numcalls = 0 - - def readline(self, size=None): - self.numcalls += 1 - if size: - return self.file.readline(size) - else: - return self.file.readline() - - def __getattr__(self, name): - file = self.__dict__['file'] - a = getattr(file, name) - if not isinstance(a, int): - setattr(self, name, a) - return a - - f = TestReadlineFile(tempfile.TemporaryFile()) - f.write('x' * 256 * 1024) - f.seek(0) - env = {'REQUEST_METHOD':'PUT'} - fs = cgi.FieldStorage(fp=f, environ=env) - # if we're not chunking properly, readline is only called twice - # (by read_binary); if we are chunking properly, it will be called 5 times - # as long as the chunksize is 1 << 16. - verify(f.numcalls > 2) - - print "Test basic FieldStorage multipart parsing" - env = {'REQUEST_METHOD':'POST', 'CONTENT_TYPE':'multipart/form-data; boundary=---------------------------721837373350705526688164684', 'CONTENT_LENGTH':'558'} - postdata = """-----------------------------721837373350705526688164684 + return self.file.readline() + + def __getattr__(self, name): + file = self.__dict__['file'] + a = getattr(file, name) + if not isinstance(a, int): + setattr(self, name, a) + return a + + f = TestReadlineFile(tempfile.TemporaryFile()) + f.write('x' * 256 * 1024) + f.seek(0) + env = {'REQUEST_METHOD':'PUT'} + fs = cgi.FieldStorage(fp=f, environ=env) + # if we're not chunking properly, readline is only called twice + # (by read_binary); if we are chunking properly, it will be called 5 times + # as long as the chunksize is 1 << 16. + self.assert_(f.numcalls > 2) + + def test_fieldstorage_multipart(self): + #Test basic FieldStorage multipart parsing + env = {'REQUEST_METHOD':'POST', 'CONTENT_TYPE':'multipart/form-data; boundary=---------------------------721837373350705526688164684', 'CONTENT_LENGTH':'558'} + postdata = """-----------------------------721837373350705526688164684 Content-Disposition: form-data; name="id" 1234 @@ -261,15 +267,19 @@ Add\x20 -----------------------------721837373350705526688164684-- """ - fs = cgi.FieldStorage(fp=StringIO(postdata), environ=env) - verify(len(fs.list) == 4) - expect = [{'name':'id', 'filename':None, 'value':'1234'}, - {'name':'title', 'filename':None, 'value':''}, - {'name':'file', 'filename':'test.txt','value':'Testing 123.\n'}, - {'name':'submit', 'filename':None, 'value':' Add '}] - for x in range(len(fs.list)): - for k, exp in expect[x].items(): - got = getattr(fs.list[x], k) - verify(got == exp) + fs = cgi.FieldStorage(fp=StringIO(postdata), environ=env) + self.assertEquals(len(fs.list), 4) + expect = [{'name':'id', 'filename':None, 'value':'1234'}, + {'name':'title', 'filename':None, 'value':''}, + {'name':'file', 'filename':'test.txt','value':'Testing 123.\n'}, + {'name':'submit', 'filename':None, 'value':' Add '}] + for x in range(len(fs.list)): + for k, exp in expect[x].items(): + got = getattr(fs.list[x], k) + self.assertEquals(got, exp) + +def test_main(): + run_unittest(CgiTests) -main() +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_class.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_class.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_class.py Tue Jan 9 23:27:11 2007 @@ -172,6 +172,14 @@ # List/dict operations +class Empty: pass + +try: + 1 in Empty() + print 'failed, should have raised TypeError' +except TypeError: + pass + 1 in testme testme[1] Modified: python/branches/bcannon-objcap/Lib/test/test_codecs.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_codecs.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_codecs.py Tue Jan 9 23:27:11 2007 @@ -425,6 +425,10 @@ ] ) + def test_bug1601501(self): + # SF bug #1601501: check that the codec works with a buffer + unicode("\xef\xbb\xbf", "utf-8-sig") + class EscapeDecodeTest(unittest.TestCase): def test_empty(self): self.assertEquals(codecs.escape_decode(""), ("", 0)) @@ -910,6 +914,18 @@ f = self.reader(self.stream) self.assertEquals(f.readlines(), [u'\ud55c\n', u'\uae00']) +class EncodedFileTest(unittest.TestCase): + + def test_basic(self): + f = StringIO.StringIO('\xed\x95\x9c\n\xea\xb8\x80') + ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8') + self.assertEquals(ef.read(), '\\\xd5\n\x00\x00\xae') + + f = StringIO.StringIO() + ef = codecs.EncodedFile(f, 'utf-8', 'latin1') + ef.write('\xc3\xbc') + self.assertEquals(f.getvalue(), '\xfc') + class Str2StrTest(unittest.TestCase): def test_read(self): @@ -1050,6 +1066,14 @@ "punycode", "unicode_internal" ] +broken_incremental_coders = broken_unicode_with_streams[:] + +# The following encodings only support "strict" mode +only_strict_mode = [ + "idna", + "zlib_codec", + "bz2_codec", +] try: import bz2 @@ -1099,6 +1123,7 @@ decodedresult += reader.read() self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) + if encoding not in broken_incremental_coders: # check incremental decoder/encoder (fetched via the Python # and C API) and iterencode()/iterdecode() try: @@ -1139,6 +1164,24 @@ result = u"".join(codecs.iterdecode(codecs.iterencode(u"", encoding), encoding)) self.assertEqual(result, u"") + if encoding not in only_strict_mode: + # check incremental decoder/encoder with errors argument + try: + encoder = codecs.getincrementalencoder(encoding)("ignore") + cencoder = _testcapi.codec_incrementalencoder(encoding, "ignore") + except LookupError: # no IncrementalEncoder + pass + else: + encodedresult = "".join(encoder.encode(c) for c in s) + decoder = codecs.getincrementaldecoder(encoding)("ignore") + decodedresult = u"".join(decoder.decode(c) for c in encodedresult) + self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) + + encodedresult = "".join(cencoder.encode(c) for c in s) + cdecoder = _testcapi.codec_incrementaldecoder(encoding, "ignore") + decodedresult = u"".join(cdecoder.decode(c) for c in encodedresult) + self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) + def test_seek(self): # all codecs should be able to encode these s = u"%s\n%s\n" % (100*u"abc123", 100*u"def456") @@ -1214,6 +1257,19 @@ (u"", len(allbytes)) ) +class WithStmtTest(unittest.TestCase): + def test_encodedfile(self): + f = StringIO.StringIO("\xc3\xbc") + with codecs.EncodedFile(f, "latin-1", "utf-8") as ef: + self.assertEquals(ef.read(), "\xfc") + + def test_streamreaderwriter(self): + f = StringIO.StringIO("\xc3\xbc") + info = codecs.lookup("utf-8") + with codecs.StreamReaderWriter(f, info.streamreader, + info.streamwriter, 'strict') as srw: + self.assertEquals(srw.read(), u"\xfc") + def test_main(): test_support.run_unittest( @@ -1234,10 +1290,12 @@ IDNACodecTest, CodecsModuleTest, StreamReaderTest, + EncodedFileTest, Str2StrTest, BasicUnicodeTest, BasicStrTest, - CharmapTest + CharmapTest, + WithStmtTest, ) Modified: python/branches/bcannon-objcap/Lib/test/test_compile.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_compile.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_compile.py Tue Jan 9 23:27:11 2007 @@ -1,5 +1,4 @@ import unittest -import warnings import sys from test import test_support Modified: python/branches/bcannon-objcap/Lib/test/test_cookie.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_cookie.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_cookie.py Tue Jan 9 23:27:11 2007 @@ -1,6 +1,7 @@ # Simple test suite for Cookie.py -from test.test_support import verify, verbose, run_doctest +from test.test_support import run_unittest, run_doctest +import unittest import Cookie import warnings @@ -8,43 +9,74 @@ ".* class is insecure.*", DeprecationWarning) -# Currently this only tests SimpleCookie +class CookieTests(unittest.TestCase): + # Currently this only tests SimpleCookie + def test_basic(self): + cases = [ + { 'data': 'chips=ahoy; vienna=finger', + 'dict': {'chips':'ahoy', 'vienna':'finger'}, + 'repr': "", + 'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger', + }, + + { 'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"', + 'dict': {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'}, + 'repr': '''''', + 'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"', + }, + + # Check illegal cookies that have an '=' char in an unquoted value + { 'data': 'keebler=E=mc2', + 'dict': {'keebler' : 'E=mc2'}, + 'repr': "", + 'output': 'Set-Cookie: keebler=E=mc2', + } + ] + + for case in cases: + C = Cookie.SimpleCookie() + 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()): + self.assertEqual(C[k].value, v) + + def test_load(self): + C = Cookie.SimpleCookie() + C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme') + + self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE') + self.assertEqual(C['Customer']['version'], '1') + self.assertEqual(C['Customer']['path'], '/acme') + + self.assertEqual(C.output(['path']), + 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme') + self.assertEqual(C.js_output(), """ + + """) + self.assertEqual(C.js_output(['path']), """ + + """) + + def test_quoted_meta(self): + # Try cookie with quoted meta-data + C = Cookie.SimpleCookie() + C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"') + self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE') + self.assertEqual(C['Customer']['version'], '1') + self.assertEqual(C['Customer']['path'], '/acme') + +def test_main(): + run_unittest(CookieTests) + run_doctest(Cookie) -cases = [ - ('chips=ahoy; vienna=finger', {'chips':'ahoy', 'vienna':'finger'}), - ('keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"', - {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'}), - - # Check illegal cookies that have an '=' char in an unquoted value - ('keebler=E=mc2', {'keebler' : 'E=mc2'}) - ] - -for data, dict in cases: - C = Cookie.SimpleCookie() ; C.load(data) - print repr(C) - print C.output(sep='\n') - for k, v in sorted(dict.iteritems()): - print ' ', k, repr( C[k].value ), repr(v) - verify(C[k].value == v) - print C[k] - -C = Cookie.SimpleCookie() -C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme') - -verify(C['Customer'].value == 'WILE_E_COYOTE') -verify(C['Customer']['version'] == '1') -verify(C['Customer']['path'] == '/acme') - -print C.output(['path']) -print C.js_output() -print C.js_output(['path']) - -# Try cookie with quoted meta-data -C = Cookie.SimpleCookie() -C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"') -verify(C['Customer'].value == 'WILE_E_COYOTE') -verify(C['Customer']['version'] == '1') -verify(C['Customer']['path'] == '/acme') - -print "If anything blows up after this line, it's from Cookie's doctest." -run_doctest(Cookie) +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_datetime.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_datetime.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_datetime.py Tue Jan 9 23:27:11 2007 @@ -844,6 +844,7 @@ t = self.theclass(2005, 3, 2) self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05") self.assertEqual(t.strftime(""), "") # SF bug #761337 + self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784 self.assertRaises(TypeError, t.strftime) # needs an arg self.assertRaises(TypeError, t.strftime, "one", "two") # too many args Modified: python/branches/bcannon-objcap/Lib/test/test_deque.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_deque.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_deque.py Tue Jan 9 23:27:11 2007 @@ -396,6 +396,12 @@ d.pop() self.assertRaises(RuntimeError, it.next) + def test_runtime_error_on_empty_deque(self): + d = deque() + it = iter(d) + d.append(10) + self.assertRaises(RuntimeError, it.next) + class Deque(deque): pass Modified: python/branches/bcannon-objcap/Lib/test/test_descr.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_descr.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_descr.py Tue Jan 9 23:27:11 2007 @@ -2143,6 +2143,13 @@ veris(Sub.test(), Base.aProp) + # Verify that super() doesn't allow keyword args + try: + super(Base, kw=1) + except TypeError: + pass + else: + raise TestFailed, "super shouldn't accept keyword args" def inherits(): if verbose: print "Testing inheritance from basic types..." @@ -3623,6 +3630,13 @@ raise TestFailed, "shouldn't be able to assign to list.__bases__" try: + D.__bases__ = (C2, list) + except TypeError: + pass + else: + assert 0, "best_base calculation found wanting" + + try: del D.__bases__ except TypeError: pass Modified: python/branches/bcannon-objcap/Lib/test/test_dict.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_dict.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_dict.py Tue Jan 9 23:27:11 2007 @@ -444,6 +444,16 @@ else: self.fail_("g[42] didn't raise KeyError") + def test_tuple_keyerror(self): + # SF #1576657 + d = {} + try: + d[(1,)] + except KeyError, e: + self.assertEqual(e.args, ((1,),)) + else: + self.fail("missing KeyError") + from test import mapping_tests Modified: python/branches/bcannon-objcap/Lib/test/test_dumbdbm.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_dumbdbm.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_dumbdbm.py Tue Jan 9 23:27:11 2007 @@ -38,6 +38,24 @@ self.read_helper(f) f.close() + def test_dumbdbm_creation_mode(self): + # On platforms without chmod, don't do anything. + if not (hasattr(os, 'chmod') and hasattr(os, 'umask')): + return + + try: + old_umask = os.umask(0002) + f = dumbdbm.open(_fname, 'c', 0637) + f.close() + finally: + os.umask(old_umask) + + import stat + st = os.stat(_fname + '.dat') + self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + st = os.stat(_fname + '.dir') + self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + def test_close_twice(self): f = dumbdbm.open(_fname) f['a'] = 'b' Modified: python/branches/bcannon-objcap/Lib/test/test_exceptions.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_exceptions.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_exceptions.py Tue Jan 9 23:27:11 2007 @@ -3,7 +3,6 @@ import os import sys import unittest -import warnings import pickle, cPickle from test.test_support import TESTFN, unlink, run_unittest @@ -183,6 +182,19 @@ test_capi1() test_capi2() + def test_WindowsError(self): + try: + WindowsError + except NameError: + pass + else: + self.failUnlessEqual(str(WindowsError(1001)), + "1001") + self.failUnlessEqual(str(WindowsError(1001, "message")), + "[Error 1001] message") + self.failUnlessEqual(WindowsError(1001, "message").errno, 22) + self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001) + def testAttributes(self): # test that exception attributes are happy @@ -196,11 +208,16 @@ (SystemExit, ('foo',), {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}), (IOError, ('foo',), - {'message' : 'foo', 'args' : ('foo',)}), + {'message' : 'foo', 'args' : ('foo',), 'filename' : None, + 'errno' : None, 'strerror' : None}), (IOError, ('foo', 'bar'), - {'message' : '', 'args' : ('foo', 'bar')}), + {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None, + 'errno' : 'foo', 'strerror' : 'bar'}), (IOError, ('foo', 'bar', 'baz'), - {'message' : '', 'args' : ('foo', 'bar')}), + {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz', + 'errno' : 'foo', 'strerror' : 'bar'}), + (IOError, ('foo', 'bar', 'baz', 'quux'), + {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}), (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'), {'message' : '', 'args' : ('errnoStr', 'strErrorStr'), 'strerror' : 'strErrorStr', 'errno' : 'errnoStr', Modified: python/branches/bcannon-objcap/Lib/test/test_format.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_format.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_format.py Tue Jan 9 23:27:11 2007 @@ -219,8 +219,8 @@ test_exc(unicode('abc %\u3000','raw-unicode-escape'), 1, ValueError, "unsupported format character '?' (0x3000) at index 5") -test_exc('%d', '1', TypeError, "int argument required") -test_exc('%g', '1', TypeError, "float argument required") +test_exc('%d', '1', TypeError, "int argument required, not str") +test_exc('%g', '1', TypeError, "float argument required, not str") test_exc('no format', '1', TypeError, "not all arguments converted during string formatting") test_exc('no format', u'1', TypeError, Modified: python/branches/bcannon-objcap/Lib/test/test_functools.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_functools.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_functools.py Tue Jan 9 23:27:11 2007 @@ -210,6 +210,13 @@ self.assertEqual(wrapper.attr, 'This is a different test') self.assertEqual(wrapper.dict_attr, f.dict_attr) + def test_builtin_update(self): + # Test for bug #1576241 + def wrapper(): + pass + functools.update_wrapper(wrapper, max) + self.assertEqual(wrapper.__name__, 'max') + self.assert_(wrapper.__doc__.startswith('max(')) class TestWraps(TestUpdateWrapper): Modified: python/branches/bcannon-objcap/Lib/test/test_global.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_global.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_global.py Tue Jan 9 23:27:11 2007 @@ -1,51 +1,51 @@ """Verify that warnings are issued for global statements following use.""" -from test.test_support import check_syntax +from test.test_support import run_unittest, check_syntax_error +import unittest import warnings +warnings.filterwarnings("error", module="") -warnings.filterwarnings("error", module="") +class GlobalTests(unittest.TestCase): -def compile_and_check(text, should_fail=1): - try: - compile(text, "", "exec") - except SyntaxError, msg: - if should_fail: - print "got SyntaxError as expected" - else: - print "raised unexpected SyntaxError:", text - else: - if should_fail: - print "should have raised SyntaxError:", text - else: - print "as expected, no SyntaxError" - -prog_text_1 = """ + def test1(self): + prog_text_1 = """\ def wrong1(): a = 1 b = 2 global a global b """ -compile_and_check(prog_text_1) + check_syntax_error(self, prog_text_1) -prog_text_2 = """ + def test2(self): + prog_text_2 = """\ def wrong2(): print x global x """ -compile_and_check(prog_text_2) + check_syntax_error(self, prog_text_2) -prog_text_3 = """ + def test3(self): + prog_text_3 = """\ def wrong3(): print x x = 2 global x """ -compile_and_check(prog_text_3) + check_syntax_error(self, prog_text_3) -prog_text_4 = """ + def test4(self): + prog_text_4 = """\ global x x = 2 """ -compile_and_check(prog_text_4, 0) + # this should work + compile(prog_text_4, "", "exec") + + +def test_main(): + run_unittest(GlobalTests) + +if __name__ == "__main__": + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_grammar.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_grammar.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_grammar.py Tue Jan 9 23:27:11 2007 @@ -8,848 +8,913 @@ # regression test, the filterwarnings() call has been added to # regrtest.py. -from test.test_support import TestFailed, verify, vereq, check_syntax +from test.test_support import run_unittest, check_syntax_error +import unittest import sys +# testing import * +from sys import * -print '1. Parser' - -print '1.1 Tokens' - -print '1.1.1 Backslashes' +class TokenTests(unittest.TestCase): -# Backslash means line continuation: -x = 1 \ -+ 1 -if x != 2: raise TestFailed, 'backslash for line continuation' - -# Backslash does not means continuation in comments :\ -x = 0 -if x != 0: raise TestFailed, 'backslash ending comment' - -print '1.1.2 Numeric literals' - -print '1.1.2.1 Plain integers' -if 0xff != 255: raise TestFailed, 'hex int' -if 0377 != 255: raise TestFailed, 'octal int' -if 2147483647 != 017777777777: raise TestFailed, 'large positive int' -try: - from sys import maxint -except ImportError: - maxint = 2147483647 -if maxint == 2147483647: - # The following test will start to fail in Python 2.4; - # change the 020000000000 to -020000000000 - if -2147483647-1 != -020000000000: raise TestFailed, 'max negative int' - # XXX -2147483648 - if 037777777777 < 0: raise TestFailed, 'large oct' - if 0xffffffff < 0: raise TestFailed, 'large hex' - for s in '2147483648', '040000000000', '0x100000000': - try: - x = eval(s) - except OverflowError: - print "OverflowError on huge integer literal " + repr(s) -elif eval('maxint == 9223372036854775807'): - if eval('-9223372036854775807-1 != -01000000000000000000000'): - raise TestFailed, 'max negative int' - if eval('01777777777777777777777') < 0: raise TestFailed, 'large oct' - if eval('0xffffffffffffffff') < 0: raise TestFailed, 'large hex' - for s in '9223372036854775808', '02000000000000000000000', \ - '0x10000000000000000': - try: - x = eval(s) - except OverflowError: - print "OverflowError on huge integer literal " + repr(s) -else: - print 'Weird maxint value', maxint - -print '1.1.2.2 Long integers' -x = 0L -x = 0l -x = 0xffffffffffffffffL -x = 0xffffffffffffffffl -x = 077777777777777777L -x = 077777777777777777l -x = 123456789012345678901234567890L -x = 123456789012345678901234567890l - -print '1.1.2.3 Floating point' -x = 3.14 -x = 314. -x = 0.314 -# XXX x = 000.314 -x = .314 -x = 3e14 -x = 3E14 -x = 3e-14 -x = 3e+14 -x = 3.e14 -x = .3e14 -x = 3.1e4 - -print '1.1.3 String literals' - -x = ''; y = ""; verify(len(x) == 0 and x == y) -x = '\''; y = "'"; verify(len(x) == 1 and x == y and ord(x) == 39) -x = '"'; y = "\""; verify(len(x) == 1 and x == y and ord(x) == 34) -x = "doesn't \"shrink\" does it" -y = 'doesn\'t "shrink" does it' -verify(len(x) == 24 and x == y) -x = "does \"shrink\" doesn't it" -y = 'does "shrink" doesn\'t it' -verify(len(x) == 24 and x == y) -x = """ + def testBackslash(self): + # Backslash means line continuation: + x = 1 \ + + 1 + self.assertEquals(x, 2, 'backslash for line continuation') + + # Backslash does not means continuation in comments :\ + x = 0 + self.assertEquals(x, 0, 'backslash ending comment') + + def testPlainIntegers(self): + self.assertEquals(0xff, 255) + self.assertEquals(0377, 255) + self.assertEquals(2147483647, 017777777777) + from sys import maxint + if maxint == 2147483647: + self.assertEquals(-2147483647-1, -020000000000) + # XXX -2147483648 + self.assert_(037777777777 > 0) + self.assert_(0xffffffff > 0) + for s in '2147483648', '040000000000', '0x100000000': + try: + x = eval(s) + except OverflowError: + self.fail("OverflowError on huge integer literal %r" % s) + elif maxint == 9223372036854775807: + self.assertEquals(-9223372036854775807-1, -01000000000000000000000) + self.assert_(01777777777777777777777 > 0) + self.assert_(0xffffffffffffffff > 0) + for s in '9223372036854775808', '02000000000000000000000', \ + '0x10000000000000000': + try: + x = eval(s) + except OverflowError: + self.fail("OverflowError on huge integer literal %r" % s) + else: + 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 + + def testFloats(self): + x = 3.14 + x = 314. + x = 0.314 + # XXX x = 000.314 + x = .314 + x = 3e14 + x = 3E14 + x = 3e-14 + x = 3e+14 + x = 3.e14 + x = .3e14 + x = 3.1e4 + + def testStringLiterals(self): + x = ''; y = ""; self.assert_(len(x) == 0 and x == y) + x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39) + x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34) + x = "doesn't \"shrink\" does it" + y = 'doesn\'t "shrink" does it' + self.assert_(len(x) == 24 and x == y) + x = "does \"shrink\" doesn't it" + y = 'does "shrink" doesn\'t it' + self.assert_(len(x) == 24 and x == y) + x = """ The "quick" brown fox jumps over the 'lazy' dog. """ -y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' -verify(x == y) -y = ''' + y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' + self.assertEquals(x, y) + y = ''' The "quick" brown fox jumps over the 'lazy' dog. -'''; verify(x == y) -y = "\n\ +''' + self.assertEquals(x, y) + y = "\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the 'lazy' dog.\n\ -"; verify(x == y) -y = '\n\ +" + self.assertEquals(x, y) + y = '\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the \'lazy\' dog.\n\ -'; verify(x == y) +' + self.assertEquals(x, y) -print '1.2 Grammar' +class GrammarTests(unittest.TestCase): -print 'single_input' # NEWLINE | simple_stmt | compound_stmt NEWLINE -# XXX can't test in a script -- this rule is only used when interactive + # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE + # XXX can't test in a script -- this rule is only used when interactive -print 'file_input' # (NEWLINE | stmt)* ENDMARKER -# Being tested as this very moment this very module - -print 'expr_input' # testlist NEWLINE -# XXX Hard to test -- used only in calls to input() - -print 'eval_input' # testlist ENDMARKER -x = eval('1, 0 or 1') - -print 'funcdef' -### 'def' NAME parameters ':' suite -### parameters: '(' [varargslist] ')' -### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME] -### | ('**'|'*' '*') NAME) -### | fpdef ['=' test] (',' fpdef ['=' test])* [','] -### fpdef: NAME | '(' fplist ')' -### fplist: fpdef (',' fpdef)* [','] -### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test) -### argument: [test '='] test # Really [keyword '='] test -def f1(): pass -f1() -f1(*()) -f1(*(), **{}) -def f2(one_argument): pass -def f3(two, arguments): pass -def f4(two, (compound, (argument, list))): pass -def f5((compound, first), two): pass -vereq(f2.func_code.co_varnames, ('one_argument',)) -vereq(f3.func_code.co_varnames, ('two', 'arguments')) -if sys.platform.startswith('java'): - vereq(f4.func_code.co_varnames, - ('two', '(compound, (argument, list))', 'compound', 'argument', - 'list',)) - vereq(f5.func_code.co_varnames, - ('(compound, first)', 'two', 'compound', 'first')) -else: - vereq(f4.func_code.co_varnames, - ('two', '.1', 'compound', 'argument', 'list')) - vereq(f5.func_code.co_varnames, - ('.0', 'two', 'compound', 'first')) -def a1(one_arg,): pass -def a2(two, args,): pass -def v0(*rest): pass -def v1(a, *rest): pass -def v2(a, b, *rest): pass -def v3(a, (b, c), *rest): return a, b, c, rest -# ceval unpacks the formal arguments into the first argcount names; -# thus, the names nested inside tuples must appear after these names. -if sys.platform.startswith('java'): - verify(v3.func_code.co_varnames == ('a', '(b, c)', 'rest', 'b', 'c')) -else: - vereq(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c')) -verify(v3(1, (2, 3), 4) == (1, 2, 3, (4,))) -def d01(a=1): pass -d01() -d01(1) -d01(*(1,)) -d01(**{'a':2}) -def d11(a, b=1): pass -d11(1) -d11(1, 2) -d11(1, **{'b':2}) -def d21(a, b, c=1): pass -d21(1, 2) -d21(1, 2, 3) -d21(*(1, 2, 3)) -d21(1, *(2, 3)) -d21(1, 2, *(3,)) -d21(1, 2, **{'c':3}) -def d02(a=1, b=2): pass -d02() -d02(1) -d02(1, 2) -d02(*(1, 2)) -d02(1, *(2,)) -d02(1, **{'b':2}) -d02(**{'a': 1, 'b': 2}) -def d12(a, b=1, c=2): pass -d12(1) -d12(1, 2) -d12(1, 2, 3) -def d22(a, b, c=1, d=2): pass -d22(1, 2) -d22(1, 2, 3) -d22(1, 2, 3, 4) -def d01v(a=1, *rest): pass -d01v() -d01v(1) -d01v(1, 2) -d01v(*(1, 2, 3, 4)) -d01v(*(1,)) -d01v(**{'a':2}) -def d11v(a, b=1, *rest): pass -d11v(1) -d11v(1, 2) -d11v(1, 2, 3) -def d21v(a, b, c=1, *rest): pass -d21v(1, 2) -d21v(1, 2, 3) -d21v(1, 2, 3, 4) -d21v(*(1, 2, 3, 4)) -d21v(1, 2, **{'c': 3}) -def d02v(a=1, b=2, *rest): pass -d02v() -d02v(1) -d02v(1, 2) -d02v(1, 2, 3) -d02v(1, *(2, 3, 4)) -d02v(**{'a': 1, 'b': 2}) -def d12v(a, b=1, c=2, *rest): pass -d12v(1) -d12v(1, 2) -d12v(1, 2, 3) -d12v(1, 2, 3, 4) -d12v(*(1, 2, 3, 4)) -d12v(1, 2, *(3, 4, 5)) -d12v(1, *(2,), **{'c': 3}) -def d22v(a, b, c=1, d=2, *rest): pass -d22v(1, 2) -d22v(1, 2, 3) -d22v(1, 2, 3, 4) -d22v(1, 2, 3, 4, 5) -d22v(*(1, 2, 3, 4)) -d22v(1, 2, *(3, 4, 5)) -d22v(1, *(2, 3), **{'d': 4}) -def d31v((x)): pass -d31v(1) -def d32v((x,)): pass -d32v((1,)) - -### lambdef: 'lambda' [varargslist] ':' test -print 'lambdef' -l1 = lambda : 0 -verify(l1() == 0) -l2 = lambda : a[d] # XXX just testing the expression -l3 = lambda : [2 < x for x in [-1, 3, 0L]] -verify(l3() == [0, 1, 0]) -l4 = lambda x = lambda y = lambda z=1 : z : y() : x() -verify(l4() == 1) -l5 = lambda x, y, z=2: x + y + z -verify(l5(1, 2) == 5) -verify(l5(1, 2, 3) == 6) -check_syntax("lambda x: x = 2") - -### stmt: simple_stmt | compound_stmt -# Tested below - -### simple_stmt: small_stmt (';' small_stmt)* [';'] -print 'simple_stmt' -x = 1; pass; del x -def foo(): - # verify statments that end with semi-colons - x = 1; pass; del x; -foo() - -### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt -# Tested below - -print 'expr_stmt' # (exprlist '=')* exprlist -1 -1, 2, 3 -x = 1 -x = 1, 2, 3 -x = y = z = 1, 2, 3 -x, y, z = 1, 2, 3 -abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) -# NB these variables are deleted below - -check_syntax("x + 1 = 1") -check_syntax("a + 1 = b + 2") - -print 'print_stmt' # 'print' (test ',')* [test] -print 1, 2, 3 -print 1, 2, 3, -print -print 0 or 1, 0 or 1, -print 0 or 1 + # file_input: (NEWLINE | stmt)* ENDMARKER + # Being tested as this very moment this very module + + # expr_input: testlist NEWLINE + # XXX Hard to test -- used only in calls to input() + + def testEvalInput(self): + # testlist ENDMARKER + x = eval('1, 0 or 1') + + def testFuncdef(self): + ### 'def' NAME parameters ':' suite + ### parameters: '(' [varargslist] ')' + ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME] + ### | ('**'|'*' '*') NAME) + ### | fpdef ['=' test] (',' fpdef ['=' test])* [','] + ### fpdef: NAME | '(' fplist ')' + ### fplist: fpdef (',' fpdef)* [','] + ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test) + ### argument: [test '='] test # Really [keyword '='] test + def f1(): pass + f1() + f1(*()) + f1(*(), **{}) + def f2(one_argument): pass + def f3(two, arguments): pass + def f4(two, (compound, (argument, list))): pass + def f5((compound, first), two): pass + self.assertEquals(f2.func_code.co_varnames, ('one_argument',)) + self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments')) + if sys.platform.startswith('java'): + self.assertEquals(f4.func_code.co_varnames, + ('two', '(compound, (argument, list))', 'compound', 'argument', + 'list',)) + self.assertEquals(f5.func_code.co_varnames, + ('(compound, first)', 'two', 'compound', 'first')) + else: + self.assertEquals(f4.func_code.co_varnames, + ('two', '.1', 'compound', 'argument', 'list')) + self.assertEquals(f5.func_code.co_varnames, + ('.0', 'two', 'compound', 'first')) + def a1(one_arg,): pass + def a2(two, args,): pass + def v0(*rest): pass + def v1(a, *rest): pass + def v2(a, b, *rest): pass + def v3(a, (b, c), *rest): return a, b, c, rest + + f1() + f2(1) + f2(1,) + f3(1, 2) + f3(1, 2,) + f4(1, (2, (3, 4))) + v0() + v0(1) + v0(1,) + v0(1,2) + v0(1,2,3,4,5,6,7,8,9,0) + v1(1) + v1(1,) + v1(1,2) + v1(1,2,3) + v1(1,2,3,4,5,6,7,8,9,0) + v2(1,2) + v2(1,2,3) + v2(1,2,3,4) + v2(1,2,3,4,5,6,7,8,9,0) + v3(1,(2,3)) + v3(1,(2,3),4) + v3(1,(2,3),4,5,6,7,8,9,0) + + # ceval unpacks the formal arguments into the first argcount names; + # thus, the names nested inside tuples must appear after these names. + if sys.platform.startswith('java'): + self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c')) + else: + self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c')) + self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,))) + def d01(a=1): pass + d01() + d01(1) + d01(*(1,)) + d01(**{'a':2}) + def d11(a, b=1): pass + d11(1) + d11(1, 2) + d11(1, **{'b':2}) + def d21(a, b, c=1): pass + d21(1, 2) + d21(1, 2, 3) + d21(*(1, 2, 3)) + d21(1, *(2, 3)) + d21(1, 2, *(3,)) + d21(1, 2, **{'c':3}) + def d02(a=1, b=2): pass + d02() + d02(1) + d02(1, 2) + d02(*(1, 2)) + d02(1, *(2,)) + d02(1, **{'b':2}) + d02(**{'a': 1, 'b': 2}) + def d12(a, b=1, c=2): pass + d12(1) + d12(1, 2) + d12(1, 2, 3) + def d22(a, b, c=1, d=2): pass + d22(1, 2) + d22(1, 2, 3) + d22(1, 2, 3, 4) + def d01v(a=1, *rest): pass + d01v() + d01v(1) + d01v(1, 2) + d01v(*(1, 2, 3, 4)) + d01v(*(1,)) + d01v(**{'a':2}) + def d11v(a, b=1, *rest): pass + d11v(1) + d11v(1, 2) + d11v(1, 2, 3) + def d21v(a, b, c=1, *rest): pass + d21v(1, 2) + d21v(1, 2, 3) + d21v(1, 2, 3, 4) + d21v(*(1, 2, 3, 4)) + d21v(1, 2, **{'c': 3}) + def d02v(a=1, b=2, *rest): pass + d02v() + d02v(1) + d02v(1, 2) + d02v(1, 2, 3) + d02v(1, *(2, 3, 4)) + d02v(**{'a': 1, 'b': 2}) + def d12v(a, b=1, c=2, *rest): pass + d12v(1) + d12v(1, 2) + d12v(1, 2, 3) + d12v(1, 2, 3, 4) + d12v(*(1, 2, 3, 4)) + d12v(1, 2, *(3, 4, 5)) + d12v(1, *(2,), **{'c': 3}) + def d22v(a, b, c=1, d=2, *rest): pass + d22v(1, 2) + d22v(1, 2, 3) + d22v(1, 2, 3, 4) + d22v(1, 2, 3, 4, 5) + d22v(*(1, 2, 3, 4)) + d22v(1, 2, *(3, 4, 5)) + d22v(1, *(2, 3), **{'d': 4}) + def d31v((x)): pass + d31v(1) + def d32v((x,)): pass + d32v((1,)) + + def testLambdef(self): + ### lambdef: 'lambda' [varargslist] ':' test + 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]] + self.assertEquals(l3(), [0, 1, 0]) + l4 = lambda x = lambda y = lambda z=1 : z : y() : x() + self.assertEquals(l4(), 1) + l5 = lambda x, y, z=2: x + y + z + self.assertEquals(l5(1, 2), 5) + self.assertEquals(l5(1, 2, 3), 6) + check_syntax_error(self, "lambda x: x = 2") + + ### stmt: simple_stmt | compound_stmt + # Tested below + + def testSimpleStmt(self): + ### simple_stmt: small_stmt (';' small_stmt)* [';'] + x = 1; pass; del x + def foo(): + # verify statments that end with semi-colons + x = 1; pass; del x; + foo() + + ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt + # Tested below + + def testExprStmt(self): + # (exprlist '=')* exprlist + 1 + 1, 2, 3 + x = 1 + x = 1, 2, 3 + x = y = z = 1, 2, 3 + x, y, z = 1, 2, 3 + abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) + + 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] + x, y, z = abc + xyz = x, y, z + + del abc + del x, y, (z, xyz) + + def testPassStmt(self): + # 'pass' + pass + + # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt + # Tested below + + def testBreakStmt(self): + # 'break' + while 1: break + + def testContinueStmt(self): + # 'continue' + i = 1 + while i: i = 0; continue + + msg = "" + while not msg: + msg = "ok" + try: + continue + msg = "continue failed to continue inside try" + except: + msg = "continue inside try called except block" + if msg != "ok": + self.fail(msg) + + msg = "" + while not msg: + msg = "finally block not called" + try: + continue + finally: + msg = "ok" + if msg != "ok": + self.fail(msg) + + def test_break_continue_loop(self): + # This test warrants an explanation. It is a test specifically for SF bugs + # #463359 and #462937. The bug is that a 'break' statement executed or + # exception raised inside a try/except inside a loop, *after* a continue + # statement has been executed in that loop, will cause the wrong number of + # arguments to be popped off the stack and the instruction pointer reset to + # a very small number (usually 0.) Because of this, the following test + # *must* written as a function, and the tracking vars *must* be function + # arguments with default values. Otherwise, the test will loop and loop. + + def test_inner(extra_burning_oil = 1, count=0): + big_hippo = 2 + while big_hippo: + count += 1 + try: + if extra_burning_oil and big_hippo == 1: + extra_burning_oil -= 1 + break + big_hippo -= 1 + continue + except: + raise + if count > 2 or big_hippo <> 1: + self.fail("continue then break in try/except in loop broken!") + test_inner() + + def testReturn(self): + # 'return' [testlist] + def g1(): return + def g2(): return 1 + g1() + x = g2() + check_syntax_error(self, "class foo:return 1") + + def testYield(self): + check_syntax_error(self, "class foo:yield 1") + + def testRaise(self): + # 'raise' test [',' test] + try: raise RuntimeError, 'just testing' + except RuntimeError: pass + try: raise KeyboardInterrupt + except KeyboardInterrupt: pass + + def testImport(self): + # 'import' dotted_as_names + import sys + import time, sys + # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) + from time import time + from time import (time) + # not testable inside a function, but already done at top of the module + # from sys import * + from sys import path, argv + from sys import (path, argv) + from sys import (path, argv,) + + def testGlobal(self): + # 'global' NAME (',' NAME)* + global a + global a, b + global one, two, three, four, five, six, seven, eight, nine, ten + + def testExec(self): + # 'exec' expr ['in' expr [',' expr]] + z = None + del z + exec 'z=1+1\n' + if z != 2: self.fail('exec \'z=1+1\'\\n') + del z + exec 'z=1+1' + if z != 2: self.fail('exec \'z=1+1\'') + z = None + del z + import types + if hasattr(types, "UnicodeType"): + exec r"""if 1: + exec u'z=1+1\n' + if z != 2: self.fail('exec u\'z=1+1\'\\n') + del z + exec u'z=1+1' + if z != 2: self.fail('exec u\'z=1+1\'')""" + g = {} + exec 'z = 1' in g + if g.has_key('__builtins__'): del g['__builtins__'] + if g != {'z': 1}: self.fail('exec \'z = 1\' in g') + g = {} + l = {} + + import warnings + warnings.filterwarnings("ignore", "global statement", module="") + exec 'global a; a = 1; b = 2' in g, l + if g.has_key('__builtins__'): del g['__builtins__'] + if l.has_key('__builtins__'): del l['__builtins__'] + if (g, l) != ({'a':1}, {'b':2}): + self.fail('exec ... in g (%s), l (%s)' %(g,l)) + + def testAssert(self): + # assert_stmt: 'assert' test [',' test] + assert 1 + assert 1, 1 + assert lambda x:x + assert 1, lambda x:x+1 + try: + assert 0, "msg" + except AssertionError, e: + self.assertEquals(e.args[0], "msg") + else: + if __debug__: + self.fail("AssertionError not raised by assert 0") + + ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef + # Tested below + + def testIf(self): + # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] + if 1: pass + if 1: pass + else: pass + if 0: pass + elif 0: pass + if 0: pass + elif 0: pass + elif 0: pass + elif 0: pass + else: pass + + def testWhile(self): + # 'while' test ':' suite ['else' ':' suite] + while 0: pass + while 0: pass + else: pass + + def testFor(self): + # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] + for i in 1, 2, 3: pass + for i, j, k in (): pass + else: pass + class Squares: + def __init__(self, max): + self.max = max + self.sofar = [] + def __len__(self): return len(self.sofar) + def __getitem__(self, i): + if not 0 <= i < self.max: raise IndexError + n = len(self.sofar) + while n <= i: + self.sofar.append(n*n) + n = n+1 + return self.sofar[i] + n = 0 + for x in Squares(10): n = n+x + if n != 285: + self.fail('for over growing sequence') + + result = [] + for x, in [(1,), (2,), (3,)]: + result.append(x) + self.assertEqual(result, [1, 2, 3]) + + def testTry(self): + ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] + ### | 'try' ':' suite 'finally' ':' suite + ### except_clause: 'except' [expr [',' expr]] + try: + 1/0 + except ZeroDivisionError: + pass + else: + pass + try: 1/0 + except EOFError: pass + except TypeError, msg: pass + except RuntimeError, msg: pass + except: pass + else: pass + try: 1/0 + except (EOFError, TypeError, ZeroDivisionError): pass + try: 1/0 + except (EOFError, TypeError, ZeroDivisionError), msg: pass + try: pass + finally: pass + + def testSuite(self): + # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT + if 1: pass + if 1: + pass + if 1: + # + # + # + pass + pass + # + pass + # + + def testTest(self): + ### and_test ('or' and_test)* + ### and_test: not_test ('and' not_test)* + ### not_test: 'not' not_test | comparison + if not 1: pass + if 1 and 1: pass + if 1 or 1: pass + if not not not 1: pass + if not 1 and 1 and 1: pass + if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass + + def testComparison(self): + ### comparison: expr (comp_op expr)* + ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' + if 1: pass + x = (1 == 1) + if 1 == 1: pass + if 1 != 1: pass + if 1 <> 1: pass + if 1 < 1: pass + if 1 > 1: pass + if 1 <= 1: pass + if 1 >= 1: pass + if 1 is 1: pass + if 1 is not 1: pass + if 1 in (): pass + if 1 not in (): pass + if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass + + def testBinaryMaskOps(self): + x = 1 & 1 + x = 1 ^ 1 + x = 1 | 1 + + def testShiftOps(self): + x = 1 << 1 + x = 1 >> 1 + x = 1 << 1 >> 1 + + def testAdditiveOps(self): + x = 1 + x = 1 + 1 + x = 1 - 1 - 1 + x = 1 - 1 + 1 - 1 + 1 + + def testMultiplicativeOps(self): + x = 1 * 1 + x = 1 / 1 + x = 1 % 1 + x = 1 / 1 * 1 % 1 + + def testUnaryOps(self): + x = +1 + x = -1 + x = ~1 + x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 + x = -1*1/1 + 1*1 - ---1*1 + + def testSelectors(self): + ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME + ### subscript: expr | [expr] ':' [expr] + + import sys, time + c = sys.path[0] + x = time.time() + x = sys.modules['time'].time() + a = '01234' + c = a[0] + c = a[-1] + s = a[0:5] + s = a[:5] + s = a[0:] + s = a[:] + s = a[-5:] + s = a[:-1] + s = a[-4:-3] + # A rough test of SF bug 1333982. http://python.org/sf/1333982 + # The testing here is fairly incomplete. + # Test cases should include: commas with 1 and 2 colons + d = {} + d[1] = 1 + d[1,] = 2 + d[1,2] = 3 + d[1,2,3] = 4 + L = list(d) + L.sort() + self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') + + def testAtoms(self): + ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING + ### dictmaker: test ':' test (',' test ':' test)* [','] + + x = (1) + x = (1 or 2 or 3) + x = (1 or 2 or 3, 2, 3) + + x = [] + x = [1] + x = [1 or 2 or 3] + x = [1 or 2 or 3, 2, 3] + x = [] + + x = {} + x = {'one': 1} + x = {'one': 1,} + x = {'one' or 'two': 1 or 2} + x = {'one': 1, 'two': 2} + x = {'one': 1, 'two': 2,} + x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} + + x = `x` + x = `1 or 2 or 3` + self.assertEqual(`1,2`, '(1, 2)') + + x = x + x = 'x' + x = 123 + + ### exprlist: expr (',' expr)* [','] + ### testlist: test (',' test)* [','] + # These have been exercised enough above + + def testClassdef(self): + # 'class' NAME ['(' [testlist] ')'] ':' suite + class B: pass + class B2(): pass + class C1(B): pass + class C2(B): pass + class D(C1, C2, B): pass + class C: + def meth1(self): pass + def meth2(self, arg): pass + def meth3(self, a1, a2): pass + + def testListcomps(self): + # list comprehension tests + nums = [1, 2, 3, 4, 5] + strs = ["Apple", "Banana", "Coconut"] + spcs = [" Apple", " Banana ", "Coco nut "] + + self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut']) + self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15]) + self.assertEqual([x for x in nums if x > 2], [3, 4, 5]) + self.assertEqual([(i, s) for i in nums for s in strs], + [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), + (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), + (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), + (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), + (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')]) + self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]], + [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), + (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), + (5, 'Banana'), (5, 'Coconut')]) + self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)], + [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]) + + def test_in_func(l): + return [None < x < 3 for x in l if x > 2] + + self.assertEqual(test_in_func(nums), [False, False, False]) + + def test_nested_front(): + self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]], + [[1, 2], [3, 4], [5, 6]]) + + test_nested_front() + + check_syntax_error(self, "[i, s for i in nums for s in strs]") + check_syntax_error(self, "[x if y]") + + suppliers = [ + (1, "Boeing"), + (2, "Ford"), + (3, "Macdonalds") + ] + + parts = [ + (10, "Airliner"), + (20, "Engine"), + (30, "Cheeseburger") + ] + + suppart = [ + (1, 10), (1, 20), (2, 20), (3, 30) + ] + + x = [ + (sname, pname) + for (sno, sname) in suppliers + for (pno, pname) in parts + for (sp_sno, sp_pno) in suppart + if sno == sp_sno and pno == sp_pno + ] + + self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), + ('Macdonalds', 'Cheeseburger')]) + + def testGenexps(self): + # generator expression tests + g = ([x for x in range(10)] for x in range(1)) + self.assertEqual(g.next(), [x for x in range(10)]) + try: + g.next() + self.fail('should produce StopIteration exception') + except StopIteration: + pass -print 'extended print_stmt' # 'print' '>>' test ',' -import sys -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() - -# syntax errors -check_syntax('print ,') -check_syntax('print >> x,') - -print 'del_stmt' # 'del' exprlist -del abc -del x, y, (z, xyz) - -print 'pass_stmt' # 'pass' -pass - -print 'flow_stmt' # break_stmt | continue_stmt | return_stmt | raise_stmt -# Tested below - -print 'break_stmt' # 'break' -while 1: break - -print 'continue_stmt' # 'continue' -i = 1 -while i: i = 0; continue - -msg = "" -while not msg: - msg = "continue + try/except ok" - try: - continue - msg = "continue failed to continue inside try" - except: - msg = "continue inside try called except block" -print msg - -msg = "" -while not msg: - msg = "finally block not called" - try: - continue - finally: - msg = "continue + try/finally ok" -print msg - - -# This test warrants an explanation. It is a test specifically for SF bugs -# #463359 and #462937. The bug is that a 'break' statement executed or -# exception raised inside a try/except inside a loop, *after* a continue -# statement has been executed in that loop, will cause the wrong number of -# arguments to be popped off the stack and the instruction pointer reset to -# a very small number (usually 0.) Because of this, the following test -# *must* written as a function, and the tracking vars *must* be function -# arguments with default values. Otherwise, the test will loop and loop. - -print "testing continue and break in try/except in loop" -def test_break_continue_loop(extra_burning_oil = 1, count=0): - big_hippo = 2 - while big_hippo: - count += 1 + a = 1 try: - if extra_burning_oil and big_hippo == 1: - extra_burning_oil -= 1 - break - big_hippo -= 1 - continue - except: - raise - if count > 2 or big_hippo <> 1: - print "continue then break in try/except in loop broken!" -test_break_continue_loop() - -print 'return_stmt' # 'return' [testlist] -def g1(): return -def g2(): return 1 -g1() -x = g2() -check_syntax("class foo:return 1") - -print 'yield_stmt' -check_syntax("class foo:yield 1") - -print 'raise_stmt' # 'raise' test [',' test] -try: raise RuntimeError, 'just testing' -except RuntimeError: pass -try: raise KeyboardInterrupt -except KeyboardInterrupt: pass + g = (a for d in a) + g.next() + self.fail('should produce TypeError') + except TypeError: + pass + + self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd']) + self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy']) + + a = [x for x in range(10)] + b = (x for x in (y for y in a)) + self.assertEqual(sum(b), sum([x for x in range(10)])) + + self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)])) + self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2])) + self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)])) + self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)])) + self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)])) + self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)])) + self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0) + check_syntax_error(self, "foo(x for x in range(10), 100)") + check_syntax_error(self, "foo(100, x for x in range(10))") + + def testComprehensionSpecials(self): + # test for outmost iterable precomputation + x = 10; g = (i for i in range(x)); x = 5 + self.assertEqual(len(list(g)), 10) + + # This should hold, since we're only precomputing outmost iterable. + x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x)) + x = 5; t = True; + self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g)) + + # Grammar allows multiple adjacent 'if's in listcomps and genexps, + # even though it's silly. Make sure it works (ifelse broke this.) + self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7]) + self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7]) + + # verify unpacking single element tuples in listcomp/genexp. + self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6]) + self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9]) + + def testIfElseExpr(self): + # Test ifelse expressions in various cases + def _checkeval(msg, ret): + "helper to check that evaluation of expressions is done correctly" + print x + return ret + + self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) + self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True]) + self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True]) + self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5) + self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5) + self.assertEqual((5 and 6 if 0 else 1), 1) + self.assertEqual(((5 and 6) if 0 else 1), 1) + self.assertEqual((5 and (6 if 1 else 1)), 6) + self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3) + self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1) + self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5) + self.assertEqual((not 5 if 1 else 1), False) + self.assertEqual((not 5 if 0 else 1), 1) + self.assertEqual((6 + 1 if 1 else 2), 7) + self.assertEqual((6 - 1 if 1 else 2), 5) + self.assertEqual((6 * 2 if 1 else 4), 12) + self.assertEqual((6 / 2 if 1 else 3), 3) + self.assertEqual((6 < 4 if 0 else 2), 2) -print 'import_name' # 'import' dotted_as_names -import sys -import time, sys -print 'import_from' # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) -from time import time -from time import (time) -from sys import * -from sys import path, argv -from sys import (path, argv) -from sys import (path, argv,) - -print 'global_stmt' # 'global' NAME (',' NAME)* -def f(): - global a - global a, b - global one, two, three, four, five, six, seven, eight, nine, ten - -print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]] -def f(): - z = None - del z - exec 'z=1+1\n' - if z != 2: raise TestFailed, 'exec \'z=1+1\'\\n' - del z - exec 'z=1+1' - if z != 2: raise TestFailed, 'exec \'z=1+1\'' - z = None - del z - import types - if hasattr(types, "UnicodeType"): - exec r"""if 1: - exec u'z=1+1\n' - if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n' - del z - exec u'z=1+1' - if z != 2: raise TestFailed, 'exec u\'z=1+1\'' -""" -f() -g = {} -exec 'z = 1' in g -if g.has_key('__builtins__'): del g['__builtins__'] -if g != {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g' -g = {} -l = {} - -import warnings -warnings.filterwarnings("ignore", "global statement", module="") -exec 'global a; a = 1; b = 2' in g, l -if g.has_key('__builtins__'): del g['__builtins__'] -if l.has_key('__builtins__'): del l['__builtins__'] -if (g, l) != ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g (%s), l (%s)' %(g,l) - - -print "assert_stmt" # assert_stmt: 'assert' test [',' test] -assert 1 -assert 1, 1 -assert lambda x:x -assert 1, lambda x:x+1 - -### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef -# Tested below - -print 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] -if 1: pass -if 1: pass -else: pass -if 0: pass -elif 0: pass -if 0: pass -elif 0: pass -elif 0: pass -elif 0: pass -else: pass - -print 'while_stmt' # 'while' test ':' suite ['else' ':' suite] -while 0: pass -while 0: pass -else: pass - -print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] -for i in 1, 2, 3: pass -for i, j, k in (): pass -else: pass -class Squares: - def __init__(self, max): - self.max = max - self.sofar = [] - def __len__(self): return len(self.sofar) - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n = n+1 - return self.sofar[i] -n = 0 -for x in Squares(10): n = n+x -if n != 285: raise TestFailed, 'for over growing sequence' - -result = [] -for x, in [(1,), (2,), (3,)]: - result.append(x) -vereq(result, [1, 2, 3]) - -print 'try_stmt' -### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] -### | 'try' ':' suite 'finally' ':' suite -### except_clause: 'except' [expr [',' expr]] -try: - 1/0 -except ZeroDivisionError: - pass -else: - pass -try: 1/0 -except EOFError: pass -except TypeError, msg: pass -except RuntimeError, msg: pass -except: pass -else: pass -try: 1/0 -except (EOFError, TypeError, ZeroDivisionError): pass -try: 1/0 -except (EOFError, TypeError, ZeroDivisionError), msg: pass -try: pass -finally: pass - -print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT -if 1: pass -if 1: - pass -if 1: - # - # - # - pass - pass - # - pass - # - -print 'test' -### and_test ('or' and_test)* -### and_test: not_test ('and' not_test)* -### not_test: 'not' not_test | comparison -if not 1: pass -if 1 and 1: pass -if 1 or 1: pass -if not not not 1: pass -if not 1 and 1 and 1: pass -if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass - -print 'comparison' -### comparison: expr (comp_op expr)* -### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' -if 1: pass -x = (1 == 1) -if 1 == 1: pass -if 1 != 1: pass -if 1 <> 1: pass -if 1 < 1: pass -if 1 > 1: pass -if 1 <= 1: pass -if 1 >= 1: pass -if 1 is 1: pass -if 1 is not 1: pass -if 1 in (): pass -if 1 not in (): pass -if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass - -print 'binary mask ops' -x = 1 & 1 -x = 1 ^ 1 -x = 1 | 1 - -print 'shift ops' -x = 1 << 1 -x = 1 >> 1 -x = 1 << 1 >> 1 - -print 'additive ops' -x = 1 -x = 1 + 1 -x = 1 - 1 - 1 -x = 1 - 1 + 1 - 1 + 1 - -print 'multiplicative ops' -x = 1 * 1 -x = 1 / 1 -x = 1 % 1 -x = 1 / 1 * 1 % 1 - -print 'unary ops' -x = +1 -x = -1 -x = ~1 -x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 -x = -1*1/1 + 1*1 - ---1*1 - -print 'selectors' -### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME -### subscript: expr | [expr] ':' [expr] -f1() -f2(1) -f2(1,) -f3(1, 2) -f3(1, 2,) -f4(1, (2, (3, 4))) -v0() -v0(1) -v0(1,) -v0(1,2) -v0(1,2,3,4,5,6,7,8,9,0) -v1(1) -v1(1,) -v1(1,2) -v1(1,2,3) -v1(1,2,3,4,5,6,7,8,9,0) -v2(1,2) -v2(1,2,3) -v2(1,2,3,4) -v2(1,2,3,4,5,6,7,8,9,0) -v3(1,(2,3)) -v3(1,(2,3),4) -v3(1,(2,3),4,5,6,7,8,9,0) -print -import sys, time -c = sys.path[0] -x = time.time() -x = sys.modules['time'].time() -a = '01234' -c = a[0] -c = a[-1] -s = a[0:5] -s = a[:5] -s = a[0:] -s = a[:] -s = a[-5:] -s = a[:-1] -s = a[-4:-3] -# A rough test of SF bug 1333982. http://python.org/sf/1333982 -# The testing here is fairly incomplete. -# Test cases should include: commas with 1 and 2 colons -d = {} -d[1] = 1 -d[1,] = 2 -d[1,2] = 3 -d[1,2,3] = 4 -L = list(d) -L.sort() -print L - - -print 'atoms' -### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING -### dictmaker: test ':' test (',' test ':' test)* [','] - -x = (1) -x = (1 or 2 or 3) -x = (1 or 2 or 3, 2, 3) - -x = [] -x = [1] -x = [1 or 2 or 3] -x = [1 or 2 or 3, 2, 3] -x = [] - -x = {} -x = {'one': 1} -x = {'one': 1,} -x = {'one' or 'two': 1 or 2} -x = {'one': 1, 'two': 2} -x = {'one': 1, 'two': 2,} -x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} - -x = `x` -x = `1 or 2 or 3` -x = x -x = 'x' -x = 123 - -### exprlist: expr (',' expr)* [','] -### testlist: test (',' test)* [','] -# These have been exercised enough above - -print 'classdef' # 'class' NAME ['(' [testlist] ')'] ':' suite -class B: pass -class B2(): pass -class C1(B): pass -class C2(B): pass -class D(C1, C2, B): pass -class C: - def meth1(self): pass - def meth2(self, arg): pass - def meth3(self, a1, a2): pass - -# list comprehension tests -nums = [1, 2, 3, 4, 5] -strs = ["Apple", "Banana", "Coconut"] -spcs = [" Apple", " Banana ", "Coco nut "] - -print [s.strip() for s in spcs] -print [3 * x for x in nums] -print [x for x in nums if x > 2] -print [(i, s) for i in nums for s in strs] -print [(i, s) for i in nums for s in [f for f in strs if "n" in f]] -print [(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)] - -def test_in_func(l): - return [None < x < 3 for x in l if x > 2] - -print test_in_func(nums) - -def test_nested_front(): - print [[y for y in [x, x + 1]] for x in [1,3,5]] - -test_nested_front() - -check_syntax("[i, s for i in nums for s in strs]") -check_syntax("[x if y]") - -suppliers = [ - (1, "Boeing"), - (2, "Ford"), - (3, "Macdonalds") -] - -parts = [ - (10, "Airliner"), - (20, "Engine"), - (30, "Cheeseburger") -] - -suppart = [ - (1, 10), (1, 20), (2, 20), (3, 30) -] - -print [ - (sname, pname) - for (sno, sname) in suppliers - for (pno, pname) in parts - for (sp_sno, sp_pno) in suppart - if sno == sp_sno and pno == sp_pno -] - -# generator expression tests -g = ([x for x in range(10)] for x in range(1)) -verify(g.next() == [x for x in range(10)]) -try: - g.next() - raise TestFailed, 'should produce StopIteration exception' -except StopIteration: - pass - -a = 1 -try: - g = (a for d in a) - g.next() - raise TestFailed, 'should produce TypeError' -except TypeError: - pass - -verify(list((x, y) for x in 'abcd' for y in 'abcd') == [(x, y) for x in 'abcd' for y in 'abcd']) -verify(list((x, y) for x in 'ab' for y in 'xy') == [(x, y) for x in 'ab' for y in 'xy']) - -a = [x for x in range(10)] -b = (x for x in (y for y in a)) -verify(sum(b) == sum([x for x in range(10)])) - -verify(sum(x**2 for x in range(10)) == sum([x**2 for x in range(10)])) -verify(sum(x*x for x in range(10) if x%2) == sum([x*x for x in range(10) if x%2])) -verify(sum(x for x in (y for y in range(10))) == sum([x for x in range(10)])) -verify(sum(x for x in (y for y in (z for z in range(10)))) == sum([x for x in range(10)])) -verify(sum(x for x in [y for y in (z for z in range(10))]) == sum([x for x in range(10)])) -verify(sum(x for x in (y for y in (z for z in range(10) if True)) if True) == sum([x for x in range(10)])) -verify(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True) == 0) -check_syntax("foo(x for x in range(10), 100)") -check_syntax("foo(100, x for x in range(10))") - -# test for outmost iterable precomputation -x = 10; g = (i for i in range(x)); x = 5 -verify(len(list(g)) == 10) - -# This should hold, since we're only precomputing outmost iterable. -x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x)) -x = 5; t = True; -verify([(i,j) for i in range(10) for j in range(5)] == list(g)) - -# Grammar allows multiple adjacent 'if's in listcomps and genexps, -# even though it's silly. Make sure it works (ifelse broke this.) -verify([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7]) -verify((x for x in range(10) if x % 2 if x % 3), [1, 5, 7]) - -# Verify unpacking single element tuples in listcomp/genexp. -vereq([x for x, in [(4,), (5,), (6,)]], [4, 5, 6]) -vereq(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9]) - -# Test ifelse expressions in various cases -def _checkeval(msg, ret): - "helper to check that evaluation of expressions is done correctly" - print x - return ret - -verify([ x() for x in lambda: True, lambda: False if x() ] == [True]) -verify([ x() for x in (lambda: True, lambda: False) if x() ] == [True]) -verify([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ] == [True]) -verify((5 if 1 else _checkeval("check 1", 0)) == 5) -verify((_checkeval("check 2", 0) if 0 else 5) == 5) -verify((5 and 6 if 0 else 1) == 1) -verify(((5 and 6) if 0 else 1) == 1) -verify((5 and (6 if 1 else 1)) == 6) -verify((0 or _checkeval("check 3", 2) if 0 else 3) == 3) -verify((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)) == 1) -verify((0 or 5 if 1 else _checkeval("check 6", 3)) == 5) -verify((not 5 if 1 else 1) == False) -verify((not 5 if 0 else 1) == 1) -verify((6 + 1 if 1 else 2) == 7) -verify((6 - 1 if 1 else 2) == 5) -verify((6 * 2 if 1 else 4) == 12) -verify((6 / 2 if 1 else 3) == 3) -verify((6 < 4 if 0 else 2) == 2) + +def test_main(): + run_unittest(TokenTests, GrammarTests) + +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_gzip.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_gzip.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_gzip.py Tue Jan 9 23:27:11 2007 @@ -128,6 +128,17 @@ f.seek(newpos) # positive seek f.close() + def test_seek_whence(self): + self.test_write() + # Try seek(whence=1), read test + + f = gzip.GzipFile(self.filename) + f.read(10) + f.seek(10, whence=1) + 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/bcannon-objcap/Lib/test/test_heapq.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_heapq.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_heapq.py Tue Jan 9 23:27:11 2007 @@ -104,20 +104,20 @@ self.assertEqual(heap_sorted, sorted(data)) def test_nsmallest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nsmallest(n, data), sorted(data)[:n]) - self.assertEqual(nsmallest(n, data, key=f), - sorted(data, key=f)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nsmallest(n, data), sorted(data)[:n]) + self.assertEqual(nsmallest(n, data, key=f), + sorted(data, key=f)[:n]) def test_nlargest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) - self.assertEqual(nlargest(n, data, key=f), - sorted(data, key=f, reverse=True)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) + self.assertEqual(nlargest(n, data, key=f), + sorted(data, key=f, reverse=True)[:n]) #============================================================================== Modified: python/branches/bcannon-objcap/Lib/test/test_httplib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_httplib.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_httplib.py Tue Jan 9 23:27:11 2007 @@ -10,9 +10,10 @@ def __init__(self, text, fileclass=StringIO.StringIO): self.text = text self.fileclass = fileclass + self.data = '' def sendall(self, data): - self.data = data + self.data += data def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': @@ -70,103 +71,86 @@ conn.request('POST', '/', body, headers) self.assertEqual(conn._buffer.count[header.lower()], 1) -# Collect output to a buffer so that we don't have to cope with line-ending -# issues across platforms. Specifically, the headers will have \r\n pairs -# and some platforms will strip them from the output file. - -def test(): - buf = StringIO.StringIO() - _stdout = sys.stdout - try: - sys.stdout = buf - _test() - finally: - sys.stdout = _stdout - - # print individual lines with endings stripped - s = buf.getvalue() - for line in s.split("\n"): - print line.strip() - -def _test(): - # Test HTTP status lines - - body = "HTTP/1.1 200 Ok\r\n\r\nText" - sock = FakeSocket(body) - resp = httplib.HTTPResponse(sock, 1) - resp.begin() - print resp.read() - resp.close() - - body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" - sock = FakeSocket(body) - resp = httplib.HTTPResponse(sock, 1) - try: +class BasicTest(TestCase): + def test_status_lines(self): + # Test HTTP status lines + + body = "HTTP/1.1 200 Ok\r\n\r\nText" + sock = FakeSocket(body) + resp = httplib.HTTPResponse(sock) resp.begin() - except httplib.BadStatusLine: - print "BadStatusLine raised as expected" - else: - print "Expect BadStatusLine" - - # Check invalid host_port - - for hp in ("www.python.org:abc", "www.python.org:"): - try: - h = httplib.HTTP(hp) - except httplib.InvalidURL: - print "InvalidURL raised as expected" - else: - print "Expect InvalidURL" - - for hp,h,p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b", 8000), - ("www.python.org:80", "www.python.org", 80), - ("www.python.org", "www.python.org", 80), - ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80)): - try: - http = httplib.HTTP(hp) - except httplib.InvalidURL: - print "InvalidURL raised erroneously" - c = http._conn - if h != c.host: raise AssertionError, ("Host incorrectly parsed", h, c.host) - if p != c.port: raise AssertionError, ("Port incorrectly parsed", p, c.host) - - # test response with multiple message headers with the same field name. - text = ('HTTP/1.1 200 OK\r\n' - 'Set-Cookie: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"\r\n' - 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' - ' Path="/acme"\r\n' - '\r\n' - 'No body\r\n') - hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"' - ', ' - 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"') - s = FakeSocket(text) - r = httplib.HTTPResponse(s, 1) - r.begin() - cookies = r.getheader("Set-Cookie") - if cookies != hdr: - raise AssertionError, "multiple headers not combined properly" - - # Test that the library doesn't attempt to read any data - # from a HEAD request. (Tickles SF bug #622042.) - sock = FakeSocket( - 'HTTP/1.1 200 OK\r\n' - 'Content-Length: 14432\r\n' - '\r\n', - NoEOFStringIO) - resp = httplib.HTTPResponse(sock, 1, method="HEAD") - resp.begin() - if resp.read() != "": - raise AssertionError, "Did not expect response from HEAD request" - resp.close() + self.assertEqual(resp.read(), 'Text') + resp.close() + body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" + sock = FakeSocket(body) + resp = httplib.HTTPResponse(sock) + self.assertRaises(httplib.BadStatusLine, resp.begin) + + def test_host_port(self): + # Check invalid host_port + + for hp in ("www.python.org:abc", "www.python.org:"): + self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp) + + for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b", 8000), + ("www.python.org:80", "www.python.org", 80), + ("www.python.org", "www.python.org", 80), + ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80)): + http = httplib.HTTP(hp) + c = http._conn + if h != c.host: self.fail("Host incorrectly parsed: %s != %s" % (h, c.host)) + if p != c.port: self.fail("Port incorrectly parsed: %s != %s" % (p, c.host)) + + def test_response_headers(self): + # test response with multiple message headers with the same field name. + text = ('HTTP/1.1 200 OK\r\n' + 'Set-Cookie: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"\r\n' + 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' + ' Path="/acme"\r\n' + '\r\n' + 'No body\r\n') + hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"' + ', ' + 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"') + s = FakeSocket(text) + r = httplib.HTTPResponse(s) + r.begin() + cookies = r.getheader("Set-Cookie") + if cookies != hdr: + self.fail("multiple headers not combined properly") + + def test_read_head(self): + # Test that the library doesn't attempt to read any data + # from a HEAD request. (Tickles SF bug #622042.) + sock = FakeSocket( + 'HTTP/1.1 200 OK\r\n' + 'Content-Length: 14432\r\n' + '\r\n', + NoEOFStringIO) + resp = httplib.HTTPResponse(sock, method="HEAD") + resp.begin() + if resp.read() != "": + self.fail("Did not expect response from HEAD request") + resp.close() + + def test_send_file(self): + expected = 'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \ + 'Accept-Encoding: identity\r\nContent-Length:' + + body = open(__file__, 'rb') + conn = httplib.HTTPConnection('example.com') + sock = FakeSocket(body) + conn.sock = sock + conn.request('GET', '/foo', body) + self.assertTrue(sock.data.startswith(expected)) class OfflineTest(TestCase): def test_responses(self): self.assertEquals(httplib.responses[httplib.NOT_FOUND], "Not Found") def test_main(verbose=None): - tests = [HeaderTests,OfflineTest] - test_support.run_unittest(*tests) + test_support.run_unittest(HeaderTests, OfflineTest, BasicTest) -test() +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_imp.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_imp.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_imp.py Tue Jan 9 23:27:11 2007 @@ -1,43 +1,47 @@ import imp -from test.test_support import TestFailed, TestSkipped -try: - import thread -except ImportError: - raise TestSkipped("test only valid when thread support is available") - -def verify_lock_state(expected): - if imp.lock_held() != expected: - raise TestFailed("expected imp.lock_held() to be %r" % expected) - -def testLock(): - LOOPS = 50 - - # The import lock may already be held, e.g. if the test suite is run - # via "import test.autotest". - lock_held_at_start = imp.lock_held() - verify_lock_state(lock_held_at_start) - - for i in range(LOOPS): - imp.acquire_lock() - verify_lock_state(True) +import thread +import unittest +from test import test_support - for i in range(LOOPS): - imp.release_lock() - # The original state should be restored now. - verify_lock_state(lock_held_at_start) +class LockTests(unittest.TestCase): - if not lock_held_at_start: - try: + """Very basic test of import lock functions.""" + + def verify_lock_state(self, expected): + self.failUnlessEqual(imp.lock_held(), expected, + "expected imp.lock_held() to be %r" % expected) + def testLock(self): + LOOPS = 50 + + # The import lock may already be held, e.g. if the test suite is run + # via "import test.autotest". + lock_held_at_start = imp.lock_held() + self.verify_lock_state(lock_held_at_start) + + for i in range(LOOPS): + imp.acquire_lock() + self.verify_lock_state(True) + + for i in range(LOOPS): imp.release_lock() - except RuntimeError: - pass - else: - raise TestFailed("release_lock() without lock should raise " - "RuntimeError") + + # The original state should be restored now. + self.verify_lock_state(lock_held_at_start) + + if not lock_held_at_start: + try: + imp.release_lock() + except RuntimeError: + pass + else: + self.fail("release_lock() without lock should raise " + "RuntimeError") def test_main(): - testLock() + test_support.run_unittest( + LockTests, + ) if __name__ == "__main__": test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_import.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_import.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_import.py Tue Jan 9 23:27:11 2007 @@ -1,21 +1,12 @@ -from test.test_support import TESTFN, TestFailed +from test.test_support import TESTFN, run_unittest, guard_warnings_filter +import unittest import os import random import sys import py_compile +import warnings -# Brief digression to test that import is case-sensitive: if we got this -# far, we know for sure that "random" exists. -try: - import RAnDoM -except ImportError: - pass -else: - raise TestFailed("import of RAnDoM should have failed (case mismatch)") - -# Another brief digression to test the accuracy of manifest float constants. -from test import double_const # don't blink -- that *was* the test def remove_files(name): for f in (name + os.extsep + "py", @@ -26,199 +17,202 @@ if os.path.exists(f): os.remove(f) -def test_with_extension(ext): # ext normally ".py"; perhaps ".pyw" - source = TESTFN + ext - pyo = TESTFN + os.extsep + "pyo" - if sys.platform.startswith('java'): - pyc = TESTFN + "$py.class" - else: - pyc = TESTFN + os.extsep + "pyc" - - f = open(source, "w") - print >> f, "# This tests Python's ability to import a", ext, "file." - a = random.randrange(1000) - b = random.randrange(1000) - print >> f, "a =", a - print >> f, "b =", b - f.close() - - try: - try: - mod = __import__(TESTFN) - except ImportError, err: - raise ValueError("import from %s failed: %s" % (ext, err)) - if mod.a != a or mod.b != b: - print a, "!=", mod.a - print b, "!=", mod.b - raise ValueError("module loaded (%s) but contents invalid" % mod) - finally: - os.unlink(source) +class ImportTest(unittest.TestCase): - try: + def testCaseSensitivity(self): + # Brief digression to test that import is case-sensitive: if we got this + # far, we know for sure that "random" exists. try: - reload(mod) - except ImportError, err: - raise ValueError("import from .pyc/.pyo failed: %s" % err) - finally: - try: - os.unlink(pyc) - except os.error: - pass - try: - os.unlink(pyo) - except os.error: + import RAnDoM + except ImportError: pass - del sys.modules[TESTFN] + else: + self.fail("import of RAnDoM should have failed (case mismatch)") -sys.path.insert(0, os.curdir) -try: - test_with_extension(os.extsep + "py") - if sys.platform.startswith("win"): - for ext in ".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw": - test_with_extension(ext) -finally: - del sys.path[0] - -# Verify that the imp module can correctly load and find .py files -import imp -x = imp.find_module("os") -os = imp.load_module("os", *x) - -def test_module_with_large_stack(module): - # create module w/list of 65000 elements to test bug #561858 - filename = module + os.extsep + 'py' - - # create a file with a list of 65000 elements - f = open(filename, 'w+') - f.write('d = [\n') - for i in range(65000): - f.write('"",\n') - f.write(']') - f.close() - - # compile & remove .py file, we only need .pyc (or .pyo) - f = open(filename, 'r') - py_compile.compile(filename) - f.close() - os.unlink(filename) - - # need to be able to load from current dir - sys.path.append('') - - # this used to crash - exec 'import ' + module - - # cleanup - del sys.path[-1] - for ext in 'pyc', 'pyo': - fname = module + os.extsep + ext - if os.path.exists(fname): - os.unlink(fname) - -test_module_with_large_stack('longlist') - -def test_failing_import_sticks(): - source = TESTFN + os.extsep + "py" - f = open(source, "w") - print >> f, "a = 1/0" - f.close() - - # New in 2.4, we shouldn't be able to import that no matter how often - # we try. - sys.path.insert(0, os.curdir) - try: - for i in 1, 2, 3: - try: - mod = __import__(TESTFN) - except ZeroDivisionError: - if TESTFN in sys.modules: - raise TestFailed("damaged module in sys.modules", i) + def testDoubleConst(self): + # Another brief digression to test the accuracy of manifest float constants. + from test import double_const # don't blink -- that *was* the test + + def testImport(self): + def test_with_extension(ext): + # ext normally ".py"; perhaps ".pyw" + source = TESTFN + ext + pyo = TESTFN + os.extsep + "pyo" + if sys.platform.startswith('java'): + pyc = TESTFN + "$py.class" else: - raise TestFailed("was able to import a damaged module", i) - finally: - sys.path.pop(0) - remove_files(TESTFN) - -test_failing_import_sticks() - -def test_failing_reload(): - # 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" - f.close() - - sys.path.insert(0, os.curdir) - try: - mod = __import__(TESTFN) - if TESTFN not in sys.modules: - raise TestFailed("expected module in sys.modules") - if mod.a != 1 or mod.b != 2: - raise TestFailed("module has wrong attribute values") - - # On WinXP, just replacing the .py file wasn't enough to - # convince reload() to reparse it. Maybe the timestamp didn't - # move enough. We force it to get reparsed by removing the - # compiled file too. - remove_files(TESTFN) + pyc = TESTFN + os.extsep + "pyc" + + f = open(source, "w") + print >> f, "# This tests Python's ability to import a", ext, "file." + a = random.randrange(1000) + b = random.randrange(1000) + print >> f, "a =", a + print >> f, "b =", b + f.close() + + try: + try: + mod = __import__(TESTFN) + except ImportError, err: + self.fail("import from %s failed: %s" % (ext, err)) + + self.assertEquals(mod.a, a, + "module loaded (%s) but contents invalid" % mod) + self.assertEquals(mod.b, b, + "module loaded (%s) but contents invalid" % mod) + finally: + os.unlink(source) + + try: + try: + reload(mod) + except ImportError, err: + self.fail("import from .pyc/.pyo failed: %s" % err) + finally: + try: + os.unlink(pyc) + except OSError: + pass + try: + os.unlink(pyo) + except OSError: + pass + del sys.modules[TESTFN] + + sys.path.insert(0, os.curdir) + try: + test_with_extension(os.extsep + "py") + if sys.platform.startswith("win"): + for ext in ".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw": + test_with_extension(ext) + finally: + del sys.path[0] + + def testImpModule(self): + # Verify that the imp module can correctly load and find .py files + import imp + x = imp.find_module("os") + os = imp.load_module("os", *x) + + def test_module_with_large_stack(self, module='longlist'): + # create module w/list of 65000 elements to test bug #561858 + filename = module + os.extsep + 'py' + + # create a file with a list of 65000 elements + f = open(filename, 'w+') + f.write('d = [\n') + for i in range(65000): + f.write('"",\n') + f.write(']') + f.close() + + # compile & remove .py file, we only need .pyc (or .pyo) + f = open(filename, 'r') + py_compile.compile(filename) + f.close() + os.unlink(filename) - # Now damage the module. + # need to be able to load from current dir + sys.path.append('') + + # this used to crash + exec 'import ' + module + + # cleanup + del sys.path[-1] + for ext in 'pyc', 'pyo': + fname = module + os.extsep + ext + if os.path.exists(fname): + os.unlink(fname) + + def test_failing_import_sticks(self): + source = TESTFN + os.extsep + "py" f = open(source, "w") - print >> f, "a = 10" - print >> f, "b = 20//0" + print >> f, "a = 1/0" f.close() + + # New in 2.4, we shouldn't be able to import that no matter how often + # we try. + sys.path.insert(0, os.curdir) try: - reload(mod) - except ZeroDivisionError: - pass - else: - raise TestFailed("was able to reload a damaged module") + for i in 1, 2, 3: + try: + mod = __import__(TESTFN) + except ZeroDivisionError: + if TESTFN in sys.modules: + self.fail("damaged module in sys.modules on %i. try" % i) + else: + self.fail("was able to import a damaged module on %i. try" % i) + finally: + sys.path.pop(0) + remove_files(TESTFN) + + def test_failing_reload(self): + # 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" + f.close() + + sys.path.insert(0, os.curdir) + try: + mod = __import__(TESTFN) + self.assert_(TESTFN in sys.modules, "expected module in sys.modules") + self.assertEquals(mod.a, 1, "module has wrong attribute values") + self.assertEquals(mod.b, 2, "module has wrong attribute values") + + # On WinXP, just replacing the .py file wasn't enough to + # convince reload() to reparse it. Maybe the timestamp didn't + # move enough. We force it to get reparsed by removing the + # compiled file too. + remove_files(TESTFN) + + # Now damage the module. + f = open(source, "w") + print >> f, "a = 10" + print >> f, "b = 20//0" + f.close() + + self.assertRaises(ZeroDivisionError, reload, mod) + + # But we still expect the module to be in sys.modules. + mod = sys.modules.get(TESTFN) + self.failIf(mod is None, "expected module to still be in sys.modules") + + # We should have replaced a w/ 10, but the old b value should + # stick. + self.assertEquals(mod.a, 10, "module has wrong attribute values") + self.assertEquals(mod.b, 2, "module has wrong attribute values") + + finally: + sys.path.pop(0) + remove_files(TESTFN) + if TESTFN in sys.modules: + del sys.modules[TESTFN] + + def test_import_name_binding(self): + # import x.y.z binds x in the current namespace + import test as x + import test.test_support + self.assert_(x is test, x.__name__) + self.assert_(hasattr(test.test_support, "__file__")) + + # import x.y.z as w binds z as w + import test.test_support as y + self.assert_(y is test.test_support, y.__name__) + + def test_import_initless_directory_warning(self): + with guard_warnings_filter(): + # Just a random non-package directory we always expect to be + # somewhere in sys.path... + warnings.simplefilter('error', ImportWarning) + self.assertRaises(ImportWarning, __import__, "site-packages") - # But we still expect the module to be in sys.modules. - mod = sys.modules.get(TESTFN) - if mod is None: - raise TestFailed("expected module to still be in sys.modules") - # We should have replaced a w/ 10, but the old b value should - # stick. - if mod.a != 10 or mod.b != 2: - raise TestFailed("module has wrong attribute values") - - finally: - sys.path.pop(0) - remove_files(TESTFN) - if TESTFN in sys.modules: - del sys.modules[TESTFN] - -test_failing_reload() - -def test_import_name_binding(): - # import x.y.z binds x in the current namespace - import test as x - import test.test_support - assert x is test, x.__name__ - assert hasattr(test.test_support, "__file__") - - # import x.y.z as w binds z as w - import test.test_support as y - assert y is test.test_support, y.__name__ - -test_import_name_binding() - -def test_import_initless_directory_warning(): - import warnings - oldfilters = warnings.filters[:] - warnings.simplefilter('error', ImportWarning); - try: - # Just a random non-package directory we always expect to be - # somewhere in sys.path... - __import__("site-packages") - except ImportWarning: - pass - else: - raise AssertionError - finally: - warnings.filters = oldfilters +def test_main(verbose=None): + run_unittest(ImportTest) -test_import_initless_directory_warning() +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_long.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_long.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_long.py Tue Jan 9 23:27:11 2007 @@ -247,17 +247,23 @@ "long(-sys.maxint-1) != -sys.maxint-1") # long -> int should not fail for hugepos_aslong or hugeneg_aslong + x = int(hugepos_aslong) try: - self.assertEqual(int(hugepos_aslong), hugepos, + self.assertEqual(x, hugepos, "converting sys.maxint to long and back to int fails") except OverflowError: self.fail("int(long(sys.maxint)) overflowed!") + if not isinstance(x, int): + raise TestFailed("int(long(sys.maxint)) should have returned int") + x = int(hugeneg_aslong) try: - self.assertEqual(int(hugeneg_aslong), hugeneg, + self.assertEqual(x, hugeneg, "converting -sys.maxint-1 to long and back to int fails") except OverflowError: self.fail("int(long(-sys.maxint-1)) overflowed!") - + if not isinstance(x, int): + raise TestFailed("int(long(-sys.maxint-1)) should have " + "returned int") # but long -> int should overflow for hugepos+1 and hugeneg-1 x = hugepos_aslong + 1 try: @@ -282,6 +288,17 @@ self.assert_(type(y) is long, "overflowing int conversion must return long not long subtype") + # long -> Py_ssize_t conversion + class X(object): + def __getslice__(self, i, j): + return i, j + + self.assertEqual(X()[-5L:7L], (-5, 7)) + # use the clamping effect to test the smallest and largest longs + # that fit a Py_ssize_t + slicemin, slicemax = X()[-2L**100:2L**100] + self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax)) + # ----------------------------------- tests of auto int->long conversion def test_auto_overflow(self): Modified: python/branches/bcannon-objcap/Lib/test/test_mailbox.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_mailbox.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_mailbox.py Tue Jan 9 23:27:11 2007 @@ -673,6 +673,19 @@ self._box.lock() self._box.unlock() + def test_folder (self): + # Test for bug #1569790: verify that folders returned by .get_folder() + # use the same factory function. + def dummy_factory (s): + return None + 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): @@ -747,6 +760,22 @@ self._box.lock() self._box.unlock() + def test_relock(self): + # Test case for bug #1575506: the mailbox class was locking the + # wrong file object in its flush() method. + msg = "Subject: sub\n\nbody\n" + key1 = self._box.add(msg) + self._box.flush() + self._box.close() + + self._box = self._factory(self._path) + self._box.lock() + key2 = self._box.add(msg) + self._box.flush() + self.assert_(self._box._locked) + self._box.close() + + class TestMbox(_TestMboxMMDF): @@ -773,7 +802,11 @@ def test_get_folder(self): # Open folders - self._box.add_folder('foo.bar') + 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') self.assert_(os.path.isdir(os.path.join(self._path, 'foo.bar'))) @@ -781,6 +814,11 @@ self.assert_(folder1.get_string(folder1.keys()[0]) == \ self._template % 'bar') + # Test for bug #1569790: verify that folders returned by .get_folder() + # use the same factory function. + self.assert_(new_folder._factory is self._box._factory) + self.assert_(folder0._factory is self._box._factory) + def test_add_and_remove_folders(self): # Delete folders self._box.add_folder('one') @@ -849,6 +887,21 @@ self.assert_(self._box.get_sequences() == {'foo':[1, 2, 3], 'unseen':[1], 'bar':[3], 'replied':[3]}) + # Test case for packing while holding the mailbox locked. + key0 = self._box.add(msg1) + key1 = self._box.add(msg1) + key2 = self._box.add(msg1) + key3 = self._box.add(msg1) + + self._box.remove(key0) + self._box.remove(key2) + self._box.lock() + self._box.pack() + self._box.unlock() + 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/bcannon-objcap/Lib/test/test_math.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_math.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_math.py Tue Jan 9 23:27:11 2007 @@ -1,208 +1,241 @@ # Python test set -- math module # XXXX Should not do tests around zero only -from test.test_support import TestFailed, verbose +from test.test_support import run_unittest, verbose +import unittest +import math seps='1e-05' eps = eval(seps) -print 'math module, testing with eps', seps -import math -def testit(name, value, expected): - if abs(value-expected) > eps: - raise TestFailed, '%s returned %f, expected %f'%\ - (name, value, expected) - -print 'constants' -testit('pi', math.pi, 3.1415926) -testit('e', math.e, 2.7182818) - -print 'acos' -testit('acos(-1)', math.acos(-1), math.pi) -testit('acos(0)', math.acos(0), math.pi/2) -testit('acos(1)', math.acos(1), 0) - -print 'asin' -testit('asin(-1)', math.asin(-1), -math.pi/2) -testit('asin(0)', math.asin(0), 0) -testit('asin(1)', math.asin(1), math.pi/2) - -print 'atan' -testit('atan(-1)', math.atan(-1), -math.pi/4) -testit('atan(0)', math.atan(0), 0) -testit('atan(1)', math.atan(1), math.pi/4) - -print 'atan2' -testit('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2) -testit('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4) -testit('atan2(0, 1)', math.atan2(0, 1), 0) -testit('atan2(1, 1)', math.atan2(1, 1), math.pi/4) -testit('atan2(1, 0)', math.atan2(1, 0), math.pi/2) - -print 'ceil' -testit('ceil(0.5)', math.ceil(0.5), 1) -testit('ceil(1.0)', math.ceil(1.0), 1) -testit('ceil(1.5)', math.ceil(1.5), 2) -testit('ceil(-0.5)', math.ceil(-0.5), 0) -testit('ceil(-1.0)', math.ceil(-1.0), -1) -testit('ceil(-1.5)', math.ceil(-1.5), -1) - -print 'cos' -testit('cos(-pi/2)', math.cos(-math.pi/2), 0) -testit('cos(0)', math.cos(0), 1) -testit('cos(pi/2)', math.cos(math.pi/2), 0) -testit('cos(pi)', math.cos(math.pi), -1) - -print 'cosh' -testit('cosh(0)', math.cosh(0), 1) -testit('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert - -print 'degrees' -testit('degrees(pi)', math.degrees(math.pi), 180.0) -testit('degrees(pi/2)', math.degrees(math.pi/2), 90.0) -testit('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0) - -print 'exp' -testit('exp(-1)', math.exp(-1), 1/math.e) -testit('exp(0)', math.exp(0), 1) -testit('exp(1)', math.exp(1), math.e) - -print 'fabs' -testit('fabs(-1)', math.fabs(-1), 1) -testit('fabs(0)', math.fabs(0), 0) -testit('fabs(1)', math.fabs(1), 1) - -print 'floor' -testit('floor(0.5)', math.floor(0.5), 0) -testit('floor(1.0)', math.floor(1.0), 1) -testit('floor(1.5)', math.floor(1.5), 1) -testit('floor(-0.5)', math.floor(-0.5), -1) -testit('floor(-1.0)', math.floor(-1.0), -1) -testit('floor(-1.5)', math.floor(-1.5), -2) - -print 'fmod' -testit('fmod(10,1)', math.fmod(10,1), 0) -testit('fmod(10,0.5)', math.fmod(10,0.5), 0) -testit('fmod(10,1.5)', math.fmod(10,1.5), 1) -testit('fmod(-10,1)', math.fmod(-10,1), 0) -testit('fmod(-10,0.5)', math.fmod(-10,0.5), 0) -testit('fmod(-10,1.5)', math.fmod(-10,1.5), -1) - -print 'frexp' -def testfrexp(name, (mant, exp), (emant, eexp)): - if abs(mant-emant) > eps or exp != eexp: - raise TestFailed, '%s returned %r, expected %r'%\ - (name, (mant, exp), (emant,eexp)) - -testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1)) -testfrexp('frexp(0)', math.frexp(0), (0, 0)) -testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) -testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) - -print 'hypot' -testit('hypot(0,0)', math.hypot(0,0), 0) -testit('hypot(3,4)', math.hypot(3,4), 5) - -print 'ldexp' -testit('ldexp(0,1)', math.ldexp(0,1), 0) -testit('ldexp(1,1)', math.ldexp(1,1), 2) -testit('ldexp(1,-1)', math.ldexp(1,-1), 0.5) -testit('ldexp(-1,1)', math.ldexp(-1,1), -2) - -print 'log' -testit('log(1/e)', math.log(1/math.e), -1) -testit('log(1)', math.log(1), 0) -testit('log(e)', math.log(math.e), 1) -testit('log(32,2)', math.log(32,2), 5) -testit('log(10**40, 10)', math.log(10**40, 10), 40) -testit('log(10**40, 10**20)', math.log(10**40, 10**20), 2) - -print 'log10' -testit('log10(0.1)', math.log10(0.1), -1) -testit('log10(1)', math.log10(1), 0) -testit('log10(10)', math.log10(10), 1) - -print 'modf' -def testmodf(name, (v1, v2), (e1, e2)): - if abs(v1-e1) > eps or abs(v2-e2): - raise TestFailed, '%s returned %r, expected %r'%\ - (name, (v1,v2), (e1,e2)) - -testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0)) -testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0)) - -print 'pow' -testit('pow(0,1)', math.pow(0,1), 0) -testit('pow(1,0)', math.pow(1,0), 1) -testit('pow(2,1)', math.pow(2,1), 2) -testit('pow(2,-1)', math.pow(2,-1), 0.5) - -print 'radians' -testit('radians(180)', math.radians(180), math.pi) -testit('radians(90)', math.radians(90), math.pi/2) -testit('radians(-45)', math.radians(-45), -math.pi/4) - -print 'sin' -testit('sin(0)', math.sin(0), 0) -testit('sin(pi/2)', math.sin(math.pi/2), 1) -testit('sin(-pi/2)', math.sin(-math.pi/2), -1) - -print 'sinh' -testit('sinh(0)', math.sinh(0), 0) -testit('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1) -testit('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0) - -print 'sqrt' -testit('sqrt(0)', math.sqrt(0), 0) -testit('sqrt(1)', math.sqrt(1), 1) -testit('sqrt(4)', math.sqrt(4), 2) - -print 'tan' -testit('tan(0)', math.tan(0), 0) -testit('tan(pi/4)', math.tan(math.pi/4), 1) -testit('tan(-pi/4)', math.tan(-math.pi/4), -1) - -print 'tanh' -testit('tanh(0)', math.tanh(0), 0) -testit('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0) - -# RED_FLAG 16-Oct-2000 Tim -# While 2.0 is more consistent about exceptions than previous releases, it -# still fails this part of the test on some platforms. For now, we only -# *run* test_exceptions() in verbose mode, so that this isn't normally -# tested. - -def test_exceptions(): - print 'exceptions' - try: - x = math.exp(-1000000000) - except: - # mathmodule.c is failing to weed out underflows from libm, or - # we've got an fp format with huge dynamic range - raise TestFailed("underflowing exp() should not have raised " - "an exception") - if x != 0: - raise TestFailed("underflowing exp() should have returned 0") - - # If this fails, probably using a strict IEEE-754 conforming libm, and x - # is +Inf afterwards. But Python wants overflows detected by default. - try: - x = math.exp(1000000000) - except OverflowError: - pass - else: - raise TestFailed("overflowing exp() didn't trigger OverflowError") - - # If this fails, it could be a puzzle. One odd possibility is that - # mathmodule.c's macros are getting confused while comparing - # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE - # as a result (and so raising OverflowError instead). - try: - x = math.sqrt(-1.0) - except ValueError: - pass - else: - raise TestFailed("sqrt(-1) didn't raise ValueError") +class MathTests(unittest.TestCase): + + def ftest(self, name, value, expected): + if abs(value-expected) > eps: + self.fail('%s returned %f, expected %f'%\ + (name, value, expected)) + + def testConstants(self): + self.ftest('pi', math.pi, 3.1415926) + self.ftest('e', math.e, 2.7182818) + + def testAcos(self): + self.assertRaises(TypeError, math.acos) + self.ftest('acos(-1)', math.acos(-1), math.pi) + self.ftest('acos(0)', math.acos(0), math.pi/2) + self.ftest('acos(1)', math.acos(1), 0) + + def testAsin(self): + self.assertRaises(TypeError, math.asin) + self.ftest('asin(-1)', math.asin(-1), -math.pi/2) + self.ftest('asin(0)', math.asin(0), 0) + self.ftest('asin(1)', math.asin(1), math.pi/2) + + def testAtan(self): + self.assertRaises(TypeError, math.atan) + self.ftest('atan(-1)', math.atan(-1), -math.pi/4) + self.ftest('atan(0)', math.atan(0), 0) + self.ftest('atan(1)', math.atan(1), math.pi/4) + + def testAtan2(self): + self.assertRaises(TypeError, math.atan2) + self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2) + self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4) + self.ftest('atan2(0, 1)', math.atan2(0, 1), 0) + self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4) + self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2) + + def testCeil(self): + self.assertRaises(TypeError, math.ceil) + self.ftest('ceil(0.5)', math.ceil(0.5), 1) + self.ftest('ceil(1.0)', math.ceil(1.0), 1) + self.ftest('ceil(1.5)', math.ceil(1.5), 2) + self.ftest('ceil(-0.5)', math.ceil(-0.5), 0) + self.ftest('ceil(-1.0)', math.ceil(-1.0), -1) + self.ftest('ceil(-1.5)', math.ceil(-1.5), -1) + + def testCos(self): + self.assertRaises(TypeError, math.cos) + self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0) + self.ftest('cos(0)', math.cos(0), 1) + self.ftest('cos(pi/2)', math.cos(math.pi/2), 0) + self.ftest('cos(pi)', math.cos(math.pi), -1) + + def testCosh(self): + self.assertRaises(TypeError, math.cosh) + self.ftest('cosh(0)', math.cosh(0), 1) + self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert + + def testDegrees(self): + self.assertRaises(TypeError, math.degrees) + self.ftest('degrees(pi)', math.degrees(math.pi), 180.0) + self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0) + self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0) + + def testExp(self): + self.assertRaises(TypeError, math.exp) + self.ftest('exp(-1)', math.exp(-1), 1/math.e) + self.ftest('exp(0)', math.exp(0), 1) + self.ftest('exp(1)', math.exp(1), math.e) + + def testFabs(self): + self.assertRaises(TypeError, math.fabs) + self.ftest('fabs(-1)', math.fabs(-1), 1) + self.ftest('fabs(0)', math.fabs(0), 0) + self.ftest('fabs(1)', math.fabs(1), 1) + + def testFloor(self): + self.assertRaises(TypeError, math.floor) + self.ftest('floor(0.5)', math.floor(0.5), 0) + self.ftest('floor(1.0)', math.floor(1.0), 1) + self.ftest('floor(1.5)', math.floor(1.5), 1) + self.ftest('floor(-0.5)', math.floor(-0.5), -1) + self.ftest('floor(-1.0)', math.floor(-1.0), -1) + self.ftest('floor(-1.5)', math.floor(-1.5), -2) + + def testFmod(self): + self.assertRaises(TypeError, math.fmod) + self.ftest('fmod(10,1)', math.fmod(10,1), 0) + self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0) + self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1) + self.ftest('fmod(-10,1)', math.fmod(-10,1), 0) + self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0) + self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1) + + def testFrexp(self): + self.assertRaises(TypeError, math.frexp) + + def testfrexp(name, (mant, exp), (emant, eexp)): + if abs(mant-emant) > eps or exp != eexp: + self.fail('%s returned %r, expected %r'%\ + (name, (mant, exp), (emant,eexp))) + + testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1)) + testfrexp('frexp(0)', math.frexp(0), (0, 0)) + testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) + testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) + + def testHypot(self): + self.assertRaises(TypeError, math.hypot) + self.ftest('hypot(0,0)', math.hypot(0,0), 0) + self.ftest('hypot(3,4)', math.hypot(3,4), 5) + + def testLdexp(self): + self.assertRaises(TypeError, math.ldexp) + self.ftest('ldexp(0,1)', math.ldexp(0,1), 0) + self.ftest('ldexp(1,1)', math.ldexp(1,1), 2) + self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5) + self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2) + + def testLog(self): + self.assertRaises(TypeError, math.log) + self.ftest('log(1/e)', math.log(1/math.e), -1) + self.ftest('log(1)', math.log(1), 0) + self.ftest('log(e)', math.log(math.e), 1) + self.ftest('log(32,2)', math.log(32,2), 5) + self.ftest('log(10**40, 10)', math.log(10**40, 10), 40) + self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2) + + def testLog10(self): + self.assertRaises(TypeError, math.log10) + self.ftest('log10(0.1)', math.log10(0.1), -1) + self.ftest('log10(1)', math.log10(1), 0) + self.ftest('log10(10)', math.log10(10), 1) + + def testModf(self): + self.assertRaises(TypeError, math.modf) + + def testmodf(name, (v1, v2), (e1, e2)): + if abs(v1-e1) > eps or abs(v2-e2): + self.fail('%s returned %r, expected %r'%\ + (name, (v1,v2), (e1,e2))) + + testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0)) + testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0)) + + def testPow(self): + self.assertRaises(TypeError, math.pow) + self.ftest('pow(0,1)', math.pow(0,1), 0) + self.ftest('pow(1,0)', math.pow(1,0), 1) + self.ftest('pow(2,1)', math.pow(2,1), 2) + self.ftest('pow(2,-1)', math.pow(2,-1), 0.5) + + def testRadians(self): + self.assertRaises(TypeError, math.radians) + self.ftest('radians(180)', math.radians(180), math.pi) + self.ftest('radians(90)', math.radians(90), math.pi/2) + self.ftest('radians(-45)', math.radians(-45), -math.pi/4) + + def testSin(self): + self.assertRaises(TypeError, math.sin) + self.ftest('sin(0)', math.sin(0), 0) + self.ftest('sin(pi/2)', math.sin(math.pi/2), 1) + self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1) + + def testSinh(self): + self.assertRaises(TypeError, math.sinh) + self.ftest('sinh(0)', math.sinh(0), 0) + self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1) + self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0) + + def testSqrt(self): + self.assertRaises(TypeError, math.sqrt) + self.ftest('sqrt(0)', math.sqrt(0), 0) + self.ftest('sqrt(1)', math.sqrt(1), 1) + self.ftest('sqrt(4)', math.sqrt(4), 2) + + def testTan(self): + self.assertRaises(TypeError, math.tan) + self.ftest('tan(0)', math.tan(0), 0) + self.ftest('tan(pi/4)', math.tan(math.pi/4), 1) + self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1) + + def testTanh(self): + self.assertRaises(TypeError, math.tanh) + self.ftest('tanh(0)', math.tanh(0), 0) + self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0) + + # RED_FLAG 16-Oct-2000 Tim + # While 2.0 is more consistent about exceptions than previous releases, it + # still fails this part of the test on some platforms. For now, we only + # *run* test_exceptions() in verbose mode, so that this isn't normally + # tested. + + if verbose: + def test_exceptions(self): + try: + x = math.exp(-1000000000) + except: + # mathmodule.c is failing to weed out underflows from libm, or + # we've got an fp format with huge dynamic range + self.fail("underflowing exp() should not have raised " + "an exception") + if x != 0: + self.fail("underflowing exp() should have returned 0") + + # If this fails, probably using a strict IEEE-754 conforming libm, and x + # is +Inf afterwards. But Python wants overflows detected by default. + try: + x = math.exp(1000000000) + except OverflowError: + pass + else: + self.fail("overflowing exp() didn't trigger OverflowError") + + # If this fails, it could be a puzzle. One odd possibility is that + # mathmodule.c's macros are getting confused while comparing + # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE + # as a result (and so raising OverflowError instead). + try: + x = math.sqrt(-1.0) + except ValueError: + pass + else: + self.fail("sqrt(-1) didn't raise ValueError") + + +def test_main(): + run_unittest(MathTests) -if verbose: - test_exceptions() +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_mmap.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_mmap.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_mmap.py Tue Jan 9 23:27:11 2007 @@ -1,190 +1,158 @@ -from test.test_support import verify, vereq, TESTFN +from test.test_support import TESTFN, run_unittest import mmap +import unittest import os, re PAGESIZE = mmap.PAGESIZE -def test_both(): - "Test mmap module on Unix systems and Windows" +class MmapTests(unittest.TestCase): - # Create a file to be mmap'ed. - if os.path.exists(TESTFN): - os.unlink(TESTFN) - f = open(TESTFN, 'w+') - - try: # unlink TESTFN no matter what - # Write 2 pages worth of data to the file - f.write('\0'* PAGESIZE) - f.write('foo') - f.write('\0'* (PAGESIZE-3) ) - f.flush() - m = mmap.mmap(f.fileno(), 2 * PAGESIZE) - f.close() + def setUp(self): + if os.path.exists(TESTFN): + os.unlink(TESTFN) - # Simple sanity checks + def tearDown(self): + try: + os.unlink(TESTFN) + except OSError: + pass - print type(m) # SF bug 128713: segfaulted on Linux - print ' Position of foo:', m.find('foo') / float(PAGESIZE), 'pages' - vereq(m.find('foo'), PAGESIZE) - - print ' Length of file:', len(m) / float(PAGESIZE), 'pages' - vereq(len(m), 2*PAGESIZE) - - print ' Contents of byte 0:', repr(m[0]) - vereq(m[0], '\0') - print ' Contents of first 3 bytes:', repr(m[0:3]) - vereq(m[0:3], '\0\0\0') - - # Modify the file's content - print "\n Modifying file's content..." - m[0] = '3' - m[PAGESIZE +3: PAGESIZE +3+3] = 'bar' - - # Check that the modification worked - print ' Contents of byte 0:', repr(m[0]) - vereq(m[0], '3') - print ' Contents of first 3 bytes:', repr(m[0:3]) - vereq(m[0:3], '3\0\0') - print ' Contents of second page:', repr(m[PAGESIZE-1 : PAGESIZE + 7]) - vereq(m[PAGESIZE-1 : PAGESIZE + 7], '\0foobar\0') + def test_basic(self): + # Test mmap module on Unix systems and Windows - m.flush() + # Create a file to be mmap'ed. + f = open(TESTFN, 'w+') + try: + # Write 2 pages worth of data to the file + f.write('\0'* PAGESIZE) + f.write('foo') + f.write('\0'* (PAGESIZE-3) ) + f.flush() + m = mmap.mmap(f.fileno(), 2 * PAGESIZE) + f.close() - # Test doing a regular expression match in an mmap'ed file - match = re.search('[A-Za-z]+', m) - if match is None: - print ' ERROR: regex match on mmap failed!' - else: - start, end = match.span(0) - length = end - start + # Simple sanity checks - print ' Regex match on mmap (page start, length of match):', - print start / float(PAGESIZE), length + tp = str(type(m)) # SF bug 128713: segfaulted on Linux + self.assertEqual(m.find('foo'), PAGESIZE) - vereq(start, PAGESIZE) - vereq(end, PAGESIZE + 6) + self.assertEqual(len(m), 2*PAGESIZE) - # test seeking around (try to overflow the seek implementation) - m.seek(0,0) - print ' Seek to zeroth byte' - vereq(m.tell(), 0) - m.seek(42,1) - print ' Seek to 42nd byte' - vereq(m.tell(), 42) - m.seek(0,2) - print ' Seek to last byte' - vereq(m.tell(), len(m)) + self.assertEqual(m[0], '\0') + self.assertEqual(m[0:3], '\0\0\0') - print ' Try to seek to negative position...' - try: - m.seek(-1) - except ValueError: - pass - else: - verify(0, 'expected a ValueError but did not get it') + # Modify the file's content + m[0] = '3' + m[PAGESIZE +3: PAGESIZE +3+3] = 'bar' - print ' Try to seek beyond end of mmap...' - try: - m.seek(1,2) - except ValueError: - pass - else: - verify(0, 'expected a ValueError but did not get it') + # Check that the modification worked + self.assertEqual(m[0], '3') + self.assertEqual(m[0:3], '3\0\0') + self.assertEqual(m[PAGESIZE-1 : PAGESIZE + 7], '\0foobar\0') - print ' Try to seek to negative position...' - try: - m.seek(-len(m)-1,2) - except ValueError: - pass - else: - verify(0, 'expected a ValueError but did not get it') + m.flush() - # Try resizing map - print ' Attempting resize()' - try: - m.resize(512) - except SystemError: - # resize() not supported - # No messages are printed, since the output of this test suite - # would then be different across platforms. - pass - else: - # resize() is supported - verify(len(m) == 512, - "len(m) is %d, but expecting 512" % (len(m),) ) - # Check that we can no longer seek beyond the new size. + # Test doing a regular expression match in an mmap'ed file + match = re.search('[A-Za-z]+', m) + if match is None: + self.fail('regex match on mmap failed!') + else: + start, end = match.span(0) + length = end - start + + self.assertEqual(start, PAGESIZE) + self.assertEqual(end, PAGESIZE + 6) + + # test seeking around (try to overflow the seek implementation) + m.seek(0,0) + self.assertEqual(m.tell(), 0) + m.seek(42,1) + self.assertEqual(m.tell(), 42) + m.seek(0,2) + self.assertEqual(m.tell(), len(m)) + + # Try to seek to negative position... + self.assertRaises(ValueError, m.seek, -1) + + # Try to seek beyond end of mmap... + self.assertRaises(ValueError, m.seek, 1, 2) + + # Try to seek to negative position... + self.assertRaises(ValueError, m.seek, -len(m)-1, 2) + + # Try resizing map try: - m.seek(513,0) - except ValueError: + m.resize(512) + except SystemError: + # resize() not supported + # No messages are printed, since the output of this test suite + # would then be different across platforms. pass else: - verify(0, 'Could seek beyond the new size') + # resize() is supported + self.assertEqual(len(m), 512) + # Check that we can no longer seek beyond the new size. + self.assertRaises(ValueError, m.seek, 513, 0) + + # Check that the underlying file is truncated too + # (bug #728515) + f = open(TESTFN) + f.seek(0, 2) + self.assertEqual(f.tell(), 512) + f.close() + self.assertEqual(m.size(), 512) - # Check that the underlying file is truncated too - # (bug #728515) - f = open(TESTFN) - f.seek(0, 2) - verify(f.tell() == 512, 'Underlying file not truncated') - f.close() - verify(m.size() == 512, 'New size not reflected in file') - - m.close() + m.close() - finally: - try: - f.close() - except OSError: - pass - try: - os.unlink(TESTFN) - except OSError: - pass + finally: + try: + f.close() + except OSError: + pass - # Test for "access" keyword parameter - try: + def test_access_parameter(self): + # Test for "access" keyword parameter mapsize = 10 - print " Creating", mapsize, "byte test data file." open(TESTFN, "wb").write("a"*mapsize) - print " Opening mmap with access=ACCESS_READ" f = open(TESTFN, "rb") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ) - verify(m[:] == 'a'*mapsize, "Readonly memory map data incorrect.") + self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.") - print " Ensuring that readonly mmap can't be slice assigned." + # Ensuring that readonly mmap can't be slice assigned try: m[:] = 'b'*mapsize except TypeError: pass else: - verify(0, "Able to write to readonly memory map") + self.fail("Able to write to readonly memory map") - print " Ensuring that readonly mmap can't be item assigned." + # Ensuring that readonly mmap can't be item assigned try: m[0] = 'b' except TypeError: pass else: - verify(0, "Able to write to readonly memory map") + self.fail("Able to write to readonly memory map") - print " Ensuring that readonly mmap can't be write() to." + # Ensuring that readonly mmap can't be write() to try: m.seek(0,0) m.write('abc') except TypeError: pass else: - verify(0, "Able to write to readonly memory map") + self.fail("Able to write to readonly memory map") - print " Ensuring that readonly mmap can't be write_byte() to." + # Ensuring that readonly mmap can't be write_byte() to try: m.seek(0,0) m.write_byte('d') except TypeError: pass else: - verify(0, "Able to write to readonly memory map") + self.fail("Able to write to readonly memory map") - print " Ensuring that readonly mmap can't be resized." + # Ensuring that readonly mmap can't be resized try: m.resize(2*mapsize) except SystemError: # resize is not universally supported @@ -192,12 +160,12 @@ except TypeError: pass else: - verify(0, "Able to resize readonly memory map") + self.fail("Able to resize readonly memory map") del m, f - verify(open(TESTFN, "rb").read() == 'a'*mapsize, + self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize, "Readonly memory map data file was modified") - print " Opening mmap with size too big" + # Opening mmap with size too big import sys f = open(TESTFN, "r+b") try: @@ -208,11 +176,11 @@ # later tests assume that the length hasn't changed. We need to # repair that. if sys.platform.startswith('win'): - verify(0, "Opening mmap with size+1 should work on Windows.") + self.fail("Opening mmap with size+1 should work on Windows.") else: # we expect a ValueError on Unix, but not on Windows if not sys.platform.startswith('win'): - verify(0, "Opening mmap with size+1 should raise ValueError.") + self.fail("Opening mmap with size+1 should raise ValueError.") m.close() f.close() if sys.platform.startswith('win'): @@ -221,12 +189,12 @@ f.truncate(mapsize) f.close() - print " Opening mmap with access=ACCESS_WRITE" + # Opening mmap with access=ACCESS_WRITE f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE) - print " Modifying write-through memory map." + # Modifying write-through memory map m[:] = 'c'*mapsize - verify(m[:] == 'c'*mapsize, + self.assertEqual(m[:], 'c'*mapsize, "Write-through memory map memory not updated properly.") m.flush() m.close() @@ -234,66 +202,45 @@ f = open(TESTFN, 'rb') stuff = f.read() f.close() - verify(stuff == 'c'*mapsize, + self.assertEqual(stuff, 'c'*mapsize, "Write-through memory map data file not updated properly.") - print " Opening mmap with access=ACCESS_COPY" + # Opening mmap with access=ACCESS_COPY f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY) - print " Modifying copy-on-write memory map." + # Modifying copy-on-write memory map m[:] = 'd'*mapsize - verify(m[:] == 'd' * mapsize, + self.assertEqual(m[:], 'd' * mapsize, "Copy-on-write memory map data not written correctly.") m.flush() - verify(open(TESTFN, "rb").read() == 'c'*mapsize, + self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize, "Copy-on-write test data file should not be modified.") - try: - print " Ensuring copy-on-write maps cannot be resized." - m.resize(2*mapsize) - except TypeError: - pass - else: - verify(0, "Copy-on-write mmap resize did not raise exception.") + # Ensuring copy-on-write maps cannot be resized + self.assertRaises(TypeError, m.resize, 2*mapsize) del m, f - try: - print " Ensuring invalid access parameter raises exception." - f = open(TESTFN, "r+b") - m = mmap.mmap(f.fileno(), mapsize, access=4) - except ValueError: - pass - else: - verify(0, "Invalid access code should have raised exception.") + + # Ensuring invalid access parameter raises exception + f = open(TESTFN, "r+b") + self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4) + f.close() if os.name == "posix": # Try incompatible flags, prot and access parameters. f = open(TESTFN, "r+b") - try: - m = mmap.mmap(f.fileno(), mapsize, flags=mmap.MAP_PRIVATE, + self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, + flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE) - except ValueError: - pass - else: - verify(0, "Incompatible parameters should raise ValueError.") f.close() - finally: - try: - os.unlink(TESTFN) - except OSError: - pass - print ' Try opening a bad file descriptor...' - try: - mmap.mmap(-2, 4096) - except mmap.error: - pass - else: - verify(0, 'expected a mmap.error but did not get it') - - # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2, - # searching for data with embedded \0 bytes didn't work. - f = open(TESTFN, 'w+') + def test_bad_file_desc(self): + # Try opening a bad file descriptor... + self.assertRaises(mmap.error, mmap.mmap, -2, 4096) + + def test_tougher_find(self): + # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2, + # searching for data with embedded \0 bytes didn't work. + f = open(TESTFN, 'w+') - try: # unlink TESTFN no matter what data = 'aabaac\x00deef\x00\x00aa\x00' n = len(data) f.write(data) @@ -304,17 +251,14 @@ for start in range(n+1): for finish in range(start, n+1): slice = data[start : finish] - vereq(m.find(slice), data.find(slice)) - vereq(m.find(slice + 'x'), -1) + self.assertEqual(m.find(slice), data.find(slice)) + self.assertEqual(m.find(slice + 'x'), -1) m.close() - finally: - os.unlink(TESTFN) - - # make sure a double close doesn't crash on Solaris (Bug# 665913) - f = open(TESTFN, 'w+') + def test_double_close(self): + # make sure a double close doesn't crash on Solaris (Bug# 665913) + f = open(TESTFN, 'w+') - try: # unlink TESTFN no matter what f.write(2**16 * 'a') # Arbitrary character f.close() @@ -324,72 +268,46 @@ mf.close() f.close() - finally: - os.unlink(TESTFN) + def test_entire_file(self): + # test mapping of entire file by passing 0 for map length + if hasattr(os, "stat"): + f = open(TESTFN, "w+") - # test mapping of entire file by passing 0 for map length - if hasattr(os, "stat"): - print " Ensuring that passing 0 as map length sets map size to current file size." - f = open(TESTFN, "w+") - - try: f.write(2**16 * 'm') # Arbitrary character f.close() f = open(TESTFN, "rb+") mf = mmap.mmap(f.fileno(), 0) - verify(len(mf) == 2**16, "Map size should equal file size.") - vereq(mf.read(2**16), 2**16 * "m") + self.assertEqual(len(mf), 2**16, "Map size should equal file size.") + self.assertEqual(mf.read(2**16), 2**16 * "m") mf.close() f.close() - finally: - os.unlink(TESTFN) - - # test mapping of entire file by passing 0 for map length - if hasattr(os, "stat"): - print " Ensuring that passing 0 as map length sets map size to current file size." - f = open(TESTFN, "w+") - try: - f.write(2**16 * 'm') # Arbitrary character - f.close() + def test_move(self): + # make move works everywhere (64-bit format problem earlier) + f = open(TESTFN, 'w+') - f = open(TESTFN, "rb+") - mf = mmap.mmap(f.fileno(), 0) - verify(len(mf) == 2**16, "Map size should equal file size.") - vereq(mf.read(2**16), 2**16 * "m") - mf.close() - f.close() - - finally: - os.unlink(TESTFN) - - # make move works everywhere (64-bit format problem earlier) - f = open(TESTFN, 'w+') - - try: # unlink TESTFN no matter what f.write("ABCDEabcde") # Arbitrary character f.flush() mf = mmap.mmap(f.fileno(), 10) mf.move(5, 0, 5) - verify(mf[:] == "ABCDEABCDE", "Map move should have duplicated front 5") + self.assertEqual(mf[:], "ABCDEABCDE", "Map move should have duplicated front 5") mf.close() f.close() - finally: - os.unlink(TESTFN) + def test_anonymous(self): + # anonymous mmap.mmap(-1, PAGE) + m = mmap.mmap(-1, PAGESIZE) + for x in xrange(PAGESIZE): + self.assertEqual(m[x], '\0', "anonymously mmap'ed contents should be zero") + + for x in xrange(PAGESIZE): + m[x] = ch = chr(x & 255) + self.assertEqual(m[x], ch) + +def test_main(): + run_unittest(MmapTests) -def test_anon(): - print " anonymous mmap.mmap(-1, PAGESIZE)..." - m = mmap.mmap(-1, PAGESIZE) - for x in xrange(PAGESIZE): - verify(m[x] == '\0', "anonymously mmap'ed contents should be zero") - - for x in xrange(PAGESIZE): - m[x] = ch = chr(x & 255) - vereq(m[x], ch) - -test_both() -test_anon() -print ' Test passed' +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_multibytecodec.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_multibytecodec.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_multibytecodec.py Tue Jan 9 23:27:11 2007 @@ -208,6 +208,16 @@ e = u'\u3406'.encode(encoding) self.failIf(filter(lambda x: x >= '\x80', e)) + def test_bug1572832(self): + if sys.maxunicode >= 0x10000: + myunichr = unichr + else: + myunichr = lambda x: unichr(0xD7C0+(x>>10)) + unichr(0xDC00+(x&0x3FF)) + + for x in xrange(0x10000, 0x110000): + # Any ISO 2022 codec will cause the segfault + myunichr(x).encode('iso_2022_jp', 'ignore') + def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(Test_MultibyteCodec)) Modified: python/branches/bcannon-objcap/Lib/test/test_new.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_new.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_new.py Tue Jan 9 23:27:11 2007 @@ -57,6 +57,14 @@ 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 Modified: python/branches/bcannon-objcap/Lib/test/test_nis.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_nis.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_nis.py Tue Jan 9 23:27:11 2007 @@ -1,32 +1,41 @@ -from test.test_support import verbose, TestFailed, TestSkipped +from test.test_support import verbose, run_unittest +import unittest import nis -print 'nis.maps()' -try: - maps = nis.maps() -except nis.error, msg: - # NIS is probably not active, so this test isn't useful - if verbose: - raise TestFailed, msg - # only do this if running under the regression suite - raise TestSkipped, msg +class NisTests(unittest.TestCase): + def test_maps(self): + try: + maps = nis.maps() + except nis.error, msg: + # NIS is probably not active, so this test isn't useful + if verbose: + self.fail("(failing because of verbose mode) %s" % msg) + return + try: + # On some systems, this map is only accessible to the + # super user + maps.remove("passwd.adjunct.byname") + except ValueError: + pass -done = 0 -for nismap in maps: - if verbose: - print nismap - mapping = nis.cat(nismap) - for k, v in mapping.items(): - if verbose: - print ' ', k, v - if not k: - continue - if nis.match(k, nismap) != v: - print "NIS match failed for key `%s' in map `%s'" % (k, nismap) - else: - # just test the one key, otherwise this test could take a - # very long time - done = 1 - break - if done: - break + done = 0 + for nismap in maps: + mapping = nis.cat(nismap) + for k, v in mapping.items(): + if not k: + continue + if nis.match(k, nismap) != v: + self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap)) + else: + # just test the one key, otherwise this test could take a + # very long time + done = 1 + break + if done: + break + +def test_main(): + run_unittest(NisTests) + +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_opcodes.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_opcodes.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_opcodes.py Tue Jan 9 23:27:11 2007 @@ -1,101 +1,110 @@ # Python test set -- part 2, opcodes -from test.test_support import TestFailed +from test.test_support import run_unittest +import unittest +class OpcodeTest(unittest.TestCase): -print '2. Opcodes' -print 'XXX Not yet fully implemented' + def test_try_inside_for_loop(self): + n = 0 + for i in range(10): + n = n+i + try: 1/0 + except NameError: pass + except ZeroDivisionError: pass + except TypeError: pass + try: pass + except: pass + try: pass + finally: pass + n = n+i + if n != 90: + self.fail('try inside for') + + def test_raise_class_exceptions(self): + + class AClass: pass + class BClass(AClass): pass + class CClass: pass + class DClass(AClass): + def __init__(self, ignore): + pass + + try: raise AClass() + except: pass + + try: raise AClass() + except AClass: pass + + try: raise BClass() + except AClass: pass + + try: raise BClass() + except CClass: self.fail() + except: pass + + a = AClass() + b = BClass() + + try: raise AClass, b + except BClass, v: + if v != b: self.fail("v!=b") + else: self.fail("no exception") + + try: raise b + except AClass, v: + if v != b: self.fail("v!=b AClass") + else: + self.fail("no exception") + + # not enough arguments + try: raise BClass, a + except TypeError: pass + else: self.fail("no exception") + + try: raise DClass, a + except DClass, v: + self.assert_(isinstance(v, DClass)) + else: + self.fail("no exception") + + def test_compare_function_objects(self): + + f = eval('lambda: None') + g = eval('lambda: None') + self.failIf(f == g) + + f = eval('lambda a: a') + g = eval('lambda a: a') + self.failIf(f == g) + + f = eval('lambda a=1: a') + g = eval('lambda a=1: a') + self.failIf(f == g) + + f = eval('lambda: 0') + g = eval('lambda: 1') + self.failIf(f == g) + + f = eval('lambda: None') + g = eval('lambda a: None') + self.failIf(f == g) + + f = eval('lambda a: None') + g = eval('lambda b: None') + self.failIf(f == g) + + f = eval('lambda a: None') + g = eval('lambda a=None: None') + self.failIf(f == g) + + f = eval('lambda a=0: None') + g = eval('lambda a=1: None') + self.failIf(f == g) -print '2.1 try inside for loop' -n = 0 -for i in range(10): - n = n+i - try: 1/0 - except NameError: pass - except ZeroDivisionError: pass - except TypeError: pass - try: pass - except: pass - try: pass - finally: pass - n = n+i -if n != 90: - raise TestFailed, 'try inside for' - - -print '2.2 raise class exceptions' - -class AClass: pass -class BClass(AClass): pass -class CClass: pass -class DClass(AClass): - def __init__(self, ignore): - pass - -try: raise AClass() -except: pass - -try: raise AClass() -except AClass: pass - -try: raise BClass() -except AClass: pass - -try: raise BClass() -except CClass: raise TestFailed -except: pass - -a = AClass() -b = BClass() - -try: raise AClass, b -except BClass, v: - if v != b: raise TestFailed, "v!=b" -else: raise TestFailed, "no exception" - -try: raise b -except AClass, v: - if v != b: raise TestFailed, "v!=b AClass" - -# not enough arguments -try: raise BClass, a -except TypeError: pass - -try: raise DClass, a -except DClass, v: - if not isinstance(v, DClass): - raise TestFailed, "v not DClass" - -print '2.3 comparing function objects' - -f = eval('lambda: None') -g = eval('lambda: None') -if f == g: raise TestFailed, "functions should not be same" - -f = eval('lambda a: a') -g = eval('lambda a: a') -if f == g: raise TestFailed, "functions should not be same" - -f = eval('lambda a=1: a') -g = eval('lambda a=1: a') -if f == g: raise TestFailed, "functions should not be same" - -f = eval('lambda: 0') -g = eval('lambda: 1') -if f == g: raise TestFailed - -f = eval('lambda: None') -g = eval('lambda a: None') -if f == g: raise TestFailed - -f = eval('lambda a: None') -g = eval('lambda b: None') -if f == g: raise TestFailed - -f = eval('lambda a: None') -g = eval('lambda a=None: None') -if f == g: raise TestFailed - -f = eval('lambda a=0: None') -g = eval('lambda a=1: None') -if f == g: raise TestFailed + +def test_main(): + run_unittest(OpcodeTest) + +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_openpty.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_openpty.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_openpty.py Tue Jan 9 23:27:11 2007 @@ -1,19 +1,23 @@ # Test to see if openpty works. (But don't worry if it isn't available.) -import os -from test.test_support import verbose, TestFailed, TestSkipped +import os, unittest +from test.test_support import run_unittest, TestSkipped -try: - if verbose: - print "Calling os.openpty()" - master, slave = os.openpty() - if verbose: - print "(master, slave) = (%d, %d)"%(master, slave) -except AttributeError: +if not hasattr(os, "openpty"): raise TestSkipped, "No openpty() available." -if not os.isatty(slave): - raise TestFailed, "Slave-end of pty is not a terminal." -os.write(slave, 'Ping!') -print os.read(master, 1024) +class OpenptyTest(unittest.TestCase): + def test(self): + master, slave = os.openpty() + if not os.isatty(slave): + self.fail("Slave-end of pty is not a terminal.") + + os.write(slave, 'Ping!') + self.assertEqual(os.read(master, 1024), 'Ping!') + +def test_main(): + run_unittest(OpenptyTest) + +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_os.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_os.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_os.py Tue Jan 9 23:27:11 2007 @@ -223,6 +223,23 @@ except TypeError: pass + def test_utime_dir(self): + delta = 1000000 + st = os.stat(test_support.TESTFN) + # round to int, because some systems may support sub-second + # time stamps in stat, but not in utime. + os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta))) + st2 = os.stat(test_support.TESTFN) + self.assertEquals(st2.st_mtime, int(st.st_mtime-delta)) + + # Restrict test to Win32, since there is no guarantee other + # systems support centiseconds + if sys.platform == 'win32': + def test_1565150(self): + t1 = 1159195039.25 + os.utime(self.fname, (t1, t1)) + self.assertEquals(os.stat(self.fname).st_mtime, t1) + from test import mapping_tests class EnvironTests(mapping_tests.BasicTestMappingProtocol): Modified: python/branches/bcannon-objcap/Lib/test/test_peepholer.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_peepholer.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_peepholer.py Tue Jan 9 23:27:11 2007 @@ -161,6 +161,41 @@ self.assert_('(None)' not in asm) self.assertEqual(asm.split().count('RETURN_VALUE'), 1) + def test_elim_jump_to_return(self): + # JUMP_FORWARD to RETURN --> RETURN + def f(cond, true_value, false_value): + return true_value if cond else false_value + asm = disassemble(f) + self.assert_('JUMP_FORWARD' not in asm) + self.assert_('JUMP_ABSOLUTE' not in asm) + self.assertEqual(asm.split().count('RETURN_VALUE'), 2) + + def test_elim_jump_after_return1(self): + # Eliminate dead code: jumps immediately after returns can't be reached + def f(cond1, cond2): + if cond1: return 1 + if cond2: return 2 + while 1: + return 3 + while 1: + if cond1: return 4 + return 5 + return 6 + asm = disassemble(f) + self.assert_('JUMP_FORWARD' not in asm) + self.assert_('JUMP_ABSOLUTE' not in asm) + self.assertEqual(asm.split().count('RETURN_VALUE'), 6) + + def test_elim_jump_after_return2(self): + # Eliminate dead code: jumps immediately after returns can't be reached + def f(cond1, cond2): + while 1: + if cond1: return 4 + asm = disassemble(f) + self.assert_('JUMP_FORWARD' not in asm) + # There should be one jump for the while loop. + self.assertEqual(asm.split().count('JUMP_ABSOLUTE'), 1) + self.assertEqual(asm.split().count('RETURN_VALUE'), 2) def test_main(verbose=None): Modified: python/branches/bcannon-objcap/Lib/test/test_poll.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_poll.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_poll.py Tue Jan 9 23:27:11 2007 @@ -1,7 +1,7 @@ # Test case for the os.poll() function -import sys, os, select, random -from test.test_support import verify, verbose, TestSkipped, TESTFN +import sys, os, select, random, unittest +from test.test_support import TestSkipped, TESTFN, run_unittest try: select.poll @@ -16,177 +16,141 @@ match.append(fd) return match -def test_poll1(): - """Basic functional test of poll object +class PollTests(unittest.TestCase): - Create a bunch of pipe and test that poll works with them. - """ - print 'Running poll test 1' - p = select.poll() - - NUM_PIPES = 12 - MSG = " This is a test." - MSG_LEN = len(MSG) - readers = [] - writers = [] - r2w = {} - w2r = {} - - for i in range(NUM_PIPES): - rd, wr = os.pipe() - p.register(rd, select.POLLIN) - p.register(wr, select.POLLOUT) - readers.append(rd) - writers.append(wr) - r2w[rd] = wr - w2r[wr] = rd - - while writers: - ready = p.poll() - ready_writers = find_ready_matching(ready, select.POLLOUT) - if not ready_writers: - raise RuntimeError, "no pipes ready for writing" - wr = random.choice(ready_writers) - os.write(wr, MSG) - - ready = p.poll() - ready_readers = find_ready_matching(ready, select.POLLIN) - if not ready_readers: - raise RuntimeError, "no pipes ready for reading" - rd = random.choice(ready_readers) - buf = os.read(rd, MSG_LEN) - verify(len(buf) == MSG_LEN) - print buf - os.close(r2w[rd]) ; os.close( rd ) - p.unregister( r2w[rd] ) - p.unregister( rd ) - writers.remove(r2w[rd]) - - poll_unit_tests() - print 'Poll test 1 complete' - -def poll_unit_tests(): - # returns NVAL for invalid file descriptor - FD = 42 - try: - os.close(FD) - except OSError: - pass - p = select.poll() - p.register(FD) - r = p.poll() - verify(r[0] == (FD, select.POLLNVAL)) - - f = open(TESTFN, 'w') - fd = f.fileno() - p = select.poll() - p.register(f) - r = p.poll() - verify(r[0][0] == fd) - f.close() - r = p.poll() - verify(r[0] == (fd, select.POLLNVAL)) - os.unlink(TESTFN) - - # type error for invalid arguments - p = select.poll() - try: - p.register(p) - except TypeError: - pass - else: - print "Bogus register call did not raise TypeError" - try: - p.unregister(p) - except TypeError: - pass - else: - print "Bogus unregister call did not raise TypeError" - - # can't unregister non-existent object - p = select.poll() - try: - p.unregister(3) - except KeyError: - pass - else: - print "Bogus unregister call did not raise KeyError" - - # Test error cases - pollster = select.poll() - class Nope: - pass - - class Almost: - def fileno(self): - return 'fileno' - - try: - pollster.register( Nope(), 0 ) - except TypeError: pass - else: print 'expected TypeError exception, not raised' - - try: - pollster.register( Almost(), 0 ) - except TypeError: pass - else: print 'expected TypeError exception, not raised' - - -# Another test case for poll(). This is copied from the test case for -# select(), modified to use poll() instead. - -def test_poll2(): - print 'Running poll test 2' - 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') - pollster = select.poll() - pollster.register( p, select.POLLIN ) - for tout in (0, 1000, 2000, 4000, 8000, 16000) + (-1,)*10: - if verbose: - print 'timeout =', tout - fdlist = pollster.poll(tout) - if (fdlist == []): - continue - fd, flags = fdlist[0] - if flags & select.POLLHUP: - line = p.readline() - if line != "": - print 'error: pipe seems to be closed, but still returns data' - continue - - elif flags & select.POLLIN: - line = p.readline() - if verbose: - print repr(line) - if not line: - if verbose: - print 'EOF' - break - continue - else: - print 'Unexpected return value from select.poll:', fdlist - p.close() - print 'Poll test 2 complete' - -def test_poll3(): - # test int overflow - print 'Running poll test 3' - pollster = select.poll() - pollster.register(1) - - try: - pollster.poll(1L << 64) - except OverflowError: - pass - else: - print 'Expected OverflowError with excessive timeout' - - x = 2 + 3 - if x != 5: - print 'Overflow must have occurred' - print 'Poll test 3 complete' - - -test_poll1() -test_poll2() -test_poll3() + def test_poll1(self): + # Basic functional test of poll object + # Create a bunch of pipe and test that poll works with them. + + p = select.poll() + + NUM_PIPES = 12 + MSG = " This is a test." + MSG_LEN = len(MSG) + readers = [] + writers = [] + r2w = {} + w2r = {} + + for i in range(NUM_PIPES): + rd, wr = os.pipe() + p.register(rd, select.POLLIN) + p.register(wr, select.POLLOUT) + readers.append(rd) + writers.append(wr) + r2w[rd] = wr + w2r[wr] = rd + + bufs = [] + + while writers: + ready = p.poll() + ready_writers = find_ready_matching(ready, select.POLLOUT) + if not ready_writers: + raise RuntimeError, "no pipes ready for writing" + wr = random.choice(ready_writers) + os.write(wr, MSG) + + ready = p.poll() + ready_readers = find_ready_matching(ready, select.POLLIN) + if not ready_readers: + raise RuntimeError, "no pipes ready for reading" + rd = random.choice(ready_readers) + buf = os.read(rd, MSG_LEN) + self.assertEqual(len(buf), MSG_LEN) + bufs.append(buf) + os.close(r2w[rd]) ; os.close( rd ) + p.unregister( r2w[rd] ) + p.unregister( rd ) + writers.remove(r2w[rd]) + + self.assertEqual(bufs, [MSG] * NUM_PIPES) + + def poll_unit_tests(self): + # returns NVAL for invalid file descriptor + FD = 42 + try: + os.close(FD) + except OSError: + pass + p = select.poll() + p.register(FD) + r = p.poll() + self.assertEqual(r[0], (FD, select.POLLNVAL)) + + f = open(TESTFN, 'w') + fd = f.fileno() + p = select.poll() + p.register(f) + r = p.poll() + self.assertEqual(r[0][0], fd) + f.close() + r = p.poll() + self.assertEqual(r[0], (fd, select.POLLNVAL)) + os.unlink(TESTFN) + + # type error for invalid arguments + p = select.poll() + self.assertRaises(TypeError, p.register, p) + self.assertRaises(TypeError, p.unregister, p) + + # can't unregister non-existent object + p = select.poll() + self.assertRaises(KeyError, p.unregister, 3) + + # Test error cases + pollster = select.poll() + class Nope: + pass + + class Almost: + def fileno(self): + return 'fileno' + + self.assertRaises(TypeError, pollster.register, Nope(), 0) + self.assertRaises(TypeError, pollster.register, Almost(), 0) + + # Another test case for poll(). This is copied from the test case for + # select(), modified to use poll() instead. + + def test_poll2(self): + 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') + pollster = select.poll() + pollster.register( p, select.POLLIN ) + for tout in (0, 1000, 2000, 4000, 8000, 16000) + (-1,)*10: + fdlist = pollster.poll(tout) + if (fdlist == []): + continue + fd, flags = fdlist[0] + if flags & select.POLLHUP: + line = p.readline() + if line != "": + self.fail('error: pipe seems to be closed, but still returns data') + continue + + elif flags & select.POLLIN: + line = p.readline() + if not line: + break + continue + else: + self.fail('Unexpected return value from select.poll: %s' % fdlist) + p.close() + + def test_poll3(self): + # test int overflow + pollster = select.poll() + pollster.register(1) + + self.assertRaises(OverflowError, pollster.poll, 1L << 64) + + x = 2 + 3 + if x != 5: + self.fail('Overflow must have occurred') + +def test_main(): + run_unittest(PollTests) + +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_pty.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_pty.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_pty.py Tue Jan 9 23:27:11 2007 @@ -115,6 +115,12 @@ os._exit(4) else: debug("Waiting for child (%d) to finish."%pid) + ##line = os.read(master_fd, 80) + ##lines = line.replace('\r\n', '\n').split('\n') + ##if False and lines != ['In child, calling os.setsid()', + ## 'Good: OSError was raised.', '']: + ## raise TestFailed("Unexpected output from child: %r" % line) + (pid, status) = os.waitpid(pid, 0) res = status >> 8 debug("Child (%d) exited with status %d (%d)."%(pid, res, status)) @@ -127,6 +133,15 @@ elif res != 4: raise TestFailed, "pty.fork() failed for unknown reasons." + ##debug("Reading from master_fd now that the child has exited") + ##try: + ## s1 = os.read(master_fd, 1024) + ##except os.error: + ## pass + ##else: + ## raise TestFailed("Read from master_fd did not raise exception") + + os.close(master_fd) # pty.fork() passed. Modified: python/branches/bcannon-objcap/Lib/test/test_pyclbr.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_pyclbr.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_pyclbr.py Tue Jan 9 23:27:11 2007 @@ -93,6 +93,9 @@ py_item = getattr(module, name) if isinstance(value, pyclbr.Function): self.assert_(isinstance(py_item, (FunctionType, BuiltinFunctionType))) + if py_item.__module__ != moduleName: + continue # skip functions that came from somewhere else + self.assertEquals(py_item.__module__, value.module) else: self.failUnless(isinstance(py_item, (ClassType, type))) if py_item.__module__ != moduleName: Modified: python/branches/bcannon-objcap/Lib/test/test_random.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_random.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_random.py Tue Jan 9 23:27:11 2007 @@ -178,10 +178,9 @@ def test_bigrand(self): # Verify warnings are raised when randrange is too large for random() - oldfilters = warnings.filters[:] - warnings.filterwarnings("error", "Underlying random") - self.assertRaises(UserWarning, self.gen.randrange, 2**60) - warnings.filters[:] = oldfilters + with test_support.guard_warnings_filter(): + warnings.filterwarnings("error", "Underlying random") + self.assertRaises(UserWarning, self.gen.randrange, 2**60) class SystemRandom_TestBasicOps(TestBasicOps): gen = random.SystemRandom() @@ -439,6 +438,14 @@ self.assertEqual(k, numbits) # note the stronger assertion self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion + def test_randrange_bug_1590891(self): + start = 1000000000000 + stop = -100000000000000000000 + step = -200 + x = self.gen.randrange(start, stop, step) + self.assert_(stop < x <= start) + self.assertEqual((x+stop)%step, 0) + _gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289, 771.3234287757674, -176.6150291498386, 12.50734324009056, -0.1385710331296526, 0.9934937113930748e-05, 0.1659470187408462e-06) Modified: python/branches/bcannon-objcap/Lib/test/test_repr.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_repr.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_repr.py Tue Jan 9 23:27:11 2007 @@ -136,7 +136,6 @@ '") warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "") -print "1. simple nesting" +class ScopeTests(unittest.TestCase): -def make_adder(x): - def adder(y): - return x + y - return adder + def testSimpleNesting(self): -inc = make_adder(1) -plus10 = make_adder(10) + def make_adder(x): + def adder(y): + return x + y + return adder -vereq(inc(1), 2) -vereq(plus10(-2), 8) + inc = make_adder(1) + plus10 = make_adder(10) -print "2. extra nesting" + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(-2), 8) -def make_adder2(x): - def extra(): # check freevars passing through non-use scopes - def adder(y): - return x + y - return adder - return extra() + def testExtraNesting(self): -inc = make_adder2(1) -plus10 = make_adder2(10) + def make_adder2(x): + def extra(): # check freevars passing through non-use scopes + def adder(y): + return x + y + return adder + return extra() -vereq(inc(1), 2) -vereq(plus10(-2), 8) + inc = make_adder2(1) + plus10 = make_adder2(10) -print "3. simple nesting + rebinding" + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(-2), 8) -def make_adder3(x): - def adder(y): - return x + y - x = x + 1 # check tracking of assignment to x in defining scope - return adder + def testSimpleAndRebinding(self): -inc = make_adder3(0) -plus10 = make_adder3(9) + def make_adder3(x): + def adder(y): + return x + y + x = x + 1 # check tracking of assignment to x in defining scope + return adder -vereq(inc(1), 2) -vereq(plus10(-2), 8) + inc = make_adder3(0) + plus10 = make_adder3(9) -print "4. nesting with global but no free" + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(-2), 8) -def make_adder4(): # XXX add exta level of indirection - def nest(): - def nest(): - def adder(y): - return global_x + y # check that plain old globals work - return adder - return nest() - return nest() + def testNestingGlobalNoFree(self): -global_x = 1 -adder = make_adder4() -vereq(adder(1), 2) + def make_adder4(): # XXX add exta level of indirection + def nest(): + def nest(): + def adder(y): + return global_x + y # check that plain old globals work + return adder + return nest() + return nest() -global_x = 10 -vereq(adder(-2), 8) + global_x = 1 + adder = make_adder4() + self.assertEqual(adder(1), 2) -print "5. nesting through class" + global_x = 10 + self.assertEqual(adder(-2), 8) -def make_adder5(x): - class Adder: - def __call__(self, y): - return x + y - return Adder() + def testNestingThroughClass(self): -inc = make_adder5(1) -plus10 = make_adder5(10) + def make_adder5(x): + class Adder: + def __call__(self, y): + return x + y + return Adder() -vereq(inc(1), 2) -vereq(plus10(-2), 8) + inc = make_adder5(1) + plus10 = make_adder5(10) -print "6. nesting plus free ref to global" + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(-2), 8) -def make_adder6(x): - global global_nest_x - def adder(y): - return global_nest_x + y - global_nest_x = x - return adder + def testNestingPlusFreeRefToGlobal(self): -inc = make_adder6(1) -plus10 = make_adder6(10) + def make_adder6(x): + global global_nest_x + def adder(y): + return global_nest_x + y + global_nest_x = x + return adder -vereq(inc(1), 11) # there's only one global -vereq(plus10(-2), 8) + inc = make_adder6(1) + plus10 = make_adder6(10) -print "7. nearest enclosing scope" + self.assertEqual(inc(1), 11) # there's only one global + self.assertEqual(plus10(-2), 8) -def f(x): - def g(y): - x = 42 # check that this masks binding in f() - def h(z): - return x + z - return h - return g(2) - -test_func = f(10) -vereq(test_func(5), 47) - -print "8. mixed freevars and cellvars" - -def identity(x): - return x - -def f(x, y, z): - def g(a, b, c): - a = a + x # 3 - def h(): - # z * (4 + 9) - # 3 * 13 - return identity(z * (b + y)) - y = c + z # 9 - return h - return g - -g = f(1, 2, 3) -h = g(2, 4, 6) -vereq(h(), 39) - -print "9. free variable in method" - -def test(): - method_and_var = "var" - class Test: - def method_and_var(self): - return "method" - def test(self): - return method_and_var - def actual_global(self): - return str("global") - def str(self): - return str(self) - return Test() - -t = test() -vereq(t.test(), "var") -vereq(t.method_and_var(), "method") -vereq(t.actual_global(), "global") - -method_and_var = "var" -class Test: - # this class is not nested, so the rules are different - def method_and_var(self): - return "method" - def test(self): - return method_and_var - def actual_global(self): - return str("global") - def str(self): - return str(self) - -t = Test() -vereq(t.test(), "var") -vereq(t.method_and_var(), "method") -vereq(t.actual_global(), "global") + def testNearestEnclosingScope(self): -print "10. recursion" + def f(x): + def g(y): + x = 42 # check that this masks binding in f() + def h(z): + return x + z + return h + return g(2) -def f(x): - def fact(n): - if n == 0: - return 1 - else: - return n * fact(n - 1) - if x >= 0: - return fact(x) - else: - raise ValueError, "x must be >= 0" + test_func = f(10) + self.assertEqual(test_func(5), 47) -vereq(f(6), 720) + def testMixedFreevarsAndCellvars(self): + def identity(x): + return x + + def f(x, y, z): + def g(a, b, c): + a = a + x # 3 + def h(): + # z * (4 + 9) + # 3 * 13 + return identity(z * (b + y)) + y = c + z # 9 + return h + return g + + g = f(1, 2, 3) + h = g(2, 4, 6) + self.assertEqual(h(), 39) + + def testFreeVarInMethod(self): + + def test(): + method_and_var = "var" + class Test: + def method_and_var(self): + return "method" + def test(self): + return method_and_var + def actual_global(self): + return str("global") + def str(self): + return str(self) + return Test() + + t = test() + self.assertEqual(t.test(), "var") + self.assertEqual(t.method_and_var(), "method") + self.assertEqual(t.actual_global(), "global") + + method_and_var = "var" + class Test: + # this class is not nested, so the rules are different + def method_and_var(self): + return "method" + def test(self): + return method_and_var + def actual_global(self): + return str("global") + def str(self): + return str(self) + + t = Test() + self.assertEqual(t.test(), "var") + self.assertEqual(t.method_and_var(), "method") + self.assertEqual(t.actual_global(), "global") + + def testRecursion(self): + + def f(x): + def fact(n): + if n == 0: + return 1 + else: + return n * fact(n - 1) + if x >= 0: + return fact(x) + else: + raise ValueError, "x must be >= 0" + + self.assertEqual(f(6), 720) -print "11. unoptimized namespaces" -check_syntax("""\ + def testUnoptimizedNamespaces(self): + + check_syntax_error(self, """\ def unoptimized_clash1(strip): def f(s): from string import * @@ -188,7 +192,7 @@ return f """) -check_syntax("""\ + check_syntax_error(self, """\ def unoptimized_clash2(): from string import * def f(s): @@ -196,7 +200,7 @@ return f """) -check_syntax("""\ + check_syntax_error(self, """\ def unoptimized_clash2(): from string import * def g(): @@ -205,8 +209,8 @@ return f """) -# XXX could allow this for exec with const argument, but what's the point -check_syntax("""\ + # XXX could allow this for exec with const argument, but what's the point + check_syntax_error(self, """\ def error(y): exec "a = 1" def f(x): @@ -214,23 +218,23 @@ return f """) -check_syntax("""\ + check_syntax_error(self, """\ def f(x): def g(): return x del x # can't del name """) -check_syntax("""\ + check_syntax_error(self, """\ def f(): def g(): - from string import * - return strip # global or local? + from string import * + return strip # global or local? """) -# and verify a few cases that should work + # and verify a few cases that should work -exec """ + exec """ def noproblem1(): from string import * f = lambda x:x @@ -247,59 +251,60 @@ y = x """ -print "12. lambdas" - -f1 = lambda x: lambda y: x + y -inc = f1(1) -plus10 = f1(10) -vereq(inc(1), 2) -vereq(plus10(5), 15) - -f2 = lambda x: (lambda : lambda y: x + y)() -inc = f2(1) -plus10 = f2(10) -vereq(inc(1), 2) -vereq(plus10(5), 15) - -f3 = lambda x: lambda y: global_x + y -global_x = 1 -inc = f3(None) -vereq(inc(2), 3) - -f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y) -g = f8(1, 2, 3) -h = g(2, 4, 6) -vereq(h(), 18) - -print "13. UnboundLocal" - -def errorInOuter(): - print y - def inner(): - return y - y = 1 - -def errorInInner(): - def inner(): - return y - inner() - y = 1 + def testLambdas(self): -try: - errorInOuter() -except UnboundLocalError: - pass -else: - raise TestFailed + f1 = lambda x: lambda y: x + y + inc = f1(1) + plus10 = f1(10) + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(5), 15) + + f2 = lambda x: (lambda : lambda y: x + y)() + inc = f2(1) + plus10 = f2(10) + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(5), 15) + + f3 = lambda x: lambda y: global_x + y + global_x = 1 + inc = f3(None) + self.assertEqual(inc(2), 3) + + f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y) + g = f8(1, 2, 3) + h = g(2, 4, 6) + self.assertEqual(h(), 18) + + def testUnboundLocal(self): + + def errorInOuter(): + print y + def inner(): + return y + y = 1 + + def errorInInner(): + def inner(): + return y + inner() + y = 1 + + try: + errorInOuter() + except UnboundLocalError: + pass + else: + self.fail() -try: - errorInInner() -except NameError: - pass -else: - raise TestFailed + try: + errorInInner() + except NameError: + pass + else: + self.fail() -# test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation + # test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation + exec """ global_x = 1 def f(): global_x += 1 @@ -308,34 +313,36 @@ except UnboundLocalError: pass else: - raise TestFailed, 'scope of global_x not correctly determined' + fail('scope of global_x not correctly determined') +""" in {'fail': self.fail} -print "14. complex definitions" + def testComplexDefinitions(self): -def makeReturner(*lst): - def returner(): - return lst - return returner + def makeReturner(*lst): + def returner(): + return lst + return returner -vereq(makeReturner(1,2,3)(), (1,2,3)) + self.assertEqual(makeReturner(1,2,3)(), (1,2,3)) -def makeReturner2(**kwargs): - def returner(): - return kwargs - return returner + def makeReturner2(**kwargs): + def returner(): + return kwargs + return returner -vereq(makeReturner2(a=11)()['a'], 11) + self.assertEqual(makeReturner2(a=11)()['a'], 11) -def makeAddPair((a, b)): - def addPair((c, d)): - return (a + c, b + d) - return addPair + def makeAddPair((a, b)): + def addPair((c, d)): + return (a + c, b + d) + return addPair -vereq(makeAddPair((1, 2))((100, 200)), (101,202)) + self.assertEqual(makeAddPair((1, 2))((100, 200)), (101,202)) -print "15. scope of global statements" + def testScopeOfGlobalStmt(self): # Examples posted by Samuele Pedroni to python-dev on 3/1/2001 + exec """\ # I x = 7 def f(): @@ -348,8 +355,8 @@ return h() return i() return g() -vereq(f(), 7) -vereq(x, 7) +self.assertEqual(f(), 7) +self.assertEqual(x, 7) # II x = 7 @@ -363,8 +370,8 @@ return h() return i() return g() -vereq(f(), 2) -vereq(x, 7) +self.assertEqual(f(), 2) +self.assertEqual(x, 7) # III x = 7 @@ -379,8 +386,8 @@ return h() return i() return g() -vereq(f(), 2) -vereq(x, 2) +self.assertEqual(f(), 2) +self.assertEqual(x, 2) # IV x = 7 @@ -395,8 +402,8 @@ return h() return i() return g() -vereq(f(), 2) -vereq(x, 2) +self.assertEqual(f(), 2) +self.assertEqual(x, 2) # XXX what about global statements in class blocks? # do they affect methods? @@ -411,34 +418,36 @@ return x g = Global() -vereq(g.get(), 13) +self.assertEqual(g.get(), 13) g.set(15) -vereq(g.get(), 13) +self.assertEqual(g.get(), 13) +""" -print "16. check leaks" + def testLeaks(self): -class Foo: - count = 0 + class Foo: + count = 0 - def __init__(self): - Foo.count += 1 + def __init__(self): + Foo.count += 1 - def __del__(self): - Foo.count -= 1 + def __del__(self): + Foo.count -= 1 -def f1(): - x = Foo() - def f2(): - return x - f2() + def f1(): + x = Foo() + def f2(): + return x + f2() -for i in range(100): - f1() + for i in range(100): + f1() -vereq(Foo.count, 0) + self.assertEqual(Foo.count, 0) -print "17. class and global" + def testClassAndGlobal(self): + exec """\ def test(x): class Foo: global x @@ -447,9 +456,9 @@ return Foo() x = 0 -vereq(test(6)(2), 8) +self.assertEqual(test(6)(2), 8) x = -1 -vereq(test(3)(2), 5) +self.assertEqual(test(3)(2), 5) looked_up_by_load_name = False class X: @@ -458,104 +467,106 @@ locals()['looked_up_by_load_name'] = True passed = looked_up_by_load_name -verify(X.passed) - -print "18. verify that locals() works" - -def f(x): - def g(y): - def h(z): - return y + z - w = x + y - y += 3 - return locals() - return g - -d = f(2)(4) -verify(d.has_key('h')) -del d['h'] -vereq(d, {'x': 2, 'y': 7, 'w': 6}) - -print "19. var is bound and free in class" - -def f(x): - class C: - def m(self): - return x - a = x - return C - -inst = f(3)() -vereq(inst.a, inst.m()) - -print "20. interaction with trace function" - -import sys -def tracer(a,b,c): - return tracer - -def adaptgetter(name, klass, getter): - kind, des = getter - if kind == 1: # AV happens when stepping from this line to next - if des == "": - des = "_%s__%s" % (klass.__name__, name) - return lambda obj: getattr(obj, des) - -class TestClass: - pass +self.assert_(X.passed) +""" -sys.settrace(tracer) -adaptgetter("foo", TestClass, (1, "")) -sys.settrace(None) - -try: sys.settrace() -except TypeError: pass -else: raise TestFailed, 'sys.settrace() did not raise TypeError' + def testLocalsFunction(self): -print "20. eval and exec with free variables" + def f(x): + def g(y): + def h(z): + return y + z + w = x + y + y += 3 + return locals() + return g + + d = f(2)(4) + self.assert_(d.has_key('h')) + del d['h'] + self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) + + def testBoundAndFree(self): + # var is bound and free in class + + def f(x): + class C: + def m(self): + return x + a = x + return C + + inst = f(3)() + self.assertEqual(inst.a, inst.m()) + + def testInteractionWithTraceFunc(self): + + import sys + def tracer(a,b,c): + return tracer + + def adaptgetter(name, klass, getter): + kind, des = getter + if kind == 1: # AV happens when stepping from this line to next + if des == "": + des = "_%s__%s" % (klass.__name__, name) + return lambda obj: getattr(obj, des) + + class TestClass: + pass + + sys.settrace(tracer) + adaptgetter("foo", TestClass, (1, "")) + sys.settrace(None) + + self.assertRaises(TypeError, sys.settrace) + + def testEvalExecFreeVars(self): + + def f(x): + return lambda: x + 1 + + g = f(3) + self.assertRaises(TypeError, eval, g.func_code) + + try: + exec g.func_code in {} + except TypeError: + pass + else: + self.fail("exec should have failed, because code contained free vars") -def f(x): - return lambda: x + 1 + def testListCompLocalVars(self): -g = f(3) -try: - eval(g.func_code) -except TypeError: - pass -else: - print "eval() should have failed, because code contained free vars" + try: + print bad + except NameError: + pass + else: + print "bad should not be defined" -try: - exec g.func_code -except TypeError: - pass -else: - print "exec should have failed, because code contained free vars" + def x(): + [bad for s in 'a b' for bad in s.split()] -print "21. list comprehension with local variables" + x() + try: + print bad + except NameError: + pass -try: - print bad -except NameError: - pass -else: - print "bad should not be defined" + def testEvalFreeVars(self): -def x(): - [bad for s in 'a b' for bad in s.split()] + def f(x): + def g(): + x + eval("x + 1") + return g -x() -try: - print bad -except NameError: - pass + f(4)() -print "22. eval with free variables" -def f(x): - def g(): - x - eval("x + 1") - return g +def test_main(): + run_unittest(ScopeTests) -f(4)() +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_set.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_set.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_set.py Tue Jan 9 23:27:11 2007 @@ -21,6 +21,11 @@ def __cmp__(self, other): raise RuntimeError +class ReprWrapper: + 'Used to test self-referential repr() calls' + def __repr__(self): + return repr(self.value) + class TestJointOps(unittest.TestCase): # Tests common to both set and frozenset @@ -244,6 +249,27 @@ self.assertRaises(RuntimeError, s.discard, BadCmp()) self.assertRaises(RuntimeError, s.remove, BadCmp()) + def test_cyclical_repr(self): + w = ReprWrapper() + s = self.thetype([w]) + w.value = s + name = repr(s).partition('(')[0] # strip class name from repr string + self.assertEqual(repr(s), '%s([%s(...)])' % (name, name)) + + def test_cyclical_print(self): + w = ReprWrapper() + s = self.thetype([w]) + w.value = s + try: + fo = open(test_support.TESTFN, "wb") + print >> fo, s, + fo.close() + fo = open(test_support.TESTFN, "rb") + self.assertEqual(fo.read(), repr(s)) + finally: + fo.close() + os.remove(test_support.TESTFN) + class TestSet(TestJointOps): thetype = set @@ -293,6 +319,17 @@ self.assert_(self.thetype(self.word) not in s) self.assertRaises(KeyError, self.s.remove, self.thetype(self.word)) + def test_remove_keyerror_unpacking(self): + # bug: www.python.org/sf/1576657 + for v1 in ['Q', (1,)]: + try: + self.s.remove(v1) + except KeyError, e: + v2 = e.args[0] + self.assertEqual(v1, v2) + else: + self.fail() + def test_discard(self): self.s.discard('a') self.assert_('a' not in self.s) Modified: python/branches/bcannon-objcap/Lib/test/test_sha.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_sha.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_sha.py Tue Jan 9 23:27:11 2007 @@ -11,9 +11,23 @@ class SHATestCase(unittest.TestCase): def check(self, data, digest): - computed = sha.new(data).hexdigest() + # Check digest matches the expected value + obj = sha.new(data) + computed = obj.hexdigest() self.assert_(computed == digest) + # Verify that the value doesn't change between two consecutive + # digest operations. + computed_again = obj.hexdigest() + self.assert_(computed == computed_again) + + # Check hexdigest() output matches digest()'s output + digest = obj.digest() + hexd = "" + for c in digest: + hexd += '%02x' % ord(c) + self.assert_(computed == hexd) + def test_case_1(self): self.check("abc", "a9993e364706816aba3e25717850c26c9cd0d89d") @@ -26,6 +40,9 @@ self.check("a" * 1000000, "34aa973cd4c4daa4f61eeb2bdbad27316534016f") + def test_case_4(self): + self.check(chr(0xAA) * 80, + '4ca0ef38f1794b28a8f8ee110ee79d48ce13be25') def test_main(): test_support.run_unittest(SHATestCase) Modified: python/branches/bcannon-objcap/Lib/test/test_struct.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_struct.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_struct.py Tue Jan 9 23:27:11 2007 @@ -50,22 +50,17 @@ def with_warning_restore(func): def _with_warning_restore(*args, **kw): - # The `warnings` module doesn't have an advertised way to restore - # its filter list. Cheat. - save_warnings_filters = warnings.filters[:] - # Grrr, we need this function to warn every time. Without removing - # the warningregistry, running test_tarfile then test_struct would fail - # on 64-bit platforms. - globals = func.func_globals - if '__warningregistry__' in globals: - del globals['__warningregistry__'] - warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) - warnings.filterwarnings("error", r""".*format requires.*""", - DeprecationWarning) - try: + with test.test_support.guard_warnings_filter(): + # Grrr, we need this function to warn every time. Without removing + # the warningregistry, running test_tarfile then test_struct would fail + # on 64-bit platforms. + globals = func.func_globals + if '__warningregistry__' in globals: + del globals['__warningregistry__'] + warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) + warnings.filterwarnings("error", r""".*format requires.*""", + DeprecationWarning) return func(*args, **kw) - finally: - warnings.filters[:] = save_warnings_filters[:] return _with_warning_restore def deprecated_err(func, *args): Modified: python/branches/bcannon-objcap/Lib/test/test_support.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_support.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_support.py Tue Jan 9 23:27:11 2007 @@ -3,7 +3,9 @@ if __name__ != 'test.test_support': raise ImportError, 'test_support must be imported from the test package' +from contextlib import contextmanager import sys +import warnings class Error(Exception): """Base class for regression test exceptions.""" @@ -245,13 +247,13 @@ withcommas = ", ".join(reprpairs) return "{%s}" % withcommas -def check_syntax(statement): +def check_syntax_error(testcase, statement): try: - compile(statement, '', 'exec') + compile(statement, '', 'exec') except SyntaxError: pass else: - print 'Missing SyntaxError: "%s"' % statement + testcase.fail('Missing SyntaxError: "%s"' % statement) def open_urlresource(url): import urllib, urlparse @@ -268,6 +270,48 @@ print >> get_original_stdout(), '\tfetching %s ...' % url fn, _ = urllib.urlretrieve(url, filename) return open(fn) + + at contextmanager +def guard_warnings_filter(): + """Guard the warnings filter from being permanently changed.""" + original_filters = warnings.filters[:] + try: + yield + finally: + warnings.filters = original_filters + +class EnvironmentVarGuard(object): + + """Class to help protect the environment variable properly. Can be used as + a context manager.""" + + def __init__(self): + from os import environ + self._environ = environ + self._unset = set() + self._reset = dict() + + def set(self, envvar, value): + if envvar not in self._environ: + self._unset.add(envvar) + else: + self._reset[envvar] = self._environ[envvar] + self._environ[envvar] = value + + def unset(self, envvar): + if envvar in self._environ: + self._reset[envvar] = self._environ[envvar] + del self._environ[envvar] + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + for envvar, value in self._reset.iteritems(): + self._environ[envvar] = value + for unset in self._unset: + del self._environ[unset] + #======================================================================= # Decorator for running a function in a different locale, correctly resetting Modified: python/branches/bcannon-objcap/Lib/test/test_syntax.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_syntax.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_syntax.py Tue Jan 9 23:27:11 2007 @@ -322,6 +322,51 @@ ... SyntaxError: 'continue' not supported inside 'finally' clause (, line 8) +There is one test for a break that is not in a loop. The compiler +uses a single data structure to keep track of try-finally and loops, +so we need to be sure that a break is actually inside a loop. If it +isn't, there should be a syntax error. + + >>> try: + ... print 1 + ... break + ... print 2 + ... finally: + ... print 3 + Traceback (most recent call last): + ... + SyntaxError: 'break' outside loop (, line 3) + +This should probably raise a better error than a SystemError (or none at all). +In 2.5 there was a missing exception and an assert was triggered in a debug +build. The number of blocks must be greater than CO_MAXBLOCKS. SF #1565514 + + >>> while 1: + ... while 2: + ... while 3: + ... while 4: + ... while 5: + ... while 6: + ... while 8: + ... while 9: + ... while 10: + ... while 11: + ... while 12: + ... while 13: + ... while 14: + ... while 15: + ... while 16: + ... while 17: + ... while 18: + ... while 19: + ... while 20: + ... while 21: + ... while 22: + ... break + Traceback (most recent call last): + ... + SystemError: too many statically nested blocks + """ import re Modified: python/branches/bcannon-objcap/Lib/test/test_tarfile.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_tarfile.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_tarfile.py Tue Jan 9 23:27:11 2007 @@ -110,7 +110,7 @@ """Test seek() method of _FileObject, incl. random reading. """ if self.sep != "|": - filename = "0-REGTYPE" + filename = "0-REGTYPE-TEXT" self.tar.extract(filename, dirname()) f = open(os.path.join(dirname(), filename), "rb") data = f.read() @@ -149,6 +149,16 @@ s2 = fobj.readlines() self.assert_(s1 == s2, "readlines() after seek failed") + fobj.seek(0) + self.assert_(len(fobj.readline()) == fobj.tell(), + "tell() after readline() failed") + fobj.seek(512) + self.assert_(len(fobj.readline()) + 512 == fobj.tell(), + "tell() after seek() and readline() failed") + fobj.seek(0) + line = fobj.readline() + self.assert_(fobj.read() == data[len(line):], + "read() after readline() failed") fobj.close() def test_old_dirtype(self): @@ -280,6 +290,46 @@ else: self.dst.addfile(tarinfo, f) + def test_add_self(self): + dstname = os.path.abspath(self.dstname) + + self.assertEqual(self.dst.name, dstname, "archive name must be absolute") + + self.dst.add(dstname) + self.assertEqual(self.dst.getnames(), [], "added the archive to itself") + + cwd = os.getcwd() + os.chdir(dirname()) + self.dst.add(dstname) + os.chdir(cwd) + self.assertEqual(self.dst.getnames(), [], "added the archive to itself") + + +class Write100Test(BaseTest): + # The name field in a tar header stores strings of at most 100 chars. + # If a string is shorter than 100 chars it has to be padded with '\0', + # which implies that a string of exactly 100 chars is stored without + # a trailing '\0'. + + def setUp(self): + self.name = "01234567890123456789012345678901234567890123456789" + self.name += "01234567890123456789012345678901234567890123456789" + + self.tar = tarfile.open(tmpname(), "w") + t = tarfile.TarInfo(self.name) + self.tar.addfile(t) + self.tar.close() + + self.tar = tarfile.open(tmpname()) + + def tearDown(self): + self.tar.close() + + def test(self): + self.assertEqual(self.tar.getnames()[0], self.name, + "failed to store 100 char filename") + + class WriteSize0Test(BaseTest): mode = 'w' @@ -362,13 +412,6 @@ is tested as well. """ - def setUp(self): - self.tar = tarfile.open(tmpname(), "w") - self.tar.posix = False - - def tearDown(self): - self.tar.close() - def _length(self, s): blocks, remainder = divmod(len(s) + 1, 512) if remainder: @@ -397,12 +440,23 @@ tarinfo.linkname = link tarinfo.type = tarfile.LNKTYPE - self.tar.addfile(tarinfo) + tar = tarfile.open(tmpname(), "w") + tar.posix = False + tar.addfile(tarinfo) v1 = self._calc_size(name, link) - v2 = self.tar.offset + v2 = tar.offset self.assertEqual(v1, v2, "GNU longname/longlink creation failed") + tar.close() + + tar = tarfile.open(tmpname()) + member = tar.next() + self.failIf(member is None, "unable to read longname member") + self.assert_(tarinfo.name == member.name and \ + tarinfo.linkname == member.linkname, \ + "unable to read longname member") + def test_longname_1023(self): self._test(("longnam/" * 127) + "longnam") @@ -571,6 +625,38 @@ self.assertEqual(tarfile.filemode(0755), '-rwxr-xr-x') self.assertEqual(tarfile.filemode(07111), '---s--s--t') +class HeaderErrorTest(unittest.TestCase): + + def test_truncated_header(self): + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "") + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "filename\0") + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 511) + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 513) + + def test_empty_header(self): + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 512) + + def test_invalid_header(self): + buf = tarfile.TarInfo("filename").tobuf() + buf = buf[:148] + "foo\0\0\0\0\0" + buf[156:] # invalid number field. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, buf) + + def test_bad_checksum(self): + buf = tarfile.TarInfo("filename").tobuf() + b = buf[:148] + " " + buf[156:] # clear the checksum field. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b) + b = "a" + buf[1:] # manipulate the buffer, so checksum won't match. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b) + +class OpenFileobjTest(BaseTest): + # Test for SF bug #1496501. + + def test_opener(self): + fobj = StringIO.StringIO("foo\n") + try: + tarfile.open("", "r", fileobj=fobj) + except tarfile.ReadError: + self.assertEqual(fobj.tell(), 0, "fileobj's position has moved") if bz2: # Bzip2 TestCases @@ -616,6 +702,8 @@ tests = [ FileModeTest, + HeaderErrorTest, + OpenFileobjTest, ReadTest, ReadStreamTest, ReadDetectTest, @@ -623,6 +711,7 @@ ReadAsteriskTest, ReadStreamAsteriskTest, WriteTest, + Write100Test, WriteSize0Test, WriteStreamTest, WriteGNULongTest, Modified: python/branches/bcannon-objcap/Lib/test/test_types.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_types.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_types.py Tue Jan 9 23:27:11 2007 @@ -1,286 +1,273 @@ # Python test set -- part 6, built-in types -from test.test_support import * +from test.test_support import run_unittest, have_unicode +import unittest +import sys -print '6. Built-in types' +class TypesTests(unittest.TestCase): -print '6.1 Truth value testing' -if None: raise TestFailed, 'None is true instead of false' -if 0: raise TestFailed, '0 is true instead of false' -if 0L: raise TestFailed, '0L is true instead of false' -if 0.0: raise TestFailed, '0.0 is true instead of false' -if '': raise TestFailed, '\'\' is true instead of false' -if not 1: raise TestFailed, '1 is false instead of true' -if not 1L: raise TestFailed, '1L is false instead of true' -if not 1.0: raise TestFailed, '1.0 is false instead of true' -if not 'x': raise TestFailed, '\'x\' is false instead of true' -if not {'x': 1}: raise TestFailed, '{\'x\': 1} is false instead of true' -def f(): pass -class C: pass -import sys -x = C() -if not f: raise TestFailed, 'f is false instead of true' -if not C: raise TestFailed, 'C is false instead of true' -if not sys: raise TestFailed, 'sys is false instead of true' -if not x: raise TestFailed, 'x is false instead of true' - -print '6.2 Boolean operations' -if 0 or 0: raise TestFailed, '0 or 0 is true instead of false' -if 1 and 1: pass -else: raise TestFailed, '1 and 1 is false instead of true' -if not 1: raise TestFailed, 'not 1 is true instead of false' - -print '6.3 Comparisons' -if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass -else: raise TestFailed, 'int comparisons failed' -if 0L < 1L <= 1L == 1L >= 1L > 0L != 1L: pass -else: raise TestFailed, 'long int comparisons failed' -if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass -else: raise TestFailed, 'float comparisons failed' -if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass -else: raise TestFailed, 'string comparisons failed' -if None is None: pass -else: raise TestFailed, 'identity test failed' - -try: float('') -except ValueError: pass -else: raise TestFailed, "float('') didn't raise ValueError" - -try: float('5\0') -except ValueError: pass -else: raise TestFailed, "float('5\0') didn't raise ValueError" - -try: 5.0 / 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 / 0.0 didn't raise ZeroDivisionError" - -try: 5.0 // 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 // 0.0 didn't raise ZeroDivisionError" - -try: 5.0 % 0.0 -except ZeroDivisionError: pass -else: raise TestFailed, "5.0 % 0.0 didn't raise ZeroDivisionError" - -try: 5 / 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 / 0L didn't raise ZeroDivisionError" - -try: 5 // 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 // 0L didn't raise ZeroDivisionError" - -try: 5 % 0L -except ZeroDivisionError: pass -else: raise TestFailed, "5 % 0L didn't raise ZeroDivisionError" - -print '6.4 Numeric types (mostly conversions)' -if 0 != 0L or 0 != 0.0 or 0L != 0.0: raise TestFailed, 'mixed comparisons' -if 1 != 1L or 1 != 1.0 or 1L != 1.0: raise TestFailed, 'mixed comparisons' -if -1 != -1L or -1 != -1.0 or -1L != -1.0: - raise TestFailed, 'int/long/float value not equal' -# calling built-in types without argument must return 0 -if int() != 0: raise TestFailed, 'int() does not return 0' -if long() != 0L: raise TestFailed, 'long() does not return 0L' -if float() != 0.0: raise TestFailed, 'float() does not return 0.0' -if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass -else: raise TestFailed, 'int() does not round properly' -if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass -else: raise TestFailed, 'long() does not round properly' -if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass -else: raise TestFailed, 'float() does not work properly' -print '6.4.1 32-bit integers' -# Ensure the first 256 integers are shared -a = 256 -b = 128*2 -if a is not b: raise TestFailed, '256 is not shared' -if 12 + 24 != 36: raise TestFailed, 'int op' -if 12 + (-24) != -12: raise TestFailed, 'int op' -if (-12) + 24 != 12: raise TestFailed, 'int op' -if (-12) + (-24) != -36: raise TestFailed, 'int op' -if not 12 < 24: raise TestFailed, 'int op' -if not -24 < -12: raise TestFailed, 'int op' -# Test for a particular bug in integer multiply -xsize, ysize, zsize = 238, 356, 4 -if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912): - raise TestFailed, 'int mul commutativity' -# And another. -m = -sys.maxint - 1 -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor - prod = divisor * j - if prod != m: - raise TestFailed, "%r * %r == %r != %r" % (divisor, j, prod, m) - if type(prod) is not int: - raise TestFailed, ("expected type(prod) to be int, not %r" % - type(prod)) -# Check for expected * overflow to long. -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor - 1 - prod = divisor * j - if type(prod) is not long: - raise TestFailed, ("expected type(%r) to be long, not %r" % - (prod, type(prod))) -# Check for expected * overflow to long. -m = sys.maxint -for divisor in 1, 2, 4, 8, 16, 32: - j = m // divisor + 1 - prod = divisor * j - if type(prod) is not long: - raise TestFailed, ("expected type(%r) to be long, not %r" % - (prod, type(prod))) - -print '6.4.2 Long integers' -if 12L + 24L != 36L: raise TestFailed, 'long op' -if 12L + (-24L) != -12L: raise TestFailed, 'long op' -if (-12L) + 24L != 12L: raise TestFailed, 'long op' -if (-12L) + (-24L) != -36L: raise TestFailed, 'long op' -if not 12L < 24L: raise TestFailed, 'long op' -if not -24L < -12L: raise TestFailed, 'long op' -x = sys.maxint -if int(long(x)) != x: raise TestFailed, 'long op' -try: y = int(long(x)+1L) -except OverflowError: raise TestFailed, 'long op' -if not isinstance(y, long): raise TestFailed, 'long op' -x = -x -if int(long(x)) != x: raise TestFailed, 'long op' -x = x-1 -if int(long(x)) != x: raise TestFailed, 'long op' -try: y = int(long(x)-1L) -except OverflowError: raise TestFailed, 'long op' -if not isinstance(y, long): raise TestFailed, 'long op' - -try: 5 << -5 -except ValueError: pass -else: raise TestFailed, 'int negative shift <<' - -try: 5L << -5L -except ValueError: pass -else: raise TestFailed, 'long negative shift <<' - -try: 5 >> -5 -except ValueError: pass -else: raise TestFailed, 'int negative shift >>' - -try: 5L >> -5L -except ValueError: pass -else: raise TestFailed, 'long negative shift >>' - -print '6.4.3 Floating point numbers' -if 12.0 + 24.0 != 36.0: raise TestFailed, 'float op' -if 12.0 + (-24.0) != -12.0: raise TestFailed, 'float op' -if (-12.0) + 24.0 != 12.0: raise TestFailed, 'float op' -if (-12.0) + (-24.0) != -36.0: raise TestFailed, 'float op' -if not 12.0 < 24.0: raise TestFailed, 'float op' -if not -24.0 < -12.0: raise TestFailed, 'float op' - -print '6.5 Sequence types' - -print '6.5.1 Strings' -if len('') != 0: raise TestFailed, 'len(\'\')' -if len('a') != 1: raise TestFailed, 'len(\'a\')' -if len('abcdef') != 6: raise TestFailed, 'len(\'abcdef\')' -if 'xyz' + 'abcde' != 'xyzabcde': raise TestFailed, 'string concatenation' -if 'xyz'*3 != 'xyzxyzxyz': raise TestFailed, 'string repetition *3' -if 0*'abcde' != '': raise TestFailed, 'string repetition 0*' -if min('abc') != 'a' or max('abc') != 'c': raise TestFailed, 'min/max string' -if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass -else: raise TestFailed, 'in/not in string' -x = 'x'*103 -if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug' - -#extended slices for strings -a = '0123456789' -vereq(a[::], a) -vereq(a[::2], '02468') -vereq(a[1::2], '13579') -vereq(a[::-1],'9876543210') -vereq(a[::-2], '97531') -vereq(a[3::-2], '31') -vereq(a[-100:100:], a) -vereq(a[100:-100:-1], a[::-1]) -vereq(a[-100L:100L:2L], '02468') - -if have_unicode: - a = unicode('0123456789', 'ascii') - vereq(a[::], a) - vereq(a[::2], unicode('02468', 'ascii')) - vereq(a[1::2], unicode('13579', 'ascii')) - vereq(a[::-1], unicode('9876543210', 'ascii')) - vereq(a[::-2], unicode('97531', 'ascii')) - vereq(a[3::-2], unicode('31', 'ascii')) - vereq(a[-100:100:], a) - vereq(a[100:-100:-1], a[::-1]) - vereq(a[-100L:100L:2L], unicode('02468', 'ascii')) - - -print '6.5.2 Tuples [see test_tuple.py]' - -print '6.5.3 Lists [see test_list.py]' - -print '6.6 Mappings == Dictionaries [see test_dict.py]' - - -try: type(1, 2) -except TypeError: pass -else: raise TestFailed, 'type(), w/2 args expected TypeError' - -try: type(1, 2, 3, 4) -except TypeError: pass -else: raise TestFailed, 'type(), w/4 args expected TypeError' - -print 'Buffers' -try: buffer('asdf', -1) -except ValueError: pass -else: raise TestFailed, "buffer('asdf', -1) should raise ValueError" -cmp(buffer("abc"), buffer("def")) # used to raise a warning: tp_compare didn't return -1, 0, or 1 - -try: buffer(None) -except TypeError: pass -else: raise TestFailed, "buffer(None) should raise TypeError" - -a = buffer('asdf') -hash(a) -b = a * 5 -if a == b: - raise TestFailed, 'buffers should not be equal' -if str(b) != ('asdf' * 5): - raise TestFailed, 'repeated buffer has wrong content' -if str(a * 0) != '': - raise TestFailed, 'repeated buffer zero times has wrong content' -if str(a + buffer('def')) != 'asdfdef': - raise TestFailed, 'concatenation of buffers yields wrong content' -if str(buffer(a)) != 'asdf': - raise TestFailed, 'composing buffers failed' -if str(buffer(a, 2)) != 'df': - raise TestFailed, 'specifying buffer offset failed' -if str(buffer(a, 0, 2)) != 'as': - raise TestFailed, 'specifying buffer size failed' -if str(buffer(a, 1, 2)) != 'sd': - raise TestFailed, 'specifying buffer offset and size failed' -try: buffer(buffer('asdf', 1), -1) -except ValueError: pass -else: raise TestFailed, "buffer(buffer('asdf', 1), -1) should raise ValueError" -if str(buffer(buffer('asdf', 0, 2), 0)) != 'as': - raise TestFailed, 'composing length-specified buffer failed' -if str(buffer(buffer('asdf', 0, 2), 0, 5000)) != 'as': - raise TestFailed, 'composing length-specified buffer failed' -if str(buffer(buffer('asdf', 0, 2), 0, -1)) != 'as': - raise TestFailed, 'composing length-specified buffer failed' -if str(buffer(buffer('asdf', 0, 2), 1, 2)) != 's': - raise TestFailed, 'composing length-specified buffer failed' - -try: a[1] = 'g' -except TypeError: pass -else: raise TestFailed, "buffer assignment should raise TypeError" - -try: a[0:1] = 'g' -except TypeError: pass -else: raise TestFailed, "buffer slice assignment should raise TypeError" - -# array.array() returns an object that does not implement a char buffer, -# something which int() uses for conversion. -import array -try: int(buffer(array.array('c'))) -except TypeError :pass -else: raise TestFailed, "char buffer (at C level) not working" + 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.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.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') + def f(): pass + class C: pass + import sys + x = C() + if not f: self.fail('f is false instead of true') + if not C: self.fail('C is false instead of true') + if not sys: self.fail('sys is false instead of true') + if not x: self.fail('x is false instead of true') + + def test_boolean_ops(self): + if 0 or 0: self.fail('0 or 0 is true instead of false') + if 1 and 1: pass + else: self.fail('1 and 1 is false instead of true') + if not 1: self.fail('not 1 is true instead of false') + + 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 + 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') + if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass + else: self.fail('string comparisons failed') + if None is None: pass + else: self.fail('identity test failed') + + def test_float_constructor(self): + self.assertRaises(ValueError, float, '') + self.assertRaises(ValueError, float, '5\0') + + def test_zero_division(self): + try: 5.0 / 0.0 + except ZeroDivisionError: pass + else: self.fail("5.0 / 0.0 didn't raise ZeroDivisionError") + + try: 5.0 // 0.0 + except ZeroDivisionError: pass + else: self.fail("5.0 // 0.0 didn't raise ZeroDivisionError") + + try: 5.0 % 0.0 + except ZeroDivisionError: pass + else: self.fail("5.0 % 0.0 didn't raise ZeroDivisionError") + + try: 5 / 0L + except ZeroDivisionError: pass + else: self.fail("5 / 0L didn't raise ZeroDivisionError") + + try: 5 // 0L + except ZeroDivisionError: pass + else: self.fail("5 // 0L didn't raise ZeroDivisionError") + + try: 5 % 0L + 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: + 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 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 + 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') + + def test_normal_integers(self): + # Ensure the first 256 integers are shared + a = 256 + b = 128*2 + if a is not b: self.fail('256 is not shared') + if 12 + 24 != 36: self.fail('int op') + if 12 + (-24) != -12: self.fail('int op') + if (-12) + 24 != 12: self.fail('int op') + if (-12) + (-24) != -36: self.fail('int op') + if not 12 < 24: self.fail('int op') + if not -24 < -12: self.fail('int op') + # Test for a particular bug in integer multiply + xsize, ysize, zsize = 238, 356, 4 + if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912): + self.fail('int mul commutativity') + # And another. + m = -sys.maxint - 1 + for divisor in 1, 2, 4, 8, 16, 32: + j = m // divisor + prod = divisor * j + if prod != m: + self.fail("%r * %r == %r != %r" % (divisor, j, prod, m)) + if type(prod) is not int: + self.fail("expected type(prod) to be int, not %r" % + type(prod)) + # Check for expected * overflow to long. + for divisor in 1, 2, 4, 8, 16, 32: + j = m // divisor - 1 + prod = divisor * j + if type(prod) is not long: + self.fail("expected type(%r) to be long, not %r" % + (prod, type(prod))) + # Check for expected * overflow to long. + m = sys.maxint + for divisor in 1, 2, 4, 8, 16, 32: + j = m // divisor + 1 + prod = divisor * j + if type(prod) is not long: + 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') + x = sys.maxint + if int(long(x)) != x: self.fail('long op') + try: y = int(long(x)+1L) + except OverflowError: self.fail('long op') + if not isinstance(y, long): self.fail('long op') + x = -x + if int(long(x)) != x: self.fail('long op') + x = x-1 + if int(long(x)) != x: self.fail('long op') + try: y = int(long(x)-1L) + except OverflowError: self.fail('long op') + if not isinstance(y, long): self.fail('long op') + + try: 5 << -5 + except ValueError: pass + else: self.fail('int negative shift <<') + + try: 5L << -5L + except ValueError: pass + else: self.fail('long negative shift <<') + + try: 5 >> -5 + except ValueError: pass + else: self.fail('int negative shift >>') + + try: 5L >> -5L + except ValueError: pass + else: self.fail('long negative shift >>') + + def test_floats(self): + if 12.0 + 24.0 != 36.0: self.fail('float op') + if 12.0 + (-24.0) != -12.0: self.fail('float op') + if (-12.0) + 24.0 != 12.0: self.fail('float op') + if (-12.0) + (-24.0) != -36.0: self.fail('float op') + if not 12.0 < 24.0: self.fail('float op') + if not -24.0 < -12.0: self.fail('float op') + + def test_strings(self): + if len('') != 0: self.fail('len(\'\')') + if len('a') != 1: self.fail('len(\'a\')') + if len('abcdef') != 6: self.fail('len(\'abcdef\')') + if 'xyz' + 'abcde' != 'xyzabcde': self.fail('string concatenation') + if 'xyz'*3 != 'xyzxyzxyz': self.fail('string repetition *3') + if 0*'abcde' != '': self.fail('string repetition 0*') + if min('abc') != 'a' or max('abc') != 'c': self.fail('min/max string') + if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass + else: self.fail('in/not in string') + x = 'x'*103 + if '%s!'%x != x+'!': self.fail('nasty string formatting bug') + + #extended slices for strings + a = '0123456789' + self.assertEqual(a[::], a) + self.assertEqual(a[::2], '02468') + self.assertEqual(a[1::2], '13579') + self.assertEqual(a[::-1],'9876543210') + self.assertEqual(a[::-2], '97531') + 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') + + if have_unicode: + a = unicode('0123456789', 'ascii') + self.assertEqual(a[::], a) + self.assertEqual(a[::2], unicode('02468', 'ascii')) + self.assertEqual(a[1::2], unicode('13579', 'ascii')) + self.assertEqual(a[::-1], unicode('9876543210', 'ascii')) + self.assertEqual(a[::-2], unicode('97531', 'ascii')) + 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')) + + + def test_type_function(self): + self.assertRaises(TypeError, type, 1, 2) + self.assertRaises(TypeError, type, 1, 2, 3, 4) + + def test_buffers(self): + self.assertRaises(ValueError, buffer, 'asdf', -1) + cmp(buffer("abc"), buffer("def")) # used to raise a warning: tp_compare didn't return -1, 0, or 1 + + self.assertRaises(TypeError, buffer, None) + + a = buffer('asdf') + hash(a) + b = a * 5 + if a == b: + self.fail('buffers should not be equal') + if str(b) != ('asdf' * 5): + self.fail('repeated buffer has wrong content') + if str(a * 0) != '': + self.fail('repeated buffer zero times has wrong content') + if str(a + buffer('def')) != 'asdfdef': + self.fail('concatenation of buffers yields wrong content') + if str(buffer(a)) != 'asdf': + self.fail('composing buffers failed') + if str(buffer(a, 2)) != 'df': + self.fail('specifying buffer offset failed') + if str(buffer(a, 0, 2)) != 'as': + self.fail('specifying buffer size failed') + if str(buffer(a, 1, 2)) != 'sd': + self.fail('specifying buffer offset and size failed') + self.assertRaises(ValueError, buffer, buffer('asdf', 1), -1) + if str(buffer(buffer('asdf', 0, 2), 0)) != 'as': + self.fail('composing length-specified buffer failed') + if str(buffer(buffer('asdf', 0, 2), 0, 5000)) != 'as': + self.fail('composing length-specified buffer failed') + if str(buffer(buffer('asdf', 0, 2), 0, -1)) != 'as': + self.fail('composing length-specified buffer failed') + if str(buffer(buffer('asdf', 0, 2), 1, 2)) != 's': + self.fail('composing length-specified buffer failed') + + try: a[1] = 'g' + except TypeError: pass + else: self.fail("buffer assignment should raise TypeError") + + try: a[0:1] = 'g' + except TypeError: pass + else: self.fail("buffer slice assignment should raise TypeError") + + # array.array() returns an object that does not implement a char buffer, + # something which int() uses for conversion. + import array + try: int(buffer(array.array('c'))) + except TypeError: pass + else: self.fail("char buffer (at C level) not working") + +def test_main(): + run_unittest(TypesTests) + +if __name__ == '__main__': + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_uu.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_uu.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_uu.py Tue Jan 9 23:27:11 2007 @@ -114,11 +114,11 @@ def test_encode(self): try: - fin = open(self.tmpin, 'wb') + fin = open(self.tmpin, 'w') fin.write(plaintext) fin.close() - fin = open(self.tmpin, 'rb') + fin = open(self.tmpin, 'r') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() @@ -130,7 +130,7 @@ self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) # in_file and out_file as filenames - uu.encode(self.tmpin, self.tmpout, mode=0644) + uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) fout = open(self.tmpout, 'r') s = fout.read() fout.close() @@ -142,11 +142,11 @@ def test_decode(self): try: - f = open(self.tmpin, 'wb') + f = open(self.tmpin, 'w') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close() - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') uu.decode(f) f.close() @@ -163,11 +163,11 @@ try: f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout)) - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') uu.decode(f) f.close() - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') self.assertRaises(uu.Error, uu.decode, f) f.close() finally: Modified: python/branches/bcannon-objcap/Lib/test/test_weakref.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_weakref.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_weakref.py Tue Jan 9 23:27:11 2007 @@ -189,7 +189,7 @@ # None as the value for the callback, where either means "no # callback". The "no callback" ref and proxy objects are supposed # to be shared so long as they exist by all callers so long as - # they are active. In Python 2.3.3 and earlier, this guaranttee + # they are active. In Python 2.3.3 and earlier, this guarantee # was not honored, and was broken in different ways for # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.) Modified: python/branches/bcannon-objcap/Lib/test/test_xdrlib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_xdrlib.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_xdrlib.py Tue Jan 9 23:27:11 2007 @@ -1,3 +1,56 @@ +from test import test_support +import unittest + import xdrlib -xdrlib._test() +class XDRTest(unittest.TestCase): + + def test_xdr(self): + p = xdrlib.Packer() + + s = 'hello world' + a = ['what', 'is', 'hapnin', 'doctor'] + + p.pack_int(42) + p.pack_uint(9) + p.pack_bool(True) + p.pack_bool(False) + p.pack_uhyper(45L) + p.pack_float(1.9) + p.pack_double(1.9) + p.pack_string(s) + p.pack_list(range(5), p.pack_uint) + p.pack_array(a, p.pack_string) + + # now verify + data = p.get_buffer() + up = xdrlib.Unpacker(data) + + self.assertEqual(up.get_position(), 0) + + self.assertEqual(up.unpack_int(), 42) + self.assertEqual(up.unpack_uint(), 9) + self.assert_(up.unpack_bool() is True) + + # remember position + pos = up.get_position() + self.assert_(up.unpack_bool() is False) + + # rewind and unpack again + up.set_position(pos) + self.assert_(up.unpack_bool() is False) + + self.assertEqual(up.unpack_uhyper(), 45L) + self.assertAlmostEqual(up.unpack_float(), 1.9) + self.assertAlmostEqual(up.unpack_double(), 1.9) + self.assertEqual(up.unpack_string(), s) + self.assertEqual(up.unpack_list(up.unpack_uint), range(5)) + self.assertEqual(up.unpack_array(up.unpack_string), a) + up.done() + self.assertRaises(EOFError, up.unpack_uint) + +def test_main(): + test_support.run_unittest(XDRTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/bcannon-objcap/Lib/test/test_xmlrpc.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_xmlrpc.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_xmlrpc.py Tue Jan 9 23:27:11 2007 @@ -86,6 +86,15 @@ s = xmlrpclib.dumps((new_d,), methodresponse=True) self.assert_(isinstance(s, str)) + def test_newstyle_class(self): + class T(object): + pass + t = T() + t.x = 100 + t.y = "Hello" + ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,))) + self.assertEquals(t2, t.__dict__) + def test_dump_big_long(self): self.assertRaises(OverflowError, xmlrpclib.dumps, (2L**99,)) Modified: python/branches/bcannon-objcap/Lib/threading.py ============================================================================== --- python/branches/bcannon-objcap/Lib/threading.py (original) +++ python/branches/bcannon-objcap/Lib/threading.py Tue Jan 9 23:27:11 2007 @@ -636,13 +636,11 @@ _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() - import atexit - atexit.register(self.__exitfunc) def _set_daemon(self): return False - def __exitfunc(self): + def _exitfunc(self): self._Thread__stop() t = _pickSomeNonDaemonThread() if t: @@ -715,9 +713,11 @@ from thread import stack_size -# Create the main thread object +# Create the main thread object, +# and make it available for the interpreter +# (Py_Main) as threading._shutdown. -_MainThread() +_shutdown = _MainThread()._exitfunc # get thread-local implementation, either from the thread # module, or from the python fallback Modified: python/branches/bcannon-objcap/Lib/tokenize.py ============================================================================== --- python/branches/bcannon-objcap/Lib/tokenize.py (original) +++ python/branches/bcannon-objcap/Lib/tokenize.py Tue Jan 9 23:27:11 2007 @@ -24,7 +24,7 @@ __author__ = 'Ka-Ping Yee ' __credits__ = \ - 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro' + 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger' import string, re from token import * Modified: python/branches/bcannon-objcap/Lib/urllib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/urllib.py (original) +++ python/branches/bcannon-objcap/Lib/urllib.py Tue Jan 9 23:27:11 2007 @@ -302,13 +302,13 @@ if proxy_passwd: import base64 - proxy_auth = base64.encodestring(proxy_passwd).strip() + proxy_auth = base64.b64encode(proxy_passwd).strip() else: proxy_auth = None if user_passwd: import base64 - auth = base64.encodestring(user_passwd).strip() + auth = base64.b64encode(user_passwd).strip() else: auth = None h = httplib.HTTP(host) @@ -387,12 +387,12 @@ if not host: raise IOError, ('https error', 'no host given') if proxy_passwd: import base64 - proxy_auth = base64.encodestring(proxy_passwd).strip() + proxy_auth = base64.b64encode(proxy_passwd).strip() else: proxy_auth = None if user_passwd: import base64 - auth = base64.encodestring(user_passwd).strip() + auth = base64.b64encode(user_passwd).strip() else: auth = None h = httplib.HTTPS(host, 0, @@ -405,8 +405,8 @@ h.putheader('Content-Length', '%d' % len(data)) else: h.putrequest('GET', selector) - if proxy_auth: h.putheader('Proxy-Authorization: Basic %s' % proxy_auth) - if auth: h.putheader('Authorization: Basic %s' % auth) + if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth) + if auth: h.putheader('Authorization', 'Basic %s' % auth) if realhost: h.putheader('Host', realhost) for args in self.addheaders: h.putheader(*args) h.endheaders() Modified: python/branches/bcannon-objcap/Lib/urllib2.py ============================================================================== --- python/branches/bcannon-objcap/Lib/urllib2.py (original) +++ python/branches/bcannon-objcap/Lib/urllib2.py Tue Jan 9 23:27:11 2007 @@ -674,7 +674,7 @@ proxy_type = orig_type if user and password: user_pass = '%s:%s' % (unquote(user), unquote(password)) - creds = base64.encodestring(user_pass).strip() + creds = base64.b64encode(user_pass).strip() req.add_header('Proxy-authorization', 'Basic ' + creds) hostport = unquote(hostport) req.set_proxy(hostport, proxy_type) @@ -798,7 +798,7 @@ user, pw = self.passwd.find_user_password(realm, host) if pw is not None: raw = "%s:%s" % (user, pw) - auth = 'Basic %s' % base64.encodestring(raw).strip() + auth = 'Basic %s' % base64.b64encode(raw).strip() if req.headers.get(self.auth_header, None) == auth: return None req.add_header(self.auth_header, auth) Modified: python/branches/bcannon-objcap/Lib/uu.py ============================================================================== --- python/branches/bcannon-objcap/Lib/uu.py (original) +++ python/branches/bcannon-objcap/Lib/uu.py Tue Jan 9 23:27:11 2007 @@ -114,6 +114,7 @@ # # Open the output file # + opened = False if out_file == '-': out_file = sys.stdout elif isinstance(out_file, basestring): @@ -123,6 +124,7 @@ except AttributeError: pass out_file = fp + opened = True # # Main decoding loop # @@ -140,6 +142,8 @@ s = in_file.readline() if not s: raise Error('Truncated input file') + if opened: + out_file.close() def test(): """uuencode/uudecode main program""" Modified: python/branches/bcannon-objcap/Lib/webbrowser.py ============================================================================== --- python/branches/bcannon-objcap/Lib/webbrowser.py (original) +++ python/branches/bcannon-objcap/Lib/webbrowser.py Tue Jan 9 23:27:11 2007 @@ -447,7 +447,7 @@ # if successful, register it if retncode is None and commd: - register("gnome", None, BackgroundBrowser(commd)) + register("gnome", None, BackgroundBrowser(commd.split())) # First, the Mozilla/Netscape browsers for browser in ("mozilla-firefox", "firefox", Modified: python/branches/bcannon-objcap/Lib/xdrlib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/xdrlib.py (original) +++ python/branches/bcannon-objcap/Lib/xdrlib.py Tue Jan 9 23:27:11 2007 @@ -227,61 +227,3 @@ def unpack_array(self, unpack_item): n = self.unpack_uint() return self.unpack_farray(n, unpack_item) - - -# test suite -def _test(): - p = Packer() - packtest = [ - (p.pack_uint, (9,)), - (p.pack_bool, (True,)), - (p.pack_bool, (False,)), - (p.pack_uhyper, (45L,)), - (p.pack_float, (1.9,)), - (p.pack_double, (1.9,)), - (p.pack_string, ('hello world',)), - (p.pack_list, (range(5), p.pack_uint)), - (p.pack_array, (['what', 'is', 'hapnin', 'doctor'], p.pack_string)), - ] - succeedlist = [1] * len(packtest) - count = 0 - for method, args in packtest: - print 'pack test', count, - try: - method(*args) - print 'succeeded' - except ConversionError, var: - print 'ConversionError:', var.msg - succeedlist[count] = 0 - count = count + 1 - data = p.get_buffer() - # now verify - up = Unpacker(data) - unpacktest = [ - (up.unpack_uint, (), lambda x: x == 9), - (up.unpack_bool, (), lambda x: x is True), - (up.unpack_bool, (), lambda x: x is False), - (up.unpack_uhyper, (), lambda x: x == 45L), - (up.unpack_float, (), lambda x: 1.89 < x < 1.91), - (up.unpack_double, (), lambda x: 1.89 < x < 1.91), - (up.unpack_string, (), lambda x: x == 'hello world'), - (up.unpack_list, (up.unpack_uint,), lambda x: x == range(5)), - (up.unpack_array, (up.unpack_string,), - lambda x: x == ['what', 'is', 'hapnin', 'doctor']), - ] - count = 0 - for method, args, pred in unpacktest: - print 'unpack test', count, - try: - if succeedlist[count]: - x = method(*args) - print pred(x) and 'succeeded' or 'failed', ':', x - else: - print 'skipping' - except ConversionError, var: - print 'ConversionError:', var.msg - count = count + 1 - - -if __name__ == '__main__': - _test() Modified: python/branches/bcannon-objcap/Lib/xmlrpclib.py ============================================================================== --- python/branches/bcannon-objcap/Lib/xmlrpclib.py (original) +++ python/branches/bcannon-objcap/Lib/xmlrpclib.py Tue Jan 9 23:27:11 2007 @@ -630,9 +630,19 @@ try: f = self.dispatch[type(value)] except KeyError: - raise TypeError, "cannot marshal %s objects" % type(value) - else: - f(self, value, write) + # check if this object can be marshalled as a structure + try: + value.__dict__ + except: + raise TypeError, "cannot marshal %s objects" % type(value) + # check if this class is a sub-class of a basic type, + # because we don't know how to marshal these types + # (e.g. a string sub-class) + for type_ in type(value).__mro__: + if type_ in self.dispatch.keys(): + raise TypeError, "cannot marshal %s objects" % type(value) + f = self.dispatch[InstanceType] + f(self, value, write) def dump_nil (self, value, write): if not self.allow_none: Modified: python/branches/bcannon-objcap/Mac/BuildScript/build-installer.py ============================================================================== --- python/branches/bcannon-objcap/Mac/BuildScript/build-installer.py (original) +++ python/branches/bcannon-objcap/Mac/BuildScript/build-installer.py Tue Jan 9 23:27:11 2007 @@ -10,9 +10,10 @@ Usage: see USAGE variable in the script. """ import platform, os, sys, getopt, textwrap, shutil, urllib2, stat, time, pwd +import grp -INCLUDE_TIMESTAMP=1 -VERBOSE=1 +INCLUDE_TIMESTAMP = 1 +VERBOSE = 1 from plistlib import Plist @@ -32,7 +33,7 @@ def shellQuote(value): """ - Return the string value in a form that can savely be inserted into + Return the string value in a form that can safely be inserted into a shell command. """ return "'%s'"%(value.replace("'", "'\"'\"'")) @@ -55,28 +56,28 @@ raise RuntimeError, "Cannot find full version??" -# The directory we'll use to create the build, will be erased and recreated -WORKDIR="/tmp/_py" +# The directory we'll use to create the build (will be erased and recreated) +WORKDIR = "/tmp/_py" -# The directory we'll use to store third-party sources, set this to something +# The directory we'll use to store third-party sources. Set this to something # else if you don't want to re-fetch required libraries every time. -DEPSRC=os.path.join(WORKDIR, 'third-party') -DEPSRC=os.path.expanduser('~/Universal/other-sources') +DEPSRC = os.path.join(WORKDIR, 'third-party') +DEPSRC = os.path.expanduser('~/Universal/other-sources') # Location of the preferred SDK -SDKPATH="/Developer/SDKs/MacOSX10.4u.sdk" -#SDKPATH="/" +SDKPATH = "/Developer/SDKs/MacOSX10.4u.sdk" +#SDKPATH = "/" -ARCHLIST=('i386', 'ppc',) +ARCHLIST = ('i386', 'ppc',) # Source directory (asume we're in Mac/BuildScript) -SRCDIR=os.path.dirname( +SRCDIR = os.path.dirname( os.path.dirname( os.path.dirname( os.path.abspath(__file__ )))) -USAGE=textwrap.dedent("""\ +USAGE = textwrap.dedent("""\ Usage: build_python [options] Options: @@ -91,7 +92,7 @@ # Instructions for building libraries that are necessary for building a # batteries included python. -LIBRARY_RECIPES=[ +LIBRARY_RECIPES = [ dict( name="Bzip2 1.0.3", url="http://www.bzip.org/1.0.3/bzip2-1.0.3.tar.gz", @@ -183,7 +184,7 @@ # Instructions for building packages inside the .mpkg. -PKG_RECIPES=[ +PKG_RECIPES = [ dict( name="PythonFramework", long_name="Python Framework", @@ -200,7 +201,7 @@ long_name="GUI Applications", source="/Applications/MacPython %(VER)s", readme="""\ - This package installs IDLE (an interactive Python IDLE), + This package installs IDLE (an interactive Python IDE), Python Launcher and Build Applet (create application bundles from python scripts). @@ -256,8 +257,7 @@ readme="""\ This package updates the system python installation on Mac OS X 10.3 to ensure that you can build new python extensions - using that copy of python after installing this version of - python. + using that copy of python after installing this version. """, postflight="../Tools/fixapplepython23.py", topdir="/Library/Frameworks/Python.framework", @@ -323,7 +323,7 @@ -def parseOptions(args = None): +def parseOptions(args=None): """ Parse arguments and update global settings. """ @@ -636,15 +636,15 @@ print "Running make" runCommand("make") - print "Runing make frameworkinstall" + print "Running make frameworkinstall" runCommand("make frameworkinstall DESTDIR=%s"%( shellQuote(rootDir))) - print "Runing make frameworkinstallextras" + print "Running make frameworkinstallextras" runCommand("make frameworkinstallextras DESTDIR=%s"%( shellQuote(rootDir))) - print "Copy required shared libraries" + print "Copying required shared libraries" if os.path.exists(os.path.join(WORKDIR, 'libraries', 'Library')): runCommand("mv %s/* %s"%( shellQuote(os.path.join( @@ -657,9 +657,13 @@ print "Fix file modes" frmDir = os.path.join(rootDir, 'Library', 'Frameworks', 'Python.framework') + gid = grp.getgrnam('admin').gr_gid + for dirpath, dirnames, filenames in os.walk(frmDir): for dn in dirnames: os.chmod(os.path.join(dirpath, dn), 0775) + os.chown(os.path.join(dirpath, dn), -1, gid) + for fn in filenames: if os.path.islink(fn): @@ -668,7 +672,8 @@ # "chmod g+w $fn" p = os.path.join(dirpath, fn) st = os.stat(p) - os.chmod(p, stat.S_IMODE(st.st_mode) | stat.S_IXGRP) + os.chmod(p, stat.S_IMODE(st.st_mode) | stat.S_IWGRP) + os.chown(p, -1, gid) # We added some directories to the search path during the configure # phase. Remove those because those directories won't be there on @@ -729,8 +734,8 @@ def packageFromRecipe(targetDir, recipe): curdir = os.getcwd() try: - # The major version (such as 2.5) is included in the pacakge name - # because haveing two version of python installed at the same time is + # The major version (such as 2.5) is included in the package name + # because having two version of python installed at the same time is # common. pkgname = '%s-%s'%(recipe['name'], getVersion()) srcdir = recipe.get('source') @@ -904,7 +909,7 @@ def buildDMG(): """ - Create DMG containing the rootDir + Create DMG containing the rootDir. """ outdir = os.path.join(WORKDIR, 'diskimage') if os.path.exists(outdir): @@ -917,7 +922,7 @@ imagepath = imagepath + '.dmg' os.mkdir(outdir) - runCommand("hdiutil create -volname 'Univeral MacPython %s' -srcfolder %s %s"%( + runCommand("hdiutil create -volname 'Universal MacPython %s' -srcfolder %s %s"%( getFullVersion(), shellQuote(os.path.join(WORKDIR, 'installer')), shellQuote(imagepath))) @@ -945,7 +950,10 @@ ref, isDirectory = Carbon.File.FSPathMakeRef(filePath) if isDirectory: + # There is a problem with getting this into the pax(1) archive, + # just ignore directory icons for now. return + tmpPath = os.path.join(filePath, "Icon\r") if not os.path.exists(tmpPath): fp = open(tmpPath, 'w') Modified: python/branches/bcannon-objcap/Mac/BuildScript/scripts/postflight.documentation ============================================================================== --- python/branches/bcannon-objcap/Mac/BuildScript/scripts/postflight.documentation (original) +++ python/branches/bcannon-objcap/Mac/BuildScript/scripts/postflight.documentation Tue Jan 9 23:27:11 2007 @@ -1,6 +1,5 @@ #!/bin/sh -# FIXME PYVER="@PYVER@" if [ -d /Developer/Documentation ]; then @@ -8,5 +7,5 @@ mkdir -p /Developer/Documentation/Python fi - ln -fhs /Library/Frameworks/Python.framework/Versions/${PYVER}/Resources/English.lproj/Documentation "/Developer/Documentation/Python/Reference Documentation" + ln -fhs /Library/Frameworks/Python.framework/Versions/${PYVER}/Resources/English.lproj/Documentation "/Developer/Documentation/Python/Reference Documentation @PYVER@" fi Modified: python/branches/bcannon-objcap/Mac/BuildScript/scripts/postflight.patch-profile ============================================================================== --- python/branches/bcannon-objcap/Mac/BuildScript/scripts/postflight.patch-profile (original) +++ python/branches/bcannon-objcap/Mac/BuildScript/scripts/postflight.patch-profile Tue Jan 9 23:27:11 2007 @@ -47,22 +47,29 @@ echo "${PYTHON_ROOT}/bin is not on your PATH or at least not early enough" case "${BSH}" in *csh) + if [ -f "${HOME}/.tcshrc" ]; then + RC="${HOME}/.tcshrc" + else + RC="${HOME}/.cshrc" + fi # Create backup copy before patching - if [ -f "${HOME}/.cshrc" ]; then - cp -fp "${HOME}/.cshrc" "${HOME}/.cshrc.pysave" + if [ -f "${RC}" ]; then + cp -fp "${RC}" "${RC}.pysave" fi - echo "" >> "${HOME}/.cshrc" - echo "# Setting PATH for MacPython ${PYVER}" >> "${HOME}/.cshrc" - echo "# The orginal version is saved in .cshrc.pysave" >> "${HOME}/.cshrc" - echo "set path=(${PYTHON_ROOT}/bin "'$path'")" >> "${HOME}/.cshrc" + echo "" >> "${RC}" + echo "# Setting PATH for MacPython ${PYVER}" >> "${RC}" + echo "# The orginal version is saved in .cshrc.pysave" >> "${RC}" + echo "set path=(${PYTHON_ROOT}/bin "'$path'")" >> "${RC}" if [ `id -ur` = 0 ]; then - chown "${USER}" "${HOME}/.cshrc" + chown "${USER}" "${RC}" fi exit 0 ;; bash) if [ -e "${HOME}/.bash_profile" ]; then PR="${HOME}/.bash_profile" + elif [ -e "${HOME}/.bash_login" ]; then + PR="${HOME}/.bash_login" elif [ -e "${HOME}/.profile" ]; then PR="${HOME}/.profile" else Modified: python/branches/bcannon-objcap/Mac/PythonLauncher/FileSettings.m ============================================================================== --- python/branches/bcannon-objcap/Mac/PythonLauncher/FileSettings.m (original) +++ python/branches/bcannon-objcap/Mac/PythonLauncher/FileSettings.m Tue Jan 9 23:27:11 2007 @@ -207,7 +207,7 @@ [NSNumber numberWithBool: inspect], @"inspect", [NSNumber numberWithBool: optimize], @"optimize", [NSNumber numberWithBool: nosite], @"nosite", - [NSNumber numberWithBool: nosite], @"nosite", + [NSNumber numberWithBool: tabs], @"tabs", others, @"others", scriptargs, @"scriptargs", [NSNumber numberWithBool: with_terminal], @"with_terminal", @@ -235,7 +235,7 @@ if (value) optimize = [value boolValue]; value = [dict objectForKey: @"nosite"]; if (value) nosite = [value boolValue]; - value = [dict objectForKey: @"nosite"]; + value = [dict objectForKey: @"tabs"]; if (value) tabs = [value boolValue]; value = [dict objectForKey: @"others"]; if (value) others = [value retain]; @@ -291,7 +291,7 @@ tabs?" -t":"", others, [self _replaceSingleQuotes:script], - scriptargs, + scriptargs ? scriptargs : @"", with_terminal? "&& echo Exit status: $? && exit 1" : " &"]; } Modified: python/branches/bcannon-objcap/Makefile.pre.in ============================================================================== --- python/branches/bcannon-objcap/Makefile.pre.in (original) +++ python/branches/bcannon-objcap/Makefile.pre.in Tue Jan 9 23:27:11 2007 @@ -345,7 +345,7 @@ # Build the shared modules sharedmods: $(BUILDPYTHON) - case $$MAKEFLAGS in \ + @case $$MAKEFLAGS in \ *-s*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py -q build;; \ *) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py build;; \ esac @@ -456,7 +456,7 @@ $(SIGNAL_OBJS) \ $(MODOBJS) \ $(srcdir)/Modules/getbuildinfo.c - $(CC) -c $(PY_CFLAGS) -DSVNVERSION=\"`LANG=C $(SVNVERSION)`\" -o $@ $(srcdir)/Modules/getbuildinfo.c + $(CC) -c $(PY_CFLAGS) -DSVNVERSION=\"`LC_ALL=C $(SVNVERSION)`\" -o $@ $(srcdir)/Modules/getbuildinfo.c Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile $(CC) -c $(PY_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \ Modified: python/branches/bcannon-objcap/Misc/ACKS ============================================================================== --- python/branches/bcannon-objcap/Misc/ACKS (original) +++ python/branches/bcannon-objcap/Misc/ACKS Tue Jan 9 23:27:11 2007 @@ -285,6 +285,7 @@ Albert Hofkamp Jonathan Hogg Gerrit Holl +Shane Holloway Rune Holm Philip Homburg Naofumi Honda @@ -613,6 +614,7 @@ Christian Tanzer Steven Taschuk Amy Taylor +Monty Taylor Tobias Thelen Robin Thomas Eric Tiedemann @@ -633,6 +635,7 @@ Bill Tutt Doobee R. Tzeck Lionel Ulmer +Roger Upole Michael Urman Hector Urtubia Dmitry Vasiliev Modified: python/branches/bcannon-objcap/Misc/NEWS ============================================================================== --- python/branches/bcannon-objcap/Misc/NEWS (original) +++ python/branches/bcannon-objcap/Misc/NEWS Tue Jan 9 23:27:11 2007 @@ -12,6 +12,59 @@ Core and builtins ----------------- +- Prevent seg fault on shutdown which could occur if an object + raised a warning. + +- Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, + to avoid relying on atexit. + +- Bug #1590891: random.randrange don't return correct value for big number + +- Patch #1586791: Better exception messages for some operations on strings, + tuples and lists. + +- Bug #1067760: Deprecate passing floats to file.seek. + +- Bug #1591996: Correctly forward exception in instance_contains(). + +- Bug #1588287: fix invalid assertion for `1,2` in debug builds. + +- Bug #1576657: when setting a KeyError for a tuple key, make sure that + the tuple isn't used as the "exception arguments tuple". + +- Bug #1565514, SystemError not raised on too many nested blocks. + +- Bug #1576174: WindowsError now displays the windows error code + again, no longer the posix error code. + +- Patch #1549049: Support long values in structmember, issue warnings + if the assigned value for structmember fields gets truncated. + +- Update the peephole optimizer to remove more dead code (jumps after returns) + and inline unconditional jumps to returns. + +- Bug #1545497: when given an explicit base, int() did ignore NULs + embedded in the string to convert. + +- Bug #1569998: break inside a try statement (outside a loop) is now + recognized and rejected. + +- list.pop(x) accepts any object x following the __index__ protocol. + +- Fix some leftovers from the conversion from int to Py_ssize_t + (relevant to strings and sequences of more than 2**31 items). + +- A number of places, including integer negation and absolute value, + were fixed to not rely on undefined behaviour of the C compiler + anymore. + +- Bug #1566800: make sure that EnvironmentError can be called with any + number of arguments, as was the case in Python 2.4. + +- Patch #1567691: super() and new.instancemethod() now don't accept + keyword arguments any more (previously they accepted them, but didn't + use them). + - Fix a bug in the parser's future statement handling that led to "with" not being recognized as a keyword after, e.g., this statement: from __future__ import division, with_statement @@ -56,6 +109,153 @@ Library ------- +- Bug #1627575: logging: 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". + +- Bug #411881: logging.handlers: bare except clause removed from + SMTPHandler.emit. Now, only ImportError is trapped. + +- Bug #411881: logging.handlers: bare except clause removed from + SocketHandler.createSocket. Now, only socket.error is trapped. + +- Bug #411881: logging: bare except clause removed from LogRecord.__init__. + Now, only ValueError, TypeError and AttributeError are trapped. + +- Patch #1504073: Fix tarfile.open() for mode "r" with a fileobj argument. + +- Patch #1182394 from Shane Holloway: speed up HMAC.hexdigest. + +- Patch #1262036: Prevent TarFiles from being added to themselves under + certain conditions. + +- Patch #1230446: tarfile.py: fix ExFileObject so that read() and tell() + work correctly together with readline(). + +- Patch #1484695: The tarfile module now raises a HeaderError exception + if a buffer given to frombuf() is invalid. + +- Bug #1503765: Fix a problem in logging.config with spaces in comma- + separated lists read from logging config files. + +- Patch #1604907: Fix problems in logging.handlers caused at logging shutdown + when syslog handlers fail to initialize because of syslogd problems. + +- Patch #1608267: fix a race condition in os.makedirs() is the directory + to be created is already there. + +- Patch #1610437: fix a tarfile bug with long filename headers. + +- Patch #1371075: Make ConfigParser accept optional dict type + for ordering, sorting, etc. + +- Bug #1563807: _ctypes built on AIX fails with ld ffi error. + +- Bug #1598620: A ctypes Structure cannot contain itself. + +- Patch #1070046: Marshal new-style objects like InstanceType + in xmlrpclib. + +- cStringIO.truncate(-1) now raises an IOError, like StringIO and + regular files. + +- Patch #1472877: Fix Tix subwidget name resolution. + +- Patch #1594554: Always close a tkSimpleDialog on ok(), even + if an exception occurs. + +- Patch #1538878: Don't make tkSimpleDialog dialogs transient if + the parent window is withdrawn. + +- Bug #1597824: return the registered function from atexit.register() + to facilitate usage as a decorator. + +- Patch #1360200: Use unmangled_version RPM spec field to deal with + file name mangling. + +- Patch #1359217: Process 2xx response in an ftplib transfer + that precedes an 1xx response. + +- Patch #1355023: support whence argument for GzipFile.seek. + +- Patch #1065257: Support passing open files as body in + HTTPConnection.request(). + +- Bug #1569790: mailbox.py: Maildir.get_folder() and MH.get_folder() + weren't passing the message factory on to newly created Maildir/MH + objects. + +- Patch #1514543: mailbox.py: In the Maildir class, report errors if there's + a filename clash instead of possibly losing a message. (Patch by David + Watson.) + +- Patch #1514544: Try to ensure that messages/indexes have been physically + written to disk after calling .flush() or .close(). (Patch by David + Watson.) + +- Patch #1592250: Add elidge argument to Tkinter.Text.search. + +- Patch #838546: Make terminal become controlling in pty.fork() + +- Patch #1351744: Add askyesnocancel helper for tkMessageBox. + +- Patch #1060577: Extract list of RPM files from spec file in + bdist_rpm + +- Bug #1586613: fix zlib and bz2 codecs' incremental en/decoders. + +- Patch #1583880: fix tarfile's problems with long names and posix/ + GNU modes. + +- Bug #1586448: the compiler module now emits the same bytecode for + list comprehensions as the builtin compiler, using the LIST_APPEND + opcode. + +- Fix codecs.EncodedFile which did not use file_encoding in 2.5.0, and + fix all codecs file wrappers to work correctly with the "with" + statement (bug #1586513). + +- Lib/modulefinder.py now handles absolute and relative imports + correctly. + +- Patch #1567274: Support SMTP over TLS. + +- Patch #1560695: Add .note.GNU-stack to ctypes' sysv.S so that + ctypes isn't considered as requiring executable stacks. + +- ctypes callback functions only support 'fundamental' data types as + result type. Raise an error when something else is used. This is a + partial fix for Bug #1574584. + +- Fix turtle so that time.sleep is imported for the entire library. Allows + the demo2 function to be executed on its own instead of only when the + module is run as a script. + +- Bug #813342: Start the IDLE subprocess with -Qnew if the parent + is started with that option. + +- Bug #1565150: Fix subsecond processing for os.utime on Windows. + +- Support for MSVC 8 was added to bdist_wininst. + +- Bug #1446043: correctly raise a LookupError if an encoding name given + to encodings.search_function() contains a dot. + +- Bug #1560617: in pyclbr, return full module name not only for classes, + but also for functions. + +- Bug #1457823: cgi.(Sv)FormContentDict's constructor now takes + keep_blank_values and strict_parsing keyword arguments. + +- Bug #1566602: correct failure of posixpath unittest when $HOME ends + with a slash. + +- Bug #1565661: in webbrowser, split() the command for the default + GNOME browser in case it is a command with args. + +- Made the error message for time.strptime when the data data and format do + match be more clear. + - Fix a bug in traceback.format_exception_only() that led to an error being raised when print_exc() was called without an exception set. In version 2.4, this printed "None", restored that behavior. @@ -73,17 +273,48 @@ - Patch #1550886: Fix decimal module context management implementation to match the localcontext() example from PEP 343. +- Bug #1545341: The 'classifier' keyword argument to the Distutils setup() + function now accepts tuples as well as lists. + - Bug #1541863: uuid.uuid1 failed to generate unique identifiers on systems with low clock resolution. - Bug #1531862: Do not close standard file descriptors in subprocess. -- fixed a bug with bsddb.DB.stat: its flags and txn keyword arguments +- fixed a bug with bsddb.DB.stat: the flags and txn keyword arguments were transposed. + Extension Modules ----------------- +- Patch #1544279: Improve thread-safety of the socket module by moving + the sock_addr_t storage out of the socket object. + +- Speed up function calls into the math module. + +- Bug #1588217: don't parse "= " as a soft line break in binascii's + a2b_qp() function, instead leave it in the string as quopri.decode() + does. + +- Bug #1599782: Fix segfault on bsddb.db.DB().type(). + +- Bug #1567666: Emulate GetFileAttributesExA for Win95. + +- Patch #1576166: Support os.utime for directories on Windows NT+. + +- Bug #1548891: The cStringIO.StringIO() constructor now encodes unicode + arguments with the system default encoding just like the write() + method does, instead of converting it to a raw buffer. + +- Patch #1572724: fix typo ('=' instead of '==') in _msi.c. + +- Bug #1572832: fix a bug in ISO-2022 codecs which may cause segfault + when encoding non-BMP unicode characters. + +- Bug #1556784: allow format strings longer than 127 characters in + datetime's strftime function. + - Fix itertools.count(n) to work with negative numbers again. - RLIMIT_SBSIZE was added to the resource module where available. @@ -102,9 +333,29 @@ - iso2022_jp_3 and iso2022_jp_2004 codec can encode JIS X 0213:2 codepoints now. +- Bug #1552726: in readline.c, avoid repeatedly polling in interactive + mode by only placing a timeout on the select() if an input hook has + been defined. This prevents an interactive Python from waking up 10 + times per second. Patch by Richard Boulton. + +- Added support for linking the bsddb module against BerkeleyDB 4.5.x. + + Tests ----- +- Added test.test_support.EnvironmentVarGuard. It's a class that provides a + context manager so that one can temporarily set or unset environment + variables. + +- Added guard_warnings_filter to test.test_support. It returns a context + manager that protects the 'warnings' module's filter from being mutated + once the context has been exited. + +- Added some tests for modulefinder. + +- Converted test_imp to use unittest. + - Fix bsddb test_basics.test06_Transactions to check the version number properly. @@ -112,13 +363,22 @@ Documentation ------------- +- Bug #1565919: document set types in the Language Reference. + +- Bug #1546052: clarify that PyString_FromString(AndSize) copies the + string pointed to by its parameter. + +- Bug #1566663: remove obsolete example from datetime docs. + - Bug #1541682: Fix example in the "Refcount details" API docs. Additionally, remove a faulty example showing PySequence_SetItem applied to a newly created list object and add notes that this isn't a good idea. -Tools ------ +Tools/Demos +----------- + +- Patch #1552024: add decorator support to unparse.py demo script. - Make auto-generated python.vim file list built-ins and exceptions in alphatbetical order. Makes output more deterministic and easier to tell if @@ -131,8 +391,25 @@ Build ----- +- Disable _XOPEN_SOURCE on NetBSD 1.x. + +- configure now checks whether gcc supports the PyArg_ParseTuple format + attribute. + +- Bug #1578513: Cross compilation was broken by a change to configure. + Repair so that it's back to how it was in 2.4.3. + +- Patch #1576954: Update VC6 build directory; remove redundant + files in VC7. + +- Bug #1568842: Fix test for uintptr_t. + - Patch #1540470, for OpenBSD 4.0. +- Fix build failure on kfreebsd and on the hurd. + +- Fix the build of the library reference in info format. + C API ----- @@ -141,6 +418,13 @@ so it can be used as an expression. +Windows +------- + +- Conditionalize definition of _CRT_SECURE_NO_DEPRECATE + and _CRT_NONSTDC_NO_DEPRECATE. + + Mac --- Modified: python/branches/bcannon-objcap/Misc/SpecialBuilds.txt ============================================================================== --- python/branches/bcannon-objcap/Misc/SpecialBuilds.txt (original) +++ python/branches/bcannon-objcap/Misc/SpecialBuilds.txt Tue Jan 9 23:27:11 2007 @@ -91,7 +91,7 @@ #define CLEANBYTE 0xCB /* clean (newly allocated) memory */ #define DEADBYTE 0xDB /* dead (newly freed) memory */ -#define FORBIDDENBYTE 0xFB /* fordidden -- untouchable bytes */ +#define FORBIDDENBYTE 0xFB /* forbidden -- untouchable bytes */ Strings of these bytes are unlikely to be valid addresses, floats, or 7-bit ASCII strings. Modified: python/branches/bcannon-objcap/Misc/developers.txt ============================================================================== --- python/branches/bcannon-objcap/Misc/developers.txt (original) +++ python/branches/bcannon-objcap/Misc/developers.txt Tue Jan 9 23:27:11 2007 @@ -17,6 +17,15 @@ Permissions History ------------------- +- Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python + project 06 Jan 2007, by NCN, as a tracker tech. He will maintain asyncore. + +- Collin Winter was given SVN access on 05 Jan 2007 by NCN, for PEP + update access. + +- Lars Gustaebel was given SVN access on 20 Dec 2006 by NCN, for tarfile.py + related work. + - 2006 Summer of Code entries: SoC developers are expected to work primarily in nondist/sandbox or on a branch of their own, and will have their work reviewed before changes are accepted into the trunk. Modified: python/branches/bcannon-objcap/Modules/_bsddb.c ============================================================================== --- python/branches/bcannon-objcap/Modules/_bsddb.c (original) +++ python/branches/bcannon-objcap/Modules/_bsddb.c Tue Jan 9 23:27:11 2007 @@ -98,7 +98,7 @@ #error "eek! DBVER can't handle minor versions > 9" #endif -#define PY_BSDDB_VERSION "4.4.6" +#define PY_BSDDB_VERSION "4.5.0" static char *rcs_id = "$Id$"; @@ -1779,9 +1779,7 @@ return NULL; CHECK_DB_NOT_CLOSED(self); - MYDB_BEGIN_ALLOW_THREADS; type = _DB_get_type(self); - MYDB_END_ALLOW_THREADS; if (type == -1) return NULL; return PyInt_FromLong(type); @@ -4129,6 +4127,7 @@ } +#if (DBVER < 45) static PyObject* DBEnv_set_lk_max(DBEnvObject* self, PyObject* args) { @@ -4144,6 +4143,7 @@ RETURN_IF_ERR(); RETURN_NONE(); } +#endif #if (DBVER >= 32) @@ -5233,7 +5233,9 @@ {"set_lg_regionmax",(PyCFunction)DBEnv_set_lg_regionmax, METH_VARARGS}, #endif {"set_lk_detect", (PyCFunction)DBEnv_set_lk_detect, METH_VARARGS}, +#if (DBVER < 45) {"set_lk_max", (PyCFunction)DBEnv_set_lk_max, METH_VARARGS}, +#endif #if (DBVER >= 32) {"set_lk_max_locks", (PyCFunction)DBEnv_set_lk_max_locks, METH_VARARGS}, {"set_lk_max_lockers", (PyCFunction)DBEnv_set_lk_max_lockers, METH_VARARGS}, @@ -5835,7 +5837,9 @@ ADD_INT(d, DB_AFTER); ADD_INT(d, DB_APPEND); ADD_INT(d, DB_BEFORE); +#if (DBVER < 45) ADD_INT(d, DB_CACHED_COUNTS); +#endif #if (DBVER >= 41) _addIntToDict(d, "DB_CHECKPOINT", 0); #else @@ -5870,7 +5874,9 @@ ADD_INT(d, DB_POSITION); ADD_INT(d, DB_PREV); ADD_INT(d, DB_PREV_NODUP); +#if (DBVER < 45) ADD_INT(d, DB_RECORDCOUNT); +#endif ADD_INT(d, DB_SET); ADD_INT(d, DB_SET_RANGE); ADD_INT(d, DB_SET_RECNO); Modified: python/branches/bcannon-objcap/Modules/_ctypes/callbacks.c ============================================================================== --- python/branches/bcannon-objcap/Modules/_ctypes/callbacks.c (original) +++ python/branches/bcannon-objcap/Modules/_ctypes/callbacks.c Tue Jan 9 23:27:11 2007 @@ -293,8 +293,11 @@ p->restype = &ffi_type_void; } else { StgDictObject *dict = PyType_stgdict(restype); - if (dict == NULL) - goto error; + if (dict == NULL || dict->setfunc == NULL) { + PyErr_SetString(PyExc_TypeError, + "invalid result type for callback function"); + goto error; + } p->setfunc = dict->setfunc; p->restype = &dict->ffi_type_pointer; } Modified: python/branches/bcannon-objcap/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/bcannon-objcap/Modules/_ctypes/callproc.c (original) +++ python/branches/bcannon-objcap/Modules/_ctypes/callproc.c Tue Jan 9 23:27:11 2007 @@ -1247,11 +1247,11 @@ static PyObject *py_dl_close(PyObject *self, PyObject *args) { - void * handle; + int handle; if (!PyArg_ParseTuple(args, "i:dlclose", &handle)) return NULL; - if (dlclose(handle)) { + if (dlclose((void*)handle)) { PyErr_SetString(PyExc_OSError, ctypes_dlerror()); return NULL; @@ -1263,12 +1263,12 @@ static PyObject *py_dl_sym(PyObject *self, PyObject *args) { char *name; - void *handle; + int handle; void *ptr; if (!PyArg_ParseTuple(args, "is:dlsym", &handle, &name)) return NULL; - ptr = ctypes_dlsym(handle, name); + ptr = ctypes_dlsym((void*)handle, name); if (!ptr) { PyErr_SetString(PyExc_OSError, ctypes_dlerror()); @@ -1286,7 +1286,7 @@ static PyObject * call_function(PyObject *self, PyObject *args) { - PPROC func; + int func; PyObject *arguments; PyObject *result; @@ -1296,7 +1296,7 @@ &PyTuple_Type, &arguments)) return NULL; - result = _CallProc(func, + result = _CallProc((PPROC)func, arguments, #ifdef MS_WIN32 NULL, @@ -1317,7 +1317,7 @@ static PyObject * call_cdeclfunction(PyObject *self, PyObject *args) { - PPROC func; + int func; PyObject *arguments; PyObject *result; @@ -1327,7 +1327,7 @@ &PyTuple_Type, &arguments)) return NULL; - result = _CallProc(func, + result = _CallProc((PPROC)func, arguments, #ifdef MS_WIN32 NULL, @@ -1510,7 +1510,7 @@ #else "On:resize", #endif - (PyObject *)&obj, &size)) + &obj, &size)) return NULL; dict = PyObject_stgdict((PyObject *)obj); Modified: python/branches/bcannon-objcap/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c ============================================================================== --- python/branches/bcannon-objcap/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c (original) +++ python/branches/bcannon-objcap/Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c Tue Jan 9 23:27:11 2007 @@ -1,4 +1,4 @@ -#ifdef __ppc__ +#if !(defined(__APPLE__) && !defined(__ppc__)) /* ----------------------------------------------------------------------- ffi.c - Copyright (c) 1998 Geoffrey Keating Modified: python/branches/bcannon-objcap/Modules/_ctypes/libffi/src/x86/sysv.S ============================================================================== --- python/branches/bcannon-objcap/Modules/_ctypes/libffi/src/x86/sysv.S (original) +++ python/branches/bcannon-objcap/Modules/_ctypes/libffi/src/x86/sysv.S Tue Jan 9 23:27:11 2007 @@ -376,3 +376,7 @@ #endif #endif /* ifndef __x86_64__ */ + +#ifdef __ELF__ +.section .note.GNU-stack,"",%progbits +#endif Modified: python/branches/bcannon-objcap/Modules/_ctypes/stgdict.c ============================================================================== --- python/branches/bcannon-objcap/Modules/_ctypes/stgdict.c (original) +++ python/branches/bcannon-objcap/Modules/_ctypes/stgdict.c Tue Jan 9 23:27:11 2007 @@ -339,14 +339,14 @@ stgdict = PyType_stgdict(type); if (!stgdict) return -1; + /* If this structure/union is already marked final we cannot assign + _fields_ anymore. */ + if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */ PyErr_SetString(PyExc_AttributeError, "_fields_ is final"); return -1; } - /* XXX This should probably be moved to a point when all this - stuff is sucessfully finished. */ - stgdict->flags |= DICTFLAG_FINAL; /* set final */ if (stgdict->ffi_type_pointer.elements) PyMem_Free(stgdict->ffi_type_pointer.elements); @@ -480,5 +480,15 @@ stgdict->size = size; stgdict->align = total_align; stgdict->length = len; /* ADD ffi_ofs? */ + + /* We did check that this flag was NOT set above, it must not + have been set until now. */ + if (stgdict->flags & DICTFLAG_FINAL) { + PyErr_SetString(PyExc_AttributeError, + "Structure or union cannot contain itself"); + return -1; + } + stgdict->flags |= DICTFLAG_FINAL; + return MakeAnonFields(type); } Modified: python/branches/bcannon-objcap/Modules/_sre.c ============================================================================== --- python/branches/bcannon-objcap/Modules/_sre.c (original) +++ python/branches/bcannon-objcap/Modules/_sre.c Tue Jan 9 23:27:11 2007 @@ -1166,9 +1166,10 @@ /* install new repeat context */ ctx->u.rep = (SRE_REPEAT*) PyObject_MALLOC(sizeof(*ctx->u.rep)); - /* XXX(nnorwitz): anything else we need to do on error? */ - if (!ctx->u.rep) + if (!ctx->u.rep) { + PyErr_NoMemory(); RETURN_FAILURE; + } ctx->u.rep->count = -1; ctx->u.rep->pattern = ctx->pattern; ctx->u.rep->prev = state->repeat; @@ -1884,6 +1885,8 @@ } TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr)); + if (PyErr_Occurred()) + return NULL; state_fini(&state); @@ -1922,6 +1925,9 @@ state_fini(&state); + if (PyErr_Occurred()) + return NULL; + return pattern_new_match(self, &state, status); } @@ -2071,6 +2077,9 @@ #endif } + if (PyErr_Occurred()) + goto error; + if (status <= 0) { if (status == 0) break; @@ -2198,6 +2207,9 @@ #endif } + if (PyErr_Occurred()) + goto error; + if (status <= 0) { if (status == 0) break; @@ -2347,6 +2359,9 @@ #endif } + if (PyErr_Occurred()) + goto error; + if (status <= 0) { if (status == 0) break; @@ -3250,6 +3265,8 @@ status = sre_umatch(state, PatternObject_GetCode(self->pattern)); #endif } + if (PyErr_Occurred()) + return NULL; match = pattern_new_match((PatternObject*) self->pattern, state, status); @@ -3281,6 +3298,8 @@ status = sre_usearch(state, PatternObject_GetCode(self->pattern)); #endif } + if (PyErr_Occurred()) + return NULL; match = pattern_new_match((PatternObject*) self->pattern, state, status); Modified: python/branches/bcannon-objcap/Modules/_ssl.c ============================================================================== --- python/branches/bcannon-objcap/Modules/_ssl.c (original) +++ python/branches/bcannon-objcap/Modules/_ssl.c Tue Jan 9 23:27:11 2007 @@ -317,7 +317,7 @@ if (!PyArg_ParseTuple(args, "O!|zz:ssl", PySocketModule.Sock_Type, - (PyObject*)&Sock, + &Sock, &key_file, &cert_file)) return NULL; Modified: python/branches/bcannon-objcap/Modules/_testcapimodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/_testcapimodule.c (original) +++ python/branches/bcannon-objcap/Modules/_testcapimodule.c Tue Jan 9 23:27:11 2007 @@ -6,6 +6,8 @@ */ #include "Python.h" +#include +#include "structmember.h" #ifdef WITH_THREAD #include "pythread.h" @@ -35,13 +37,13 @@ platforms have these hardcoded. Better safe than sorry. */ static PyObject* -sizeof_error(const char* fatname, const char* typename, +sizeof_error(const char* fatname, const char* typname, int expected, int got) { char buf[1024]; PyOS_snprintf(buf, sizeof(buf), "%.200s #define == %d but sizeof(%.200s) == %d", - fatname, expected, typename, got); + fatname, expected, typname, got); PyErr_SetString(TestError, buf); return (PyObject*)NULL; } @@ -615,7 +617,7 @@ { PyObject *rc; PyGILState_STATE s = PyGILState_Ensure(); - rc = PyObject_CallFunction(callable, ""); + rc = PyObject_CallFunction((PyObject *)callable, ""); Py_XDECREF(rc); PyGILState_Release(s); } @@ -665,6 +667,9 @@ PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ Py_END_ALLOW_THREADS + /* Release lock we acquired above. This is required on HP-UX. */ + PyThread_release_lock(thread_done); + PyThread_free_lock(thread_done); Py_RETURN_NONE; } @@ -756,6 +761,105 @@ #define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);} +typedef struct { + char byte_member; + unsigned char ubyte_member; + short short_member; + unsigned short ushort_member; + int int_member; + unsigned int uint_member; + long long_member; + unsigned long ulong_member; + float float_member; + double double_member; +} all_structmembers; + +typedef struct { + PyObject_HEAD + all_structmembers structmembers; +} test_structmembers; + +static struct PyMemberDef test_members[] = { + {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL}, + {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL}, + {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL}, + {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL}, + {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL}, + {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL}, + {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL}, + {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL}, + {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL}, + {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL}, + {NULL} +}; + + +static PyObject *test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs){ + static char *keywords[]={"T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", "T_INT", "T_UINT", + "T_LONG", "T_ULONG", "T_FLOAT", "T_DOUBLE", NULL}; + test_structmembers *ob=PyObject_New(test_structmembers, type); + if (ob==NULL) + return NULL; + memset(&ob->structmembers, 0, sizeof(all_structmembers)); + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|bBhHiIlkfd", keywords, + &ob->structmembers.byte_member, &ob->structmembers.ubyte_member, + &ob->structmembers.short_member, &ob->structmembers.ushort_member, + &ob->structmembers.int_member, &ob->structmembers.uint_member, + &ob->structmembers.long_member, &ob->structmembers.ulong_member, + &ob->structmembers.float_member, &ob->structmembers.double_member)){ + Py_DECREF(ob); + return NULL; + } + return (PyObject *)ob; +} + +static void test_structmembers_free(PyObject *ob){ + PyObject_FREE(ob); +} + +static PyTypeObject test_structmembersType = { + PyObject_HEAD_INIT(NULL) + 0, + "test_structmembersType", + sizeof(test_structmembers), /* tp_basicsize */ + 0, /* tp_itemsize */ + test_structmembers_free, /* destructor 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, + PyObject_GenericSetAttr, + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + "Type containing all structmember types", + 0, /* traverseproc tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + test_members, /* tp_members */ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + test_structmembers_new, /* tp_new */ +}; + + PyMODINIT_FUNC init_testcapi(void) { @@ -765,16 +869,28 @@ if (m == NULL) return; + test_structmembersType.ob_type=&PyType_Type; + Py_INCREF(&test_structmembersType); + PyModule_AddObject(m, "test_structmembersType", (PyObject *)&test_structmembersType); + + PyModule_AddObject(m, "CHAR_MAX", PyInt_FromLong(CHAR_MAX)); + PyModule_AddObject(m, "CHAR_MIN", PyInt_FromLong(CHAR_MIN)); PyModule_AddObject(m, "UCHAR_MAX", PyInt_FromLong(UCHAR_MAX)); + PyModule_AddObject(m, "SHRT_MAX", PyInt_FromLong(SHRT_MAX)); + PyModule_AddObject(m, "SHRT_MIN", PyInt_FromLong(SHRT_MIN)); PyModule_AddObject(m, "USHRT_MAX", PyInt_FromLong(USHRT_MAX)); + PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX)); + PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN)); PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX)); - PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX)); - PyModule_AddObject(m, "INT_MIN", PyInt_FromLong(INT_MIN)); - PyModule_AddObject(m, "LONG_MIN", PyInt_FromLong(LONG_MIN)); - PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN)); - PyModule_AddObject(m, "INT_MAX", PyInt_FromLong(INT_MAX)); PyModule_AddObject(m, "LONG_MAX", PyInt_FromLong(LONG_MAX)); + PyModule_AddObject(m, "LONG_MIN", PyInt_FromLong(LONG_MIN)); + PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX)); + PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX)); + PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN)); + PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX)); + PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN)); PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyInt_FromSsize_t(PY_SSIZE_T_MAX)); + PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN)); TestError = PyErr_NewException("_testcapi.error", NULL, NULL); Py_INCREF(TestError); Modified: python/branches/bcannon-objcap/Modules/audioop.c ============================================================================== --- python/branches/bcannon-objcap/Modules/audioop.c (original) +++ python/branches/bcannon-objcap/Modules/audioop.c Tue Jan 9 23:27:11 2007 @@ -472,8 +472,12 @@ double aj_m1, aj_lm1; double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor; + /* Passing a short** for an 's' argument is correct only + if the string contents is aligned for interpretation + as short[]. Due to the definition of PyStringObject, + this is currently (Python 2.6) the case. */ if ( !PyArg_ParseTuple(args, "s#s#:findfit", - &cp1, &len1, &cp2, &len2) ) + (char**)&cp1, &len1, (char**)&cp2, &len2) ) return 0; if ( len1 & 1 || len2 & 1 ) { PyErr_SetString(AudioopError, "Strings should be even-sized"); @@ -530,7 +534,7 @@ double sum_ri_2, sum_aij_ri, result; if ( !PyArg_ParseTuple(args, "s#s#:findfactor", - &cp1, &len1, &cp2, &len2) ) + (char**)&cp1, &len1, (char**)&cp2, &len2) ) return 0; if ( len1 & 1 || len2 & 1 ) { PyErr_SetString(AudioopError, "Strings should be even-sized"); @@ -562,7 +566,8 @@ double aj_m1, aj_lm1; double result, best_result; - if ( !PyArg_ParseTuple(args, "s#i:findmax", &cp1, &len1, &len2) ) + if ( !PyArg_ParseTuple(args, "s#i:findmax", + (char**)&cp1, &len1, &len2) ) return 0; if ( len1 & 1 ) { PyErr_SetString(AudioopError, "Strings should be even-sized"); Modified: python/branches/bcannon-objcap/Modules/binascii.c ============================================================================== --- python/branches/bcannon-objcap/Modules/binascii.c (original) +++ python/branches/bcannon-objcap/Modules/binascii.c Tue Jan 9 23:27:11 2007 @@ -1057,8 +1057,7 @@ in++; if (in >= datalen) break; /* Soft line breaks */ - if ((data[in] == '\n') || (data[in] == '\r') || - (data[in] == ' ') || (data[in] == '\t')) { + if ((data[in] == '\n') || (data[in] == '\r')) { if (data[in] != '\n') { while (in < datalen && data[in] != '\n') in++; } Modified: python/branches/bcannon-objcap/Modules/bz2module.c ============================================================================== --- python/branches/bcannon-objcap/Modules/bz2module.c (original) +++ python/branches/bcannon-objcap/Modules/bz2module.c Tue Jan 9 23:27:11 2007 @@ -996,7 +996,7 @@ char small_buffer[SMALLCHUNK]; char *buffer = small_buffer; size_t buffersize = SMALLCHUNK; - int bytesread = 0; + Py_off_t bytesread = 0; size_t readsize; int chunksize; int bzerror; Modified: python/branches/bcannon-objcap/Modules/cPickle.c ============================================================================== --- python/branches/bcannon-objcap/Modules/cPickle.c (original) +++ python/branches/bcannon-objcap/Modules/cPickle.c Tue Jan 9 23:27:11 2007 @@ -1024,7 +1024,7 @@ static int save_long(Picklerobject *self, PyObject *args) { - int size; + Py_ssize_t size; int res = -1; PyObject *repr = NULL; @@ -1066,7 +1066,7 @@ * byte at the start, and cut it back later if possible. */ nbytes = (nbits >> 3) + 1; - if ((int)nbytes < 0 || (size_t)(int)nbytes != nbytes) { + if (nbytes > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "long too large " "to pickle"); goto finally; @@ -1208,12 +1208,14 @@ c_str[1] = size; len = 2; } - else { + else if (size <= INT_MAX) { c_str[0] = BINSTRING; for (i = 1; i < 5; i++) c_str[i] = (int)(size >> ((i - 1) * 8)); len = 5; } + else + return -1; /* string too large */ if (self->write_func(self, c_str, len) < 0) return -1; @@ -1286,7 +1288,7 @@ static int save_unicode(Picklerobject *self, PyObject *args, int doput) { - int size, len; + Py_ssize_t size, len; PyObject *repr=0; if (!PyUnicode_Check(args)) @@ -1325,6 +1327,8 @@ if ((size = PyString_Size(repr)) < 0) goto err; + if (size > INT_MAX) + return -1; /* string too large */ c_str[0] = BINUNICODE; for (i = 1; i < 5; i++) Modified: python/branches/bcannon-objcap/Modules/cStringIO.c ============================================================================== --- python/branches/bcannon-objcap/Modules/cStringIO.c (original) +++ python/branches/bcannon-objcap/Modules/cStringIO.c Tue Jan 9 23:27:11 2007 @@ -289,7 +289,17 @@ if (!IO__opencheck(self)) return NULL; if (!PyArg_ParseTuple(args, "|n:truncate", &pos)) return NULL; - if (pos < 0) pos = self->pos; + + if (PyTuple_Size(args) == 0) { + /* No argument passed, truncate to current position */ + pos = self->pos; + } + + if (pos < 0) { + errno = EINVAL; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } if (self->string_size > pos) self->string_size = pos; self->pos = self->string_size; @@ -657,11 +667,9 @@ char *buf; Py_ssize_t size; - if (PyObject_AsReadBuffer(s, (const void **)&buf, &size)) { - PyErr_Format(PyExc_TypeError, "expected read buffer, %.200s found", - s->ob_type->tp_name); + if (PyObject_AsCharBuffer(s, (const char **)&buf, &size) != 0) return NULL; - } + self = PyObject_New(Iobject, &Itype); if (!self) return NULL; Py_INCREF(s); Modified: python/branches/bcannon-objcap/Modules/cjkcodecs/_codecs_iso2022.c ============================================================================== --- python/branches/bcannon-objcap/Modules/cjkcodecs/_codecs_iso2022.c (original) +++ python/branches/bcannon-objcap/Modules/cjkcodecs/_codecs_iso2022.c Tue Jan 9 23:27:11 2007 @@ -592,9 +592,11 @@ { DBCHAR coded; assert(*length == 1); - TRYMAP_ENC(cp949, coded, *data) - if (!(coded & 0x8000)) - return coded; + if (*data < 0x10000) { + TRYMAP_ENC(cp949, coded, *data) + if (!(coded & 0x8000)) + return coded; + } return MAP_UNMAPPABLE; } @@ -628,11 +630,13 @@ { DBCHAR coded; assert(*length == 1); - if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */ - return 0x2140; - else TRYMAP_ENC(jisxcommon, coded, *data) { - if (!(coded & 0x8000)) - return coded; + if (*data < 0x10000) { + if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */ + return 0x2140; + else TRYMAP_ENC(jisxcommon, coded, *data) { + if (!(coded & 0x8000)) + return coded; + } } return MAP_UNMAPPABLE; } @@ -665,9 +669,11 @@ { DBCHAR coded; assert(*length == 1); - TRYMAP_ENC(jisxcommon, coded, *data) { - if (coded & 0x8000) - return coded & 0x7fff; + if (*data < 0x10000) { + TRYMAP_ENC(jisxcommon, coded, *data) { + if (coded & 0x8000) + return coded & 0x7fff; + } } return MAP_UNMAPPABLE; } @@ -970,9 +976,11 @@ { DBCHAR coded; assert(*length == 1); - TRYMAP_ENC(gbcommon, coded, *data) { - if (!(coded & 0x8000)) - return coded; + if (*data < 0x10000) { + TRYMAP_ENC(gbcommon, coded, *data) { + if (!(coded & 0x8000)) + return coded; + } } return MAP_UNMAPPABLE; } Modified: python/branches/bcannon-objcap/Modules/collectionsmodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/collectionsmodule.c (original) +++ python/branches/bcannon-objcap/Modules/collectionsmodule.c Tue Jan 9 23:27:11 2007 @@ -911,15 +911,14 @@ { PyObject *item; - if (it->counter == 0) - return NULL; - if (it->deque->state != it->state) { it->counter = 0; PyErr_SetString(PyExc_RuntimeError, "deque mutated during iteration"); return NULL; } + if (it->counter == 0) + return NULL; assert (!(it->b == it->deque->rightblock && it->index > it->deque->rightindex)); Modified: python/branches/bcannon-objcap/Modules/datetimemodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/datetimemodule.c (original) +++ python/branches/bcannon-objcap/Modules/datetimemodule.c Tue Jan 9 23:27:11 2007 @@ -1149,9 +1149,9 @@ PyObject *newfmt = NULL; /* py string, the output format */ char *pnew; /* pointer to available byte in output format */ - char totalnew; /* number bytes total in output format buffer, + int totalnew; /* number bytes total in output format buffer, exclusive of trailing \0 */ - char usednew; /* number bytes used so far in output format buffer */ + int usednew; /* number bytes used so far in output format buffer */ char *ptoappend; /* pointer to string to append to output buffer */ int ntoappend; /* # of bytes to append to output buffer */ Modified: python/branches/bcannon-objcap/Modules/dbmmodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/dbmmodule.c (original) +++ python/branches/bcannon-objcap/Modules/dbmmodule.c Tue Jan 9 23:27:11 2007 @@ -208,11 +208,13 @@ static PyObject * dbm_has_key(register dbmobject *dp, PyObject *args) { + char *tmp_ptr; datum key, val; int tmp_size; - if (!PyArg_ParseTuple(args, "s#:has_key", &key.dptr, &tmp_size)) + if (!PyArg_ParseTuple(args, "s#:has_key", &tmp_ptr, &tmp_size)) return NULL; + key.dptr = tmp_ptr; key.dsize = tmp_size; check_dbmobject_open(dp); val = dbm_fetch(dp->di_dbm, key); @@ -224,11 +226,13 @@ { datum key, val; PyObject *defvalue = Py_None; + char *tmp_ptr; int tmp_size; if (!PyArg_ParseTuple(args, "s#|O:get", - &key.dptr, &tmp_size, &defvalue)) + &tmp_ptr, &tmp_size, &defvalue)) return NULL; + key.dptr = tmp_ptr; key.dsize = tmp_size; check_dbmobject_open(dp); val = dbm_fetch(dp->di_dbm, key); @@ -245,11 +249,13 @@ { datum key, val; PyObject *defvalue = NULL; + char *tmp_ptr; int tmp_size; if (!PyArg_ParseTuple(args, "s#|S:setdefault", - &key.dptr, &tmp_size, &defvalue)) + &tmp_ptr, &tmp_size, &defvalue)) return NULL; + key.dptr = tmp_ptr; key.dsize = tmp_size; check_dbmobject_open(dp); val = dbm_fetch(dp->di_dbm, key); Modified: python/branches/bcannon-objcap/Modules/gcmodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/gcmodule.c (original) +++ python/branches/bcannon-objcap/Modules/gcmodule.c Tue Jan 9 23:27:11 2007 @@ -1179,6 +1179,7 @@ "disable() -- Disable automatic garbage collection.\n" "isenabled() -- Returns true if automatic collection is enabled.\n" "collect() -- Do a full collection right now.\n" +"get_count() -- Return the current collection counts.\n" "set_debug() -- Set debugging flags.\n" "get_debug() -- Get debugging flags.\n" "set_threshold() -- Set the collection thresholds.\n" Modified: python/branches/bcannon-objcap/Modules/linuxaudiodev.c ============================================================================== --- python/branches/bcannon-objcap/Modules/linuxaudiodev.c (original) +++ python/branches/bcannon-objcap/Modules/linuxaudiodev.c Tue Jan 9 23:27:11 2007 @@ -28,7 +28,9 @@ #if defined(linux) #include +#ifndef HAVE_STDINT_H typedef unsigned long uint32_t; +#endif #elif defined(__FreeBSD__) #include Modified: python/branches/bcannon-objcap/Modules/main.c ============================================================================== --- python/branches/bcannon-objcap/Modules/main.c (original) +++ python/branches/bcannon-objcap/Modules/main.c Tue Jan 9 23:27:11 2007 @@ -177,6 +177,33 @@ return 0; } +/* Wait until threading._shutdown completes, provided + the threading module was imported in the first place. + The shutdown routine will wait until all non-daemon + "threading" threads have completed. */ +#include "abstract.h" +static void +WaitForThreadShutdown(void) +{ +#ifdef WITH_THREAD + PyObject *result; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_shutdown", ""); + if (result == NULL) + PyErr_WriteUnraisable(threading); + else + Py_DECREF(result); + Py_DECREF(threading); +#endif +} + /* Main program */ int @@ -514,6 +541,8 @@ /* XXX */ sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + WaitForThreadShutdown(); + Py_Finalize(); #ifdef RISCOS if (Py_RISCOSWimpFlag) Modified: python/branches/bcannon-objcap/Modules/mathmodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/mathmodule.c (original) +++ python/branches/bcannon-objcap/Modules/mathmodule.c Tue Jan 9 23:27:11 2007 @@ -48,10 +48,10 @@ } static PyObject * -math_1(PyObject *args, double (*func) (double), char *argsfmt) +math_1(PyObject *arg, double (*func) (double)) { - double x; - if (! PyArg_ParseTuple(args, argsfmt, &x)) + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) return NULL; errno = 0; PyFPE_START_PROTECT("in math_1", return 0) @@ -65,10 +65,15 @@ } static PyObject * -math_2(PyObject *args, double (*func) (double, double), char *argsfmt) +math_2(PyObject *args, double (*func) (double, double), char *funcname) { + PyObject *ox, *oy; double x, y; - if (! PyArg_ParseTuple(args, argsfmt, &x, &y)) + if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) return NULL; errno = 0; PyFPE_START_PROTECT("in math_2", return 0) @@ -83,13 +88,13 @@ #define FUNC1(funcname, func, docstring) \ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_1(args, func, "d:" #funcname); \ + return math_1(args, func); \ }\ PyDoc_STRVAR(math_##funcname##_doc, docstring); #define FUNC2(funcname, func, docstring) \ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_2(args, func, "dd:" #funcname); \ + return math_2(args, func, #funcname); \ }\ PyDoc_STRVAR(math_##funcname##_doc, docstring); @@ -135,11 +140,11 @@ "tanh(x)\n\nReturn the hyperbolic tangent of x.") static PyObject * -math_frexp(PyObject *self, PyObject *args) +math_frexp(PyObject *self, PyObject *arg) { - double x; int i; - if (! PyArg_ParseTuple(args, "d:frexp", &x)) + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) return NULL; errno = 0; x = frexp(x, &i); @@ -179,10 +184,10 @@ "ldexp(x, i) -> x * (2**i)"); static PyObject * -math_modf(PyObject *self, PyObject *args) +math_modf(PyObject *self, PyObject *arg) { - double x, y; - if (! PyArg_ParseTuple(args, "d:modf", &x)) + double y, x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) return NULL; errno = 0; x = modf(x, &y); @@ -208,7 +213,7 @@ */ static PyObject* -loghelper(PyObject* args, double (*func)(double), char *format, PyObject *arg) +loghelper(PyObject* arg, double (*func)(double), char *funcname) { /* If it is long, do it ourselves. */ if (PyLong_Check(arg)) { @@ -229,7 +234,7 @@ } /* Else let libm handle it by itself. */ - return math_1(args, func, format); + return math_1(arg, func); } static PyObject * @@ -239,28 +244,15 @@ PyObject *base = NULL; PyObject *num, *den; PyObject *ans; - PyObject *newargs; if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base)) return NULL; - if (base == NULL) - return loghelper(args, log, "d:log", arg); - newargs = PyTuple_Pack(1, arg); - if (newargs == NULL) - return NULL; - num = loghelper(newargs, log, "d:log", arg); - Py_DECREF(newargs); - if (num == NULL) - return NULL; + num = loghelper(arg, log, "log"); + if (num == NULL || base == NULL) + return num; - newargs = PyTuple_Pack(1, base); - if (newargs == NULL) { - Py_DECREF(num); - return NULL; - } - den = loghelper(newargs, log, "d:log", base); - Py_DECREF(newargs); + den = loghelper(base, log, "log"); if (den == NULL) { Py_DECREF(num); return NULL; @@ -277,25 +269,23 @@ If the base not specified, returns the natural logarithm (base e) of x."); static PyObject * -math_log10(PyObject *self, PyObject *args) +math_log10(PyObject *self, PyObject *arg) { - PyObject *arg; - - if (!PyArg_UnpackTuple(args, "log10", 1, 1, &arg)) - return NULL; - return loghelper(args, log10, "d:log10", arg); + return loghelper(arg, log10, "log10"); } PyDoc_STRVAR(math_log10_doc, "log10(x) -> the base 10 logarithm of x."); +/* XXX(nnorwitz): Should we use the platform M_PI or something more accurate + like: 3.14159265358979323846264338327950288 */ static const double degToRad = 3.141592653589793238462643383 / 180.0; static PyObject * -math_degrees(PyObject *self, PyObject *args) +math_degrees(PyObject *self, PyObject *arg) { - double x; - if (! PyArg_ParseTuple(args, "d:degrees", &x)) + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) return NULL; return PyFloat_FromDouble(x / degToRad); } @@ -304,10 +294,10 @@ "degrees(x) -> converts angle x from radians to degrees"); static PyObject * -math_radians(PyObject *self, PyObject *args) +math_radians(PyObject *self, PyObject *arg) { - double x; - if (! PyArg_ParseTuple(args, "d:radians", &x)) + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) return NULL; return PyFloat_FromDouble(x * degToRad); } @@ -316,31 +306,31 @@ "radians(x) -> converts angle x from degrees to radians"); static PyMethodDef math_methods[] = { - {"acos", math_acos, METH_VARARGS, math_acos_doc}, - {"asin", math_asin, METH_VARARGS, math_asin_doc}, - {"atan", math_atan, METH_VARARGS, math_atan_doc}, + {"acos", math_acos, METH_O, math_acos_doc}, + {"asin", math_asin, METH_O, math_asin_doc}, + {"atan", math_atan, METH_O, math_atan_doc}, {"atan2", math_atan2, METH_VARARGS, math_atan2_doc}, - {"ceil", math_ceil, METH_VARARGS, math_ceil_doc}, - {"cos", math_cos, METH_VARARGS, math_cos_doc}, - {"cosh", math_cosh, METH_VARARGS, math_cosh_doc}, - {"degrees", math_degrees, METH_VARARGS, math_degrees_doc}, - {"exp", math_exp, METH_VARARGS, math_exp_doc}, - {"fabs", math_fabs, METH_VARARGS, math_fabs_doc}, - {"floor", math_floor, METH_VARARGS, math_floor_doc}, + {"ceil", math_ceil, METH_O, math_ceil_doc}, + {"cos", math_cos, METH_O, math_cos_doc}, + {"cosh", math_cosh, METH_O, math_cosh_doc}, + {"degrees", math_degrees, METH_O, math_degrees_doc}, + {"exp", math_exp, METH_O, math_exp_doc}, + {"fabs", math_fabs, METH_O, math_fabs_doc}, + {"floor", math_floor, METH_O, math_floor_doc}, {"fmod", math_fmod, METH_VARARGS, math_fmod_doc}, - {"frexp", math_frexp, METH_VARARGS, math_frexp_doc}, + {"frexp", math_frexp, METH_O, math_frexp_doc}, {"hypot", math_hypot, METH_VARARGS, math_hypot_doc}, {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc}, {"log", math_log, METH_VARARGS, math_log_doc}, - {"log10", math_log10, METH_VARARGS, math_log10_doc}, - {"modf", math_modf, METH_VARARGS, math_modf_doc}, + {"log10", math_log10, METH_O, math_log10_doc}, + {"modf", math_modf, METH_O, math_modf_doc}, {"pow", math_pow, METH_VARARGS, math_pow_doc}, - {"radians", math_radians, METH_VARARGS, math_radians_doc}, - {"sin", math_sin, METH_VARARGS, math_sin_doc}, - {"sinh", math_sinh, METH_VARARGS, math_sinh_doc}, - {"sqrt", math_sqrt, METH_VARARGS, math_sqrt_doc}, - {"tan", math_tan, METH_VARARGS, math_tan_doc}, - {"tanh", math_tanh, METH_VARARGS, math_tanh_doc}, + {"radians", math_radians, METH_O, math_radians_doc}, + {"sin", math_sin, METH_O, math_sin_doc}, + {"sinh", math_sinh, METH_O, math_sinh_doc}, + {"sqrt", math_sqrt, METH_O, math_sqrt_doc}, + {"tan", math_tan, METH_O, math_tan_doc}, + {"tanh", math_tanh, METH_O, math_tanh_doc}, {NULL, NULL} /* sentinel */ }; @@ -358,6 +348,8 @@ if (m == NULL) goto finally; d = PyModule_GetDict(m); + if (d == NULL) + goto finally; if (!(v = PyFloat_FromDouble(atan(1.0) * 4.0))) goto finally; Modified: python/branches/bcannon-objcap/Modules/ossaudiodev.c ============================================================================== --- python/branches/bcannon-objcap/Modules/ossaudiodev.c (original) +++ python/branches/bcannon-objcap/Modules/ossaudiodev.c Tue Jan 9 23:27:11 2007 @@ -34,7 +34,9 @@ #if defined(linux) +#ifndef HAVE_STDINT_H typedef unsigned long uint32_t; +#endif #elif defined(__FreeBSD__) Modified: python/branches/bcannon-objcap/Modules/posixmodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/posixmodule.c (original) +++ python/branches/bcannon-objcap/Modules/posixmodule.c Tue Jan 9 23:27:11 2007 @@ -792,7 +792,7 @@ /* XXX endianness */ __int64 out; out = time_in + secs_between_epochs; - out = out * 10000000 + nsec_in; + out = out * 10000000 + nsec_in / 100; memcpy(out_ptr, &out, sizeof(out)); } @@ -828,6 +828,106 @@ return 0; } +/* Emulate GetFileAttributesEx[AW] on Windows 95 */ +static int checked = 0; +static BOOL (CALLBACK *gfaxa)(LPCSTR, GET_FILEEX_INFO_LEVELS, LPVOID); +static BOOL (CALLBACK *gfaxw)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID); +static void +check_gfax() +{ + HINSTANCE hKernel32; + if (checked) + return; + checked = 1; + hKernel32 = GetModuleHandle("KERNEL32"); + *(FARPROC*)&gfaxa = GetProcAddress(hKernel32, "GetFileAttributesExA"); + *(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW"); +} + +static BOOL WINAPI +Py_GetFileAttributesExA(LPCSTR pszFile, + GET_FILEEX_INFO_LEVELS level, + LPVOID pv) +{ + BOOL result; + HANDLE hFindFile; + WIN32_FIND_DATAA FileData; + LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; + /* First try to use the system's implementation, if that is + available and either succeeds to gives an error other than + that it isn't implemented. */ + check_gfax(); + if (gfaxa) { + result = gfaxa(pszFile, level, pv); + if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) + return result; + } + /* It's either not present, or not implemented. + Emulate using FindFirstFile. */ + if (level != GetFileExInfoStandard) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + /* Use GetFileAttributes to validate that the file name + does not contain wildcards (which FindFirstFile would + accept). */ + if (GetFileAttributesA(pszFile) == 0xFFFFFFFF) + return FALSE; + hFindFile = FindFirstFileA(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; +} + +static BOOL WINAPI +Py_GetFileAttributesExW(LPCWSTR pszFile, + GET_FILEEX_INFO_LEVELS level, + LPVOID pv) +{ + BOOL result; + HANDLE hFindFile; + WIN32_FIND_DATAW FileData; + LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; + /* First try to use the system's implementation, if that is + available and either succeeds to gives an error other than + that it isn't implemented. */ + check_gfax(); + if (gfaxa) { + result = gfaxw(pszFile, level, pv); + if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) + return result; + } + /* It's either not present, or not implemented. + Emulate using FindFirstFile. */ + if (level != GetFileExInfoStandard) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + /* Use GetFileAttributes to validate that the file name + does not contain wildcards (which FindFirstFile would + accept). */ + if (GetFileAttributesW(pszFile) == 0xFFFFFFFF) + return FALSE; + hFindFile = FindFirstFileW(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; +} + static int win32_stat(const char* path, struct win32_stat *result) { @@ -835,7 +935,7 @@ int code; char *dot; /* XXX not supported on Win95 and NT 3.x */ - if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { + if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { /* Protocol violation: we explicitly clear errno, instead of setting it to a POSIX error. Callers should use GetLastError. */ errno = 0; @@ -863,7 +963,7 @@ const wchar_t *dot; WIN32_FILE_ATTRIBUTE_DATA info; /* XXX not supported on Win95 and NT 3.x */ - if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { + if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { /* Protocol violation: we explicitly clear errno, instead of setting it to a POSIX error. Callers should use GetLastError. */ errno = 0; @@ -2458,7 +2558,8 @@ wpath = PyUnicode_AS_UNICODE(obwpath); Py_BEGIN_ALLOW_THREADS hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, 0, NULL); + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); Py_END_ALLOW_THREADS if (hFile == INVALID_HANDLE_VALUE) return win32_error_unicode("utime", wpath); @@ -2473,7 +2574,8 @@ return NULL; Py_BEGIN_ALLOW_THREADS hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, 0, NULL); + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); Py_END_ALLOW_THREADS if (hFile == INVALID_HANDLE_VALUE) { win32_error("utime", apath); @@ -2501,11 +2603,11 @@ if (extract_time(PyTuple_GET_ITEM(arg, 0), &atimesec, &ausec) == -1) goto done; - time_t_to_FILE_TIME(atimesec, ausec, &atime); + time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); if (extract_time(PyTuple_GET_ITEM(arg, 1), &mtimesec, &musec) == -1) goto done; - time_t_to_FILE_TIME(mtimesec, musec, &mtime); + time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); } if (!SetFileTime(hFile, NULL, &atime, &mtime)) { /* Avoid putting the file name into the error here, @@ -5585,17 +5687,53 @@ static PyObject * posix_readlink(PyObject *self, PyObject *args) { + PyObject* v; char buf[MAXPATHLEN]; char *path; int n; - if (!PyArg_ParseTuple(args, "s:readlink", &path)) +#ifdef Py_USING_UNICODE + int arg_is_unicode = 0; +#endif + + if (!PyArg_ParseTuple(args, "et:readlink", + Py_FileSystemDefaultEncoding, &path)) return NULL; +#ifdef Py_USING_UNICODE + v = PySequence_GetItem(args, 0); + if (v == NULL) return NULL; + + if (PyUnicode_Check(v)) { + arg_is_unicode = 1; + } + Py_DECREF(v); +#endif + Py_BEGIN_ALLOW_THREADS n = readlink(path, buf, (int) sizeof buf); Py_END_ALLOW_THREADS if (n < 0) return posix_error_with_filename(path); - return PyString_FromStringAndSize(buf, n); + + v = PyString_FromStringAndSize(buf, n); +#ifdef Py_USING_UNICODE + if (arg_is_unicode) { + PyObject *w; + + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "strict"); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else { + /* fall back to the original byte string, as + discussed in patch #683592 */ + PyErr_Clear(); + } + } +#endif + return v; } #endif /* HAVE_READLINK */ @@ -8617,3 +8755,4 @@ } #endif + Modified: python/branches/bcannon-objcap/Modules/socketmodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/socketmodule.c (original) +++ python/branches/bcannon-objcap/Modules/socketmodule.c Tue Jan 9 23:27:11 2007 @@ -364,19 +364,16 @@ #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM #define sockaddr_l2 sockaddr_l2cap #define sockaddr_rc sockaddr_rfcomm -#define _BT_SOCKADDR_MEMB(s, proto) &((s)->sock_addr) #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb) #elif defined(__NetBSD__) #define sockaddr_l2 sockaddr_bt #define sockaddr_rc sockaddr_bt #define sockaddr_sco sockaddr_bt -#define _BT_SOCKADDR_MEMB(s, proto) &((s)->sock_addr) #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb) #else -#define _BT_SOCKADDR_MEMB(s, proto) (&((s)->sock_addr).bt_##proto) #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb) @@ -388,6 +385,8 @@ #define SEGMENT_SIZE (32 * 1024 -1) #endif +#define SAS2SA(x) ((struct sockaddr *)(x)) + /* * Constants for getnameinfo() */ @@ -1174,7 +1173,7 @@ static int getsockaddrarg(PySocketSockObject *s, PyObject *args, - struct sockaddr **addr_ret, int *len_ret) + struct sockaddr *addr_ret, int *len_ret) { switch (s->sock_family) { @@ -1184,9 +1183,10 @@ struct sockaddr_un* addr; char *path; int len; - addr = (struct sockaddr_un*)&(s->sock_addr).un; if (!PyArg_Parse(args, "t#", &path, &len)) return 0; + + addr = (struct sockaddr_un*)addr_ret; #ifdef linux if (len > 0 && path[0] == 0) { /* Linux abstract namespace extension */ @@ -1209,7 +1209,6 @@ } addr->sun_family = s->sock_family; memcpy(addr->sun_path, path, len); - *addr_ret = (struct sockaddr *) addr; #if defined(PYOS_OS2) *len_ret = sizeof(*addr); #else @@ -1224,7 +1223,7 @@ { struct sockaddr_nl* addr; int pid, groups; - addr = (struct sockaddr_nl *)&(s->sock_addr).nl; + addr = (struct sockaddr_nl *)addr_ret; if (!PyTuple_Check(args)) { PyErr_Format( PyExc_TypeError, @@ -1238,7 +1237,6 @@ addr->nl_family = AF_NETLINK; addr->nl_pid = pid; addr->nl_groups = groups; - *addr_ret = (struct sockaddr *) addr; *len_ret = sizeof(*addr); return 1; } @@ -1249,7 +1247,6 @@ struct sockaddr_in* addr; char *host; int port, result; - addr=(struct sockaddr_in*)&(s->sock_addr).in; if (!PyTuple_Check(args)) { PyErr_Format( PyExc_TypeError, @@ -1261,6 +1258,7 @@ if (!PyArg_ParseTuple(args, "eti:getsockaddrarg", "idna", &host, &port)) return 0; + addr=(struct sockaddr_in*)addr_ret; result = setipaddr(host, (struct sockaddr *)addr, sizeof(*addr), AF_INET); PyMem_Free(host); @@ -1268,7 +1266,6 @@ return 0; addr->sin_family = AF_INET; addr->sin_port = htons((short)port); - *addr_ret = (struct sockaddr *) addr; *len_ret = sizeof *addr; return 1; } @@ -1279,7 +1276,6 @@ struct sockaddr_in6* addr; char *host; int port, flowinfo, scope_id, result; - addr = (struct sockaddr_in6*)&(s->sock_addr).in6; flowinfo = scope_id = 0; if (!PyTuple_Check(args)) { PyErr_Format( @@ -1294,6 +1290,7 @@ &scope_id)) { return 0; } + addr = (struct sockaddr_in6*)addr_ret; result = setipaddr(host, (struct sockaddr *)addr, sizeof(*addr), AF_INET6); PyMem_Free(host); @@ -1303,7 +1300,6 @@ addr->sin6_port = htons((short)port); addr->sin6_flowinfo = flowinfo; addr->sin6_scope_id = scope_id; - *addr_ret = (struct sockaddr *) addr; *len_ret = sizeof *addr; return 1; } @@ -1315,9 +1311,10 @@ switch (s->sock_proto) { case BTPROTO_L2CAP: { - struct sockaddr_l2 *addr = (struct sockaddr_l2 *) _BT_SOCKADDR_MEMB(s, l2); + struct sockaddr_l2 *addr; char *straddr; + addr = (struct sockaddr_l2 *)addr_ret; _BT_L2_MEMB(addr, family) = AF_BLUETOOTH; if (!PyArg_ParseTuple(args, "si", &straddr, &_BT_L2_MEMB(addr, psm))) { @@ -1328,15 +1325,15 @@ if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0) return 0; - *addr_ret = (struct sockaddr *) addr; *len_ret = sizeof *addr; return 1; } case BTPROTO_RFCOMM: { - struct sockaddr_rc *addr = (struct sockaddr_rc *) _BT_SOCKADDR_MEMB(s, rc); + struct sockaddr_rc *addr; char *straddr; + addr = (struct sockaddr_rc *)addr_ret; _BT_RC_MEMB(addr, family) = AF_BLUETOOTH; if (!PyArg_ParseTuple(args, "si", &straddr, &_BT_RC_MEMB(addr, channel))) { @@ -1347,16 +1344,16 @@ if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0) return 0; - *addr_ret = (struct sockaddr *) addr; *len_ret = sizeof *addr; return 1; } #if !defined(__FreeBSD__) case BTPROTO_SCO: { - struct sockaddr_sco *addr = (struct sockaddr_sco *) _BT_SOCKADDR_MEMB(s, sco); + struct sockaddr_sco *addr; char *straddr; + addr = (struct sockaddr_sco *)addr_ret; _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH; straddr = PyString_AsString(args); if (straddr == NULL) { @@ -1367,7 +1364,6 @@ if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0) return 0; - *addr_ret = (struct sockaddr *) addr; *len_ret = sizeof *addr; return 1; } @@ -1409,22 +1405,21 @@ s->errorhandler(); return 0; } - addr = &(s->sock_addr.ll); - addr->sll_family = AF_PACKET; - addr->sll_protocol = htons((short)protoNumber); - addr->sll_ifindex = ifr.ifr_ifindex; - addr->sll_pkttype = pkttype; - addr->sll_hatype = hatype; if (halen > 8) { PyErr_SetString(PyExc_ValueError, "Hardware address must be 8 bytes or less"); return 0; } + addr = (struct sockaddr_ll*)addr_ret; + addr->sll_family = AF_PACKET; + addr->sll_protocol = htons((short)protoNumber); + addr->sll_ifindex = ifr.ifr_ifindex; + addr->sll_pkttype = pkttype; + addr->sll_hatype = hatype; if (halen != 0) { memcpy(&addr->sll_addr, haddr, halen); } addr->sll_halen = halen; - *addr_ret = (struct sockaddr *) addr; *len_ret = sizeof *addr; return 1; } @@ -1551,8 +1546,7 @@ Py_BEGIN_ALLOW_THREADS timeout = internal_select(s, 0); if (!timeout) - newfd = accept(s->sock_fd, (struct sockaddr *) &addrbuf, - &addrlen); + newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen); Py_END_ALLOW_THREADS if (timeout == 1) { @@ -1578,7 +1572,7 @@ SOCKETCLOSE(newfd); goto finally; } - addr = makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf, + addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, s->sock_proto); if (addr == NULL) goto finally; @@ -1819,14 +1813,14 @@ static PyObject * sock_bind(PySocketSockObject *s, PyObject *addro) { - struct sockaddr *addr; + sock_addr_t addrbuf; int addrlen; int res; - if (!getsockaddrarg(s, addro, &addr, &addrlen)) + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) return NULL; Py_BEGIN_ALLOW_THREADS - res = bind(s->sock_fd, addr, addrlen); + res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen); Py_END_ALLOW_THREADS if (res < 0) return s->errorhandler(); @@ -1952,16 +1946,16 @@ static PyObject * sock_connect(PySocketSockObject *s, PyObject *addro) { - struct sockaddr *addr; + sock_addr_t addrbuf; int addrlen; int res; int timeout; - if (!getsockaddrarg(s, addro, &addr, &addrlen)) + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) return NULL; Py_BEGIN_ALLOW_THREADS - res = internal_connect(s, addr, addrlen, &timeout); + res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); Py_END_ALLOW_THREADS if (timeout == 1) { @@ -1986,16 +1980,16 @@ static PyObject * sock_connect_ex(PySocketSockObject *s, PyObject *addro) { - struct sockaddr *addr; + sock_addr_t addrbuf; int addrlen; int res; int timeout; - if (!getsockaddrarg(s, addro, &addr, &addrlen)) + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) return NULL; Py_BEGIN_ALLOW_THREADS - res = internal_connect(s, addr, addrlen, &timeout); + res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); Py_END_ALLOW_THREADS /* Signals are not errors (though they may raise exceptions). Adapted @@ -2075,11 +2069,11 @@ return NULL; memset(&addrbuf, 0, addrlen); Py_BEGIN_ALLOW_THREADS - res = getsockname(s->sock_fd, (struct sockaddr *) &addrbuf, &addrlen); + res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen); Py_END_ALLOW_THREADS if (res < 0) return s->errorhandler(); - return makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf, addrlen, + return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, s->sock_proto); } @@ -2104,11 +2098,11 @@ return NULL; memset(&addrbuf, 0, addrlen); Py_BEGIN_ALLOW_THREADS - res = getpeername(s->sock_fd, (struct sockaddr *) &addrbuf, &addrlen); + res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen); Py_END_ALLOW_THREADS if (res < 0) return s->errorhandler(); - return makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf, addrlen, + return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, s->sock_proto); } @@ -2216,7 +2210,7 @@ /* * This is the guts of the recv() and recv_into() methods, which reads into a - * char buffer. If you have any inc/def ref to do to the objects that contain + * char buffer. If you have any inc/dec ref to do to the objects that contain * the buffer, do it in the caller. This function returns the number of bytes * succesfully read. If there was an error, it returns -1. Note that it is * also possible that we return a number of bytes smaller than the request @@ -2443,14 +2437,14 @@ #ifndef MS_WINDOWS #if defined(PYOS_OS2) && !defined(PYCC_GCC) n = recvfrom(s->sock_fd, cbuf, len, flags, - (struct sockaddr *) &addrbuf, &addrlen); + SAS2SA(&addrbuf), &addrlen); #else n = recvfrom(s->sock_fd, cbuf, len, flags, (void *) &addrbuf, &addrlen); #endif #else n = recvfrom(s->sock_fd, cbuf, len, flags, - (struct sockaddr *) &addrbuf, &addrlen); + SAS2SA(&addrbuf), &addrlen); #endif } Py_END_ALLOW_THREADS @@ -2464,7 +2458,7 @@ return -1; } - if (!(*addr = makesockaddr(s->sock_fd, (struct sockaddr *) &addrbuf, + if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, s->sock_proto))) return -1; @@ -2664,7 +2658,7 @@ { PyObject *addro; char *buf; - struct sockaddr *addr; + sock_addr_t addrbuf; int addrlen, len, n = -1, flags, timeout; flags = 0; @@ -2675,16 +2669,16 @@ return NULL; } - if (!getsockaddrarg(s, addro, &addr, &addrlen)) - return NULL; - if (!IS_SELECTABLE(s)) return select_error(); + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + Py_BEGIN_ALLOW_THREADS timeout = internal_select(s, 1); if (!timeout) - n = sendto(s->sock_fd, buf, len, flags, addr, addrlen); + n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen); Py_END_ALLOW_THREADS if (timeout == 1) { @@ -2973,10 +2967,9 @@ if (!PyArg_ParseTuple(args, "s:gethostbyname", &name)) return NULL; - if (setipaddr(name, (struct sockaddr *)&addrbuf, sizeof(addrbuf), AF_INET) < 0) + if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0) return NULL; - return makeipaddr((struct sockaddr *)&addrbuf, - sizeof(struct sockaddr_in)); + return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in)); } PyDoc_STRVAR(gethostbyname_doc, Modified: python/branches/bcannon-objcap/Modules/socketmodule.h ============================================================================== --- python/branches/bcannon-objcap/Modules/socketmodule.h (original) +++ python/branches/bcannon-objcap/Modules/socketmodule.h Tue Jan 9 23:27:11 2007 @@ -114,7 +114,6 @@ int sock_family; /* Address family, e.g., AF_INET */ int sock_type; /* Socket type, e.g., SOCK_STREAM */ int sock_proto; /* Protocol type, usually 0 */ - sock_addr_t sock_addr; /* Socket address */ PyObject *(*errorhandler)(void); /* Error handler; checks errno, returns NULL and sets a Python exception */ Modified: python/branches/bcannon-objcap/Modules/threadmodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/threadmodule.c (original) +++ python/branches/bcannon-objcap/Modules/threadmodule.c Tue Jan 9 23:27:11 2007 @@ -25,6 +25,7 @@ static void lock_dealloc(lockobject *self) { + assert(self->lock_lock); /* Unlock the lock so it's safe to free it */ PyThread_acquire_lock(self->lock_lock, 0); PyThread_release_lock(self->lock_lock); Modified: python/branches/bcannon-objcap/Modules/timemodule.c ============================================================================== --- python/branches/bcannon-objcap/Modules/timemodule.c (original) +++ python/branches/bcannon-objcap/Modules/timemodule.c Tue Jan 9 23:27:11 2007 @@ -659,7 +659,7 @@ time_tzset. In the future, some parts of it can be moved back (for platforms that don't HAVE_WORKING_TZSET, when we know what they are), and the extranious calls to tzset(3) should be removed. - I havn't done this yet, as I don't want to change this code as + I haven't done this yet, as I don't want to change this code as little as possible when introducing the time.tzset and time.tzsetwall methods. This should simply be a method of doing the following once, at the top of this function and removing the call to tzset() from Modified: python/branches/bcannon-objcap/Modules/unicodedata.c ============================================================================== --- python/branches/bcannon-objcap/Modules/unicodedata.c (original) +++ python/branches/bcannon-objcap/Modules/unicodedata.c Tue Jan 9 23:27:11 2007 @@ -75,7 +75,7 @@ {NULL} }; -// forward declaration +/* forward declaration */ static PyTypeObject UCD_Type; static PyObject* Modified: python/branches/bcannon-objcap/Objects/abstract.c ============================================================================== --- python/branches/bcannon-objcap/Objects/abstract.c (original) +++ python/branches/bcannon-objcap/Objects/abstract.c Tue Jan 9 23:27:11 2007 @@ -1652,20 +1652,18 @@ if (cmp > 0) { switch (operation) { case PY_ITERSEARCH_COUNT: - ++n; - if (n <= 0) { - /* XXX(nnorwitz): int means ssize_t */ + if (n == PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, - "count exceeds C int size"); + "count exceeds C integer size"); goto Fail; } + ++n; break; case PY_ITERSEARCH_INDEX: if (wrapped) { - /* XXX(nnorwitz): int means ssize_t */ PyErr_SetString(PyExc_OverflowError, - "index exceeds C int size"); + "index exceeds C integer size"); goto Fail; } goto Done; @@ -1680,9 +1678,9 @@ } if (operation == PY_ITERSEARCH_INDEX) { - ++n; - if (n <= 0) + if (n == PY_SSIZE_T_MAX) wrapped = 1; + ++n; } } Modified: python/branches/bcannon-objcap/Objects/classobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/classobject.c (original) +++ python/branches/bcannon-objcap/Objects/classobject.c Tue Jan 9 23:27:11 2007 @@ -1318,15 +1318,17 @@ /* Couldn't find __contains__. */ if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + Py_ssize_t rc; /* Assume the failure was simply due to that there is no * __contains__ attribute, and try iterating instead. */ PyErr_Clear(); - return _PySequence_IterSearch((PyObject *)inst, member, - PY_ITERSEARCH_CONTAINS) > 0; + rc = _PySequence_IterSearch((PyObject *)inst, member, + PY_ITERSEARCH_CONTAINS); + if (rc >= 0) + return rc > 0; } - else - return -1; + return -1; } static PySequenceMethods @@ -2256,6 +2258,8 @@ PyObject *self; PyObject *classObj = NULL; + if (!_PyArg_NoKeywords("instancemethod", kw)) + return NULL; if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3, &func, &self, &classObj)) return NULL; Modified: python/branches/bcannon-objcap/Objects/dictnotes.txt ============================================================================== --- python/branches/bcannon-objcap/Objects/dictnotes.txt (original) +++ python/branches/bcannon-objcap/Objects/dictnotes.txt Tue Jan 9 23:27:11 2007 @@ -44,7 +44,7 @@ d.setdefault(word, []).append(pagenumber) Note, the second example is a use case characterized by a get and set - to the same key. There are similar used cases with a __contains__ + to the same key. There are similar use cases with a __contains__ followed by a get, set, or del to the same key. Part of the justification for d.setdefault is combining the two lookups into one. Modified: python/branches/bcannon-objcap/Objects/dictobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/dictobject.c (original) +++ python/branches/bcannon-objcap/Objects/dictobject.c Tue Jan 9 23:27:11 2007 @@ -12,6 +12,20 @@ typedef PyDictEntry dictentry; typedef PyDictObject dictobject; +/* Set a key error with the specified argument, wrapping it in a + * tuple automatically so that tuple keys are not unpacked as the + * exception arguments. */ +static void +set_key_error(PyObject *arg) +{ + PyObject *tup; + tup = PyTuple_Pack(1, arg); + if (!tup) + return; /* caller will expect error to be set anyway */ + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); +} + /* Define this out if you don't want conversion statistics on exit. */ #undef SHOW_CONVERSION_COUNTS @@ -307,6 +321,8 @@ else if (ep->me_key == dummy && freeslot == NULL) freeslot = ep; } + assert(0); /* NOT REACHED */ + return 0; } /* @@ -366,6 +382,8 @@ if (ep->me_key == dummy && freeslot == NULL) freeslot = ep; } + assert(0); /* NOT REACHED */ + return 0; } /* @@ -661,7 +679,7 @@ if (ep == NULL) return -1; if (ep->me_value == NULL) { - PyErr_SetObject(PyExc_KeyError, key); + set_key_error(key); return -1; } old_key = ep->me_key; @@ -970,7 +988,7 @@ return PyObject_CallFunctionObjArgs(missing, (PyObject *)mp, key, NULL); } - PyErr_SetObject(PyExc_KeyError, key); + set_key_error(key); return NULL; } else @@ -1742,7 +1760,7 @@ Py_INCREF(deflt); return deflt; } - PyErr_SetObject(PyExc_KeyError, key); + set_key_error(key); return NULL; } old_key = ep->me_key; Modified: python/branches/bcannon-objcap/Objects/exceptions.c ============================================================================== --- python/branches/bcannon-objcap/Objects/exceptions.c (original) +++ python/branches/bcannon-objcap/Objects/exceptions.c Tue Jan 9 23:27:11 2007 @@ -510,7 +510,7 @@ if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) return -1; - if (PyTuple_GET_SIZE(args) <= 1) { + if (PyTuple_GET_SIZE(args) <= 1 || PyTuple_GET_SIZE(args) > 3) { return 0; } @@ -828,9 +828,9 @@ return NULL; } - if (self->myerrno) { - Py_INCREF(self->myerrno); - PyTuple_SET_ITEM(tuple, 0, self->myerrno); + if (self->winerror) { + Py_INCREF(self->winerror); + PyTuple_SET_ITEM(tuple, 0, self->winerror); } else { Py_INCREF(Py_None); @@ -852,7 +852,7 @@ Py_DECREF(fmt); Py_DECREF(tuple); } - else if (self->myerrno && self->strerror) { + else if (self->winerror && self->strerror) { PyObject *fmt; PyObject *tuple; @@ -866,9 +866,9 @@ return NULL; } - if (self->myerrno) { - Py_INCREF(self->myerrno); - PyTuple_SET_ITEM(tuple, 0, self->myerrno); + if (self->winerror) { + Py_INCREF(self->winerror); + PyTuple_SET_ITEM(tuple, 0, self->winerror); } else { Py_INCREF(Py_None); Modified: python/branches/bcannon-objcap/Objects/fileobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/fileobject.c (original) +++ python/branches/bcannon-objcap/Objects/fileobject.c Tue Jan 9 23:27:11 2007 @@ -540,7 +540,7 @@ int whence; int ret; Py_off_t offset; - PyObject *offobj; + PyObject *offobj, *off_index; if (f->f_fp == NULL) return err_closed(); @@ -548,12 +548,25 @@ whence = 0; if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence)) return NULL; + off_index = PyNumber_Index(offobj); + if (!off_index) { + if (!PyFloat_Check(offobj)) + return NULL; + /* Deprecated in 2.6 */ + PyErr_Clear(); + if (PyErr_Warn(PyExc_DeprecationWarning, + "integer argument expected, got float")) + return NULL; + off_index = offobj; + Py_INCREF(offobj); + } #if !defined(HAVE_LARGEFILE_SUPPORT) - offset = PyInt_AsLong(offobj); + offset = PyInt_AsLong(off_index); #else - offset = PyLong_Check(offobj) ? - PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj); + offset = PyLong_Check(off_index) ? + PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index); #endif + Py_DECREF(off_index); if (PyErr_Occurred()) return NULL; @@ -1001,6 +1014,7 @@ size_t nfree; /* # of free buffer slots; pvend-pvfree */ size_t total_v_size; /* total # of slots in buffer */ size_t increment; /* amount to increment the buffer */ + size_t prev_v_size; /* Optimize for normal case: avoid _PyString_Resize if at all * possible via first reading into stack buffer "buf". @@ -1115,8 +1129,11 @@ /* expand buffer and try again */ assert(*(pvend-1) == '\0'); increment = total_v_size >> 2; /* mild exponential growth */ + prev_v_size = total_v_size; total_v_size += increment; - if (total_v_size > PY_SSIZE_T_MAX) { + /* check for overflow */ + if (total_v_size <= prev_v_size || + total_v_size > PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "line is longer than a Python string can hold"); Py_DECREF(v); @@ -1125,7 +1142,7 @@ if (_PyString_Resize(&v, (int)total_v_size) < 0) return NULL; /* overwrite the trailing null byte */ - pvfree = BUF(v) + (total_v_size - increment - 1); + pvfree = BUF(v) + (prev_v_size - 1); } if (BUF(v) + total_v_size != p) _PyString_Resize(&v, p - BUF(v)); Modified: python/branches/bcannon-objcap/Objects/intobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/intobject.c (original) +++ python/branches/bcannon-objcap/Objects/intobject.c Tue Jan 9 23:27:11 2007 @@ -546,6 +546,17 @@ } } +/* Integer overflow checking for unary negation: on a 2's-complement + * box, -x overflows iff x is the most negative long. In this case we + * get -x == x. However, -x is undefined (by C) if x /is/ the most + * negative long (it's a signed overflow case), and some compilers care. + * So we cast x to unsigned long first. However, then other compilers + * warn about applying unary minus to an unsigned operand. Hence the + * weird "0-". + */ +#define UNARY_NEG_WOULD_OVERFLOW(x) \ + ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x)) + /* Return type of i_divmod */ enum divmod_result { DIVMOD_OK, /* Correct result */ @@ -565,7 +576,7 @@ return DIVMOD_ERROR; } /* (-sys.maxint-1)/-1 is the only overflow case. */ - if (y == -1 && x == LONG_MIN) + if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x)) return DIVMOD_OVERFLOW; xdivy = x / y; xmody = x - xdivy * y; @@ -754,10 +765,10 @@ static PyObject * int_neg(PyIntObject *v) { - register long a, x; + register long a; a = v->ob_ival; - x = -a; - if (a < 0 && x < 0) { + /* check for overflow */ + if (UNARY_NEG_WOULD_OVERFLOW(a)) { PyObject *o = PyLong_FromLong(a); if (o != NULL) { PyObject *result = PyNumber_Negative(o); @@ -766,7 +777,7 @@ } return NULL; } - return PyInt_FromLong(x); + return PyInt_FromLong(-a); } static PyObject * @@ -976,8 +987,25 @@ return PyInt_FromLong(0L); if (base == -909) return PyNumber_Int(x); - if (PyString_Check(x)) - return PyInt_FromString(PyString_AS_STRING(x), NULL, base); + if (PyString_Check(x)) { + /* Since PyInt_FromString doesn't have a length parameter, + * check here for possible NULs in the string. */ + char *string = PyString_AS_STRING(x); + if (strlen(string) != PyString_Size(x)) { + /* create a repr() of the input string, + * just like PyInt_FromString does */ + PyObject *srepr; + srepr = PyObject_Repr(x); + if (srepr == NULL) + return NULL; + PyErr_Format(PyExc_ValueError, + "invalid literal for int() with base %d: %s", + base, PyString_AS_STRING(srepr)); + Py_DECREF(srepr); + return NULL; + } + return PyInt_FromString(string, NULL, base); + } #ifdef Py_USING_UNICODE if (PyUnicode_Check(x)) return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x), Modified: python/branches/bcannon-objcap/Objects/listobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/listobject.c (original) +++ python/branches/bcannon-objcap/Objects/listobject.c Tue Jan 9 23:27:11 2007 @@ -863,17 +863,12 @@ listpop(PyListObject *self, PyObject *args) { Py_ssize_t i = -1; - PyObject *v, *arg = NULL; + PyObject *v; int status; - if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg)) + if (!PyArg_ParseTuple(args, "|n:pop", &i)) return NULL; - if (arg != NULL) { - if (PyInt_Check(arg)) - i = PyInt_AS_LONG((PyIntObject*) arg); - else if (!PyArg_ParseTuple(args, "|n:pop", &i)) - return NULL; - } + if (self->ob_size == 0) { /* Special-case most common failure cause */ PyErr_SetString(PyExc_IndexError, "pop from empty list"); @@ -951,9 +946,10 @@ if (res == NULL) return -1; if (!PyInt_Check(res)) { + PyErr_Format(PyExc_TypeError, + "comparison function must return int, not %.200s", + res->ob_type->tp_name); Py_DECREF(res); - PyErr_SetString(PyExc_TypeError, - "comparison function must return int"); return -1; } i = PyInt_AsLong(res); @@ -2496,8 +2492,9 @@ } } else { - PyErr_SetString(PyExc_TypeError, - "list indices must be integers"); + PyErr_Format(PyExc_TypeError, + "list indices must be integers, not %.200s", + item->ob_type->tp_name); return NULL; } } @@ -2613,6 +2610,11 @@ garbage = (PyObject**) PyMem_MALLOC(slicelength*sizeof(PyObject*)); + if (!garbage) { + Py_DECREF(seq); + PyErr_NoMemory(); + return -1; + } selfitems = self->ob_item; seqitems = PySequence_Fast_ITEMS(seq); @@ -2635,8 +2637,9 @@ } } else { - PyErr_SetString(PyExc_TypeError, - "list indices must be integers"); + PyErr_Format(PyExc_TypeError, + "list indices must be integers, not %.200s", + item->ob_type->tp_name); return -1; } } Modified: python/branches/bcannon-objcap/Objects/longobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/longobject.c (original) +++ python/branches/bcannon-objcap/Objects/longobject.c Tue Jan 9 23:27:11 2007 @@ -193,6 +193,18 @@ return (PyObject *)v; } +/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define + * anything about what happens when a signed integer operation overflows, + * and some compilers think they're doing you a favor by being "clever" + * then. The bit pattern for the largest postive signed long is + * (unsigned long)LONG_MAX, and for the smallest negative signed long + * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN. + * However, some other compilers warn about applying unary minus to an + * unsigned operand. Hence the weird "0-". + */ +#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) +#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN) + /* Get a C long int from a long int object. Returns -1 and sets an error condition if overflow occurs. */ @@ -225,14 +237,16 @@ if ((x >> SHIFT) != prev) goto overflow; } - /* Haven't lost any bits, but if the sign bit is set we're in - * trouble *unless* this is the min negative number. So, - * trouble iff sign bit set && (positive || some bit set other - * than the sign bit). - */ - if ((long)x < 0 && (sign > 0 || (x << 1) != 0)) - goto overflow; - return (long)x * sign; + /* Haven't lost any bits, but casting to long requires extra care + * (see comment above). + */ + if (x <= (unsigned long)LONG_MAX) { + return (long)x * sign; + } + else if (sign < 0 && x == PY_ABS_LONG_MIN) { + return LONG_MIN; + } + /* else overflow */ overflow: PyErr_SetString(PyExc_OverflowError, @@ -268,14 +282,16 @@ if ((x >> SHIFT) != prev) goto overflow; } - /* Haven't lost any bits, but if the sign bit is set we're in - * trouble *unless* this is the min negative number. So, - * trouble iff sign bit set && (positive || some bit set other - * than the sign bit). + /* Haven't lost any bits, but casting to a signed type requires + * extra care (see comment above). */ - if ((Py_ssize_t)x < 0 && (sign > 0 || (x << 1) != 0)) - goto overflow; - return (Py_ssize_t)x * sign; + if (x <= (size_t)PY_SSIZE_T_MAX) { + return (Py_ssize_t)x * sign; + } + else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) { + return PY_SSIZE_T_MIN; + } + /* else overflow */ overflow: PyErr_SetString(PyExc_OverflowError, @@ -1167,7 +1183,7 @@ { register PyLongObject *a = (PyLongObject *)aa; PyStringObject *str; - Py_ssize_t i; + Py_ssize_t i, j, sz; Py_ssize_t size_a; char *p; int bits; @@ -1187,11 +1203,18 @@ ++bits; i >>= 1; } - i = 5 + (addL ? 1 : 0) + (size_a*SHIFT + bits-1) / bits; - str = (PyStringObject *) PyString_FromStringAndSize((char *)0, i); + i = 5 + (addL ? 1 : 0); + j = size_a*SHIFT + bits-1; + sz = i + j / bits; + if (j / SHIFT < size_a || sz < i) { + PyErr_SetString(PyExc_OverflowError, + "long is too large to format"); + return NULL; + } + str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz); if (str == NULL) return NULL; - p = PyString_AS_STRING(str) + i; + p = PyString_AS_STRING(str) + sz; *p = '\0'; if (addL) *--p = 'L'; @@ -1305,7 +1328,7 @@ } while ((*q++ = *p++) != '\0'); q--; _PyString_Resize((PyObject **)&str, - (int) (q - PyString_AS_STRING(str))); + (Py_ssize_t) (q - PyString_AS_STRING(str))); } return (PyObject *)str; } @@ -1363,14 +1386,14 @@ while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base) ++p; *str = p; - n = (p - start) * bits_per_char; - if (n / bits_per_char != p - start) { + /* n <- # of Python digits needed, = ceiling(n/SHIFT). */ + 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"); return NULL; } - /* n <- # of Python digits needed, = ceiling(n/SHIFT). */ - n = (n + SHIFT - 1) / SHIFT; + n = n / SHIFT; z = _PyLong_New(n); if (z == NULL) return NULL; Modified: python/branches/bcannon-objcap/Objects/obmalloc.c ============================================================================== --- python/branches/bcannon-objcap/Objects/obmalloc.c (original) +++ python/branches/bcannon-objcap/Objects/obmalloc.c Tue Jan 9 23:27:11 2007 @@ -691,7 +691,8 @@ #undef Py_ADDRESS_IN_RANGE -#if defined(__GNUC__) && (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) +#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \ + (__GNUC__ >= 4)) #define Py_NO_INLINE __attribute__((__noinline__)) #else #define Py_NO_INLINE Modified: python/branches/bcannon-objcap/Objects/setobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/setobject.c (original) +++ python/branches/bcannon-objcap/Objects/setobject.c Tue Jan 9 23:27:11 2007 @@ -10,6 +10,20 @@ #include "Python.h" #include "structmember.h" +/* Set a key error with the specified argument, wrapping it in a + * tuple automatically so that tuple keys are not unpacked as the + * exception arguments. */ +static void +set_key_error(PyObject *arg) +{ + PyObject *tup; + tup = PyTuple_Pack(1, arg); + if (!tup) + return; /* caller will expect error to be set anyway */ + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); +} + /* This must be >= 1. */ #define PERTURB_SHIFT 5 @@ -179,11 +193,13 @@ if (entry->key == dummy && freeslot == NULL) freeslot = entry; } + assert(0); /* NOT REACHED */ + return 0; } /* Internal routine to insert a new key into the table. -Used both by the internal resize routine and by the public insert routine. +Used by the public insert routine. Eats a reference to key. */ static int @@ -216,6 +232,35 @@ } /* +Internal routine used by set_table_resize() to insert an item which is +known to be absent from the set. This routine also assumes that +the set contains no deleted entries. Besides the performance benefit, +using set_insert_clean() in set_table_resize() is dangerous (SF bug #1456209). +Note that no refcounts are changed by this routine; if needed, the caller +is responsible for incref'ing `key`. +*/ +static void +set_insert_clean(register PySetObject *so, PyObject *key, long hash) +{ + register size_t i; + register size_t perturb; + register size_t mask = (size_t)so->mask; + setentry *table = so->table; + register setentry *entry; + + i = hash & mask; + entry = &table[i]; + for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + } + so->fill++; + entry->key = key; + entry->hash = hash; + so->used++; +} + +/* Restructure the table by allocating a new table and reinserting all keys again. When entries have been deleted, the new table may actually be smaller than the old one. @@ -296,11 +341,7 @@ } else { /* ACTIVE */ --i; - if(set_insert_key(so, entry->key, entry->hash) == -1) { - if (is_oldtable_malloced) - PyMem_DEL(oldtable); - return -1; - } + set_insert_clean(so, entry->key, entry->hash); } } @@ -531,34 +572,54 @@ Py_ssize_t pos=0; char *emit = ""; /* No separator emitted on first pass */ char *separator = ", "; + int status = Py_ReprEnter((PyObject*)so); + + if (status != 0) { + if (status < 0) + return status; + fprintf(fp, "%s(...)", so->ob_type->tp_name); + return 0; + } fprintf(fp, "%s([", so->ob_type->tp_name); while (set_next(so, &pos, &entry)) { fputs(emit, fp); emit = separator; - if (PyObject_Print(entry->key, fp, 0) != 0) + if (PyObject_Print(entry->key, fp, 0) != 0) { + Py_ReprLeave((PyObject*)so); return -1; + } } fputs("])", fp); + Py_ReprLeave((PyObject*)so); return 0; } static PyObject * set_repr(PySetObject *so) { - PyObject *keys, *result, *listrepr; + PyObject *keys, *result=NULL, *listrepr; + int status = Py_ReprEnter((PyObject*)so); + + if (status != 0) { + if (status < 0) + return NULL; + return PyString_FromFormat("%s(...)", so->ob_type->tp_name); + } keys = PySequence_List((PyObject *)so); if (keys == NULL) - return NULL; + goto done; listrepr = PyObject_Repr(keys); Py_DECREF(keys); if (listrepr == NULL) - return NULL; + goto done; result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name, PyString_AS_STRING(listrepr)); Py_DECREF(listrepr); +done: + Py_ReprLeave((PyObject*)so); return result; } @@ -1162,7 +1223,19 @@ } while ((key = PyIter_Next(it)) != NULL) { - int rv = set_contains_key(so, key); + int rv; + setentry entry; + long hash = PyObject_Hash(key); + + if (hash == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + entry.hash = hash; + entry.key = key; + rv = set_contains_entry(so, &entry); if (rv == -1) { Py_DECREF(it); Py_DECREF(result); @@ -1170,7 +1243,7 @@ return NULL; } if (rv) { - if (set_add_key(result, key) == -1) { + if (set_add_entry(result, &entry) == -1) { Py_DECREF(it); Py_DECREF(result); Py_DECREF(key); @@ -1381,11 +1454,18 @@ PyObject *value; int rv; while (PyDict_Next(other, &pos, &key, &value)) { - rv = set_discard_key(so, key); + 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); if (rv == -1) return NULL; if (rv == DISCARD_NOTFOUND) { - if (set_add_key(so, key) == -1) + if (set_add_entry(so, &an_entry) == -1) return NULL; } } @@ -1638,7 +1718,7 @@ Py_DECREF(tmpkey); return result; } else if (rv == DISCARD_NOTFOUND) { - PyErr_SetObject(PyExc_KeyError, key); + set_key_error(key); return NULL; } Py_RETURN_NONE; Modified: python/branches/bcannon-objcap/Objects/stringobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/stringobject.c (original) +++ python/branches/bcannon-objcap/Objects/stringobject.c Tue Jan 9 23:27:11 2007 @@ -804,10 +804,22 @@ return ret; } if (flags & Py_PRINT_RAW) { + char *data = op->ob_sval; + Py_ssize_t size = op->ob_size; + while (size > INT_MAX) { + /* Very long strings cannot be written atomically. + * But don't write exactly INT_MAX bytes at a time + * to avoid memory aligment issues. + */ + const int chunk_size = INT_MAX & ~0x3FFF; + fwrite(data, 1, chunk_size, fp); + data += chunk_size; + size -= chunk_size; + } #ifdef __VMS - if (op->ob_size) fwrite(op->ob_sval, (int) op->ob_size, 1, fp); + if (size) fwrite(data, (int)size, 1, fp); #else - fwrite(op->ob_sval, 1, (int) op->ob_size, fp); + fwrite(data, 1, (int)size, fp); #endif return 0; } @@ -844,7 +856,7 @@ register PyStringObject* op = (PyStringObject*) obj; size_t newsize = 2 + 4 * op->ob_size; PyObject *v; - if (newsize > PY_SSIZE_T_MAX) { + if (newsize > PY_SSIZE_T_MAX || newsize / 4 != op->ob_size) { PyErr_SetString(PyExc_OverflowError, "string is too large to make repr"); } @@ -1059,8 +1071,9 @@ return PyUnicode_Contains(str_obj, sub_obj); #endif if (!PyString_Check(sub_obj)) { - PyErr_SetString(PyExc_TypeError, - "'in ' requires string as left operand"); + PyErr_Format(PyExc_TypeError, + "'in ' requires string as left operand, " + "not %.200s", sub_obj->ob_type->tp_name); return -1; } } @@ -1228,8 +1241,9 @@ } } else { - PyErr_SetString(PyExc_TypeError, - "string indices must be integers"); + PyErr_Format(PyExc_TypeError, + "string indices must be integers, not %.200s", + item->ob_type->tp_name); return NULL; } } @@ -4136,7 +4150,8 @@ double x; x = PyFloat_AsDouble(v); if (x == -1.0 && PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, "float argument required"); + PyErr_Format(PyExc_TypeError, "float argument required, " + "not %.200s", v->ob_type->tp_name); return -1; } if (prec < 0) @@ -4237,7 +4252,7 @@ return NULL; } llen = PyString_Size(result); - if (llen > PY_SSIZE_T_MAX) { + if (llen > INT_MAX) { PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong"); return NULL; } @@ -4331,7 +4346,8 @@ x = PyInt_AsLong(v); if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, "int argument required"); + PyErr_Format(PyExc_TypeError, "int argument required, not %.200s", + v->ob_type->tp_name); return -1; } if (x < 0 && type == 'u') { @@ -4726,9 +4742,10 @@ default: PyErr_Format(PyExc_ValueError, "unsupported format character '%c' (0x%x) " - "at index %i", + "at index %zd", c, c, - (int)(fmt - 1 - PyString_AsString(format))); + (Py_ssize_t)(fmt - 1 - + PyString_AsString(format))); goto error; } if (sign) { Modified: python/branches/bcannon-objcap/Objects/tupleobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/tupleobject.c (original) +++ python/branches/bcannon-objcap/Objects/tupleobject.c Tue Jan 9 23:27:11 2007 @@ -620,8 +620,9 @@ } } else { - PyErr_SetString(PyExc_TypeError, - "tuple indices must be integers"); + PyErr_Format(PyExc_TypeError, + "tuple indices must be integers, not %.200s", + item->ob_type->tp_name); return NULL; } } Modified: python/branches/bcannon-objcap/Objects/typeobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/typeobject.c (original) +++ python/branches/bcannon-objcap/Objects/typeobject.c Tue Jan 9 23:27:11 2007 @@ -98,7 +98,7 @@ s = strrchr(type->tp_name, '.'); if (s != NULL) return PyString_FromStringAndSize( - type->tp_name, (int)(s - type->tp_name)); + type->tp_name, (Py_ssize_t)(s - type->tp_name)); return PyString_FromString("__builtin__"); } } @@ -3714,7 +3714,7 @@ 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 same of backwards compatibility (?), just shut up. */ + 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", @@ -3931,7 +3931,7 @@ 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 same of backwards compatibility (?), just shut up. */ + 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__()", @@ -4087,19 +4087,10 @@ return -1; len = PyInt_AsSsize_t(res); Py_DECREF(res); - if (len == -1 && PyErr_Occurred()) - return -1; -#if SIZEOF_SIZE_T < SIZEOF_INT - /* Overflow check -- range of PyInt is more than C ssize_t */ - if (len != (int)len) { - PyErr_SetString(PyExc_OverflowError, - "__len__() should return 0 <= outcome < 2**31"); - return -1; - } -#endif if (len < 0) { - PyErr_SetString(PyExc_ValueError, - "__len__() should return >= 0"); + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "__len__() should return >= 0"); return -1; } return len; @@ -5733,6 +5724,8 @@ PyObject *obj = NULL; PyTypeObject *obj_type = NULL; + if (!_PyArg_NoKeywords("super", kwds)) + return -1; if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj)) return -1; if (obj == Py_None) Modified: python/branches/bcannon-objcap/Objects/unicodeobject.c ============================================================================== --- python/branches/bcannon-objcap/Objects/unicodeobject.c (original) +++ python/branches/bcannon-objcap/Objects/unicodeobject.c Tue Jan 9 23:27:11 2007 @@ -2384,6 +2384,7 @@ Py_UNICODE unimax = PyUnicode_GetMax(); #endif + /* XXX overflow detection missing */ v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE); if (v == NULL) goto onError; @@ -3170,6 +3171,7 @@ Py_ssize_t needed = (targetsize - extrachars) + \ (targetsize << 2); extrachars += needed; + /* XXX overflow detection missing */ if (_PyUnicode_Resize(&v, PyUnicode_GET_SIZE(v) + needed) < 0) { Py_DECREF(x); @@ -7762,10 +7764,11 @@ default: PyErr_Format(PyExc_ValueError, "unsupported format character '%c' (0x%x) " - "at index %i", + "at index %zd", (31<=c && c<=126) ? (char)c : '?', (int)c, - (int)(fmt -1 - PyUnicode_AS_UNICODE(uformat))); + (Py_ssize_t)(fmt - 1 - + PyUnicode_AS_UNICODE(uformat))); goto onError; } if (sign) { Modified: python/branches/bcannon-objcap/PC/VC6/_bsddb.dsp ============================================================================== Binary files. No diff available. Modified: python/branches/bcannon-objcap/PC/VC6/_ssl.mak ============================================================================== --- python/branches/bcannon-objcap/PC/VC6/_ssl.mak (original) +++ python/branches/bcannon-objcap/PC/VC6/_ssl.mak Tue Jan 9 23:27:11 2007 @@ -2,17 +2,17 @@ !IFDEF DEBUG MODULE=_ssl_d.pyd TEMP_DIR=x86-temp-debug/_ssl -CFLAGS=/Od /Zi /MDd /LDd /DDEBUG /D_DEBUG +CFLAGS=/Od /Zi /MDd /LDd /DDEBUG /D_DEBUG /DWIN32 SSL_LIB_DIR=$(SSL_DIR)/out32.dbg !ELSE MODULE=_ssl.pyd TEMP_DIR=x86-temp-release/_ssl -CFLAGS=/Ox /MD /LD +CFLAGS=/Ox /MD /LD /DWIN32 SSL_LIB_DIR=$(SSL_DIR)/out32 !ENDIF INCLUDES=-I ../../Include -I .. -I $(SSL_DIR)/inc32 -LIBS=gdi32.lib wsock32.lib /libpath:$(SSL_LIB_DIR) libeay32.lib ssleay32.lib +LIBS=gdi32.lib wsock32.lib user32.lib advapi32.lib /libpath:$(SSL_LIB_DIR) libeay32.lib ssleay32.lib SOURCE=../../Modules/_ssl.c $(SSL_LIB_DIR)/libeay32.lib $(SSL_LIB_DIR)/ssleay32.lib Modified: python/branches/bcannon-objcap/PC/VC6/_tkinter.dsp ============================================================================== Binary files. No diff available. Modified: python/branches/bcannon-objcap/PC/VC6/bz2.dsp ============================================================================== Binary files. No diff available. Modified: python/branches/bcannon-objcap/PC/VC6/pcbuild.dsw ============================================================================== Binary files. No diff available. Modified: python/branches/bcannon-objcap/PC/VC6/pythoncore.dsp ============================================================================== Binary files. No diff available. Modified: python/branches/bcannon-objcap/PC/VC6/readme.txt ============================================================================== --- python/branches/bcannon-objcap/PC/VC6/readme.txt (original) +++ python/branches/bcannon-objcap/PC/VC6/readme.txt Tue Jan 9 23:27:11 2007 @@ -62,40 +62,37 @@ _tkinter Python wrapper for the Tk windowing system. Requires building - Tcl/Tk first. Following are instructions for Tcl/Tk 8.4.3: + Tcl/Tk first. Following are instructions for Tcl/Tk 8.4.12. Get source ---------- - Go to - http://prdownloads.sourceforge.net/tcl/ - and download - tcl843-src.zip - tk843-src.zip - Unzip into - dist\tcl8.4.3\ - dist\tk8.4.3\ - respectively. + In the dist directory, run + svn export http://svn.python.org/projects/external/tcl8.4.12 + svn export http://svn.python.org/projects/external/tk8.4.12 + svn export http://svn.python.org/projects/external/tix-8.4.0 - Build Tcl first (done here w/ MSVC 6 on Win98SE) + Build Tcl first (done here w/ MSVC 6 on Win2K) --------------- - cd dist\tcl8.4.3\win - run vcvars32.bat [necessary even on Win2K] + cd dist\tcl8.4.12\win + run vcvars32.bat nmake -f makefile.vc - nmake -f makefile.vc INSTALLDIR=..\..\tcl84 install + nmake -f makefile.vc INSTALLDIR=..\..\tcltk install XXX Should we compile with OPTS=threads? - XXX Some tests failed in "nmake -f makefile.vc test". - XXX all.tcl: Total 10480 Passed 9743 Skipped 719 Failed 18 - XXX - XXX That was on Win98SE. On Win2K: - XXX all.tcl Total 10480 Passed 9781 Skipped 698 Failed 1 + Optional: run tests, via + nmake -f makefile.vc test + + all.tcl: Total 10835 Passed 10096 Skipped 732 Failed 7 + Sourced 129 Test Files. + Files with failing tests: exec.test expr.test io.test main.test string.test stri + ngObj.test Build Tk -------- - cd dist\tk8.4.3\win - nmake -f makefile.vc TCLDIR=..\..\tcl8.4.3 - nmake -f makefile.vc TCLDIR=..\..\tcl8.4.3 INSTALLDIR=..\..\tcl84 install + cd dist\tk8.4.12\win + nmake -f makefile.vc TCLDIR=..\..\tcl8.4.12 + nmake -f makefile.vc TCLDIR=..\..\tcl8.4.12 INSTALLDIR=..\..\tcltk install XXX Should we compile with OPTS=threads? @@ -103,96 +100,59 @@ XXX failed. It popped up tons of little windows, and did lots of XXX stuff, and nothing blew up. - XXX Our installer copies a lot of stuff out of the Tcl/Tk install - XXX directory. Is all of that really needed for Python use of Tcl/Tk? - - Make sure the installer matches - ------------------------------- - Ensure that the Wise compiler vrbl _TCLDIR_ is set to the name of - the common Tcl/Tk installation directory (tcl84 for the instructions - above). This is needed so the installer can copy various Tcl/Tk - files into the Python distribution. - - -zlib - Python wrapper for the zlib compression library. Get the source code - for version 1.1.4 from a convenient mirror at: - http://www.gzip.org/zlib/ - Unpack into dist\zlib-1.1.4. - A custom pre-link step in the zlib project settings should manage to - build zlib-1.1.4\zlib.lib by magic before zlib.pyd (or zlib_d.pyd) is - linked in PCbuild\. - However, the zlib project is not smart enough to remove anything under - zlib-1.1.4\ when you do a clean, so if you want to rebuild zlib.lib - you need to clean up zlib-1.1.4\ by hand. + Built Tix + --------- + cd dist\tix-8.4.0\win + nmake -f python.mak + nmake -f python.mak install bz2 Python wrapper for the libbz2 compression library. Homepage http://sources.redhat.com/bzip2/ - Download the source tarball, bzip2-1.0.2.tar.gz. - Unpack into dist\bzip2-1.0.2. WARNING: If you're using WinZip, you - must disable its "TAR file smart CR/LF conversion" feature (under - Options -> Configuration -> Miscellaneous -> Other) for the duration. - - A custom pre-link step in the bz2 project settings should manage to - build bzip2-1.0.2\libbz2.lib by magic before bz2.pyd (or bz2_d.pyd) is - linked in PCbuild\. - However, the bz2 project is not smart enough to remove anything under - bzip2-1.0.2\ when you do a clean, so if you want to rebuild bzip2.lib - you need to clean up bzip2-1.0.2\ by hand. - - The build step shouldn't yield any warnings or errors, and should end - by displaying 6 blocks each terminated with - FC: no differences encountered - If FC finds differences, see the warning abou WinZip above (when I - first tried it, sample3.ref failed due to CRLF conversion). + Download the source from the python.org copy into the dist + directory: + + svn export http://svn.python.org/projects/external/bzip2-1.0.3 + + And requires building bz2 first. - All of this managed to build bzip2-1.0.2\libbz2.lib, which the Python + cd dist\bzip2-1.0.3 + nmake -f makefile.msc + + All of this managed to build bzip2-1.0.3\libbz2.lib, which the Python project links in. _bsddb - Go to Sleepycat's download page: - http://www.sleepycat.com/download/ + To use the version of bsddb that Python is built with by default, invoke + (in the dist directory) + + svn export http://svn.python.org/projects/external/db-4.4.20 + + Then open db-4.4.20\build_win32\Berkeley_DB.dsw and build the "db_static" + project for "Release" mode. + + Alternatively, if you want to start with the original sources, + go to Sleepycat's download page: + http://www.sleepycat.com/downloads/releasehistorybdb.html + + and download version 4.4.20. - and download version 4.1.25. The file name is db-4.1.25.NC.zip. - XXX with or without strong cryptography? I picked "without". + With or without strong cryptography? You can choose either with or + without strong cryptography, as per the instructions below. By + default, Python is built and distributed WITHOUT strong crypto. - Unpack into - dist\db-4.1.25 + Unpack the sources; if you downloaded the non-crypto version, rename + the directory from db-4.4.20.NC to db-4.4.20. - [If using WinZip to unpack the db-4.1.25.NC distro, that requires - renaming the directory (to remove ".NC") after unpacking. - ] - - Open - dist\db-4.1.25\docs\index.html - - and follow the Windows instructions for building the Sleepycat - software. Note that Berkeley_DB.dsw is in the build_win32 subdirectory. - Build the Release version ("build_all -- Win32 Release"). - - XXX We're actually linking against Release_static\libdb41s.lib. - XXX This yields the following warnings: -""" -Compiling... -_bsddb.c -Linking... - Creating library ./_bsddb.lib and object ./_bsddb.exp -LINK : warning LNK4049: locally defined symbol "_malloc" imported -LINK : warning LNK4049: locally defined symbol "_free" imported -LINK : warning LNK4049: locally defined symbol "_fclose" imported -LINK : warning LNK4049: locally defined symbol "_fopen" imported -_bsddb.pyd - 0 error(s), 4 warning(s) -""" - XXX This isn't encouraging, but I don't know what to do about it. + Now apply any patches that apply to your version. To run extensive tests, pass "-u bsddb" to regrtest.py. test_bsddb3.py is then enabled. Running in verbose mode may be helpful. XXX The test_bsddb3 tests don't always pass, on Windows (according to - XXX me) or on Linux (according to Barry). I had much better luck - XXX on Win2K than on Win98SE. The common failure mode across platforms + XXX me) or on Linux (according to Barry). (I had much better luck + XXX on Win2K than on Win98SE.) The common failure mode across platforms XXX is XXX DBAgainError: (11, 'Resource temporarily unavailable -- unable XXX to join the environment') Deleted: /python/branches/bcannon-objcap/PC/VC6/zlib.dsp ============================================================================== Binary file. No diff available. Modified: python/branches/bcannon-objcap/PC/_msi.c ============================================================================== --- python/branches/bcannon-objcap/PC/_msi.c (original) +++ python/branches/bcannon-objcap/PC/_msi.c Tue Jan 9 23:27:11 2007 @@ -495,7 +495,7 @@ status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, &fval, sval, &ssize); - if (status = ERROR_MORE_DATA) { + if (status == ERROR_MORE_DATA) { sval = malloc(ssize); status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, &fval, sval, &ssize); Modified: python/branches/bcannon-objcap/PC/pyconfig.h ============================================================================== --- python/branches/bcannon-objcap/PC/pyconfig.h (original) +++ python/branches/bcannon-objcap/PC/pyconfig.h Tue Jan 9 23:27:11 2007 @@ -39,8 +39,12 @@ would be ISO C conforming). Neither renaming is feasible, so we just silence the warnings. */ +#ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 +#endif +#ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif /* Windows CE does not have these */ #ifndef MS_WINCE Modified: python/branches/bcannon-objcap/PC/python_nt.rc ============================================================================== --- python/branches/bcannon-objcap/PC/python_nt.rc (original) +++ python/branches/bcannon-objcap/PC/python_nt.rc Tue Jan 9 23:27:11 2007 @@ -61,7 +61,7 @@ VALUE "FileDescription", "Python Core\0" VALUE "FileVersion", PYTHON_VERSION VALUE "InternalName", "Python DLL\0" - VALUE "LegalCopyright", "Copyright ? 2001-2006 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" + VALUE "LegalCopyright", "Copyright ? 2001-2007 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" VALUE "OriginalFilename", PYTHON_DLL_NAME "\0" VALUE "ProductName", "Python\0" VALUE "ProductVersion", PYTHON_VERSION Modified: python/branches/bcannon-objcap/PCbuild/python20.wse ============================================================================== --- python/branches/bcannon-objcap/PCbuild/python20.wse (original) +++ python/branches/bcannon-objcap/PCbuild/python20.wse Tue Jan 9 23:27:11 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/branches/bcannon-objcap/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/bcannon-objcap/PCbuild/pythoncore.vcproj (original) +++ python/branches/bcannon-objcap/PCbuild/pythoncore.vcproj Tue Jan 9 23:27:11 2007 @@ -464,9 +464,6 @@ RelativePath="..\Python\compile.c"> - - + + - - - - cur = tok->buf + cur; tok->line_start = tok->cur; /* replace "\r\n" with "\n" */ - /* For Mac leave the \r, giving syntax error */ + /* For Mac leave the \r, giving a syntax error */ pt = tok->inp - 2; if (pt >= tok->buf && *pt == '\r') { *pt++ = '\n'; Modified: python/branches/bcannon-objcap/Python/ast.c ============================================================================== --- python/branches/bcannon-objcap/Python/ast.c (original) +++ python/branches/bcannon-objcap/Python/ast.c Tue Jan 9 23:27:11 2007 @@ -532,6 +532,7 @@ || 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); Modified: python/branches/bcannon-objcap/Python/bltinmodule.c ============================================================================== --- python/branches/bcannon-objcap/Python/bltinmodule.c (original) +++ python/branches/bcannon-objcap/Python/bltinmodule.c Tue Jan 9 23:27:11 2007 @@ -2062,10 +2062,11 @@ } PyDoc_STRVAR(sum_doc, -"sum(sequence, start=0) -> value\n\ +"sum(sequence[, start]) -> value\n\ \n\ Returns the sum of a sequence of numbers (NOT strings) plus the value\n\ -of parameter 'start'. When the sequence is empty, returns start."); +of parameter 'start' (which defaults to 0). When the sequence is\n\ +empty, returns start."); static PyObject * Modified: python/branches/bcannon-objcap/Python/ceval.c ============================================================================== --- python/branches/bcannon-objcap/Python/ceval.c (original) +++ python/branches/bcannon-objcap/Python/ceval.c Tue Jan 9 23:27:11 2007 @@ -186,10 +186,10 @@ PyObject * PyEval_GetCallStats(PyObject *self) { - return Py_BuildValue("iiiiiiiiii", + return Py_BuildValue("iiiiiiiiiii", pcall[0], pcall[1], pcall[2], pcall[3], pcall[4], pcall[5], pcall[6], pcall[7], - pcall[8], pcall[9]); + pcall[8], pcall[9], pcall[10]); } #else #define PCALL(O) @@ -741,7 +741,16 @@ this wasn't always true before 2.3! PyFrame_New now sets f->f_lasti to -1 (i.e. the index *before* the first instruction) and YIELD_VALUE doesn't fiddle with f_lasti any more. So this - does work. Promise. */ + does work. Promise. + + When the PREDICT() macros are enabled, some opcode pairs follow in + direct succession without updating f->f_lasti. A successful + prediction effectively links the two codes together as if they + were a single new opcode; accordingly,f->f_lasti will point to + the first code in the pair (for instance, GET_ITER followed by + FOR_ITER is effectively a single opcode and f->f_lasti will point + at to the beginning of the combined pair.) + */ next_instr = first_instr + f->f_lasti + 1; stack_pointer = f->f_stacktop; assert(stack_pointer != NULL); @@ -4046,8 +4055,10 @@ value = PyObject_GetAttr(v, name); if (value == NULL) err = -1; - else + else if (PyDict_CheckExact(locals)) err = PyDict_SetItem(locals, name, value); + else + err = PyObject_SetItem(locals, name, value); Py_DECREF(name); Py_XDECREF(value); if (err != 0) Modified: python/branches/bcannon-objcap/Python/compile.c ============================================================================== --- python/branches/bcannon-objcap/Python/compile.c (original) +++ python/branches/bcannon-objcap/Python/compile.c Tue Jan 9 23:27:11 2007 @@ -6,9 +6,10 @@ * object: * 1. Checks for future statements. See future.c * 2. Builds a symbol table. See symtable.c. - * 3. Generate code for basic blocks. See compiler_mod() in this file. + * 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 * (mod_ty) has cases for expressions and interactive statements. @@ -16,7 +17,8 @@ * CAUTION: The VISIT_* macros abort the current function when they * encounter a problem. So don't invoke them when there is memory * which needs to be released. Code blocks are OK, as the compiler - * structure takes care of releasing those. + * structure takes care of releasing those. Use the arena to manage + * objects. */ #include "Python.h" @@ -32,16 +34,6 @@ int Py_OptimizeFlag = 0; -/* - ISSUES: - - opcode_stack_effect() function should be reviewed since stack depth bugs - could be really hard to find later. - - Dead code is being generated (i.e. after unconditional jumps). - XXX(nnorwitz): not sure this is still true -*/ - #define DEFAULT_BLOCK_SIZE 16 #define DEFAULT_BLOCKS 8 #define DEFAULT_CODE_SIZE 128 @@ -115,11 +107,11 @@ PyObject *u_private; /* for private name mangling */ int u_argcount; /* number of arguments for block */ - /* Pointer to the most recently allocated block. By following b_list - members, you can reach all early allocated blocks. */ + /* Pointer to the most recently allocated block. By following b_list + members, you can reach all early allocated blocks. */ basicblock *u_blocks; basicblock *u_curblock; /* pointer to current block */ - int u_tmpname; /* temporary variables for list comps */ + int u_tmpname; /* temporary variables for list comps */ int u_nfblocks; struct fblockinfo u_fblock[CO_MAXBLOCKS]; @@ -152,17 +144,6 @@ PyArena *c_arena; /* pointer to memory allocation arena */ }; -struct assembler { - PyObject *a_bytecode; /* string containing bytecode */ - int a_offset; /* offset into bytecode */ - int a_nblocks; /* number of reachable blocks */ - basicblock **a_postorder; /* list of blocks in dfs postorder */ - PyObject *a_lnotab; /* string containing lnotab */ - int a_lnotab_off; /* offset into lnotab */ - int a_lineno; /* last lineno of emitted instruction */ - int a_lineno_off; /* bytecode offset of last lineno */ -}; - static int compiler_enter_scope(struct compiler *, identifier, void *, int); static void compiler_free(struct compiler *); static basicblock *compiler_new_block(struct compiler *); @@ -187,6 +168,8 @@ basicblock *); static void compiler_pop_fblock(struct compiler *, enum fblocktype, basicblock *); +/* Returns true if there is a loop on the fblock stack. */ +static int compiler_in_loop(struct compiler *); static int inplace_binop(struct compiler *, operator_ty); static int expr_constant(expr_ty e); @@ -394,47 +377,6 @@ return dest; } -/* - -Leave this debugging code for just a little longer. - -static void -compiler_display_symbols(PyObject *name, PyObject *symbols) -{ -PyObject *key, *value; -int flags; -Py_ssize_t pos = 0; - -fprintf(stderr, "block %s\n", PyString_AS_STRING(name)); -while (PyDict_Next(symbols, &pos, &key, &value)) { -flags = PyInt_AsLong(value); -fprintf(stderr, "var %s:", PyString_AS_STRING(key)); -if (flags & DEF_GLOBAL) -fprintf(stderr, " declared_global"); -if (flags & DEF_LOCAL) -fprintf(stderr, " local"); -if (flags & DEF_PARAM) -fprintf(stderr, " param"); -if (flags & DEF_STAR) -fprintf(stderr, " stararg"); -if (flags & DEF_DOUBLESTAR) -fprintf(stderr, " starstar"); -if (flags & DEF_INTUPLE) -fprintf(stderr, " tuple"); -if (flags & DEF_FREE) -fprintf(stderr, " free"); -if (flags & DEF_FREE_GLOBAL) -fprintf(stderr, " global"); -if (flags & DEF_FREE_CLASS) -fprintf(stderr, " free/class"); -if (flags & DEF_IMPORT) -fprintf(stderr, " import"); -fprintf(stderr, "\n"); -} - fprintf(stderr, "\n"); -} -*/ - static void compiler_unit_check(struct compiler_unit *u) { @@ -608,7 +550,7 @@ return NULL; } memset((void *)b, 0, sizeof(basicblock)); - /* Extend the singly linked list of blocks with new block. */ + /* Extend the singly linked list of blocks with new block. */ b->b_list = u->u_blocks; u->u_blocks = b; return b; @@ -647,7 +589,7 @@ /* Returns the offset of the next instruction in the current block's b_instr array. Resizes the b_instr as necessary. Returns -1 on failure. - */ +*/ static int compiler_next_instr(struct compiler *c, basicblock *b) @@ -691,7 +633,7 @@ already been set. If it has been set, the call has no effect. Every time a new node is b - */ +*/ static void compiler_set_lineno(struct compiler *c, int off) @@ -1053,8 +995,8 @@ from the current block to the new block. */ -/* XXX The returns inside these macros make it impossible to decref - objects created in the local function. +/* The returns inside these macros make it impossible to decref objects + created in the local function. Local objects should use the arena. */ @@ -2058,7 +2000,7 @@ { int i, n; - /* Always assign a lineno to the next instruction for a stmt. */ + /* Always assign a lineno to the next instruction for a stmt. */ c->u->u_lineno = s->lineno; c->u->u_lineno_set = false; @@ -2157,7 +2099,7 @@ case Pass_kind: break; case Break_kind: - if (!c->u->u_nfblocks) + if (!compiler_in_loop(c)) return compiler_error(c, "'break' outside loop"); ADDOP(c, BREAK_LOOP); break; @@ -2517,7 +2459,6 @@ } return 1; } -#undef CMPCAST static int compiler_call(struct compiler *c, expr_ty e) @@ -2617,7 +2558,7 @@ } ADDOP_JABS(c, JUMP_ABSOLUTE, start); compiler_use_next_block(c, anchor); - /* delete the append method added to locals */ + /* delete the temporary list name added to locals */ if (gen_index == 1) if (!compiler_nameop(c, tmpname, Del)) return 0; @@ -2630,15 +2571,9 @@ { identifier tmp; int rc = 0; - static identifier append; asdl_seq *generators = e->v.ListComp.generators; assert(e->kind == ListComp_kind); - if (!append) { - append = PyString_InternFromString("append"); - if (!append) - return 0; - } tmp = compiler_new_tmpname(c); if (!tmp) return 0; @@ -2937,9 +2872,9 @@ { 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. - */ + /* If expr e has a different line number than the last expr/stmt, + 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; @@ -2983,14 +2918,6 @@ case Yield_kind: if (c->u->u_ste->ste_type != FunctionBlock) return compiler_error(c, "'yield' outside function"); - /* - for (i = 0; i < c->u->u_nfblocks; i++) { - if (c->u->u_fblock[i].fb_type == FINALLY_TRY) - return compiler_error( - c, "'yield' not allowed in a 'try' " - "block with a 'finally' clause"); - } - */ if (e->v.Yield.value) { VISIT(c, expr, e->v.Yield.value); } @@ -3129,8 +3056,11 @@ compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { struct fblockinfo *f; - if (c->u->u_nfblocks >= CO_MAXBLOCKS) + if (c->u->u_nfblocks >= CO_MAXBLOCKS) { + PyErr_SetString(PyExc_SystemError, + "too many statically nested blocks"); return 0; + } f = &c->u->u_fblock[c->u->u_nfblocks++]; f->fb_type = t; f->fb_block = b; @@ -3147,6 +3077,16 @@ assert(u->u_fblock[u->u_nfblocks].fb_block == b); } +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; +} /* Raises a SyntaxError and returns 0. If something goes wrong, a different exception may be raised. */ @@ -3308,7 +3248,6 @@ return 1; } - static int compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { @@ -3356,12 +3295,26 @@ return compiler_handle_subscr(c, kindname, ctx); } + +/* End of the compiler section, beginning of the assembler section */ + /* do depth-first search of basic block graph, starting with block. post records the block indices in post-order. XXX must handle implicit jumps from one block to next */ +struct assembler { + PyObject *a_bytecode; /* string containing bytecode */ + int a_offset; /* offset into bytecode */ + int a_nblocks; /* number of reachable blocks */ + basicblock **a_postorder; /* list of blocks in dfs postorder */ + PyObject *a_lnotab; /* string containing lnotab */ + int a_lnotab_off; /* offset into lnotab */ + int a_lineno; /* last lineno of emitted instruction */ + int a_lineno_off; /* bytecode offset of last lineno */ +}; + static void dfs(struct compiler *c, basicblock *b, struct assembler *a) { Modified: python/branches/bcannon-objcap/Python/errors.c ============================================================================== --- python/branches/bcannon-objcap/Python/errors.c (original) +++ python/branches/bcannon-objcap/Python/errors.c Tue Jan 9 23:27:11 2007 @@ -551,7 +551,8 @@ goto failure; } if (PyDict_GetItemString(dict, "__module__") == NULL) { - modulename = PyString_FromStringAndSize(name, (int)(dot-name)); + modulename = PyString_FromStringAndSize(name, + (Py_ssize_t)(dot-name)); if (modulename == NULL) goto failure; if (PyDict_SetItemString(dict, "__module__", modulename) != 0) @@ -639,7 +640,8 @@ if (warnings_module != NULL) { dict = PyModule_GetDict(warnings_module); - func = PyDict_GetItemString(dict, "warn"); + if (dict != NULL) + func = PyDict_GetItemString(dict, "warn"); } if (func == NULL) { PySys_WriteStderr("warning: %s\n", message); Modified: python/branches/bcannon-objcap/Python/getargs.c ============================================================================== --- python/branches/bcannon-objcap/Python/getargs.c (original) +++ python/branches/bcannon-objcap/Python/getargs.c Tue Jan 9 23:27:11 2007 @@ -815,7 +815,7 @@ #endif else return converterr("string", arg, msgbuf, bufsize); - if ((int)strlen(*p) != PyString_Size(arg)) + if ((Py_ssize_t)strlen(*p) != PyString_Size(arg)) return converterr("string without null bytes", arg, msgbuf, bufsize); } @@ -882,7 +882,7 @@ format++; } else if (*p != NULL && - (int)strlen(*p) != PyString_Size(arg)) + (Py_ssize_t)strlen(*p) != PyString_Size(arg)) return converterr( "string without null bytes or None", arg, msgbuf, bufsize); @@ -1029,7 +1029,8 @@ PyMem_Free()ing it after usage */ - if ((int)strlen(PyString_AS_STRING(s)) != size) { + if ((Py_ssize_t)strlen(PyString_AS_STRING(s)) + != size) { Py_DECREF(s); return converterr( "(encoded string without NULL bytes)", Modified: python/branches/bcannon-objcap/Python/getcopyright.c ============================================================================== --- python/branches/bcannon-objcap/Python/getcopyright.c (original) +++ python/branches/bcannon-objcap/Python/getcopyright.c Tue Jan 9 23:27:11 2007 @@ -4,7 +4,7 @@ static char cprt[] = "\ -Copyright (c) 2001-2006 Python Software Foundation.\n\ +Copyright (c) 2001-2007 Python Software Foundation.\n\ All Rights Reserved.\n\ \n\ Copyright (c) 2000 BeOpen.com.\n\ Modified: python/branches/bcannon-objcap/Python/import.c ============================================================================== --- python/branches/bcannon-objcap/Python/import.c (original) +++ python/branches/bcannon-objcap/Python/import.c Tue Jan 9 23:27:11 2007 @@ -65,9 +65,10 @@ Python 2.5c1: 62121 (fix wrong lnotab with for loops and storing constants that should have been removed) Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp) + Python 2.6a0: 62141 (peephole optimizations) . */ -#define MAGIC (62131 | ((long)'\r'<<16) | ((long)'\n'<<24)) +#define MAGIC (62141 | ((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 @@ -1029,7 +1030,7 @@ /* Return an importer object for a sys.path/pkg.__path__ item 'p', possibly by fetching it from the path_importer_cache dict. If it - wasn't yet cached, traverse path_hooks until it a hook is found + wasn't yet cached, traverse path_hooks until a hook is found that can handle the path item. Return None if no hook could; this tells our caller it should fall back to the builtin import mechanism. Cache the result in path_importer_cache. @@ -1801,7 +1802,7 @@ /* Initialize a built-in module. - Return 1 for succes, 0 if the module is not found, and -1 with + Return 1 for success, 0 if the module is not found, and -1 with an exception set if the initialization failed. */ static int Modified: python/branches/bcannon-objcap/Python/marshal.c ============================================================================== --- python/branches/bcannon-objcap/Python/marshal.c (original) +++ python/branches/bcannon-objcap/Python/marshal.c Tue Jan 9 23:27:11 2007 @@ -546,6 +546,11 @@ int size; PyLongObject *ob; n = r_long(p); + if (n < -INT_MAX || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, + "bad marshal data"); + return NULL; + } size = n<0 ? -n : n; ob = _PyLong_New(size); if (ob == NULL) @@ -654,7 +659,7 @@ case TYPE_INTERNED: case TYPE_STRING: n = r_long(p); - if (n < 0) { + if (n < 0 || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data"); return NULL; } @@ -689,7 +694,7 @@ char *buffer; n = r_long(p); - if (n < 0) { + if (n < 0 || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data"); return NULL; } @@ -710,7 +715,7 @@ case TYPE_TUPLE: n = r_long(p); - if (n < 0) { + if (n < 0 || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data"); return NULL; } @@ -733,7 +738,7 @@ case TYPE_LIST: n = r_long(p); - if (n < 0) { + if (n < 0 || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data"); return NULL; } @@ -831,10 +836,11 @@ v = NULL; - argcount = r_long(p); - nlocals = r_long(p); - stacksize = r_long(p); - flags = r_long(p); + /* XXX ignore long->int overflows for now */ + argcount = (int)r_long(p); + nlocals = (int)r_long(p); + stacksize = (int)r_long(p); + flags = (int)r_long(p); code = r_object(p); if (code == NULL) goto code_error; @@ -859,7 +865,7 @@ name = r_object(p); if (name == NULL) goto code_error; - firstlineno = r_long(p); + firstlineno = (int)r_long(p); lnotab = r_object(p); if (lnotab == NULL) goto code_error; @@ -1031,10 +1037,16 @@ wf.strings = (version > 0) ? PyDict_New() : NULL; w_object(x, &wf); Py_XDECREF(wf.strings); - if (wf.str != NULL) - _PyString_Resize(&wf.str, - (int) (wf.ptr - - PyString_AS_STRING((PyStringObject *)wf.str))); + if (wf.str != NULL) { + char *base = PyString_AS_STRING((PyStringObject *)wf.str); + if (wf.ptr - base > PY_SSIZE_T_MAX) { + Py_DECREF(wf.str); + PyErr_SetString(PyExc_OverflowError, + "too much marshall data for a string"); + return NULL; + } + _PyString_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)); + } if (wf.error) { Py_XDECREF(wf.str); PyErr_SetString(PyExc_ValueError, Modified: python/branches/bcannon-objcap/Python/modsupport.c ============================================================================== --- python/branches/bcannon-objcap/Python/modsupport.c (original) +++ python/branches/bcannon-objcap/Python/modsupport.c Tue Jan 9 23:27:11 2007 @@ -421,7 +421,7 @@ "string too long for Python string"); return NULL; } - n = (int)m; + n = (Py_ssize_t)m; } v = PyString_FromStringAndSize(str, n); } Modified: python/branches/bcannon-objcap/Python/mystrtoul.c ============================================================================== --- python/branches/bcannon-objcap/Python/mystrtoul.c (original) +++ python/branches/bcannon-objcap/Python/mystrtoul.c Tue Jan 9 23:27:11 2007 @@ -195,13 +195,10 @@ return (unsigned long)-1; } -/* Checking for overflow in PyOS_strtol is a PITA since C doesn't define - * anything about what happens when a signed integer operation overflows, - * and some compilers think they're doing you a favor by being "clever" - * then. Python assumes a 2's-complement representation, so that the bit - * pattern for the largest postive signed long is LONG_MAX, and for - * the smallest negative signed long is LONG_MAX + 1. +/* Checking for overflow in PyOS_strtol is a PITA; see comments + * about PY_ABS_LONG_MIN in longobject.c. */ +#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) long PyOS_strtol(char *str, char **ptr, int base) @@ -224,8 +221,7 @@ if (sign == '-') result = -result; } - else if (sign == '-' && uresult == (unsigned long)LONG_MAX + 1) { - assert(LONG_MIN == -LONG_MAX-1); + else if (sign == '-' && uresult == PY_ABS_LONG_MIN) { result = LONG_MIN; } else { Modified: python/branches/bcannon-objcap/Python/peephole.c ============================================================================== --- python/branches/bcannon-objcap/Python/peephole.c (original) +++ python/branches/bcannon-objcap/Python/peephole.c Tue Jan 9 23:27:11 2007 @@ -523,6 +523,13 @@ case SETUP_EXCEPT: case SETUP_FINALLY: tgt = GETJUMPTGT(codestr, i); + /* Replace JUMP_* to a RETURN into just a RETURN */ + if (UNCONDITIONAL_JUMP(opcode) && + codestr[tgt] == RETURN_VALUE) { + codestr[i] = RETURN_VALUE; + memset(codestr+i+1, NOP, 2); + continue; + } if (!UNCONDITIONAL_JUMP(codestr[tgt])) continue; tgttgt = GETJUMPTGT(codestr, tgt); @@ -540,12 +547,16 @@ goto exitUnchanged; /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ + /* Remove unreachable JUMPs after RETURN */ case RETURN_VALUE: - if (i+4 >= codelen || - codestr[i+4] != RETURN_VALUE || - !ISBASICBLOCK(blocks,i,5)) + if (i+4 >= codelen) continue; - memset(codestr+i+1, NOP, 4); + if (codestr[i+4] == RETURN_VALUE && + ISBASICBLOCK(blocks,i,5)) + memset(codestr+i+1, NOP, 4); + else if (UNCONDITIONAL_JUMP(codestr[i+1]) && + ISBASICBLOCK(blocks,i,4)) + memset(codestr+i+1, NOP, 3); break; } } Modified: python/branches/bcannon-objcap/Python/structmember.c ============================================================================== --- python/branches/bcannon-objcap/Python/structmember.c (original) +++ python/branches/bcannon-objcap/Python/structmember.c Tue Jan 9 23:27:11 2007 @@ -62,29 +62,28 @@ addr += l->offset; switch (l->type) { case T_BYTE: - v = PyInt_FromLong( - (long) (((*(char*)addr & 0xff) ^ 0x80) - 0x80)); + v = PyInt_FromLong(*(char*)addr); break; case T_UBYTE: - v = PyInt_FromLong((long) *(char*)addr & 0xff); + v = PyLong_FromUnsignedLong(*(unsigned char*)addr); break; case T_SHORT: - v = PyInt_FromLong((long) *(short*)addr); + v = PyInt_FromLong(*(short*)addr); break; case T_USHORT: - v = PyInt_FromLong((long) *(unsigned short*)addr); + v = PyLong_FromUnsignedLong(*(unsigned short*)addr); break; case T_INT: - v = PyInt_FromLong((long) *(int*)addr); + v = PyInt_FromLong(*(int*)addr); break; case T_UINT: - v = PyInt_FromLong((long) *(unsigned int*)addr); + v = PyLong_FromUnsignedLong(*(unsigned int*)addr); break; case T_LONG: v = PyInt_FromLong(*(long*)addr); break; case T_ULONG: - v = PyLong_FromDouble((double) *(unsigned long*)addr); + v = PyLong_FromUnsignedLong(*(unsigned long*)addr); break; case T_FLOAT: v = PyFloat_FromDouble((double)*(float*)addr); @@ -175,68 +174,107 @@ } addr += l->offset; switch (l->type) { - case T_BYTE: - case T_UBYTE: - if (!PyInt_Check(v)) { - PyErr_BadArgument(); + case T_BYTE:{ + long long_val; + long_val = PyInt_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) return -1; - } - *(char*)addr = (char) PyInt_AsLong(v); + /* XXX: For compatibility, only warn about truncations + for now. */ + if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN)) + PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to char"); + *(char*)addr = (char)long_val; break; - case T_SHORT: - case T_USHORT: - if (!PyInt_Check(v)) { - PyErr_BadArgument(); - return -1; } - *(short*)addr = (short) PyInt_AsLong(v); - break; - case T_UINT: - case T_INT: - if (!PyInt_Check(v)) { - PyErr_BadArgument(); + case T_UBYTE:{ + long long_val; + long_val = PyInt_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) return -1; - } - *(int*)addr = (int) PyInt_AsLong(v); + if ((long_val > UCHAR_MAX) || (long_val < 0)) + PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to unsigned char"); + *(unsigned char*)addr = (unsigned char)long_val; break; - case T_LONG: - if (!PyInt_Check(v)) { - PyErr_BadArgument(); + } + case T_SHORT:{ + long long_val; + long_val = PyInt_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) return -1; + if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN)) + PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to short"); + *(short*)addr = (short)long_val; + break; } - *(long*)addr = PyInt_AsLong(v); + case T_USHORT:{ + long long_val; + long_val = PyInt_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + if ((long_val > USHRT_MAX) || (long_val < 0)) + PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to unsigned short"); + *(unsigned short*)addr = (unsigned short)long_val; break; - case T_ULONG: - if (PyInt_Check(v)) - *(long*)addr = PyInt_AsLong(v); - else if (PyLong_Check(v)) - *(long*)addr = PyLong_AsLong(v); - else { - PyErr_BadArgument(); + } + case T_INT:{ + long long_val; + long_val = PyInt_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) return -1; + if ((long_val > INT_MAX) || (long_val < INT_MIN)) + PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to int"); + *(int *)addr = (int)long_val; + break; + } + case T_UINT:{ + unsigned long ulong_val; + ulong_val = PyLong_AsUnsignedLong(v); + if ((ulong_val == (unsigned int)-1) && PyErr_Occurred()) { + /* XXX: For compatibility, accept negative int values + as well. */ + PyErr_Clear(); + ulong_val = PyLong_AsLong(v); + if ((ulong_val == (unsigned int)-1) && PyErr_Occurred()) + return -1; + PyErr_Warn(PyExc_RuntimeWarning, "Writing negative value into unsigned field"); + } + if (ulong_val > UINT_MAX) + PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to unsigned int"); + *(unsigned int *)addr = (unsigned int)ulong_val; + break; + } + case T_LONG:{ + *(long*)addr = PyLong_AsLong(v); + if ((*(long*)addr == -1) && PyErr_Occurred()) + return -1; + break; + } + case T_ULONG:{ + *(unsigned long*)addr = PyLong_AsUnsignedLong(v); + if ((*(unsigned long*)addr == (unsigned long)-1) + && PyErr_Occurred()) { + /* XXX: For compatibility, accept negative int values + as well. */ + PyErr_Clear(); + *(unsigned long*)addr = PyLong_AsLong(v); + if ((*(unsigned long*)addr == (unsigned int)-1) && PyErr_Occurred()) + return -1; + PyErr_Warn(PyExc_RuntimeWarning, "Writing negative value into unsigned field"); } break; - case T_FLOAT: - if (PyInt_Check(v)) - *(float*)addr = - (float) PyInt_AsLong(v); - else if (PyFloat_Check(v)) - *(float*)addr = - (float) PyFloat_AsDouble(v); - else { - PyErr_BadArgument(); - return -1; } + case T_FLOAT:{ + double double_val; + double_val = PyFloat_AsDouble(v); + if ((double_val == -1) && PyErr_Occurred()) + return -1; + *(float*)addr = (float)double_val; break; + } case T_DOUBLE: - if (PyInt_Check(v)) - *(double*)addr = (double) PyInt_AsLong(v); - else if (PyFloat_Check(v)) - *(double*)addr = PyFloat_AsDouble(v); - else { - PyErr_BadArgument(); + *(double*)addr = PyFloat_AsDouble(v); + if ((*(double*)addr == -1) && PyErr_Occurred()) return -1; - } break; case T_OBJECT: case T_OBJECT_EX: Modified: python/branches/bcannon-objcap/Python/sysmodule.c ============================================================================== --- python/branches/bcannon-objcap/Python/sysmodule.c (original) +++ python/branches/bcannon-objcap/Python/sysmodule.c Tue Jan 9 23:27:11 2007 @@ -983,6 +983,8 @@ br_start = python + 8; br_end = strchr(br_start, '/'); + assert(br_end); + /* Works even for trunk, as we are in trunk/Python/sysmodule.c */ br_end2 = strchr(br_end+1, '/'); @@ -995,6 +997,8 @@ } else if (istag || strncmp(br_start, "branches", 8) == 0) { len = br_end2 - br_start; + assert(len >= 13); + assert(len < (sizeof(patchlevel_revision) - 13)); strncpy(branch, br_start, len); branch[len] = '\0'; @@ -1225,7 +1229,7 @@ p = strchr(path, delim); if (p == NULL) p = strchr(path, '\0'); /* End of string */ - w = PyString_FromStringAndSize(path, (int) (p - path)); + w = PyString_FromStringAndSize(path, (Py_ssize_t) (p - path)); if (w == NULL) { Py_DECREF(v); return NULL; Modified: python/branches/bcannon-objcap/README ============================================================================== --- python/branches/bcannon-objcap/README (original) +++ python/branches/bcannon-objcap/README Tue Jan 9 23:27:11 2007 @@ -1,7 +1,8 @@ -This is Python version 2.5 rc 1 -=============================== +This is Python version 2.6 alpha 0 +================================== -Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 +Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. @@ -223,6 +224,11 @@ available for all modern systems, either in the form of updated compilers from the vendor, or one of the free compilers (gcc). +If "make install" fails mysteriously during the "compiling the library" +step, make sure that you don't have any of the PYTHONPATH or PYTHONHOME +environment variables set, as they may interfere with the newly built +executable which is compiling the library. + Unsupported systems ------------------- Modified: python/branches/bcannon-objcap/Tools/msi/uuids.py ============================================================================== --- python/branches/bcannon-objcap/Tools/msi/uuids.py (original) +++ python/branches/bcannon-objcap/Tools/msi/uuids.py Tue Jan 9 23:27:11 2007 @@ -22,6 +22,8 @@ '2.4.2150':'{b191e49c-ea23-43b2-b28a-14e0784069b8}', # 2.4.2 '2.4.3121':'{f669ed4d-1dce-41c4-9617-d985397187a1}', # 2.4.3c1 '2.4.3150':'{75e71add-042c-4f30-bfac-a9ec42351313}', # 2.4.3 + '2.4.4121':'{cd2862db-22a4-4688-8772-85407ea21550}', # 2.4.4c1 + '2.4.4150':'{60e2c8c9-6cf3-4b1a-9618-e304946c94e6}', # 2.4.4 '2.5.101': '{bc14ce3e-5e72-4a64-ac1f-bf59a571898c}', # 2.5a1 '2.5.102': '{5eed51c1-8e9d-4071-94c5-b40de5d49ba5}', # 2.5a2 '2.5.103': '{73dcd966-ffec-415f-bb39-8342c1f47017}', # 2.5a3 Modified: python/branches/bcannon-objcap/Tools/scripts/findnocoding.py ============================================================================== --- python/branches/bcannon-objcap/Tools/scripts/findnocoding.py (original) +++ python/branches/bcannon-objcap/Tools/scripts/findnocoding.py Tue Jan 9 23:27:11 2007 @@ -5,7 +5,7 @@ Usage: nocoding.py dir1 [dir2...] """ -__author__ = "Oleg Broytmann, Reinhold Birkenfeld" +__author__ = "Oleg Broytmann, Georg Brandl" import sys, os, re, getopt Modified: python/branches/bcannon-objcap/Tools/scripts/pysource.py ============================================================================== --- python/branches/bcannon-objcap/Tools/scripts/pysource.py (original) +++ python/branches/bcannon-objcap/Tools/scripts/pysource.py Tue Jan 9 23:27:11 2007 @@ -15,7 +15,7 @@ walk_python_files() recursively lists all Python files under the given directories. """ -__author__ = "Oleg Broytmann, Reinhold Birkenfeld" +__author__ = "Oleg Broytmann, Georg Brandl" __all__ = ["has_python_ext", "looks_like_python", "can_be_compiled", "walk_python_files"] Modified: python/branches/bcannon-objcap/configure ============================================================================== --- python/branches/bcannon-objcap/configure (original) +++ python/branches/bcannon-objcap/configure Tue Jan 9 23:27:11 2007 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 51727 . +# From configure.in Revision: 52456 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.59 for python 2.6. # @@ -1555,6 +1555,11 @@ # Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish. OpenBSD/2.* | OpenBSD/3.[0123456789] | OpenBSD/4.[0]) define_xopen_source=no;; + # Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of + # _NETBSD_SOURCE disables certain features (eg. setgroups). Reported by + # Marc Recht + NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6A-S) + define_xopen_source=no;; # On Solaris 2.6, sys/wait.h is inconsistent in the usage # of union __?sigval. Reported by Stuart Bishop. SunOS/5.6) @@ -4036,6 +4041,71 @@ fi fi +# Check whether GCC supports PyArg_ParseTuple format +if test "$GCC" = "yes" +then + echo "$as_me:$LINENO: checking whether gcc supports ParseTuple __format__" >&5 +echo $ECHO_N "checking whether gcc supports ParseTuple __format__... $ECHO_C" >&6 + save_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS -Werror" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + + void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2))); + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&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); } && + { ac_try='test -z "$ac_c_werror_flag" + || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1 +_ACEOF + + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 + +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext + CFLAGS=$save_CFLAGS +fi + # On some compilers, pthreads are available without further options # (e.g. MacOS X). On some of these systems, the compiler will not # complain if unaccepted options are passed (e.g. gcc on Mac OS X). @@ -4631,10 +4701,11 @@ + for ac_header in asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ fcntl.h grp.h \ -shadow.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ -signal.h stropts.h termios.h thread.h \ +io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ +shadow.h signal.h stdint.h stropts.h termios.h thread.h \ unistd.h utime.h \ sys/audioio.h sys/bsdtty.h sys/file.h sys/loadavg.h sys/lock.h sys/mkdev.h \ sys/modem.h \ @@ -10073,20 +10144,28 @@ fi -echo "$as_me:$LINENO: checking for uintptr_t support" >&5 -echo $ECHO_N "checking for uintptr_t support... $ECHO_C" >&6 -have_uintptr_t=no -cat >conftest.$ac_ext <<_ACEOF +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 + 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. */ +#ifdef HAVE_STDINT_H + #include + #endif int main () { -uintptr_t x; x = (uintptr_t)0; +if ((uintptr_t *) 0) + return 0; +if (sizeof (uintptr_t)) + return 0; ; return 0; } @@ -10113,23 +10192,23 @@ ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_UINTPTR_T 1 -_ACEOF - - have_uintptr_t=yes - + ac_cv_type_uintptr_t=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 +ac_cv_type_uintptr_t=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -echo "$as_me:$LINENO: result: $have_uintptr_t" >&5 -echo "${ECHO_T}$have_uintptr_t" >&6 -if test "$have_uintptr_t" = yes ; then +fi +echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 +echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6 +if test $ac_cv_type_uintptr_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINTPTR_T 1 +_ACEOF + 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 @@ -10546,6 +10625,8 @@ fi + + # Hmph. AC_CHECK_SIZEOF() doesn't include . echo "$as_me:$LINENO: checking size of off_t" >&5 echo $ECHO_N "checking size of off_t... $ECHO_C" >&6 @@ -22040,55 +22121,38 @@ echo "$as_me:$LINENO: checking for /dev/ptmx" >&5 echo $ECHO_N "checking for /dev/ptmx... $ECHO_C" >&6 -if test "${ac_cv_file__dev_ptmx+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - test "$cross_compiling" = yes && - { { echo "$as_me:$LINENO: error: cannot check for file existence when cross compiling" >&5 -echo "$as_me: error: cannot check for file existence when cross compiling" >&2;} - { (exit 1); exit 1; }; } -if test -r "/dev/ptmx"; then - ac_cv_file__dev_ptmx=yes -else - ac_cv_file__dev_ptmx=no -fi -fi -echo "$as_me:$LINENO: result: $ac_cv_file__dev_ptmx" >&5 -echo "${ECHO_T}$ac_cv_file__dev_ptmx" >&6 -if test $ac_cv_file__dev_ptmx = yes; then + +if test -r /dev/ptmx +then + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 cat >>confdefs.h <<\_ACEOF #define HAVE_DEV_PTMX 1 _ACEOF +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 fi echo "$as_me:$LINENO: checking for /dev/ptc" >&5 echo $ECHO_N "checking for /dev/ptc... $ECHO_C" >&6 -if test "${ac_cv_file__dev_ptc+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - test "$cross_compiling" = yes && - { { echo "$as_me:$LINENO: error: cannot check for file existence when cross compiling" >&5 -echo "$as_me: error: cannot check for file existence when cross compiling" >&2;} - { (exit 1); exit 1; }; } -if test -r "/dev/ptc"; then - ac_cv_file__dev_ptc=yes -else - ac_cv_file__dev_ptc=no -fi -fi -echo "$as_me:$LINENO: result: $ac_cv_file__dev_ptc" >&5 -echo "${ECHO_T}$ac_cv_file__dev_ptc" >&6 -if test $ac_cv_file__dev_ptc = yes; then + +if test -r /dev/ptc +then + echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6 cat >>confdefs.h <<\_ACEOF #define HAVE_DEV_PTC 1 _ACEOF +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 fi - echo "$as_me:$LINENO: checking for %zd printf() format support" >&5 echo $ECHO_N "checking for %zd printf() format support... $ECHO_C" >&6 if test "$cross_compiling" = yes; then Modified: python/branches/bcannon-objcap/configure.in ============================================================================== --- python/branches/bcannon-objcap/configure.in (original) +++ python/branches/bcannon-objcap/configure.in Tue Jan 9 23:27:11 2007 @@ -203,6 +203,11 @@ # Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish. OpenBSD/2.* | OpenBSD/3.@<:@0123456789@:>@ | OpenBSD/4.@<:@0@:>@) define_xopen_source=no;; + # Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of + # _NETBSD_SOURCE disables certain features (eg. setgroups). Reported by + # Marc Recht + NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6[A-S]) + define_xopen_source=no;; # On Solaris 2.6, sys/wait.h is inconsistent in the usage # of union __?sigval. Reported by Stuart Bishop. SunOS/5.6) @@ -890,6 +895,22 @@ fi fi +# Check whether GCC supports PyArg_ParseTuple format +if test "$GCC" = "yes" +then + AC_MSG_CHECKING(whether gcc supports ParseTuple __format__) + save_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS -Werror" + AC_TRY_COMPILE([ + void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2))); + ],, + AC_DEFINE(HAVE_ATTRIBUTE_FORMAT_PARSETUPLE, 1, [Define if GCC supports __attribute__((format(PyArg_ParseTuple, 2, 3)))]) + AC_MSG_RESULT(yes), + AC_MSG_RESULT(no) + ) + CFLAGS=$save_CFLAGS +fi + # On some compilers, pthreads are available without further options # (e.g. MacOS X). On some of these systems, the compiler will not # complain if unaccepted options are passed (e.g. gcc on Mac OS X). @@ -1068,8 +1089,8 @@ AC_HEADER_STDC AC_CHECK_HEADERS(asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ fcntl.h grp.h \ -shadow.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ -signal.h stropts.h termios.h thread.h \ +io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ +shadow.h signal.h stdint.h stropts.h termios.h thread.h \ unistd.h utime.h \ sys/audioio.h sys/bsdtty.h sys/file.h sys/loadavg.h sys/lock.h sys/mkdev.h \ sys/modem.h \ @@ -1197,16 +1218,12 @@ AC_CHECK_SIZEOF(long long, 8) fi -AC_MSG_CHECKING(for uintptr_t support) -have_uintptr_t=no -AC_TRY_COMPILE([], [uintptr_t x; x = (uintptr_t)0;], [ - AC_DEFINE(HAVE_UINTPTR_T, 1, [Define this if you have the type uintptr_t.]) - have_uintptr_t=yes -]) -AC_MSG_RESULT($have_uintptr_t) -if test "$have_uintptr_t" = yes ; then -AC_CHECK_SIZEOF(uintptr_t, 4) -fi +AC_CHECK_TYPES(uintptr_t, + [AC_CHECK_SIZEOF(uintptr_t, 4)], + [], [#ifdef HAVE_STDINT_H + #include + #endif]) + # Hmph. AC_CHECK_SIZEOF() doesn't include . AC_MSG_CHECKING(size of off_t) @@ -3342,8 +3359,27 @@ AC_MSG_RESULT(no) ) -AC_CHECK_FILE(/dev/ptmx, AC_DEFINE(HAVE_DEV_PTMX, 1, [Define if we have /dev/ptmx.])) -AC_CHECK_FILE(/dev/ptc, AC_DEFINE(HAVE_DEV_PTC, 1, [Define if we have /dev/ptc.])) +AC_MSG_CHECKING(for /dev/ptmx) + +if test -r /dev/ptmx +then + AC_MSG_RESULT(yes) + AC_DEFINE(HAVE_DEV_PTMX, 1, + [Define if we have /dev/ptmx.]) +else + AC_MSG_RESULT(no) +fi + +AC_MSG_CHECKING(for /dev/ptc) + +if test -r /dev/ptc +then + AC_MSG_RESULT(yes) + AC_DEFINE(HAVE_DEV_PTC, 1, + [Define if we have /dev/ptc.]) +else + AC_MSG_RESULT(no) +fi AC_MSG_CHECKING(for %zd printf() format support) AC_TRY_RUN([#include Modified: python/branches/bcannon-objcap/pyconfig.h.in ============================================================================== --- python/branches/bcannon-objcap/pyconfig.h.in (original) +++ python/branches/bcannon-objcap/pyconfig.h.in Tue Jan 9 23:27:11 2007 @@ -40,6 +40,9 @@ /* Define to 1 if you have the header file. */ #undef HAVE_ASM_TYPES_H +/* Define if GCC supports __attribute__((format(PyArg_ParseTuple, 2, 3))) */ +#undef HAVE_ATTRIBUTE_FORMAT_PARSETUPLE + /* Define to 1 if you have the `bind_textdomain_codeset' function. */ #undef HAVE_BIND_TEXTDOMAIN_CODESET @@ -677,7 +680,7 @@ /* Define this if you have tcl and TCL_UTF_MAX==6 */ #undef HAVE_UCS4_TCL -/* Define this if you have the type uintptr_t. */ +/* Define to 1 if the system has the type `uintptr_t'. */ #undef HAVE_UINTPTR_T /* Define to 1 if you have the `uname' function. */ Modified: python/branches/bcannon-objcap/setup.py ============================================================================== --- python/branches/bcannon-objcap/setup.py (original) +++ python/branches/bcannon-objcap/setup.py Tue Jan 9 23:27:11 2007 @@ -610,7 +610,7 @@ # a release. Most open source OSes come with one or more # versions of BerkeleyDB already installed. - max_db_ver = (4, 4) + max_db_ver = (4, 5) min_db_ver = (3, 3) db_setup_debug = False # verbose debug prints from this script? @@ -627,7 +627,7 @@ '/sw/include/db3', ] # 4.x minor number specific paths - for x in (0,1,2,3,4): + for x in (0,1,2,3,4,5): db_inc_paths.append('/usr/include/db4%d' % x) db_inc_paths.append('/usr/include/db4.%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x) @@ -635,7 +635,7 @@ db_inc_paths.append('/pkg/db-4.%d/include' % x) db_inc_paths.append('/opt/db-4.%d/include' % x) # 3.x minor number specific paths - for x in (2,3): + for x in (3,): db_inc_paths.append('/usr/include/db3%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x) db_inc_paths.append('/usr/local/include/db3%d' % x) @@ -683,7 +683,8 @@ # save the include directory with the db.h version # (first occurrance only) db_ver_inc_map[db_ver] = d - print "db.h: found", db_ver, "in", d + if db_setup_debug: + 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 @@ -723,8 +724,9 @@ if db_setup_debug: print "db lib: ", dblib, "not found" except db_found: - print "db lib: using", db_ver, dblib - if db_setup_debug: print "db: lib dir", dblib_dir, "inc dir", db_incdir + if db_setup_debug: + 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 @@ -745,7 +747,7 @@ dblib_dir = None # The sqlite interface - sqlite_setup_debug = True # verbose debug prints from this script? + sqlite_setup_debug = False # verbose debug prints from this script? # We hunt for #define SQLITE_VERSION "n.n.n" # We need to find >= sqlite version 3.0.8 @@ -777,7 +779,8 @@ for x in sqlite_version.split(".")]) if sqlite_version_tuple >= MIN_SQLITE_VERSION_NUMBER: # we win! - print "%s/sqlite3.h: version %s"%(d, sqlite_version) + if sqlite_setup_debug: + print "%s/sqlite3.h: version %s"%(d, sqlite_version) sqlite_incdir = d break else: From python-checkins at python.org Tue Jan 9 23:45:07 2007 From: python-checkins at python.org (brett.cannon) Date: Tue, 9 Jan 2007 23:45:07 +0100 (CET) Subject: [Python-checkins] r53330 - sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/importlib.py sandbox/trunk/import_in_py/mock_importer.py sandbox/trunk/import_in_py/mock_importlib.py sandbox/trunk/import_in_py/test_importer.py sandbox/trunk/import_in_py/test_importlib.py Message-ID: <20070109224507.5190A1E4007@bag.python.org> Author: brett.cannon Date: Tue Jan 9 23:45:05 2007 New Revision: 53330 Added: sandbox/trunk/import_in_py/importlib.py - copied unchanged from r53322, sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/mock_importlib.py - copied, changed from r53280, sandbox/trunk/import_in_py/mock_importer.py sandbox/trunk/import_in_py/test_importlib.py - copied, changed from r53280, sandbox/trunk/import_in_py/test_importer.py Removed: sandbox/trunk/import_in_py/importer.py sandbox/trunk/import_in_py/mock_importer.py sandbox/trunk/import_in_py/test_importer.py Log: Rename the module importlib. Deleted: /sandbox/trunk/import_in_py/importer.py ============================================================================== --- /sandbox/trunk/import_in_py/importer.py Tue Jan 9 23:45:05 2007 +++ (empty file) @@ -1,902 +0,0 @@ -"""Implementation of Python's import machinery in Python source code. - -The Import class implements the semantics of import. This means that an -instance of this class can be called to properly check sys.modules, -sys.meta_path, sys.path, etc. to import the requested module. - -The importing of built-in, frozen, extension, .py, and .pyc files are all -handled by implementing importers and loaders as specified by PEP 302. This -leads to the ability to easily control imports based on the type of module. -There is also a clear distinction between how the module is stored and how it -is formatted (e.g., a Python source file does not require it be stored as a -file on a filesystem). - -To help with the distinction between how a module is stored compared to its -format the idea of handlers is introduced. A handler implements a specific -interface while specifying the type of module it handles (usually by the what -one would expect as a file extension if the module was on a filesystem). This -allows a PEP 302 importer/loader to represent how a module is stored while the -handler deals with how the module is formatted. - -A handler is expected to implement the handle_code method only. The handler -for Python source and bytecode modules goes farther and defines an extensive -interface that is designed so that alternatives on module formatting can be -supported easily without needing to write a new importer/loader. The Python -source and bytecode handler also expects loaders to define a more extensive -interface to allow for different backend stores (e.g., databases) to use the -handler without modification. All of this helps with code reuse and possible -errors from the complicated relationship between Python source and bytecode -modules. - - -==================== -References on import -==================== -* Language reference - http://docs.python.org/ref/import.html -* __import__ function - http://docs.python.org/lib/built-in-funcs.html -* Packages - http://www.python.org/doc/essays/packages.html -* PEP 235: Import on Case-Insensitive Platforms - http://www.python.org/dev/peps/pep-0235 -* PEP 275: Import Modules from Zip Archives - http://www.python.org/dev/peps/pep-0273 -* PEP 302: New Import Hooks - http://www.python.org/dev/peps/pep-0302/ -* PEP 328: Imports: Multi-line and Absolute/Relative - http://www.python.org/dev/peps/pep-0328 - -============ -Known Issues -============ -* runpy ('-m' command-line option for Python) does not work. - + Requires get_code to be implemented for loaders. - + Uses pkgutil.get_loader which fakes a loader if __loader__ is not defined. - + New loaders do define __loader__ but not get_code, and thus dies on an - AttributeError. - + Possible fix - - Implement optional interface for loaders. - - Do not have new loaders set __loader__. - * Might happen because of security issues. -* warnings and stack level. - + Affected tests - - test___all__ - - test_imageop - + 'warnings' assumes that the import code does not show up in the call - stack. - + Because import now implemented in Python, import does show up in the - call stack. - + Trick of specifying going back in the call stack two levels so warning - shows up in the caller will cause the warning no longer holds true. - + Possible fixes - - Special module deprecation function. - - Code in warnings.warn to handle special import case. - - Flag on warnings.warn that warning is for an import and ignore stack - level argument. - * Could also infer from type of warning. -* test_pkg - + Old-style test that compares output. - + Setting of __loader__ leads to different output. - -""" -from __future__ import with_statement - -# Built-in modules. -import imp -import sys -import marshal -# Not built-in. -import errno -import os -import contextlib -import warnings - - -def _set__import__(): - """Set __import__ to an instance of Import.""" - global original__import__ - original__import__ = __import__ - __builtins__['__import__'] = Import() - -def _reset__import__(): - """Set __import__ back to the original implementation (assumes - _set__import__ was called previously).""" - __builtins__['__import__'] = original__import__ - -def _w_long(x): - """Convert a 32-bit integer to little-endian. - - XXX Temporary until marshal's long functions are exposed. - - """ - bytes = [] - bytes.append(x & 0xFF) - bytes.append((x >> 8) & 0xFF) - bytes.append((x >> 16) & 0xFF) - bytes.append((x >> 24) & 0xFF) - return ''.join(chr(x) for x in bytes) - -def _r_long(bytes): - """Convert 4 bytes in little-endian to an integer. - - XXX Temporary until marshal's long function are exposed. - - """ - x = ord(bytes[0]) - x |= ord(bytes[1]) << 8 - x |= ord(bytes[2]) << 16 - x |= ord(bytes[3]) << 24 - return x - -def _case_ok(directory, file_name): - """Verify that file_name (as found in 'directory') has the proper case. - - The path is assumed to already exist. - - XXX Temporary until imp's case_ok function can be exposed. - - XXX Better to roll this into a single function some how so that existence - check can be part of case check and thus cut down on stat calls? - - """ - # If platform is not case-sensitive *or* the environment variable - # PYTHONCASEOK is defined, then os.path.exists already handled the case by - # either doing a case-sensitive check or from the user saying he does not - # want case-sensitivity, respectively. - if sys.platform not in ('win32', 'mac', 'riscos', 'darwin', 'cygwin', - 'os2emx') or os.environ.get('PYTHONCASEOK'): - return True - directory_contents = os.listdir(directory) - if file_name in directory_contents: - return True - else: - return False - - -class _BuiltinFrozenBaseImporter(object): - - """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. - - """ - - @classmethod - def find_module(cls, 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 - else: - return None - - @classmethod - def load_module(cls, fullname): - """Load a built-in or frozen module. - - 'imp' code for loading a built-in or frozen module handles the setting - of a module in sys.modules before initializing the module. This means - that we do not need to perform that step as outlined by PEP 302. - - """ - try: - return sys.modules[fullname] - except KeyError: - mod = cls._load(fullname) - if not mod: - raise ImportError("expected built-in module not loaded") - return mod - - -class BuiltinImporter(_BuiltinFrozenBaseImporter): - - """sys.meta_path class for importing built-in modules. - - XXX Possible optimization is to bail out in find_module() if 'path' is set - to a value. - - """ - - _find = imp.is_builtin - _load = imp.init_builtin - - -class FrozenImporter(_BuiltinFrozenBaseImporter): - - """sys.meta_path class for importing frozen modules.""" - - _find = imp.is_frozen - _load = imp.init_frozen - - -class FileSystemFactory(object): - - """Factory function for sys.path_hooks for directory entries on sys.path. - - The path to be handled, if it is a filesystem directory, is used to - initialize a new FileSystemImporter for that path entry. An instantiated - object stores various handlers that are to be used to decide if the path - entry contains the module to be imported. - - XXX Possible optimization would be to get the directory's contents and make - sure that only handlers for the files in the directory are given to the - returned importer. This would kill the ability to add a new module into - the directory during run-time that is a new type of file, though. - - """ - - def __init__(self, *handlers): - """Store handlers to be used in attempting to import. - - The order that the handlers are specified are the order in which - the handlers will be passed on to any instantiated importers. - - """ - self.handlers = handlers - - def __call__(self, path_entry): - """If path_entry is a directory, return an importer object for it, else - raise ImportError. - - Both relative and absolute paths are accepted (the former because of - interactive interpreter usage). - - """ - absolute_path = os.path.abspath(path_entry) - if os.path.isdir(absolute_path): - return FileSystemImporter(absolute_path, *self.handlers) - else: - raise ImportError("can only handle directories") - - -class FileSystemImporter(object): - - """Importer for the filesystem using the passed-in handlers.""" - - def __init__(self, path_entry, *handlers): - """Store the path this importer handles and the handlers to use. - - The order of the handlers determines precedence of file types. - - """ - self.path_entry = path_entry - self.handlers = handlers - self.loader = FileSystemLoader - - def find_module(self, fullname, path=None): - """Determine if this path entry can handle this import, and if so, - return a loader for the module on this path entry based on the handlers - registered. - - 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. - - """ - tail_module = fullname.rsplit('.', 1)[-1] - package_directory = os.path.join(self.path_entry, tail_module) - for handler in self.handlers: - for file_ext in handler.handles: - # XXX Backwards-incompatible to use anything but .py/.pyc - # files for __init__? - init_filename = '__init__' + file_ext - package_init = os.path.join(package_directory, init_filename) - # Check if it is a package with an __init__ file. - if (os.path.isfile(package_init) and - _case_ok(self.path_entry, tail_module) and - _case_ok(package_directory, init_filename)): - return self.loader(package_init, handler, package_directory) - # See if it is a module. - file_name = tail_module + file_ext - file_path = os.path.join(self.path_entry, file_name) - if (os.path.isfile(file_path) and - _case_ok(self.path_entry, file_name)): - return self.loader(file_path, handler) - else: - # Raise a warning if it matches a directory w/o an __init__ file. - if (os.path.isdir(package_directory) and - _case_ok(self.path_entry, tail_module)): - warnings.warn("Not importing directory %s: missing __init__.py" - % package_directory, - ImportWarning) - return None - - -class FileSystemLoader(object): - - """Loader for the filesystem. - - It implements the needed API for the PyPycHandler. - - """ - - def __init__(self, file_path, handler, package=None): - """Store the path to the file to use for the import and the handler to - use along with whether this is a package (this does not include modules - within a package).""" - self.file_path = file_path - self.handler = handler - self.package = package - - def load_module(self, fullname): - """Load the module from self.path using self.handler. - - The handler is expected to implement a handle_code method that will - deal with initializing the module passed to it. - - """ - try: - module = self.handler.handle_code(self, fullname, - self.file_path, self.package) - # Don't leave any partially initialised modules behind. - except: - if fullname in sys.modules: - del sys.modules[fullname] - raise - else: - return module - - def mod_time(self, path): - """Return the modification time for the specified path as an integer. - - This method is required as part of the interface needed for - PyPycHandler. - - """ - return int(os.stat(path).st_mtime) - - def split_path(self, path): - """Split the specified path into a base path and the type of the - path. - - This method is required for PyPycHandler. - - """ - return os.path.splitext(path) - - def create_path(self, base_path, type_, must_exist=False): - """Create a new path based on a base path and requested path type. - - If must_exist is True, the path must already exist in order to return a - path instead of None. - - This method is required for PyPycHandler. - - """ - path = base_path + type_ - if must_exist: - path = path if os.path.exists(path) else None - return path - - def read_data(self, path, binary=False): - """Open the path and return the data read from it in the specified - format. - - This method is required for PyPycHandler. - - """ - with open(path, 'rb' if binary else 'U') as data_file: - data = data_file.read() - return data - - def write_data(self, data, path, binary=False): - """Write data to a specified path as either binary or textual data. - - If the path cannot be accessed, then exit silently. - - This method is required for PyPycHandler. - - """ - try: - with open(path, 'wb' if binary else 'w') as data_file: - data_file.write(data) - except IOError, exc: - if exc.errno == errno.EACCES: - pass - else: - raise - - -class PyPycHandler(object): - - """Handle reading Python bytecode/source with writing out of bytecode as - needed. - - The handle_code method is the key entry point for this class. - - """ - - def __init__(self, source_handles=None, bytecode_handles=None): - """Specify the file types for source and bytecode to be handled by this - handler and set 'handles' appropriately as tuples (empty tuples are - acceptable). - - Not specifying handles will lead to reasonable defaults being used. - - """ - if source_handles is None: - self.source_handles = ('.py',) - else: - self.source_handles = source_handles - if bytecode_handles is None: - self.bytecode_handles = ('.pyc',) if __debug__ else ('.pyo',) - else: - self.bytecode_handles = bytecode_handles - self.handles = self.bytecode_handles + self.source_handles - - def new_module(self, name): - """Retun a new module to be initialized (with __name__ set).""" - return imp.new_module(name) - - def parse_pyc(self, data): - """Split data into magic number, timestamp, and bytecode.""" - return data[:4], _r_long(data[4:8]), data[8:] - - def check_magic(self, magic): - """Check whether the magic number is correct or not for the current - running interpreter.""" - return imp.get_magic() == magic - - def code_from_bytecode(self, bytecode): - """Create a code object from bytecode. - - ValueError is expected to be raised if a code object can not be created - from the bytecode. - - """ - return marshal.loads(bytecode) - - def code_from_source(self, source, path): - """Create a code object from source.""" - return compile(source, str(path), 'exec') - - def create_pyc(self, bytecode, timestamp): - """Create data to be written out for a .pyc file.""" - data = imp.get_magic() - data += _w_long(timestamp) - data += marshal.dumps(bytecode) - return data - - def handle_code(self, loader, mod_name, path, package=None): - """Handle creating a new module object for the module mod_name that is - to be initialized with data from 'path' and, if a package, has a - 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: - - * split_path(path) - Take in an opaque path object and split it into a base path and a - string representing the type of the path (which should be in the - 'handles' attribute of the handler). - * create_path(base_path, type_, must_exist) - Create an opaque path object from a base path and the type of path - that is desired. If must_exist is True the path must already - exist. - * mod_time(path) - Return the last modification time for a path as an integer. - * read_data(path, binary) - Read the data from the specified path. 'binary' is a boolean that - flags whether the data should be read as binary data or text data. - * write_data(data, path, binary) - Write data to a path. 'binary' flags whether the data should be - written as binary or textual data. - - """ - source_path = None - source_timestamp = None - bytecode_path = None - module = sys.modules.get(mod_name) - if module is None: - module = self.new_module(mod_name) - sys.modules[mod_name] = module - # __file__, __path__, and __loader__ *must* be set on the module before - # any code is executed by the import. __name__ is set by new_module. - module.__loader__ = loader - module.__file__ = path - if package is not None: - module.__path__ = [package] - base_path, type_ = loader.split_path(path) - if type_ in self.bytecode_handles: - # Attempt to use bytecode. - bytecode_path = path - source_path = None - pyc_data = loader.read_data(path, True) - magic, pyc_timestamp, bytecode = self.parse_pyc(pyc_data) - # Try to find corresponding source code. - for source_handle in self.source_handles: - source_path = loader.create_path(base_path, source_handle, True) - if source_path: - break - try: - # Verify that the magic number is valid. - if not self.check_magic(magic): - raise ImportError("bad magic number") - # Verify that the bytecode is not stale. - if source_path: - source_timestamp = loader.mod_time(source_path) - if pyc_timestamp < source_timestamp: - raise ImportError("bytcode is stale") - # Bytecode is valid. - module.__file__ = path - try: - code_object = self.code_from_bytecode(bytecode) - except ValueError: - # Since bad bytecode halts the import entirely having the - # source code is useless. Use this fact to signal that - # the ImportError being raised should propagate. - source_path = None - raise ImportError('Non-code object in %s' % - str(bytecode_path)) - exec code_object in module.__dict__ - return module - except ImportError: - # No source code to use to recover from bad bytecode. - if not source_path: - raise - if type_ in self.source_handles: - # Asked directly to handle source code. - source_path = path - # Get the source code. - source = loader.read_data(source_path, False) - module.__file__ = source_path - code = self.code_from_source(source, source_path) - # See if there is a corresponding path to bytecode. - if not bytecode_path: - if self.bytecode_handles: - bytecode_handle = self.bytecode_handles[0] - bytecode_path = loader.create_path(base_path, - bytecode_handle) - source_timestamp = loader.mod_time(source_path) - # If there is a possible path to bytecode, generate .pyc file. - if bytecode_path: - if not source_timestamp: - source_timestamp = loader.mod_time(source_path) - pyc = self.create_pyc(code, source_timestamp) - loader.write_data(pyc, bytecode_path, True) - exec code in module.__dict__ - return module - - -class ExtensionFileHandler(object): - - """A handler for loading extension modules.""" - - def __init__(self): - """Set 'handles'.""" - self.handles = tuple(suffix[0] for suffix in imp.get_suffixes() - if suffix[2] == imp.C_EXTENSION) - - def handle_code(self, loader, mod_name, extension_path, package=None): - """Import an extension module.""" - module = imp.load_dynamic(mod_name, extension_path) - if package is not None: - module.__path__ = [package] - return module - - -class ImportLockContext(object): - - """Context manager for the import lock.""" - - def __enter__(self): - """Acquire the import lock.""" - imp.acquire_lock() - - def __exit__(self, exc_type, exc_value, exc_traceback): - """Release the import lock regardless of any raised exceptions.""" - imp.release_lock() - - -class Import(object): - - """Class that implements the __import__ interface. - - Backwards compatibility is maintained by extending sys.meta_path - interally (for handling built-in and frozen modules) and providing a - default path hooks entry (for extension modules, .py, and .pyc - files). Both are controlled during instance initialization. - - """ - - def __init__(self, default_path_hook=None, - 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 - self.default_path_hook = default_path_hook - if not self.default_path_hook: - # Create a handler to deal with extension modules, .py, and .pyc - # files. Built-in and frozen modules are handled by sys.meta_path - # entries. - handlers = ExtensionFileHandler(), PyPycHandler() - self.default_path_hook = FileSystemFactory(*handlers) - - def _search_meta_path(self, name, path=None): - """Check the importers on sys.meta_path for a loader along with the - extended meta path sequence stored within this instance. - - The extended sys.meta_path entries are searched after the entries on - sys.meta_path. - - """ - for entry in (tuple(sys.meta_path) + self.extended_meta_path): - loader = entry.find_module(name, path) - if loader: - return loader - else: - raise ImportError("No module named %s" % name) - - def _sys_path_importer(self, path_entry): - """Return the importer for the specified path, from - sys.path_importer_cache if possible. - - If None is stored in sys.path_importer_cache then use the default path - hook. - - """ - try: - # See if an importer is cached. - importer = sys.path_importer_cache[path_entry] - # If None was returned, use default importer factory. - if importer is None: - # XXX Would it break backwards-compatibility to set the importer - # in sys.path_importer_cache, replacing the None entry? - return self.default_path_hook(path_entry) - else: - return importer - except KeyError: - # No cached importer found; try to get a new one from - # sys.path_hooks. - for importer_factory in sys.path_hooks: - try: - importer = importer_factory(path_entry) - # XXX Going to break backwards-compatibility by storing - # an instance of the default importer? None still handled - # properly so shouldn't be any different than some other - # importer being stored. - sys.path_importer_cache[path_entry] = importer - return importer - except ImportError: - continue - else: - # No importer factory on sys.path_hooks works; use the default - # importer factory. - try: - importer = self.default_path_hook(path_entry) - sys.path_importer_cache[path_entry] = importer - return importer - except ImportError: - sys.path_importer_cache[path_entry] = None - raise ImportError("no importer found for %s" % path_entry) - - def _search_std_path(self, name, path=None): - """Check sys.path or 'path' (depending if 'path' is set) for the - named module and return its loader.""" - if path: - search_paths = path - else: - search_paths = sys.path - for entry in search_paths: - try: - importer = self._sys_path_importer(entry) - except ImportError: - continue - loader = importer.find_module(name) - if loader: - return loader - else: - raise ImportError("No module found named %s" % name) - - def _import_module(self, name, path=None): - """Import the specified module with no handling of parent modules. - - If None is set for a value in sys.modules (to signify that a relative - import was attempted and failed) then ImportError is raised. - - """ - if name in sys.modules: - value = sys.modules[name] - if value is None: - raise ImportError("relative import redirect") - else: - return value - try: - # Attempt to find a loader on sys.meta_path. - loader = self._search_meta_path(name, path) - except ImportError: - # sys.meta_path search failed. Attempt to find a loader on - # sys.path. If this fails then module cannot be found. - 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) - - def _import_full_module(self, name): - """Import a module along with its parent modules and set into - sys.modules.""" - # Import the module (importing its parent modules first). - name_parts = name.split('.') - current_name_parts = [] - parent_module = None - path_list = None - # XXX Any perk to being optimistic and assuming parent modules were - # imported already, and thus search in the reverse order for the first module - # to be found? - for name_part in name_parts: - current_name_parts.append(name_part) - # Recreating name every time around the loop is sub-optimal, but - # does away with base case of a non-dotted name. - current_name = ".".join(current_name_parts) - if parent_module: - try: - path_list = parent_module.__path__ - except AttributeError: - pass - module = self._import_module(current_name, path_list) - if parent_module: - setattr(parent_module, name_part, module) - parent_module = module - - def _classic_resolve_name(self, name, caller_name, caller_is_package): - """Return the absolute name of the module specified in 'name' as based - on the name of the caller and whether it is a package.""" - if caller_is_package: - base_name = caller_name - else: - if '.' not in caller_name: - # Importing in a top-level module, so name is already absolute. - return name - else: - base_name = caller_name.rsplit('.', 1)[0] - return base_name + '.' + name - - def _resolve_name(self, name, caller_name, caller_is_package, level): - """Return the absolute name of the module specified by 'name' based on - where the module is being imported and the requested change in dotted - name level. - - Absolute imports always take the form of ``from import ...``. - This means that the number of leading dots in '' becomes 'level' - and the rest of '' becomes 'name'. This leads to the possibility - that 'name' is the empty string, representing the current package. - - """ - if caller_is_package: - level -= 1 - if caller_name.count('.') < level: - raise ImportError("attempted relative import beyond top-level " - "pacakge") - base_name = caller_name.rsplit('.', level)[0] - if name: - return base_name + '.' + name - else: - return base_name - - 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. - - 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 - module being requested is an absolute name this is simple (and - relative_name is an empty string). But if the requested module was - a relative import (as signaled by relative_name having a non-false - value), then the name up to the first dot in the relative name resolved - to an absolute name is to be returned. - - When fromlist is not empty and the module being imported is a package, - then the values - in fromlist need to be checked for. If a value is not a pre-existing - attribute a relative import is attempted. If it fails then suppressed - the failure silently. - - """ - if not fromlist: - if relative_name: - absolute_base = absolute_name.rpartition(relative_name)[0] - relative_head = relative_name.split('.', 1)[0] - to_return = absolute_base + relative_head - else: - to_return = absolute_name.split('.', 1)[0] - return sys.modules[to_return] - # When fromlist is not empty, return the actual module specified in - # the import. - else: - module = sys.modules[absolute_name] - if hasattr(module, '__path__') and hasattr(module, '__name__'): - # When fromlist has a value and the imported module is a - # package, then if a name in fromlist is not found as an - # attribute on module, try a relative import to find it. - # Failure is fine and the exception is suppressed. - check_for = list(fromlist) - if '*' in check_for and hasattr(module, '__all__'): - check_for.extend(module.__all__) - for item in check_for: - if item == '*': - continue - if not hasattr(module, item): - resolved_name = self._resolve_name(item, module.__name__, - True, 1) - try: - self._import_full_module(resolved_name) - except ImportError: - pass - return module - - def __call__(self, name, globals={}, locals={}, fromlist=[], level=-1): - """Import a module. - - The 'name' argument is the name of the module to be imported (e.g., - 'foo' in ``import foo`` or ``from foo import ...``). - - 'globals' and 'locals' are the global and local namespace dictionaries - of the module where the import statement appears. 'globals' is used to - introspect the __path__ and __name__ attributes of the module making - the call. 'local's is ignored. - - 'fromlist' lists any specific objects that are to eventually be put - into the namespace (e.g., ``from for.bar import baz`` would have 'baz' - in the fromlist, and this includes '*'). An entry of '*' will lead to - a check for __all__ being defined on the module. If it is defined then - the values in __all__ will be checked to make sure that all values are - attributes on the module, attempting a module import relative to 'name' - to set that attribute. - - When 'name' is a dotted name, there are two different situations to - consider for the return value. One is when the fromlist is empty. - In this situation the import statement imports and returns the name up - to the first dot. All subsequent names are imported but set as - attributes as needed on parent modules. When fromlist is not empty - then the module represented by the full dotted name is returned. - - 'level' represents how to handle possible relative imports. If 'level' - is set to -1 then the module name could be either relative or absolute. - A value of 0 is for absolute module names., Any positive value - represents the number of dots listed in the relative import statement - (e.g. has a value of 2 for ``from .. import foo``). - - """ - if not name and level < 1: - raise ValueError("Empty module name") - is_pkg = True if '__path__' in globals else False - caller_name = globals.get('__name__') - with ImportLockContext(): - if level and caller_name: - # Handle the classic style of import: relative first, then - # absolute. - if level == -1: - relative_name = self._classic_resolve_name(name, caller_name, - is_pkg) - imported_name = relative_name - try: - # Try a relative import. - self._import_full_module(imported_name) - except ImportError: - # If the relative import fails (or is redirected), try an - # absolute import. - imported_name = name - self._import_full_module(imported_name) - # Redirection entry for resolved relative name to instead - # redirect to the absolute import. - sys.modules[relative_name] = None - # If using absolute imports with a relative path, only attempt with - # the fully-resolved module name. - else: - imported_name = self._resolve_name(name, caller_name, is_pkg, - level) - # This call will also handle setting the attribute on the - # package. - self._import_full_module(imported_name) - # Absolute module import of a top-level module. - else: - imported_name = name - self._import_full_module(name) - relative_name = '' if imported_name == name else name - return self._return_module(imported_name, relative_name, fromlist) Deleted: /sandbox/trunk/import_in_py/mock_importer.py ============================================================================== --- /sandbox/trunk/import_in_py/mock_importer.py Tue Jan 9 23:45:05 2007 +++ (empty file) @@ -1,278 +0,0 @@ -import sys -import marshal -import imp -from test import test_support -from importer import _w_long - -def log_call(method): - """Log method calls to self.log.""" - def log_and_call(self, *args, **kwargs): - self.log.append(method.__name__) - return method(self, *args, **kwargs) - return log_and_call - -class MockModule(object): - - """A mock module.""" - - def __init__(self, name=None, file_path=None, pkg_list=None, __all__=None): - if name is not None: - self.__name__ = name - if file_path is not None: - self.__file__ = file_path - if pkg_list is not None: - self.__path__ = pkg_list - if __all__ is not None: - self.__all__ = __all__ - - -class MockHandler(object): - - """Mock a handler.""" - - def __init__(self, *handles): - self.handles = handles - - def handle_code(self, loader, mod_name, path, package=None): - """Mock implementation of a handler. - - An object that can have arbitrary attributes attached to it must be - returned. - - """ - module = sys.modules.get(mod_name) - if module is None: - module = self - sys.modules[mod_name] = self - try: - module.loader = loader - module.module_name = mod_name - module.path = path - module.package = package - except AttributeError: - pass - return module - -class MockPyPycLoader(object): - - """Mock loader object for testing importer.PyPycHandler. - - Opaque path objects are two-item tuple consisting of a string representing - the base path and another string representing the type. - - """ - - def __init__(self, file_path, handler, package=None): - """Store arguments passed into the constructor for verification.""" - self.file_path = file_path - self.handler = handler - self.package = package - - @classmethod - def setup(cls, good_magic=True, good_timestamp=True, pyc_exists=True, - py_exists=True, good_bytecode=True): - """Set up the mock loader based on possible scenarios of source and - bytecode combinations/issues.""" - self = cls('', '') - self.module_name = 'test_module' - self.py_ext = "source" if py_exists else None - self.pyc_ext = "bytecode" if pyc_exists else None - self.base_path = "base path" - self.py_path = (self.base_path, self.py_ext) - self.pyc_path = (self.base_path, self.pyc_ext) - self.modification_time = 1 - # Needed for read_data on source path. - self.attr_name = 'test_attr' - self.attr_value = None - self.source = "%s = %s" % (self.attr_name, self.attr_value) - code_object = compile(self.source, "", 'exec') - bytecode = marshal.dumps(code_object) - if good_magic: - pyc = imp.get_magic() - else: - magic = imp.get_magic() - pyc = magic[:3] + chr(ord(magic[3]) - 1) - if good_timestamp: - pyc += _w_long(self.modification_time) - else: - pyc += _w_long(self.modification_time - 1) - # Needed for read_data on .pyc path. - if good_bytecode: - self.pyc = pyc + bytecode - else: - self.pyc = pyc + "asd4asfasd4ae4fds" - self.log = [] - return self - - def _create_handler(self, handler): - if self.py_ext: - py_ext = (self.py_ext,) - else: - py_ext = tuple() - if self.pyc_ext: - pyc_ext = (self.pyc_ext,) - else: - pyc_ext = tuple() - return handler(py_ext, pyc_ext) - - def _handle_py(self, handler, package=None): - args = [self, self.module_name, self.py_path] - if package is not None: - args.append(package) - return handler.handle_code(*args) - - def _handle_pyc(self, handler, package=None): - args = [self, self.module_name, self.pyc_path] - if package is not None: - args.append(package) - return handler.handle_code(*args) - - def _verify_module(self, module, test_metadata=True): - if not hasattr(module, 'test_attr'): - raise test_support.TestFailed("test_attr attribute missing") - if not module.test_attr is None: - raise test_support.TestFailed("test_attr not set to None") - if test_metadata: - assert module.__name__ == self.module_name - assert module.__loader__ == self - assert self.base_path in module.__file__ - assert (self.pyc_ext in module.__file__ or - self.py_ext in module.__file__) - - return True - - def load_module(self, fullname): - """Return what the method was called with.""" - return fullname - - @log_call - def split_path(self, path): - """'path' should be a two-item tuple, so just return it since the - caller expects two items back.""" - assert (path[0] == self.base_path and - path[1] in (self.py_ext, self.pyc_ext)) - - return path - - @log_call - def create_path(self, base, type_, must_exist=False): - """Create a tuple from 'base' and type_.""" - assert base == self.base_path - assert type_ in (self.py_ext, self.pyc_ext) - - if must_exist: - if type_ not in (self.py_ext, self.pyc_ext): - return None - else: - return (base, type_) - else: - return (base, type_) - - @log_call - def mod_time(self, path): - """Consider self.modification_time the baseline modification time.""" - assert path[0] == self.base_path - assert path[1] == self.py_ext - - return self.modification_time - - @log_call - def read_data(self, path, binary): - """Return the proper source or binary data based on the path.""" - assert path[0] == self.base_path - assert path[1] in (self.py_ext, self.pyc_ext) - - if binary: - assert self.pyc_ext and path[1] == self.pyc_ext - return self.pyc - else: - assert self.py_ext and path[1] == self.py_ext - return self.source - - @log_call - def write_data(self, data, path, binary): - """Should only be requested to write to a bytecode path.""" - assert path[0] == self.base_path - assert self.pyc_ext - assert path[1] == self.pyc_ext, "%s != %s" % (path[1], self.pyc_ext) - assert binary - assert data[:4] == imp.get_magic() - assert _w_long(self.modification_time) == data[4:8] - module = MockModule(self.module_name) - code = marshal.loads(data[8:]) - exec code in module.__dict__ - assert self._verify_module(module, False) - - return None - - -# Mock Importers (with optional path_hooks support). - -class ErrorImporter(object): - - """Mock importer to have a guaranteed error point.""" - - def find_module(self, fullname, path=None): - self.find_request = fullname, path - raise ImportError - - @classmethod - def set_on_sys_path(cls): - error_entry = '' - sys.path.append(error_entry) - ins = cls() - sys.path_importer_cache[error_entry] = ins - return ins - - -class PassImporter(object): - - """Mock importer that always pass on importing a module.""" - - def __call__(self, path_entry): - """Always pass when asked to create an importer.""" - raise ImportError - - def find_module(self, fullname, path=None): - self.find_request = fullname, path - return None - - @classmethod - def set_on_sys_path(cls): - pass_entry = '' - sys.path.append(pass_entry) - ins = cls() - sys.path_importer_cache[pass_entry] = ins - return ins - - -class SucceedImporter(object): - - """Mock importer that always succeed by returning 'self'.""" - - def __init__(self): - self.path_entries = [] - self.loaded_modules = [] - - def __call__(self, path_entry): - self.path_entries.append(path_entry) - return self - - def find_module(self, fullname, path=None): - self.find_request = fullname, path - return self - - def load_module(self, fullname): - self.load_request = fullname - module = MockModule(fullname, '') - self.loaded_modules.append(module) - sys.modules[fullname] = module - return module - - @classmethod - def set_on_sys_path(cls): - succeed_entry = '' - sys.path.append(succeed_entry) - ins = cls() - sys.path_importer_cache[succeed_entry] = ins - return ins Copied: sandbox/trunk/import_in_py/mock_importlib.py (from r53280, sandbox/trunk/import_in_py/mock_importer.py) ============================================================================== --- sandbox/trunk/import_in_py/mock_importer.py (original) +++ sandbox/trunk/import_in_py/mock_importlib.py Tue Jan 9 23:45:05 2007 @@ -2,7 +2,7 @@ import marshal import imp from test import test_support -from importer import _w_long +from importlib import _w_long def log_call(method): """Log method calls to self.log.""" Deleted: /sandbox/trunk/import_in_py/test_importer.py ============================================================================== --- /sandbox/trunk/import_in_py/test_importer.py Tue Jan 9 23:45:05 2007 +++ (empty file) @@ -1,1525 +0,0 @@ -import importer - -import unittest -from test import test_support -import mock_importer - -import contextlib -import imp -import marshal -import new -import os -import py_compile -import shutil -import StringIO -import sys -import tempfile -import warnings - - -class BuiltinFrozen_Tester(unittest.TestCase): - - """Common test cases for built-in and frozen modules. - - Expected attributes: - * self.importer - The meta_path importer to test. - * self.module_name - Name of a module that the importer can import. - * self.bad_module_names - Sequence of module names that cannot be imported. - - """ - - def test_find_module_basic(self): - # Make sure expected modules can be found. - self.failUnless(self.importer.find_module(self.module_name)) - - def test_find_module_failures(self): - # Modules of the wrong type should not be found. - for module_name in self.bad_module_names: - self.failUnlessEqual(self.importer.find_module(module_name), None) - - def test_find_module_arg_count(self): - # Cover proper number of arguments. - self.failUnlessRaises(TypeError, self.importer.find_module) - self.failUnlessRaises(TypeError, self.importer.find_module, - self.module_name, None, None) - - def test_load_module_prev_import_check(self): - # If a module is already in sys.modules it should be returned without - # being re-initialized. - self.failUnlessEqual(self.importer.load_module(self.module_name), - sys.modules[self.module_name]) - - def test_load_module_new_import(self): - # Make sure importing of a module that was not done before works - # properly. - # Do not forget to put any removed module back into sys.modules! - # Certain modules like 'sys' have some attributes that are set - # only once during interpreter initialization and are never set - # again afterwards. - mod = None - try: - if self.module_name in sys.modules: - mod = sys.modules[self.module_name] - del sys.modules[self.module_name] - loaded_module = self.importer.load_module(self.module_name) - self.failUnlessEqual(self.module_name, loaded_module.__name__) - finally: - if mod: - sys.modules[self.module_name] = mod - - def test_load_module_ImportError(self): - self.failUnlessRaises(ImportError, - self.importer.load_module, - self.bad_module_names[0]) - - def test_load_module_arg_count(self): - self.failUnlessRaises(TypeError, self.importer.load_module) - self.failUnlessRaises(TypeError, self.importer.load_module, - self.module_name, None, None) - - -class BuiltinImporterTests(BuiltinFrozen_Tester): - - """Test the built-in module importer.""" - - importer = importer.BuiltinImporter - module_name = 'sys' - bad_module_names = ('tokenize', 'time', '__hello__') - - -class FrozenImporterTests(BuiltinFrozen_Tester): - - """Test the frozen module importer. - - Python include the __hello__ and __phello__ frozen modules (as defined in - Python/frozen.c). Both do output to the screen, though, which should be - suppressed during testing. - - """ - - importer = importer.FrozenImporter - module_name = '__hello__' - bad_module_names = ('tokenize', 'time', 'sys') - - def setUp(self): - """Importing the testing frozen modules outputs to stdout. Redirect - stdout to block that.""" - self._orig_stdout = sys.stdout - sys.stdout = StringIO.StringIO() - - def tearDown(self): - """Reset stdout to what it is by default.""" - sys.stdout = self._orig_stdout - -class FrozenPackageModuleTests(FrozenImporterTests): - - """Tests the frozen module import for modules in packages.""" - - module_name = '__phello__.spam' - -class FrozenPackageInitTests(FrozenImporterTests): - - """Tests the frozen module import for package __init__ modules.""" - - module_name = '__phello__' - - -class TestPyPycFiles(unittest.TestCase): - - """Base class to help in generating a fresh source and bytecode file. - - Structure of created files: - * directory/ - + py_path [module_name + py_ext] - + pyc_path [module_name +pyc_ext] - - """ - - def setUp(self, faked_names=True): - """Generate the path to a temporary file to test with. - - If faked_names is true then all names are non-standard compared to - normal Python files. - - """ - # Set needed info for file paths. - if faked_names: - self.module_name = '' - self.py_ext = '.source' - self.pyc_ext = '.bytecode' - else: - self.module_name = '_test_module' - self.py_ext = '.py' - self.pyc_ext = '.pyc' if __debug__ else '.pyo' - try: - del sys.modules[self.module_name] - except KeyError: - pass - self.directory = tempfile.gettempdir() - self.test_attr = ('test_attr', None) - self.py_path = os.path.join(self.directory, - self.module_name+self.py_ext) - self.pyc_path = os.path.join(self.directory, - self.module_name+self.pyc_ext) - # Create source file. - self.source = '%s = %r' % self.test_attr - with open(self.py_path, 'w') as py_file: - py_file.write(self.source) - # Create bytecode file. - py_compile.compile(self.py_path, self.pyc_path, 'exec') - code = compile(self.source, self.pyc_path, 'exec') - self.bytecode = marshal.dumps(code) - sys.path.insert(0, self.directory) - - def tearDown(self): - """If the temporary path was used, make sure to clean up.""" - if self.directory in sys.path: - sys.path.remove(self.directory) - if os.path.exists(self.py_path): - os.remove(self.py_path) - if os.path.exists(self.pyc_path): - os.remove(self.pyc_path) - - def verify_module(self, module, file_path=None): - """Verify that the module is correct.""" - if file_path: - self.failUnlessEqual(module.__name__, self.module_name) - self.failUnlessEqual(module.__file__, file_path) - self.failUnless(hasattr(module, self.test_attr[0])) - self.failUnlessEqual(getattr(module, self.test_attr[0]), - self.test_attr[1]) - - -class TestPyPycPackages(TestPyPycFiles): - - """Create a testing package. - - Structure of created files (on top of files created in superclasses): - * self.directory/ - + top_level_module_path [top_level_module_name + py_ext] - + pkg_path/ [pkg_name] - - pkg_init_path [ '__init__' + py_ext] - - pkg_module_path [module_name + py_ext] - - sub_pkg_path/ [sub_pkg_name] - * sub_pkg_init_path ['__init__' + py_ext] - * sub_pkg_module_path [module_name + py_ext] - - """ - - def setUp(self, faked_names=True): - TestPyPycFiles.setUp(self, faked_names) - self.top_level_module_name = 'top_level_' + self.module_name - self.top_level_module_path = os.path.join(self.directory, - self.top_level_module_name+self.py_ext) - with open(self.top_level_module_path, 'w') as top_level_file: - top_level_file.write(self.source) - if faked_names: - self.pkg_name = '' - else: - self.pkg_name = '_test_pkg' - self.pkg_path = os.path.join(self.directory, self.pkg_name) - try: - os.mkdir(self.pkg_path) - except OSError: - self.tearDown() - os.mkdir(self.pkg_path) - self.pkg_init_path = os.path.join(self.pkg_path, - '__init__'+self.py_ext) - with open(self.pkg_init_path, 'w') as pkg_file: - pkg_file.write(self.source) - self.pkg_module_name = '.'.join([self.pkg_name, self.module_name]) - self.pkg_module_path = os.path.join(self.pkg_path, - self.module_name+self.py_ext) - with open(self.pkg_module_path, 'w') as module_file: - module_file.write(self.source) - self.sub_pkg_tail_name = 'sub_pkg' - self.sub_pkg_name = '.'.join([self.pkg_name, self.sub_pkg_tail_name]) - self.sub_pkg_path = os.path.join(self.pkg_path, self.sub_pkg_tail_name) - os.mkdir(self.sub_pkg_path) - self.sub_pkg_init_path = os.path.join(self.sub_pkg_path, - '__init__'+self.py_ext) - with open(self.sub_pkg_init_path, 'w') as subpkg_file: - subpkg_file.write(self.source) - self.sub_pkg_module_name = '.'.join([self.sub_pkg_name, - self.module_name]) - self.sub_pkg_module_path = os.path.join(self.sub_pkg_path, - self.module_name+self.py_ext) - with open(self.sub_pkg_module_path, 'w') as submodule_file: - submodule_file.write(self.source) - - def tearDown(self): - TestPyPycFiles.tearDown(self) - os.remove(self.top_level_module_path) - pyc_path = (os.path.splitext(self.top_level_module_path)[0] + - self.pyc_ext) - if os.path.exists(pyc_path): - os.remove(pyc_path) - shutil.rmtree(self.pkg_path) - - def verify_package(self, module, actual_name=None): - self.failUnless(hasattr(module, self.test_attr[0])) - self.failUnlessEqual(getattr(module, self.test_attr[0]), - self.test_attr[1]) - if module.__name__ == self.pkg_name: - self.failUnlessEqual(module.__file__, self.pkg_init_path) - self.failUnlessEqual(module.__path__, [self.pkg_path]) - # Module in top-level package. - if actual_name and self.pkg_module_name in actual_name: - self.failUnless(hasattr(module, self.module_name)) - sub_module = getattr(module, self.module_name) - self.failUnlessEqual(sub_module.__name__, self.pkg_module_name) - self.failUnlessEqual(sub_module.__file__, self.pkg_module_path) - self.verify_module(sub_module) - # Package within top-level package. - if actual_name and self.sub_pkg_name in actual_name: - self.failUnless(hasattr(module, self.sub_pkg_tail_name)) - sub_pkg = getattr(module, self.sub_pkg_tail_name) - self.failUnlessEqual(sub_pkg.__name__, self.sub_pkg_name) - self.failUnlessEqual(sub_pkg.__file__, self.sub_pkg_init_path) - self.failUnlessEqual(sub_pkg.__path__, [self.sub_pkg_path]) - self.verify_module(sub_pkg) - if actual_name == self.sub_pkg_module_name: - self.failUnless(hasattr(sub_pkg, self.module_name)) - sub_module = getattr(sub_pkg, self.module_name) - self.failUnlessEqual(sub_module.__name__, - self.sub_pkg_module_name) - self.failUnlessEqual(sub_module.__file__, - self.sub_pkg_module_path) - self.verify_module(sub_module) - if module.__name__ == self.pkg_module_name: - self.failUnlessEqual(module.__file__, self.pkg_module_path) - - -class FileSystemFactoryTests(unittest.TestCase): - - """Test the filesystem path_hooks factory function.""" - - def setUp(self): - mock_handler = mock_importer.MockHandler('.X') - self.factory = importer.FileSystemFactory(mock_handler) - - def test_absolute_path_accepted(self): - # Passing in an absolute path to a directory should be accepted. - importer_ = self.factory(os.path.abspath(os.getcwd())) - self.failUnless(isinstance(importer_, importer.FileSystemImporter)) - - def test_relative_path_accepted(self): - # Passing in a relative directory path should be accepted. - importer_ = self.factory('') - self.failUnless(isinstance(importer_, importer.FileSystemImporter)) - - def test_bad_directory(self): - # Should raise ImportError when used on a non-existing directory. - self.failUnlessRaises(ImportError, self.factory, 'sdadfasdfsdfsadfsdf') - - def test_file(self): - # Passing in a file should raise ImportError. - with open(test_support.TESTFN, 'w') as test_file: - test_file.write('for testing FileSystemFactory') - try: - self.failUnlessRaises(ImportError, self.factory, - test_support.TESTFN) - finally: - os.remove(test_support.TESTFN) - - -class FileSystemImporterTests(TestPyPycPackages): - - """Test the filesystem importer.""" - - def setUp(self): - """Create a basic importer.""" - TestPyPycPackages.setUp(self) - self.handler = mock_importer.MockHandler(self.py_ext) - self.importer = importer.FileSystemImporter(self.directory, - self.handler) - self.importer.loader = mock_importer.MockPyPycLoader - - def test_module_case_sensitivity(self): - # Case-sensitivity should always matter as long as PYTHONCASEOK is not - # set. - name_len = len(self.top_level_module_name) - bad_case_name = (self.top_level_module_name[:name_len/2].upper() + - self.top_level_module_name[name_len/2:].lower()) - env_guard = test_support.EnvironmentVarGuard() - env_guard.unset('PYTHONCASEOK') - with env_guard: - self.failUnless(not self.importer.find_module(bad_case_name)) - if sys.platform not in ('win32', 'mac', 'darwin', 'cygwin', 'os2emx', - 'riscos'): - return - env_guard = test_support.EnvironmentVarGuard() - env_guard.set('PYTHONCASEOK', '1') - with env_guard: - assert os.environ['PYTHONCASEOK'] - self.failUnless(self.importer.find_module(bad_case_name)) - - def test_package_case_sensitivity(self): - # Case-sensitivity should always matter as long as PYTHONCASEOK is not - # set. - name_len = len(self.pkg_name) - bad_case_name = (self.pkg_name[:name_len/2].upper() + - self.pkg_name[name_len/2:].lower()) - bad_init_name = os.path.join(self.directory, self.pkg_name, - '__INit__.py') - env_guard = test_support.EnvironmentVarGuard() - env_guard.unset('PYTHONCASEOK') - with env_guard: - self.failUnless(not self.importer.find_module(bad_case_name)) - os.unlink(self.pkg_init_path) - with open(bad_init_name, 'w') as init_file: - init_file.write('# Test case-sensitivity of imports.') - self.failUnless(not self.importer.find_module(self.pkg_name)) - if sys.platform not in ('win32', 'mac', 'darwin', 'cygwin', 'os2emx', - 'riscos'): - return - os.unlink(bad_init_name) - with open(self.pkg_init_path, 'w') as init_file: - init_file.write('# Used for testing import.') - env_guard = test_support.EnvironmentVarGuard() - env_guard.set('PYTHONCASEOK', '1') - with env_guard: - assert os.environ['PYTHONCASEOK'] - self.failUnless(self.importer.find_module(bad_case_name)) - with open(bad_init_name, 'w') as init_file: - init_file.write('# Used to test case-insensitivity of import.') - self.failUnless(self.importer.find_module(self.pkg_name)) - - def test_find_module_single_handler(self): - # Having a single handler should work without issue. - loader = self.importer.find_module(self.module_name) - self.failUnless(isinstance(loader, mock_importer.MockPyPycLoader)) - self.failUnlessEqual(loader.file_path, self.py_path) - self.failUnless(isinstance(loader.handler, mock_importer.MockHandler)) - self.failUnless(loader.package is None) - - def test_find_module_cannot_find(self): - # Should return None if it can't find the module. - found = self.importer.find_module('gobbledeegook') - self.failUnlessEqual(found, None) - - def test_find_module_multiple_handlers(self): - # Modules should be found based on the order of the handlers. - # mock - first_handler = mock_importer.MockHandler('.not_found') - second_handler = mock_importer.MockHandler(self.py_ext) - fs_importer = importer.FileSystemImporter(self.directory, - first_handler, - second_handler) - fs_importer.loader = mock_importer.MockPyPycLoader - loader = fs_importer.find_module(self.module_name) - self.failUnless(isinstance(loader, mock_importer.MockPyPycLoader)) - self.failUnlessEqual(loader.file_path, self.py_path) - self.failUnless(isinstance(loader.handler, mock_importer.MockHandler)) - - def test_pkg_discovery(self): - # If a module name refers to a directory with an __init__ file it - # should be recognized as a package. - loader = self.importer.find_module(self.pkg_name) - self.failUnless(isinstance(loader, mock_importer.MockPyPycLoader)) - self.failUnlessEqual(loader.file_path, self.pkg_init_path) - self.failUnlessEqual(loader.handler, self.handler) - self.failUnlessEqual(loader.package, self.pkg_path) - - def test_pkg_before_module(self): - # Importing a name that is represented as both a package and a module - # should give precedence to the package. - module_path = os.path.join(self.directory, self.pkg_name + self.py_ext) - with open(module_path, 'w') as test_file: - test_file.write("blah") - try: - loader = self.importer.find_module(self.pkg_name) - self.failUnlessEqual(loader.file_path, self.pkg_init_path) - finally: - os.remove(module_path) - - def test_directory_no_init_warning(self): - # If a directory matches for a package name but lacks an __init__.py - # file then raise ImportWarning. - os.remove(self.pkg_init_path) - with test_support.guard_warnings_filter(): - warnings.simplefilter('error', ImportWarning) - self.failUnlessRaises(ImportWarning, self.importer.find_module, - self.pkg_name) - - -class FileSystemLoaderMockEnv(unittest.TestCase): - - """Helper for settting up mock environment for testing - importer.FileSystemLoader.""" - - def setUp(self): - """Create a fresh loader per run.""" - mock_handler = mock_importer.MockHandler() - self.test_path = "" - self.pkg_path = "" - self.pkg_init_path = os.path.join(self.pkg_path, '__init__.test') - self.module_name = "test_module_name" - self.pkg_name = "test_pkg" - self.loader = importer.FileSystemLoader(self.test_path, - mock_handler) - - def tearDown(self): - """Make sure that there is no straggling modules in sys.modules.""" - try: - del sys.modules[self.module_name] - except KeyError: - pass - try: - del sys.modules[self.pkg_name] - except KeyError: - pass - - -class FileSystemLoaderBlackBoxTests(FileSystemLoaderMockEnv): - - """Test the filesystem loader's PEP 302 API compliance.""" - - def test_load_module_fresh(self): - # Test a basic module load where there is no sys.modules entry. - new_module = self.loader.load_module(self.module_name) - self.failUnlessEqual(new_module.loader, self.loader) - self.failUnlessEqual(new_module.module_name, self.module_name) - self.failUnlessEqual(new_module.path, self.test_path) - - def test_load_module_sys_modules(self): - # Make sure that the loader returns the module from sys.modules if it - # is there. - sys.modules[self.module_name] = self.module_name - loaded_module = self.loader.load_module(self.module_name) - self.failUnless(loaded_module is self.module_name) - - 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 handle_code(*args): - raise ImportError - - loader = importer.FileSystemLoader(self.test_path, RaiseErrorHandler()) - try: - loader.load_module(self.module_name) - except ImportError: - self.failUnless(self.module_name not in sys.modules) - - def test_package_init(self): - # Test that instantiating a loader for handling a package works - # properly. - pkg_loader = importer.FileSystemLoader(self.pkg_init_path, - mock_importer.MockHandler(), - self.pkg_path) - module = pkg_loader.load_module(self.pkg_name) - self.failUnlessEqual(module.loader, pkg_loader) - self.failUnlessEqual(module.path, self.pkg_init_path) - self.failUnlessEqual(module.module_name, self.pkg_name) - self.failUnlessEqual(module.package, self.pkg_path) - - -class FileSystemLoaderWhiteBoxTests(FileSystemLoaderMockEnv): - - """Test the filesystem loader's non-PEP 302 API.""" - - def setUp(self): - """Set up a test file.""" - super(FileSystemLoaderWhiteBoxTests, self).setUp() - self.directory = tempfile.gettempdir() - self.file_ext = ".test" - self.module_name = "import_test" - self.file_name = self.module_name + self.file_ext - self.file_path = os.path.join(self.directory, self.file_name) - self.data = "File used for testing 'importer' module.\r\n42" - with open(self.file_path, 'w') as test_file: - test_file.write(self.data) - - def tearDown(self): - """Delete the test file.""" - super(FileSystemLoaderWhiteBoxTests, self).tearDown() - try: - os.remove(self.file_path) - except OSError: - pass - - def test_mod_time(self): - # Modification time for the passed-in path should match the file. - true_mod_time = os.stat(self.file_path).st_mtime - mod_time = self.loader.mod_time(self.file_path) - self.failUnless(isinstance(mod_time, (int, long))) - self.failUnlessEqual(mod_time, true_mod_time) - - def test_split_path(self): - # Should split a path just like os.path.splitext(). - true_split_path = os.path.splitext(self.file_path) - split_path = self.loader.split_path(self.file_path) - self.failUnlessEqual(split_path, true_split_path) - - def test_create_path(self): - # Should work like concatenating two strings. - true_path = self.file_path - path = self.loader.create_path(*self.loader.split_path( - self.file_path)) - self.failUnlessEqual(path, true_path) - self.failUnlessEqual(None, self.loader.create_path('sadfasdfd', 'aaa', - True)) - self.failUnlessEqual('ab', self.loader.create_path('a', 'b')) - - def test_read_data(self): - # Should be able to read a file. - data = self.loader.read_data(self.file_path, False) - self.failUnlessEqual(data, self.data.replace('\r', '')) - data = self.loader.read_data(self.file_path, True) - self.failUnlessEqual(data, self.data) - test_text = '1\r\n2' - - def test_write_data(self): - # Should be able to write a file. - self.loader.write_data(self.data, self.file_path, True) - with open(self.file_path, 'rb') as test_file: - data = test_file.read() - self.failUnlessEqual(data, self.data) - # XXX How to test data written with/without 'b'? - - -class PyPycHandlerSupportingMethodTests(TestPyPycFiles): - - """Test the py/pyc handler.""" - - def setUp(self): - TestPyPycFiles.setUp(self) - self.handler = importer.PyPycHandler() - - def test_init(self): - # Test __init__ usage. - proper_bytecode_ext = '.pyc' if __debug__ else '.pyo' - for source_ext, bytecode_ext in ((None, None), (('A',), None), - (None, ('A',)), (('A',), ('B',))): - handler = importer.PyPycHandler(source_ext, bytecode_ext) - if source_ext is None: - source = ('.py',) - if bytecode_ext is None: - bytecode = (proper_bytecode_ext,) - self.failUnlessEqual(self.handler.source_handles, source) - self.failUnlessEqual(self.handler.bytecode_handles, bytecode) - self.failUnlessEqual(self.handler.handles, bytecode + source) - - def test_new_module(self): - # Should return a new module with the proper value for __name__. - module = self.handler.new_module('test') - self.failUnlessEqual('test', module.__name__) - self.failUnless(isinstance(module, importer.__class__)) - - def test_parse_pyc(self): - # Split up data from .pyc file for the magic number, timestamp, - # and bytecode. - with open(self.pyc_path, 'rb') as bytecode_file: - pyc = bytecode_file.read() - magic, timestamp, bytecode = self.handler.parse_pyc(pyc) - code = marshal.loads(bytecode) - module = mock_importer.MockModule(self.module_name, self.py_path) - exec code in module.__dict__ - self.verify_module(module, self.py_path) - - def test_check_magic(self): - # Compare a number against the magic number. - magic_number = imp.get_magic() - self.failUnless(self.handler.check_magic(magic_number)) - smaller_number = magic_number[:3] + chr(ord(magic_number[3]) - 1) - self.failUnless(not self.handler.check_magic(smaller_number)) - larger_number = magic_number[:3] + chr(ord(magic_number[3]) + 1) - self.failUnless(not self.handler.check_magic(larger_number)) - - def test_code_from_bytecode(self): - # Create a code object from bytecode; raises ValueError if code object - # cannot be created. - code_object = self.handler.code_from_bytecode(self.bytecode) - module = mock_importer.MockModule(self.module_name) - exec code_object in module.__dict__ - self.verify_module(module) - self.failUnlessRaises(ValueError, self.handler.code_from_bytecode, - "234lkjfdase4") - - def test_code_from_source(self): - # Create a code object from source. - code = self.handler.code_from_source(self.source, self.py_path) - module = mock_importer.MockModule(self.module_name) - exec code in module.__dict__ - self.verify_module(module) - - def test_create_pyc(self): - # Test creating bytes for creating a .pyc file. - bytecode = 'bytecode' - timestamp = 42 - data = self.handler.create_pyc(bytecode, timestamp) - self.failUnlessEqual(imp.get_magic(), data[:4]) - # XXX Using importer module's marshal long function. - self.failUnlessEqual(timestamp, importer._r_long(data[4:8])) - self.failUnlessEqual(marshal.dumps(bytecode), data[8:]) - - -class PyPycHandlerHandleCodeTests(unittest.TestCase): - - """Test PyPycHandler.handle_code(). - - Various situations that must be handled (and thus tested): - * Valid .pyc - + .py exists [test_good_pyc_w_py] - + No .py . - * Invalid .pyc - + Reasons it is invalid - - Bad magic number. - * With .py [test_bad_magic_w_py] - * Without .py [test_bad_magic_no_py] - - .pyc stale based on timestamp. - * Requires .py [test_bad_timestamp_w_py] - - Bytecode is malformed. - * With .py [test_bad_bytecode_w_py] - * Without .py [test_bad_bytecode_no_py] - * No .pyc - + Valid .py - - Regenerate .pyc [test_py_w_pyc] - - Do not create .pyc [test_py_no_pyc] - - """ - - def test_good_pyc_w_py(self): - # Test using a .pyc file that is valid and a .py file exists. - loader = mock_importer.MockPyPycLoader.setup() - handler = loader._create_handler(importer.PyPycHandler) - module = loader._handle_pyc(handler) - loader._verify_module(module) - # Source code should never be read, only bytecode. - self.failUnlessEqual(loader.log.count('read_data'), 1) - # Bytecode should not be written. - self.failUnless("write_data" not in loader.log) - - def test_bad_magic_no_py(self): - # ImportError should be raised when a .pyc has a bad magic number and - # there is no corresponding .py file. - loader = mock_importer.MockPyPycLoader.setup(good_magic=False, - py_exists=False) - handler = loader._create_handler(importer.PyPycHandler) - self.failUnlessRaises(ImportError, loader._handle_pyc, handler) - - def test_bad_bytecode_no_py(self): - # A .pyc file with bad bytecode (but good magic number and timestamp) - # should raise an ImportError. - loader = mock_importer.MockPyPycLoader.setup(py_exists=False, - good_bytecode=False) - handler = loader._create_handler(importer.PyPycHandler) - self.failUnlessRaises(ImportError, loader._handle_pyc, handler) - - def test_bad_magic_w_py(self): - # A .pyc file with a bad magic number should lead to the .py file being - # used to generate a new .pyc. - loader = mock_importer.MockPyPycLoader.setup(good_magic=False) - handler = loader._create_handler(importer.PyPycHandler) - module = loader._handle_pyc(handler) - loader._verify_module(module) - self.failUnless("write_data" in loader.log) - - def test_bad_timestamp_w_py(self): - # A .pyc file with a outdated timestamp should be regenerated. - loader = mock_importer.MockPyPycLoader.setup(good_timestamp=False) - handler = loader._create_handler(importer.PyPycHandler) - module = loader._handle_pyc(handler) - loader._verify_module(module) - self.failUnless("write_data" in loader.log) - - def test_bad_bytecode_w_py(self): - # Even when there is a valid .py file, if the .pyc file has bad bytecode - # ImportError is raised. - loader = mock_importer.MockPyPycLoader.setup(good_bytecode=False) - handler = loader._create_handler(importer.PyPycHandler) - self.failUnlessRaises(ImportError, loader._handle_pyc, handler) - - def test_py_no_pyc(self): - # Test importing a .py file where no .pyc path is available. - loader = mock_importer.MockPyPycLoader.setup(pyc_exists=False) - handler = loader._create_handler(importer.PyPycHandler) - module = loader._handle_py(handler) - loader._verify_module(module) - self.failUnless('write_data' not in loader.log) - # No attempt should be made to read bytecode. - self.failUnlessEqual(loader.log.count('read_data'), 1) - - def test_py_w_pyc(self): - # Test importing a .py file and a .pyc path is available. - loader = mock_importer.MockPyPycLoader.setup() - handler = loader._create_handler(importer.PyPycHandler) - module = loader._handle_py(handler) - loader._verify_module(module) - self.failUnless('write_data' in loader.log) - - def test_package_init(self): - # Handling a package should set __path__ properly. - loader = mock_importer.MockPyPycLoader.setup(pyc_exists=False) - handler = loader._create_handler(importer.PyPycHandler) - pkg_path = 'pkg path' - module = loader._handle_py(handler, pkg_path) - loader._verify_module(module) - self.failUnlessEqual(module.__path__, [pkg_path]) - - def test_sys_modules_used(self): - # Handler should re-initialize an existing module in sys.modules - # (needed for 'reload'). - loader = mock_importer.MockPyPycLoader.setup() - original_module = mock_importer.MockModule(loader.module_name) - original_value = -13 - assert loader.attr_value != original_value - setattr(original_module, loader.attr_name, original_value) - sys.modules[loader.module_name] = original_module - handler = loader._create_handler(importer.PyPycHandler) - new_module = loader._handle_pyc(handler) - self.failUnless(new_module is original_module) - self.failUnlessEqual(getattr(new_module, loader.attr_name), - loader.attr_value) - - -class ExtensionHandlerTests(unittest.TestCase): - - """Test that extension modules can be loaded.""" - - def setUp(self): - """Find an extension module to test against.""" - self.handler = importer.ExtensionFileHandler() - for entry in sys.path: - if not os.path.isdir(entry): - continue - ext_paths = [ext for ext in os.listdir(entry) - if any(True for suffix in self.handler.handles - if ext.endswith(suffix))] - if ext_paths: - break - else: - raise test_support.TestSkipped("not extension modules found") - 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_importer.MockHandler() - - def test_handle_code(self): - # Make sure an extension module can be loaded. - module = self.handler.handle_code(self.loader, self.module_name, - self.ext_path) - # There should be at least one attribute that does not start with '_'. - self.failUnless(any(True for attr in dir(module) - if not attr.startswith('_'))) - - -class ImportHelper(unittest.TestCase): - - """Common helper methods for testing the Importer class.""" - - def setUp(self): - """Store a copy of the 'sys' attribute pertaining to imports.""" - # Don't backup sys.modules since dict is cached. - # Don't clear sys.modules as it can wreak havoc - # (e.g., losing __builtin__). - self.old_sys_modules = sys.modules.copy() - self.old_meta_path = sys.meta_path[:] - sys.meta_path = [] - self.old_sys_path = sys.path[:] - sys.path = [] - self.old_path_hooks = sys.path_hooks[:] - sys.path_hooks = [] - self.old_path_importer_cache = sys.path_importer_cache.copy() - sys.path_importer_cache.clear() - self.default_importer = mock_importer.PassImporter() - self.importer = importer.Import(self.default_importer, tuple()) - - def tearDown(self): - """Restore backup of import-related attributes in 'sys'.""" - sys.modules.clear() - sys.modules.update(self.old_sys_modules) - sys.meta_path = self.old_meta_path - sys.path = self.old_sys_path - sys.path_hooks = self.old_path_hooks - sys.path_importer_cache = self.old_path_importer_cache - - def clear_sys_modules(*modules): - for module in modules: - try: - del sys.modules[module] - except KeyError: - pass - - -class ImportHelper2(ImportHelper): - - """Create mock modules.""" - - def setUp(self): - ImportHelper.setUp(self) - self.parent_name = '' - self.child_name = '' - self.full_child_name = '.'.join([self.parent_name, self.child_name]) - self.parent_module = mock_importer.MockModule(self.parent_name) - self.child_module = mock_importer.MockModule(self.full_child_name) - setattr(self.parent_module, self.child_name, self.child_module) - -class ImportNameResolutionTests(ImportHelper2): - - """Test the absolute name resolution for relative imports.""" - - def test_classic_relative_import_in_package(self): - # Importing from within a package's __init__ file should lead to a - # resolved import name of the package name tacked on to the name of the - # module being imported. - resolved_name = self.importer._classic_resolve_name(self.child_name, - self.parent_name, - True) - self.failUnlessEqual(resolved_name, self.full_child_name) - - def test_classic_relative_import_in_module(self): - # Importing within a module in a package should lead to the importer's - # module name being removed and replaced with the name of what is to be - # imported. - calling_from = self.parent_name + '.' + '' - resolved_name = self.importer._classic_resolve_name(self.child_name, - calling_from, - False) - self.failUnlessEqual(resolved_name, self.full_child_name) - - def test_relative_import_in_package_for_a_module(self): - # Trying to import a single level within a package within it's __init__ - # module should stay within the package. - # ``from .child_name import ...`` in a package. - resolved_name = self.importer._resolve_name(self.child_name, - self.parent_name, True, 1) - self.failUnlessEqual(resolved_name, self.full_child_name) - - def test_relative_import_in_module_for_a_module(self): - # Importing from within a module in a package should try to import from - # within the same directory as the module requesting the import. - # ``from .child_name import ...`` in a package module. - calling_from = self.parent_name + '.' + '' - resolved_name = self.importer._resolve_name(self.child_name, - calling_from, False, 1) - self.failUnlessEqual(resolved_name, self.full_child_name) - - def test_relative_import_deep_in_package(self): - # Calling from a deep point in the package should still work. - depth = 10 - name_extension = (str(x) for x in xrange(10)) - calling_from = self.parent_name + '.' + '.'.join(name_extension) - resolved_name = self.importer._resolve_name(self.child_name, - calling_from, False, depth) - self.failUnlessEqual(resolved_name, self.full_child_name) - - def test_attempt_to_escape_out_of_package_init(self): - # Attempting to go too high out of a package in its __init__ file - # should raise ImportError. - # ``from ..child_name import ...`` in a top-level package. - self.failUnlessRaises(ImportError, self.importer._resolve_name, - self.child_name, self.parent_name, True, 2) - - def test_attempt_to_escape_out_of_package_module(self): - # Attempting to go too high in the package from a module should raise - # ImportError. - # ``from ..child_name import ...`` in a top-level package module. - calling_from = self.parent_name + '.' + '' - self.failUnlessRaises(ImportError, self.importer._resolve_name, - self.child_name, calling_from, False, 2) - - def test_relative_import_in_top_level(self): - # Attempting a relative import in a top-level location should raise - # ImportError. - # ``from .child_name import ...`` outside of a package. - self.failUnlessRaises(ImportError, self.importer._resolve_name, - self.child_name, self.parent_name, False, 1) - - def test_relative_import_in_package_init(self): - # ``from . import ...`` in a package. - resolved_name = self.importer._resolve_name('', self.parent_name, True, - 1) - self.failUnlessEqual(resolved_name, self.parent_name) - - def test_relative_import_in_package_module(self): - # ``from . import ...`` in a package module. - resolved_name = self.importer._resolve_name('', self.full_child_name, - False, 1) - self.failUnlessEqual(resolved_name, self.parent_name) - - def test_relative_import_redirection(self): - # Having a relative module name resolve to a name that has a value of - # None in sys.modules should redirect to import an absolute import for - # the specified name. - module_name = '' - pkg_name = '' - resolved_relative_name = module_name + '.' + pkg_name - expected_module = mock_importer.MockModule(module_name) - sys.modules[resolved_relative_name] = None - sys.modules[module_name] = expected_module - importing_globals = {'__name__':pkg_name, '__path__':['some path']} - imported = self.importer(module_name, importing_globals, level=-1) - self.failUnless(imported is expected_module) - - -class ImportFromListTests(ImportHelper2): - - """Test conditions based on fromlist.""" - - def test_fromlist_relative_import(self): - # Any items specified in fromlist while importing a package needs to be - # checked as to whether it is a pre-existing attribute or should be - # considered a declaration for a relative import. - module_name = '' - pkg_name = '' - full_module_name = pkg_name + '.' + module_name - # Already have package imported. - pkg_module = mock_importer.MockModule(pkg_name, pkg_list=['some path']) - sys.modules[pkg_name] = pkg_module - # Make sure implicit import succeeds. - succeed = mock_importer.SucceedImporter() - sys.meta_path.append(succeed) - # Import the package with a fromlist of the module. - module = self.importer._return_module(pkg_name, '', - fromlist=[module_name]) - self.failUnless(hasattr(module, module_name)) - fromlist_module = getattr(module, module_name) - self.failUnlessEqual(fromlist_module.__name__, full_module_name) - - def test_fromlist_nonexistent(self): - # If something listed in a fromlist does not exist the import - # should still succeed. - pkg_name = '' - pkg_module = mock_importer.MockModule(pkg_name, pkg_list=['some path']) - sys.modules[pkg_name] = pkg_module - nonexistent_attr = 'asdfsdfd' - module = self.importer._return_module(pkg_name, '', - fromlist=[nonexistent_attr]) - self.failUnless(not hasattr(module, nonexistent_attr)) - - def test_fromlist_existing(self): - # A value in fromlist that already exists should not lead to a relative - # import. - pkg_name = '' - pkg_module = mock_importer.MockModule(pkg_name, pkg_list=['some path']) - attr = 'some_attr' - setattr(pkg_module, attr, None) - sys.modules[pkg_name] = pkg_module - failing_import = mock_importer.ErrorImporter() - sys.meta_path.append(failing_import) - module = self.importer(pkg_name, fromlist=[attr]) - self.failUnless(hasattr(module, attr)) - self.failUnless(not hasattr(failing_import, 'find_request')) - - def test_fromlist_nonpackage(self): - # No implicit imports of values in fromlist should be done if a module - # is what is being imported specifically. - module_name = '' - module = mock_importer.MockModule(module_name) - sys.modules[module_name] = module - failing_import = mock_importer.ErrorImporter() - sys.meta_path.append(failing_import) - imported_module = self.importer(module_name, fromlist=['sadfsdd']) - self.failUnless(not hasattr(failing_import, 'find_request')) - - def test_fromlist_relative_import_all(self): - # When '*' is passed in for fromlist, __all__ should be used for the - # possibility of a relative import. - module_name = '' - pkg_name = '' - full_module_name = pkg_name + '.' + module_name - pkg_module = mock_importer.MockModule(pkg_name, pkg_list=['some path'], - __all__=[module_name]) - sys.modules[pkg_name] = pkg_module - succeed = mock_importer.SucceedImporter() - sys.meta_path.append(succeed) - # Also tests that fromlist can be a tuple and still work. - module = self.importer(pkg_name, fromlist=('*',)) - self.failUnless(hasattr(module, module_name)) - relative_module = getattr(module, module_name) - self.failUnlessEqual(relative_module.__name__, full_module_name) - - def test_empty_fromlist(self): - # An empty fromlist means that the root module is returned. - sys.modules[self.parent_name] = self.parent_module - sys.modules[self.full_child_name] = self.child_module - module = self.importer._return_module(self.full_child_name, '', []) - self.failUnless(module is self.parent_module) - - def test_nonempty_fromlist(self): - # A fromlist with values should return the specified module. - sys.modules[self.parent_name] = self.parent_module - sys.modules[self.full_child_name] = self.child_module - test_attr_name = 'test_attr' - setattr(self.child_module, test_attr_name, None) - module = self.importer._return_module(self.full_child_name, '', - [test_attr_name]) - self.failUnless(module is self.child_module) - - def test_relative_import_empty_fromlist(self): - # If a relative import (with no dot) is performed with an empty fromlist - # then the module specified in the relative name is returned. - sys.modules[self.full_child_name] = self.child_module - sys.modules[self.parent_name] = self.parent_module - module = self.importer._return_module(self.full_child_name, - self.child_name, []) - self.failUnless(module is self.child_module) - - def test_deep_relative_import_empty_fromlist(self): - # If the relative name of a module has a dot, return the module that - # resolves to the absolute name of the module up to the first dot. - sys.modules[self.full_child_name] = self.child_module - sys.modules[self.parent_name] = self.parent_module - extra_depth = '.baz' - absolute_name = self.full_child_name + extra_depth - relative_name = self.child_name + extra_depth - module = self.importer._return_module(absolute_name, relative_name, []) - self.failUnless(module is self.child_module) - - -class ImportMiscTests(ImportHelper2): - - """Test miscellaneous parts of the Import class. - - Tests of the default values for __init__ are handled in the integration - tests. - - """ - - def test_sys_module_return(self): - # A module found in sys.modules should be returned immediately. - sys.modules[self.parent_name] = self.parent_module - module = self.importer._import_module(self.parent_name) - self.failUnless(module is self.parent_module) - - def test_sys_module_None(self): - # If sys.modules contains None for a module name, then raise ImportError. - module_name = '' - sys.modules[module_name] = None - self.failUnlessRaises(ImportError, self.importer._import_module, - module_name) - - def test_parent_missing(self): - # An import should fail if a parent module cannot be found. - sys.modules[self.full_child_name] = self.child_module - self.failUnlessRaises(ImportError, self.importer, self.full_child_name) - - def test_parent_imported(self): - # If a parent module is already imported, importing a child module - # should work (along with setting the attribute on the parent for the - # child module). - delattr(self.parent_module, self.child_name) - succeed_importer = mock_importer.SucceedImporter() - sys.meta_path.append(succeed_importer) - sys.modules[self.parent_name] = self.parent_module - self.importer(self.full_child_name) - self.failUnless(hasattr(self.parent_module, self.child_name)) - self.failUnlessEqual(getattr(self.parent_module, self.child_name), - sys.modules[self.full_child_name]) - - def test_parent_not_imported(self): - # If a parent module is not imported yet, it should be imported. - # The attribute on the parent module for the child module should also - # be set. - delattr(self.parent_module, self.child_name) - succeed_importer = mock_importer.SucceedImporter() - sys.meta_path.append(succeed_importer) - self.importer(self.full_child_name) - self.failUnless(self.parent_name in sys.modules) - self.failUnless(self.full_child_name in sys.modules) - self.failUnless(hasattr(sys.modules[self.parent_name], self.child_name)) - self.failUnlessEqual(getattr(sys.modules[self.parent_name], - self.child_name), - sys.modules[self.full_child_name]) - - def test_None_not_set_for_import_failure(self): - # If an import that is tried both relative and absolute fails there - # should not be an entry of None for the resolved relative name. - module_name = '' - pkg_name = '' - resolved_name = module_name + '.' + pkg_name - importing_globals = {'__name__':pkg_name, '__path__':['path']} - self.failUnlessRaises(ImportError, self.importer, module_name, - importing_globals, {}, [], -1) - self.failUnless(resolved_name not in sys.modules) - - def test_empty_string(self): - # An empty string should raise ValueError if level is not > 0. - for level in (-1, 0): - self.failUnlessRaises(ValueError, self.importer, '', {}, {}, level) - - -class ImportMetaPathTests(ImportHelper): - - """Test meta_path usage.""" - - def test_search_meta_path(self): - # Test search method of sys.meta_path. - # Should raise ImportError on error. - self.clear_sys_modules('sys') - self.failUnlessRaises(ImportError, self.importer._search_meta_path, - 'sys') - # Verify call order. - meta_path = (mock_importer.PassImporter(), - mock_importer.SucceedImporter()) - sys.meta_path = meta_path - loader = self.importer._search_meta_path('sys') - for entry in meta_path: - self.failUnlessEqual(entry.find_request, ('sys', None)) - self.failUnless(loader is meta_path[-1]) - - def test_extended_meta_path(self): - # Default meta_path entries set during initialization should be - # queried after sys.meta_path. - self.clear_sys_modules('sys') - pass_importer = mock_importer.PassImporter() - sys.meta_path = [pass_importer] - succeed_importer = mock_importer.SucceedImporter() - importer_ = importer.Import(extended_meta_path=(succeed_importer,)) - module = importer_._import_module('sys') - for meta_importer in (pass_importer, succeed_importer): - self.failUnlessEqual(meta_importer.find_request, ('sys', None)) - self.failUnless(module in succeed_importer.loaded_modules) - - def test_parent_path(self): - # If a parent module has __path__ defined it should be passed as an - # argument during importing. - pkg_name = '' - module_name = '' - test_path = [''] - pkg_module = mock_importer.MockModule(pkg_name) - pkg_module.__path__ = test_path - sys.modules[pkg_name] = pkg_module - succeed_importer = mock_importer.SucceedImporter() - sys.meta_path.append(succeed_importer) - full_module_name = '.'.join([pkg_name, module_name]) - lookup_args = (full_module_name, test_path) - self.importer(full_module_name) - self.failUnless(full_module_name in sys.modules) - self.failUnlessEqual(succeed_importer.find_request, lookup_args) - self.failUnlessEqual(succeed_importer.load_request, lookup_args[0]) - - -class ImportStdPathTests(ImportHelper): - - """Test sys.path usage.""" - - def test_default_importer_factory(self): - # Make sure that the object passed in during initialization is used - # when sys.path_importer_cache has a value of None. - module_name = '' - self.clear_sys_modules(module_name) - succeed_importer = mock_importer.SucceedImporter() - importer_ = importer.Import(succeed_importer, tuple()) - sys.meta_path = [] - sys.path = [''] - sys.path_importer_cache[''] = None - module = importer_._import_module(module_name) - self.failUnlessEqual(succeed_importer.find_request, - (module_name, None)) - self.failUnless(module in succeed_importer.loaded_modules) - - def test_search_std_path(self): - # Test sys.path searching for a loader. - module_name = '' - self.clear_sys_modules(module_name) - importer_ = importer.Import(extended_meta_path=()) - sys.path = [] - pass_importer = mock_importer.PassImporter.set_on_sys_path() - succeed_importer = mock_importer.SucceedImporter.set_on_sys_path() - sys_path = (pass_importer, succeed_importer) - module = importer_._import_module(module_name) - for entry in sys_path: - self.failUnlessEqual(entry.find_request, (module_name, None)) - self.failUnless(module in succeed_importer.loaded_modules) - - def test_importer_cache_preexisting(self): - # A pre-existing importer should be returned if it exists in - # sys.path_importer_cache. - module_name = '' - self.clear_sys_modules(module_name) - sys.path = [] - succeed_importer = mock_importer.SucceedImporter.set_on_sys_path() - loader = self.importer._search_std_path(module_name) - self.failUnless(loader is succeed_importer) - - def test_importer_cache_from_path_hooks(self): - # If an entry does not exist for a sys.path entry in the importer cache - # then sys.path_hooks should be searched and if one is found then cache - # it. - module_name = '' - self.clear_sys_modules(module_name) - path_entry = '' - succeed_importer = mock_importer.SucceedImporter() - sys.path = [path_entry] - sys.path_importer_cache.clear() - sys.path_hooks = [succeed_importer] - loader = self.importer._search_std_path(module_name) - self.failUnless(loader is succeed_importer) - self.failUnless(sys.path_importer_cache[path_entry] is - succeed_importer) - - def test_importer_cache_no_path_hooks(self): - # If an entry does not exist for a sys.path entry in the importer cache - # and sys.path_hooks has nothing for the entry, None should be set. - module_name = '' - self.clear_sys_modules(module_name) - path_entry = '' - sys.path = [path_entry] - sys.path_hooks = [] - sys.path_importer_cache.clear() - self.failUnlessRaises(ImportError, self.importer._search_std_path, - module_name) - self.failUnless(sys.path_importer_cache[path_entry] is None) - - def test_searching_package_path(self): - # If importing in a package then search path is the package's __path__ - # value; otherwise it is sys.path. - succeed_importer = mock_importer.SucceedImporter() - sys.path_hooks.append(succeed_importer) - search_paths = ['test path'] - module_name = '.' - loader = self.importer._search_std_path(module_name, search_paths) - self.failUnless(loader is succeed_importer) - self.failUnless(search_paths[0] in succeed_importer.path_entries) - self.failUnlessEqual(succeed_importer.find_request, - (module_name, None)) - self.failUnless(search_paths[0] in sys.path_importer_cache) - self.clear_sys_modules(module_name) - del sys.path_importer_cache[search_paths[0]] - succeed_importer.path_entries = [] - self.importer._import_module(module_name, search_paths) - self.failUnless(search_paths[0] in succeed_importer.path_entries) - - -class IntegrationTests(TestPyPycPackages): - - """Tests that verify the default semantics are what is expected. - - Tests should verify that: - * The proper module was returned. - * All expected modules were added to sys.modules. - * All modules imported by the call have the proper attributes. - - There are currently no tests for the import lock. - - Need to test (both relative and absolute imports as needed): - * import module - * import package - * import package.module - * from module import attribute - * from package import module - * from package import attribute - * from package.module import attribute - * from package import * - + With __all__ - - """ - - def setUp(self): - TestPyPycPackages.setUp(self, False) - self.import_ = importer.Import() - self.cached_modules = [] - if self.module_name in sys.modules: - del sys.modules[self.module_name] - if self.pkg_name in sys.modules: - del sys.modules[self.pkg_name] - if self.pkg_module_name in sys.modules: - del sys.modules[self.pkg_module_name] - - def tearDown(self): - TestPyPycPackages.tearDown(self) - for module_name, module in self.cached_modules: - sys.modules[module_name] = module - - def clear_sys_modules(self, *modules): - """Remove specified modules from sys.modules for a test and put back - during teardown.""" - for module_name in modules: - try: - self.cached_modules.append((module_name, - sys.modules[module_name])) - del sys.modules[module_name] - except KeyError: - pass - - def test_builtin(self): - # Test importing a built-in module. - # ``import sys`` - self.clear_sys_modules('sys') - module = self.import_('sys') - self.failUnlessEqual(module.__name__, 'sys') - # Only test for attributes that are not set during interpreter - # creation! - self.failUnless(hasattr(module, 'exc_info')) - self.failUnless(hasattr(module, 'version')) - - def test_frozen(self): - # Importing a frozen module should work. - # ``import __hello__`` - self.clear_sys_modules('__hello__') - faked_stdout = StringIO.StringIO() - sys.stdout = faked_stdout - try: - module = self.import_('__hello__') - self.failUnlessEqual(module.__name__, '__hello__') - self.failUnless('frozen' in module.__file__) - finally: - sys.stdout = sys.__stdout__ - - def test_extension(self): - # Should be able to import extension modules. - # ``import time`` - module = self.import_('time') - self.failUnlessEqual(module.__name__, 'time') - self.failUnless(hasattr(module, 'time')) - - def test_pyc_w_py(self): - # Should be able to import a .pyc file when a .py is also present. - # ``import pyc`` with a corresponding .py . - module = self.import_(self.module_name) - self.verify_module(module, self.pyc_path) - - def test_pyc_wo_py(self): - # Importing just a .pyc file (w/ no .py) should be okay. - # ``import pyc`` from a .pyc . - os.remove(self.py_path) - module = self.import_(self.module_name) - self.verify_module(module, self.pyc_path) - - def test_sys_modules(self): - # Should be able to pull from sys.modules even if a file does not exist - # for the module. - # ``import module`` from sys.modules. - test_module_name = '<' + self.module_name + '>' - test_module = mock_importer.MockModule(test_module_name) - sys.modules[test_module_name] = test_module - try: - module = self.import_(test_module_name) - self.failUnless(module is test_module) - finally: - del sys.modules[test_module_name] - - def test_py_creating_pyc(self): - # Importing a .py file should work and generate a .pyc file. - # ``import py`` creating a .pyc . - os.remove(self.pyc_path) - module = self.import_(self.module_name) - self.verify_module(module) - self.failUnless(os.path.exists(self.pyc_path)) - with open(self.pyc_path, 'rb') as pyc_file: - data = pyc_file.read() - self.failUnlessEqual(data[:4], imp.get_magic()) - py_mod = int(os.stat(self.py_path).st_mtime) - # XXX Using importer's _r_long. - pyc_mod = importer._r_long(data[4:8]) - self.failUnlessEqual(py_mod, pyc_mod) - code = marshal.loads(data[8:]) - module = mock_importer.MockModule(self.module_name) - exec code in module.__dict__ - self.verify_module(module) - - def test_top_level_package(self): - # Should be able to import a top-level package. - # ``import package`` - module = self.import_(self.pkg_name) - self.verify_package(module) - - def test_package_module(self): - # A module within a top-level package should work with the package not - # already imported. - # ``import package.module`` - assert '.' in self.pkg_module_name - module = self.import_(self.pkg_module_name) - self.verify_package(module, self.pkg_module_name) - - def test_sub_package(self): - # A package within a package should work. - # ``import package.subpackage`` - module = self.import_(self.sub_pkg_name) - self.verify_package(module, self.sub_pkg_name) - - def test_sub_package_module(self): - # A module contained within a sub-package should work. - # ``import package.subpackage.module`` - module = self.import_(self.sub_pkg_module_name) - self.verify_package(module, self.sub_pkg_module_name) - - def test_classic_relative_import_in_package_init(self): - # Importing within a package's __init__ file using a relative name - # should work properly. - # ``import module`` for 'package' where 'module' is 'package.module'. - package_globals = {'__name__':self.pkg_name, '__path__':['some_path']} - module = self.import_(self.module_name, package_globals, level=-1) - self.verify_package(module, self.pkg_module_name) - - def test_classic_relative_import_in_module(self): - # Importing using a relative name in a module in a package should work. - # ``import module`` for 'package.some_module' where 'module' is - # 'package.module'. - module_globals = {'__name__':self.pkg_name + '.' + 'another_module'} - module = self.import_(self.module_name, module_globals, level=-1) - self.verify_package(module, self.pkg_module_name) - - def test_absolute_name_in_classic_relative_context(self): - # Importing a module that happens to be ambiguous in terms of being - # relative or absolute, but only exists in an absolute name context, - # should work. It should also lead to a value for None in sys.modules - # for the resolved relative name. - # ``import module`` for 'package' where 'module' is 'module'. - package_module_globals = {'__name__':self.pkg_module_name} - module = self.import_(self.top_level_module_name, - package_module_globals, level=-1) - resolved_name = self.pkg_name + '.' + self.top_level_module_name - self.verify_package(module) - self.failUnlessEqual(module.__name__, self.top_level_module_name) - self.failUnless(sys.modules[resolved_name] is None) - - def test_relative_import_in_package_init(self): - # Importing a module with a relative name in a package's __init__ file - # should work. - # ``from . import module`` for 'package'. - caller_globals = {'__name__':self.pkg_name, '__path__':[self.pkg_path]} - module = self.import_('', caller_globals, fromlist=[self.module_name], - level=1) - self.verify_package(module, self.pkg_name) - - def test_relative_import_in_package(self): - # Importing a module with a relative name in another module should - # work. - # ``from . import module`` for 'package.module'. - caller_globals = {'__name__':self.pkg_module_name} - module = self.import_('', caller_globals, fromlist=[self.module_name], - level=1) - self.verify_package(module, self.pkg_name) - - def test_relative_import_in_subpackages(self): - # ``from .. import module`` in 'package.subpackage'. - caller_globals = {'__name__':self.sub_pkg_name, - '__path__':[self.sub_pkg_path]} - module = self.import_('', caller_globals, fromlist=[self.module_name], - level=2) - self.verify_package(module, self.pkg_name) - - def test_relative_import_of_package(self): - # ``from ..subpackage import module`` in 'package.subpackage'. - # XXX - caller_globals = {'__name__':self.sub_pkg_name, - '__path__':[self.sub_pkg_path]} - module = self.import_(self.sub_pkg_tail_name, caller_globals, - fromlist=[self.module_name], level=2) - self.verify_package(module, self.sub_pkg_name) - - def test_relative_import_return(self): - # When importing from a relative name, the module up to the first dot - # of that relative name (made absolute) should be returned. - # ``import subpackage.module`` for 'package.module'. - module_globals = {'__name__':self.pkg_module_name} - relative_name = self.sub_pkg_tail_name + '.' + self.module_name - module = self.import_(relative_name, module_globals) - self.verify_package(module, self.sub_pkg_name) - - - -def test_main(): - test_classes = [cls for cls in globals().itervalues() - if isinstance(cls, type) and - cls.__name__.endswith('Tests')] - test_support.run_unittest(*test_classes) - - -if __name__ == '__main__': - test_main() Copied: sandbox/trunk/import_in_py/test_importlib.py (from r53280, sandbox/trunk/import_in_py/test_importer.py) ============================================================================== --- sandbox/trunk/import_in_py/test_importer.py (original) +++ sandbox/trunk/import_in_py/test_importlib.py Tue Jan 9 23:45:05 2007 @@ -1,8 +1,8 @@ -import importer +import importlib import unittest from test import test_support -import mock_importer +import mock_importlib import contextlib import imp @@ -85,7 +85,7 @@ """Test the built-in module importer.""" - importer = importer.BuiltinImporter + importer = importlib.BuiltinImporter module_name = 'sys' bad_module_names = ('tokenize', 'time', '__hello__') @@ -100,7 +100,7 @@ """ - importer = importer.FrozenImporter + importer = importlib.FrozenImporter module_name = '__hello__' bad_module_names = ('tokenize', 'time', 'sys') @@ -298,18 +298,18 @@ """Test the filesystem path_hooks factory function.""" def setUp(self): - mock_handler = mock_importer.MockHandler('.X') - self.factory = importer.FileSystemFactory(mock_handler) + mock_handler = mock_importlib.MockHandler('.X') + self.factory = importlib.FileSystemFactory(mock_handler) def test_absolute_path_accepted(self): # Passing in an absolute path to a directory should be accepted. importer_ = self.factory(os.path.abspath(os.getcwd())) - self.failUnless(isinstance(importer_, importer.FileSystemImporter)) + self.failUnless(isinstance(importer_, importlib.FileSystemImporter)) def test_relative_path_accepted(self): # Passing in a relative directory path should be accepted. importer_ = self.factory('') - self.failUnless(isinstance(importer_, importer.FileSystemImporter)) + self.failUnless(isinstance(importer_, importlib.FileSystemImporter)) def test_bad_directory(self): # Should raise ImportError when used on a non-existing directory. @@ -333,10 +333,10 @@ def setUp(self): """Create a basic importer.""" TestPyPycPackages.setUp(self) - self.handler = mock_importer.MockHandler(self.py_ext) - self.importer = importer.FileSystemImporter(self.directory, + self.handler = mock_importlib.MockHandler(self.py_ext) + self.importer = importlib.FileSystemImporter(self.directory, self.handler) - self.importer.loader = mock_importer.MockPyPycLoader + self.importer.loader = mock_importlib.MockPyPycLoader def test_module_case_sensitivity(self): # Case-sensitivity should always matter as long as PYTHONCASEOK is not @@ -391,9 +391,9 @@ def test_find_module_single_handler(self): # Having a single handler should work without issue. loader = self.importer.find_module(self.module_name) - self.failUnless(isinstance(loader, mock_importer.MockPyPycLoader)) + self.failUnless(isinstance(loader, mock_importlib.MockPyPycLoader)) self.failUnlessEqual(loader.file_path, self.py_path) - self.failUnless(isinstance(loader.handler, mock_importer.MockHandler)) + self.failUnless(isinstance(loader.handler, mock_importlib.MockHandler)) self.failUnless(loader.package is None) def test_find_module_cannot_find(self): @@ -404,22 +404,22 @@ def test_find_module_multiple_handlers(self): # Modules should be found based on the order of the handlers. # mock - first_handler = mock_importer.MockHandler('.not_found') - second_handler = mock_importer.MockHandler(self.py_ext) - fs_importer = importer.FileSystemImporter(self.directory, + first_handler = mock_importlib.MockHandler('.not_found') + second_handler = mock_importlib.MockHandler(self.py_ext) + fs_importer = importlib.FileSystemImporter(self.directory, first_handler, second_handler) - fs_importer.loader = mock_importer.MockPyPycLoader + fs_importer.loader = mock_importlib.MockPyPycLoader loader = fs_importer.find_module(self.module_name) - self.failUnless(isinstance(loader, mock_importer.MockPyPycLoader)) + self.failUnless(isinstance(loader, mock_importlib.MockPyPycLoader)) self.failUnlessEqual(loader.file_path, self.py_path) - self.failUnless(isinstance(loader.handler, mock_importer.MockHandler)) + self.failUnless(isinstance(loader.handler, mock_importlib.MockHandler)) def test_pkg_discovery(self): # If a module name refers to a directory with an __init__ file it # should be recognized as a package. loader = self.importer.find_module(self.pkg_name) - self.failUnless(isinstance(loader, mock_importer.MockPyPycLoader)) + self.failUnless(isinstance(loader, mock_importlib.MockPyPycLoader)) self.failUnlessEqual(loader.file_path, self.pkg_init_path) self.failUnlessEqual(loader.handler, self.handler) self.failUnlessEqual(loader.package, self.pkg_path) @@ -449,17 +449,17 @@ class FileSystemLoaderMockEnv(unittest.TestCase): """Helper for settting up mock environment for testing - importer.FileSystemLoader.""" + importlib.FileSystemLoader.""" def setUp(self): """Create a fresh loader per run.""" - mock_handler = mock_importer.MockHandler() + mock_handler = mock_importlib.MockHandler() self.test_path = "" self.pkg_path = "" self.pkg_init_path = os.path.join(self.pkg_path, '__init__.test') self.module_name = "test_module_name" self.pkg_name = "test_pkg" - self.loader = importer.FileSystemLoader(self.test_path, + self.loader = importlib.FileSystemLoader(self.test_path, mock_handler) def tearDown(self): @@ -498,7 +498,7 @@ def handle_code(*args): raise ImportError - loader = importer.FileSystemLoader(self.test_path, RaiseErrorHandler()) + loader = importlib.FileSystemLoader(self.test_path, RaiseErrorHandler()) try: loader.load_module(self.module_name) except ImportError: @@ -507,8 +507,8 @@ def test_package_init(self): # Test that instantiating a loader for handling a package works # properly. - pkg_loader = importer.FileSystemLoader(self.pkg_init_path, - mock_importer.MockHandler(), + pkg_loader = importlib.FileSystemLoader(self.pkg_init_path, + mock_importlib.MockHandler(), self.pkg_path) module = pkg_loader.load_module(self.pkg_name) self.failUnlessEqual(module.loader, pkg_loader) @@ -529,7 +529,7 @@ self.module_name = "import_test" self.file_name = self.module_name + self.file_ext self.file_path = os.path.join(self.directory, self.file_name) - self.data = "File used for testing 'importer' module.\r\n42" + self.data = "File used for testing 'importlib' module.\r\n42" with open(self.file_path, 'w') as test_file: test_file.write(self.data) @@ -587,14 +587,14 @@ def setUp(self): TestPyPycFiles.setUp(self) - self.handler = importer.PyPycHandler() + self.handler = importlib.PyPycHandler() def test_init(self): # Test __init__ usage. proper_bytecode_ext = '.pyc' if __debug__ else '.pyo' for source_ext, bytecode_ext in ((None, None), (('A',), None), (None, ('A',)), (('A',), ('B',))): - handler = importer.PyPycHandler(source_ext, bytecode_ext) + handler = importlib.PyPycHandler(source_ext, bytecode_ext) if source_ext is None: source = ('.py',) if bytecode_ext is None: @@ -607,7 +607,7 @@ # Should return a new module with the proper value for __name__. module = self.handler.new_module('test') self.failUnlessEqual('test', module.__name__) - self.failUnless(isinstance(module, importer.__class__)) + self.failUnless(isinstance(module, importlib.__class__)) def test_parse_pyc(self): # Split up data from .pyc file for the magic number, timestamp, @@ -616,7 +616,7 @@ pyc = bytecode_file.read() magic, timestamp, bytecode = self.handler.parse_pyc(pyc) code = marshal.loads(bytecode) - module = mock_importer.MockModule(self.module_name, self.py_path) + module = mock_importlib.MockModule(self.module_name, self.py_path) exec code in module.__dict__ self.verify_module(module, self.py_path) @@ -633,7 +633,7 @@ # Create a code object from bytecode; raises ValueError if code object # cannot be created. code_object = self.handler.code_from_bytecode(self.bytecode) - module = mock_importer.MockModule(self.module_name) + module = mock_importlib.MockModule(self.module_name) exec code_object in module.__dict__ self.verify_module(module) self.failUnlessRaises(ValueError, self.handler.code_from_bytecode, @@ -642,7 +642,7 @@ def test_code_from_source(self): # Create a code object from source. code = self.handler.code_from_source(self.source, self.py_path) - module = mock_importer.MockModule(self.module_name) + module = mock_importlib.MockModule(self.module_name) exec code in module.__dict__ self.verify_module(module) @@ -652,8 +652,8 @@ timestamp = 42 data = self.handler.create_pyc(bytecode, timestamp) self.failUnlessEqual(imp.get_magic(), data[:4]) - # XXX Using importer module's marshal long function. - self.failUnlessEqual(timestamp, importer._r_long(data[4:8])) + # XXX Using importlib module's marshal long function. + self.failUnlessEqual(timestamp, importlib._r_long(data[4:8])) self.failUnlessEqual(marshal.dumps(bytecode), data[8:]) @@ -684,8 +684,8 @@ def test_good_pyc_w_py(self): # Test using a .pyc file that is valid and a .py file exists. - loader = mock_importer.MockPyPycLoader.setup() - handler = loader._create_handler(importer.PyPycHandler) + loader = mock_importlib.MockPyPycLoader.setup() + handler = loader._create_handler(importlib.PyPycHandler) module = loader._handle_pyc(handler) loader._verify_module(module) # Source code should never be read, only bytecode. @@ -696,32 +696,32 @@ def test_bad_magic_no_py(self): # ImportError should be raised when a .pyc has a bad magic number and # there is no corresponding .py file. - loader = mock_importer.MockPyPycLoader.setup(good_magic=False, + loader = mock_importlib.MockPyPycLoader.setup(good_magic=False, py_exists=False) - handler = loader._create_handler(importer.PyPycHandler) + handler = loader._create_handler(importlib.PyPycHandler) self.failUnlessRaises(ImportError, loader._handle_pyc, handler) def test_bad_bytecode_no_py(self): # A .pyc file with bad bytecode (but good magic number and timestamp) # should raise an ImportError. - loader = mock_importer.MockPyPycLoader.setup(py_exists=False, + loader = mock_importlib.MockPyPycLoader.setup(py_exists=False, good_bytecode=False) - handler = loader._create_handler(importer.PyPycHandler) + handler = loader._create_handler(importlib.PyPycHandler) self.failUnlessRaises(ImportError, loader._handle_pyc, handler) def test_bad_magic_w_py(self): # A .pyc file with a bad magic number should lead to the .py file being # used to generate a new .pyc. - loader = mock_importer.MockPyPycLoader.setup(good_magic=False) - handler = loader._create_handler(importer.PyPycHandler) + loader = mock_importlib.MockPyPycLoader.setup(good_magic=False) + handler = loader._create_handler(importlib.PyPycHandler) module = loader._handle_pyc(handler) loader._verify_module(module) self.failUnless("write_data" in loader.log) def test_bad_timestamp_w_py(self): # A .pyc file with a outdated timestamp should be regenerated. - loader = mock_importer.MockPyPycLoader.setup(good_timestamp=False) - handler = loader._create_handler(importer.PyPycHandler) + loader = mock_importlib.MockPyPycLoader.setup(good_timestamp=False) + handler = loader._create_handler(importlib.PyPycHandler) module = loader._handle_pyc(handler) loader._verify_module(module) self.failUnless("write_data" in loader.log) @@ -729,14 +729,14 @@ def test_bad_bytecode_w_py(self): # Even when there is a valid .py file, if the .pyc file has bad bytecode # ImportError is raised. - loader = mock_importer.MockPyPycLoader.setup(good_bytecode=False) - handler = loader._create_handler(importer.PyPycHandler) + loader = mock_importlib.MockPyPycLoader.setup(good_bytecode=False) + handler = loader._create_handler(importlib.PyPycHandler) self.failUnlessRaises(ImportError, loader._handle_pyc, handler) def test_py_no_pyc(self): # Test importing a .py file where no .pyc path is available. - loader = mock_importer.MockPyPycLoader.setup(pyc_exists=False) - handler = loader._create_handler(importer.PyPycHandler) + loader = mock_importlib.MockPyPycLoader.setup(pyc_exists=False) + handler = loader._create_handler(importlib.PyPycHandler) module = loader._handle_py(handler) loader._verify_module(module) self.failUnless('write_data' not in loader.log) @@ -745,16 +745,16 @@ def test_py_w_pyc(self): # Test importing a .py file and a .pyc path is available. - loader = mock_importer.MockPyPycLoader.setup() - handler = loader._create_handler(importer.PyPycHandler) + loader = mock_importlib.MockPyPycLoader.setup() + handler = loader._create_handler(importlib.PyPycHandler) module = loader._handle_py(handler) loader._verify_module(module) self.failUnless('write_data' in loader.log) def test_package_init(self): # Handling a package should set __path__ properly. - loader = mock_importer.MockPyPycLoader.setup(pyc_exists=False) - handler = loader._create_handler(importer.PyPycHandler) + loader = mock_importlib.MockPyPycLoader.setup(pyc_exists=False) + handler = loader._create_handler(importlib.PyPycHandler) pkg_path = 'pkg path' module = loader._handle_py(handler, pkg_path) loader._verify_module(module) @@ -763,13 +763,13 @@ def test_sys_modules_used(self): # Handler should re-initialize an existing module in sys.modules # (needed for 'reload'). - loader = mock_importer.MockPyPycLoader.setup() - original_module = mock_importer.MockModule(loader.module_name) + loader = mock_importlib.MockPyPycLoader.setup() + original_module = mock_importlib.MockModule(loader.module_name) original_value = -13 assert loader.attr_value != original_value setattr(original_module, loader.attr_name, original_value) sys.modules[loader.module_name] = original_module - handler = loader._create_handler(importer.PyPycHandler) + handler = loader._create_handler(importlib.PyPycHandler) new_module = loader._handle_pyc(handler) self.failUnless(new_module is original_module) self.failUnlessEqual(getattr(new_module, loader.attr_name), @@ -782,7 +782,7 @@ def setUp(self): """Find an extension module to test against.""" - self.handler = importer.ExtensionFileHandler() + self.handler = importlib.ExtensionFileHandler() for entry in sys.path: if not os.path.isdir(entry): continue @@ -795,7 +795,7 @@ raise test_support.TestSkipped("not extension modules found") 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_importer.MockHandler() + self.loader = mock_importlib.MockHandler() def test_handle_code(self): # Make sure an extension module can be loaded. @@ -824,8 +824,8 @@ sys.path_hooks = [] self.old_path_importer_cache = sys.path_importer_cache.copy() sys.path_importer_cache.clear() - self.default_importer = mock_importer.PassImporter() - self.importer = importer.Import(self.default_importer, tuple()) + self.default_importer = mock_importlib.PassImporter() + self.importer = importlib.Import(self.default_importer, tuple()) def tearDown(self): """Restore backup of import-related attributes in 'sys'.""" @@ -853,8 +853,8 @@ self.parent_name = '' self.child_name = '' self.full_child_name = '.'.join([self.parent_name, self.child_name]) - self.parent_module = mock_importer.MockModule(self.parent_name) - self.child_module = mock_importer.MockModule(self.full_child_name) + self.parent_module = mock_importlib.MockModule(self.parent_name) + self.child_module = mock_importlib.MockModule(self.full_child_name) setattr(self.parent_module, self.child_name, self.child_module) class ImportNameResolutionTests(ImportHelper2): @@ -947,7 +947,7 @@ module_name = '' pkg_name = '' resolved_relative_name = module_name + '.' + pkg_name - expected_module = mock_importer.MockModule(module_name) + expected_module = mock_importlib.MockModule(module_name) sys.modules[resolved_relative_name] = None sys.modules[module_name] = expected_module importing_globals = {'__name__':pkg_name, '__path__':['some path']} @@ -967,10 +967,10 @@ pkg_name = '' full_module_name = pkg_name + '.' + module_name # Already have package imported. - pkg_module = mock_importer.MockModule(pkg_name, pkg_list=['some path']) + pkg_module = mock_importlib.MockModule(pkg_name, pkg_list=['some path']) sys.modules[pkg_name] = pkg_module # Make sure implicit import succeeds. - succeed = mock_importer.SucceedImporter() + succeed = mock_importlib.SucceedImporter() sys.meta_path.append(succeed) # Import the package with a fromlist of the module. module = self.importer._return_module(pkg_name, '', @@ -983,7 +983,7 @@ # If something listed in a fromlist does not exist the import # should still succeed. pkg_name = '' - pkg_module = mock_importer.MockModule(pkg_name, pkg_list=['some path']) + pkg_module = mock_importlib.MockModule(pkg_name, pkg_list=['some path']) sys.modules[pkg_name] = pkg_module nonexistent_attr = 'asdfsdfd' module = self.importer._return_module(pkg_name, '', @@ -994,11 +994,11 @@ # A value in fromlist that already exists should not lead to a relative # import. pkg_name = '' - pkg_module = mock_importer.MockModule(pkg_name, pkg_list=['some path']) + pkg_module = mock_importlib.MockModule(pkg_name, pkg_list=['some path']) attr = 'some_attr' setattr(pkg_module, attr, None) sys.modules[pkg_name] = pkg_module - failing_import = mock_importer.ErrorImporter() + failing_import = mock_importlib.ErrorImporter() sys.meta_path.append(failing_import) module = self.importer(pkg_name, fromlist=[attr]) self.failUnless(hasattr(module, attr)) @@ -1008,9 +1008,9 @@ # No implicit imports of values in fromlist should be done if a module # is what is being imported specifically. module_name = '' - module = mock_importer.MockModule(module_name) + module = mock_importlib.MockModule(module_name) sys.modules[module_name] = module - failing_import = mock_importer.ErrorImporter() + failing_import = mock_importlib.ErrorImporter() sys.meta_path.append(failing_import) imported_module = self.importer(module_name, fromlist=['sadfsdd']) self.failUnless(not hasattr(failing_import, 'find_request')) @@ -1021,10 +1021,10 @@ module_name = '' pkg_name = '' full_module_name = pkg_name + '.' + module_name - pkg_module = mock_importer.MockModule(pkg_name, pkg_list=['some path'], + pkg_module = mock_importlib.MockModule(pkg_name, pkg_list=['some path'], __all__=[module_name]) sys.modules[pkg_name] = pkg_module - succeed = mock_importer.SucceedImporter() + succeed = mock_importlib.SucceedImporter() sys.meta_path.append(succeed) # Also tests that fromlist can be a tuple and still work. module = self.importer(pkg_name, fromlist=('*',)) @@ -1102,7 +1102,7 @@ # should work (along with setting the attribute on the parent for the # child module). delattr(self.parent_module, self.child_name) - succeed_importer = mock_importer.SucceedImporter() + succeed_importer = mock_importlib.SucceedImporter() sys.meta_path.append(succeed_importer) sys.modules[self.parent_name] = self.parent_module self.importer(self.full_child_name) @@ -1115,7 +1115,7 @@ # The attribute on the parent module for the child module should also # be set. delattr(self.parent_module, self.child_name) - succeed_importer = mock_importer.SucceedImporter() + succeed_importer = mock_importlib.SucceedImporter() sys.meta_path.append(succeed_importer) self.importer(self.full_child_name) self.failUnless(self.parent_name in sys.modules) @@ -1153,8 +1153,8 @@ self.failUnlessRaises(ImportError, self.importer._search_meta_path, 'sys') # Verify call order. - meta_path = (mock_importer.PassImporter(), - mock_importer.SucceedImporter()) + meta_path = (mock_importlib.PassImporter(), + mock_importlib.SucceedImporter()) sys.meta_path = meta_path loader = self.importer._search_meta_path('sys') for entry in meta_path: @@ -1165,10 +1165,10 @@ # Default meta_path entries set during initialization should be # queried after sys.meta_path. self.clear_sys_modules('sys') - pass_importer = mock_importer.PassImporter() + pass_importer = mock_importlib.PassImporter() sys.meta_path = [pass_importer] - succeed_importer = mock_importer.SucceedImporter() - importer_ = importer.Import(extended_meta_path=(succeed_importer,)) + succeed_importer = mock_importlib.SucceedImporter() + importer_ = importlib.Import(extended_meta_path=(succeed_importer,)) module = importer_._import_module('sys') for meta_importer in (pass_importer, succeed_importer): self.failUnlessEqual(meta_importer.find_request, ('sys', None)) @@ -1180,10 +1180,10 @@ pkg_name = '' module_name = '' test_path = [''] - pkg_module = mock_importer.MockModule(pkg_name) + pkg_module = mock_importlib.MockModule(pkg_name) pkg_module.__path__ = test_path sys.modules[pkg_name] = pkg_module - succeed_importer = mock_importer.SucceedImporter() + succeed_importer = mock_importlib.SucceedImporter() sys.meta_path.append(succeed_importer) full_module_name = '.'.join([pkg_name, module_name]) lookup_args = (full_module_name, test_path) @@ -1202,8 +1202,8 @@ # when sys.path_importer_cache has a value of None. module_name = '' self.clear_sys_modules(module_name) - succeed_importer = mock_importer.SucceedImporter() - importer_ = importer.Import(succeed_importer, tuple()) + succeed_importer = mock_importlib.SucceedImporter() + importer_ = importlib.Import(succeed_importer, tuple()) sys.meta_path = [] sys.path = [''] sys.path_importer_cache[''] = None @@ -1216,10 +1216,10 @@ # Test sys.path searching for a loader. module_name = '' self.clear_sys_modules(module_name) - importer_ = importer.Import(extended_meta_path=()) + importer_ = importlib.Import(extended_meta_path=()) sys.path = [] - pass_importer = mock_importer.PassImporter.set_on_sys_path() - succeed_importer = mock_importer.SucceedImporter.set_on_sys_path() + pass_importer = mock_importlib.PassImporter.set_on_sys_path() + succeed_importer = mock_importlib.SucceedImporter.set_on_sys_path() sys_path = (pass_importer, succeed_importer) module = importer_._import_module(module_name) for entry in sys_path: @@ -1232,7 +1232,7 @@ module_name = '' self.clear_sys_modules(module_name) sys.path = [] - succeed_importer = mock_importer.SucceedImporter.set_on_sys_path() + succeed_importer = mock_importlib.SucceedImporter.set_on_sys_path() loader = self.importer._search_std_path(module_name) self.failUnless(loader is succeed_importer) @@ -1243,7 +1243,7 @@ module_name = '' self.clear_sys_modules(module_name) path_entry = '' - succeed_importer = mock_importer.SucceedImporter() + succeed_importer = mock_importlib.SucceedImporter() sys.path = [path_entry] sys.path_importer_cache.clear() sys.path_hooks = [succeed_importer] @@ -1268,7 +1268,7 @@ def test_searching_package_path(self): # If importing in a package then search path is the package's __path__ # value; otherwise it is sys.path. - succeed_importer = mock_importer.SucceedImporter() + succeed_importer = mock_importlib.SucceedImporter() sys.path_hooks.append(succeed_importer) search_paths = ['test path'] module_name = '.' @@ -1311,7 +1311,7 @@ def setUp(self): TestPyPycPackages.setUp(self, False) - self.import_ = importer.Import() + self.import_ = importlib.Import() self.cached_modules = [] if self.module_name in sys.modules: del sys.modules[self.module_name] @@ -1385,7 +1385,7 @@ # for the module. # ``import module`` from sys.modules. test_module_name = '<' + self.module_name + '>' - test_module = mock_importer.MockModule(test_module_name) + test_module = mock_importlib.MockModule(test_module_name) sys.modules[test_module_name] = test_module try: module = self.import_(test_module_name) @@ -1405,10 +1405,10 @@ self.failUnlessEqual(data[:4], imp.get_magic()) py_mod = int(os.stat(self.py_path).st_mtime) # XXX Using importer's _r_long. - pyc_mod = importer._r_long(data[4:8]) + pyc_mod = importlib._r_long(data[4:8]) self.failUnlessEqual(py_mod, pyc_mod) code = marshal.loads(data[8:]) - module = mock_importer.MockModule(self.module_name) + module = mock_importlib.MockModule(self.module_name) exec code in module.__dict__ self.verify_module(module) From python-checkins at python.org Wed Jan 10 00:17:50 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 10 Jan 2007 00:17:50 +0100 (CET) Subject: [Python-checkins] r53331 - python/branches/bcannon-objcap Message-ID: <20070109231750.BB9EF1E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 10 00:17:50 2007 New Revision: 53331 Modified: python/branches/bcannon-objcap/ (props changed) Log: Externally define importlib directory for import rewrite in sandbox. From python-checkins at python.org Wed Jan 10 00:18:47 2007 From: python-checkins at python.org (thomas.wouters) Date: Wed, 10 Jan 2007 00:18:47 +0100 (CET) Subject: [Python-checkins] r53332 - in python/branches/p3yk: Doc/README Doc/api/newtypes.tex Doc/howto/functional.rst Doc/lib/libbsddb.tex Doc/lib/libbz2.tex Doc/lib/libctypes.tex Doc/lib/libfuncs.tex Doc/lib/liblogging.tex Doc/lib/libmmap.tex Doc/lib/libsimplexmlrpc.tex Doc/lib/libsocket.tex Doc/lib/libsqlite3.tex Doc/lib/libstdtypes.tex Doc/lib/libtarfile.tex Doc/lib/libtest.tex Doc/lib/liburlparse.tex Doc/mac/toolbox.tex Doc/whatsnew/whatsnew25.tex LICENSE Lib/CGIHTTPServer.py Lib/SimpleHTTPServer.py Lib/StringIO.py Lib/bsddb/dbobj.py Lib/bsddb/test/test_1413192.py Lib/bsddb/test/test_associate.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_dbobj.py Lib/bsddb/test/test_dbshelve.py Lib/bsddb/test/test_dbtables.py Lib/bsddb/test/test_env_close.py Lib/bsddb/test/test_join.py Lib/bsddb/test/test_lock.py Lib/bsddb/test/test_misc.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_thread.py Lib/cookielib.py Lib/difflib.py Lib/dumbdbm.py Lib/heapq.py Lib/hmac.py Lib/idlelib/AutoCompleteWindow.py Lib/idlelib/NEWS.txt Lib/logging/__init__.py Lib/logging/handlers.py Lib/mailbox.py Lib/pty.py Lib/pydoc.py Lib/random.py Lib/sre_parse.py Lib/subprocess.py Lib/tarfile.py Lib/test/test_compile.py Lib/test/test_deque.py Lib/test/test_dumbdbm.py Lib/test/test_exceptions.py Lib/test/test_heapq.py Lib/test/test_import.py Lib/test/test_pty.py Lib/test/test_random.py Lib/test/test_repr.py Lib/test/test_set.py Lib/test/test_struct.py Lib/test/test_support.py Lib/test/test_tarfile.py Lib/test/test_uu.py Lib/test/test_weakref.py Lib/threading.py Lib/urllib.py Misc/ACKS Misc/developers.txt Modules/_bsddb.c Modules/bz2module.c Modules/collectionsmodule.c Modules/main.c Modules/socketmodule.c Modules/timemodule.c Objects/dictnotes.txt Objects/setobject.c PC/python_nt.rc PCbuild/python20.wse PCbuild8/python20.wse Python/ceval.c Python/errors.c Python/getcopyright.c README setup.py Message-ID: <20070109231847.994651E4008@bag.python.org> Author: thomas.wouters Date: Wed Jan 10 00:18:33 2007 New Revision: 53332 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/README python/branches/p3yk/Doc/api/newtypes.tex python/branches/p3yk/Doc/howto/functional.rst python/branches/p3yk/Doc/lib/libbsddb.tex python/branches/p3yk/Doc/lib/libbz2.tex python/branches/p3yk/Doc/lib/libctypes.tex python/branches/p3yk/Doc/lib/libfuncs.tex python/branches/p3yk/Doc/lib/liblogging.tex python/branches/p3yk/Doc/lib/libmmap.tex python/branches/p3yk/Doc/lib/libsimplexmlrpc.tex python/branches/p3yk/Doc/lib/libsocket.tex python/branches/p3yk/Doc/lib/libsqlite3.tex python/branches/p3yk/Doc/lib/libstdtypes.tex python/branches/p3yk/Doc/lib/libtarfile.tex python/branches/p3yk/Doc/lib/libtest.tex python/branches/p3yk/Doc/lib/liburlparse.tex python/branches/p3yk/Doc/mac/toolbox.tex python/branches/p3yk/Doc/whatsnew/whatsnew25.tex python/branches/p3yk/LICENSE python/branches/p3yk/Lib/CGIHTTPServer.py python/branches/p3yk/Lib/SimpleHTTPServer.py python/branches/p3yk/Lib/StringIO.py python/branches/p3yk/Lib/bsddb/dbobj.py python/branches/p3yk/Lib/bsddb/test/test_1413192.py python/branches/p3yk/Lib/bsddb/test/test_associate.py python/branches/p3yk/Lib/bsddb/test/test_basics.py python/branches/p3yk/Lib/bsddb/test/test_dbobj.py python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py python/branches/p3yk/Lib/bsddb/test/test_dbtables.py python/branches/p3yk/Lib/bsddb/test/test_env_close.py python/branches/p3yk/Lib/bsddb/test/test_join.py python/branches/p3yk/Lib/bsddb/test/test_lock.py python/branches/p3yk/Lib/bsddb/test/test_misc.py python/branches/p3yk/Lib/bsddb/test/test_recno.py python/branches/p3yk/Lib/bsddb/test/test_thread.py python/branches/p3yk/Lib/cookielib.py python/branches/p3yk/Lib/difflib.py python/branches/p3yk/Lib/dumbdbm.py python/branches/p3yk/Lib/heapq.py python/branches/p3yk/Lib/hmac.py python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py python/branches/p3yk/Lib/idlelib/NEWS.txt python/branches/p3yk/Lib/logging/__init__.py python/branches/p3yk/Lib/logging/handlers.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/pty.py python/branches/p3yk/Lib/pydoc.py python/branches/p3yk/Lib/random.py python/branches/p3yk/Lib/sre_parse.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/test/test_compile.py python/branches/p3yk/Lib/test/test_deque.py python/branches/p3yk/Lib/test/test_dumbdbm.py python/branches/p3yk/Lib/test/test_exceptions.py python/branches/p3yk/Lib/test/test_heapq.py python/branches/p3yk/Lib/test/test_import.py python/branches/p3yk/Lib/test/test_pty.py python/branches/p3yk/Lib/test/test_random.py python/branches/p3yk/Lib/test/test_repr.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_support.py python/branches/p3yk/Lib/test/test_tarfile.py python/branches/p3yk/Lib/test/test_uu.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/threading.py python/branches/p3yk/Lib/urllib.py python/branches/p3yk/Misc/ACKS python/branches/p3yk/Misc/developers.txt python/branches/p3yk/Modules/_bsddb.c python/branches/p3yk/Modules/bz2module.c python/branches/p3yk/Modules/collectionsmodule.c python/branches/p3yk/Modules/main.c python/branches/p3yk/Modules/socketmodule.c python/branches/p3yk/Modules/timemodule.c python/branches/p3yk/Objects/dictnotes.txt python/branches/p3yk/Objects/setobject.c python/branches/p3yk/PC/python_nt.rc python/branches/p3yk/PCbuild/python20.wse python/branches/p3yk/PCbuild8/python20.wse python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/errors.c python/branches/p3yk/Python/getcopyright.c python/branches/p3yk/README python/branches/p3yk/setup.py Log: Merged revisions 53005-53303 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53012 | walter.doerwald | 2006-12-12 22:55:31 +0100 (Tue, 12 Dec 2006) | 2 lines Fix typo. ........ r53023 | brett.cannon | 2006-12-13 23:31:37 +0100 (Wed, 13 Dec 2006) | 2 lines Remove an unneeded import of 'warnings'. ........ r53025 | brett.cannon | 2006-12-14 00:02:38 +0100 (Thu, 14 Dec 2006) | 2 lines Remove unneeded imports of 'warnings'. ........ r53026 | brett.cannon | 2006-12-14 00:09:53 +0100 (Thu, 14 Dec 2006) | 4 lines Add test.test_support.guard_warnings_filter . This function returns a context manager that protects warnings.filter from being modified once the context is exited. ........ r53029 | george.yoshida | 2006-12-14 03:22:44 +0100 (Thu, 14 Dec 2006) | 2 lines Note that guard_warnings_filter was added in 2.6 ........ r53031 | vinay.sajip | 2006-12-14 09:53:55 +0100 (Thu, 14 Dec 2006) | 1 line Added news on recent changes to logging ........ r53032 | andrew.kuchling | 2006-12-14 19:57:53 +0100 (Thu, 14 Dec 2006) | 1 line [Patch #1599256 from David Watson] check that os.fsync is available before using it ........ r53042 | kurt.kaiser | 2006-12-15 06:13:11 +0100 (Fri, 15 Dec 2006) | 6 lines 1. Avoid hang when encountering a duplicate in a completion list. Bug 1571112. 2. Duplicate some old entries from Python's NEWS to IDLE's NEWS.txt M AutoCompleteWindow.py M NEWS.txt ........ r53048 | andrew.kuchling | 2006-12-18 18:12:31 +0100 (Mon, 18 Dec 2006) | 1 line [Bug #1618083] Add missing word; make a few grammar fixes ........ r53050 | andrew.kuchling | 2006-12-18 18:16:05 +0100 (Mon, 18 Dec 2006) | 1 line Bump version ........ r53051 | andrew.kuchling | 2006-12-18 18:22:07 +0100 (Mon, 18 Dec 2006) | 1 line [Bug #1616726] Fix description of generator.close(); if you raise some random exception, the exception is raised and doesn't trigger a RuntimeError ........ r53052 | andrew.kuchling | 2006-12-18 18:38:14 +0100 (Mon, 18 Dec 2006) | 1 line Describe new methods in Queue module ........ r53053 | andrew.kuchling | 2006-12-18 20:22:24 +0100 (Mon, 18 Dec 2006) | 1 line [Patch #1615868 by Lars Gustaebel] Use Py_off_t to fix BZ2File.seek() for offsets > 2Gb ........ r53057 | andrew.kuchling | 2006-12-18 22:29:07 +0100 (Mon, 18 Dec 2006) | 1 line Fix markup ........ r53063 | thomas.wouters | 2006-12-19 09:17:50 +0100 (Tue, 19 Dec 2006) | 5 lines Make sre's SubPattern objects accept slice objects like it already accepts simple slices. ........ r53065 | andrew.kuchling | 2006-12-19 15:13:05 +0100 (Tue, 19 Dec 2006) | 6 lines [Patch #1618455 by Ben Maurer] Improve speed of HMAC by using str.translate() instead of a more general XOR that has to construct a list. Slightly modified from Maurer's patch: the _strxor() function is no longer necessary at all. ........ r53066 | andrew.kuchling | 2006-12-19 15:28:23 +0100 (Tue, 19 Dec 2006) | 9 lines [Bug #1613651] Document socket.recv_into, socket.recvfrom_into Also, the text for recvfrom told you to read recv() for an explanation of the 'flags' argument, but recv() just pointed you at the man page. Copied the man-page text to recvfrom(), recvfrom_into, recv_into to avoid the pointless redirection. I don't have LaTeX on this machine; hope my markup is OK. ........ r53067 | andrew.kuchling | 2006-12-19 15:29:04 +0100 (Tue, 19 Dec 2006) | 1 line Comment typo ........ r53068 | andrew.kuchling | 2006-12-19 16:11:41 +0100 (Tue, 19 Dec 2006) | 1 line [Patch #1617413 from Dug Song] Fix HTTP Basic authentication via HTTPS ........ r53071 | andrew.kuchling | 2006-12-19 16:18:12 +0100 (Tue, 19 Dec 2006) | 1 line [Patch #1600491 from Jim Jewett] Describe how to build help files on Windows ........ r53073 | andrew.kuchling | 2006-12-19 16:43:10 +0100 (Tue, 19 Dec 2006) | 6 lines [Patch #1587139 by kxroberto] Protect lock acquisition/release with try...finally to ensure the lock is always released. This could use the 'with' statement, but the patch uses 'finally'. 2.5 backport candidate. ........ r53074 | vinay.sajip | 2006-12-19 19:29:11 +0100 (Tue, 19 Dec 2006) | 1 line Updated documentation for findCaller() to indicate that a 3-tuple is now returned, rather than a 2-tuple. ........ r53090 | georg.brandl | 2006-12-19 23:06:46 +0100 (Tue, 19 Dec 2006) | 3 lines Patch #1484695: The tarfile module now raises a HeaderError exception if a buffer given to frombuf() is invalid. ........ r53099 | raymond.hettinger | 2006-12-20 07:42:06 +0100 (Wed, 20 Dec 2006) | 5 lines Bug #1590891: random.randrange don't return correct value for big number Needs to be backported. ........ r53106 | georg.brandl | 2006-12-20 12:55:16 +0100 (Wed, 20 Dec 2006) | 3 lines Testcase for patch #1484695. ........ r53110 | andrew.kuchling | 2006-12-20 20:48:20 +0100 (Wed, 20 Dec 2006) | 17 lines [Apply length-checking.diff from bug #1599254] Add length checking to single-file mailbox formats: before doing a flush() on a mailbox, seek to the end and verify its length is unchanged, raising ExternalClashError if the file's length has changed. This fix avoids potential data loss if some other process appends to the mailbox file after the table of contents has been generated; instead of overwriting the modified file, you'll get the exception. I also noticed that the self._lookup() call in self.flush() wasn't necessary (everything that sets self._pending to True also calls self.lookup()), and replaced it by an assertion. 2.5 backport candidate. ........ r53112 | andrew.kuchling | 2006-12-20 20:57:10 +0100 (Wed, 20 Dec 2006) | 1 line [Bug #1619674] Make sum() use the term iterable, not sequence ........ r53113 | andrew.kuchling | 2006-12-20 20:58:11 +0100 (Wed, 20 Dec 2006) | 1 line Two grammar fixes ........ r53115 | andrew.kuchling | 2006-12-20 21:11:12 +0100 (Wed, 20 Dec 2006) | 5 lines Some other built-in functions are described with 'sequence' arguments that should really be 'iterable'; this commit changes them. Did I miss any? Did I introduce any errors? ........ r53117 | andrew.kuchling | 2006-12-20 21:20:42 +0100 (Wed, 20 Dec 2006) | 1 line [Bug #1619680] in_dll() arguments are documented in the wrong order ........ r53120 | neal.norwitz | 2006-12-21 05:38:00 +0100 (Thu, 21 Dec 2006) | 1 line Lars asked for permission on on python-dev for work on tarfile.py ........ r53125 | andrew.kuchling | 2006-12-21 14:40:29 +0100 (Thu, 21 Dec 2006) | 1 line Mention the os.SEEK_* constants ........ r53129 | walter.doerwald | 2006-12-21 19:06:30 +0100 (Thu, 21 Dec 2006) | 2 lines Fix typo. ........ r53131 | thomas.heller | 2006-12-21 19:30:56 +0100 (Thu, 21 Dec 2006) | 3 lines Fix wrong markup of an argument in a method signature. Will backport. ........ r53137 | andrew.kuchling | 2006-12-22 01:50:56 +0100 (Fri, 22 Dec 2006) | 1 line Typo fix ........ r53139 | andrew.kuchling | 2006-12-22 14:25:02 +0100 (Fri, 22 Dec 2006) | 1 line [Bug #737202; fix from Titus Brown] Make CGIHTTPServer work for scripts in sub-directories ........ r53141 | andrew.kuchling | 2006-12-22 16:04:45 +0100 (Fri, 22 Dec 2006) | 6 lines [Bug #802128] Make the mode argument of dumbdbm actually work the way it's described, and add a test for it. 2.5 bugfix candidate, maybe; arguably this patch changes the API of dumbdbm and shouldn't be added in a point-release. ........ r53142 | andrew.kuchling | 2006-12-22 16:16:58 +0100 (Fri, 22 Dec 2006) | 6 lines [Bug #802128 continued] Modify mode depending on the process umask. Is there really no other way to read the umask than to set it? Hope this works on Windows... ........ r53145 | andrew.kuchling | 2006-12-22 17:43:26 +0100 (Fri, 22 Dec 2006) | 1 line [Bug #776202] Apply Walter Doerwald's patch to use text mode for encoded files ........ r53146 | andrew.kuchling | 2006-12-22 19:41:42 +0100 (Fri, 22 Dec 2006) | 9 lines [Patch #783050 from Patrick Lynch] The emulation of forkpty() is incorrect; the master should close the slave fd. Added a test to test_pty.py that reads from the master_fd after doing a pty.fork(); without the fix it hangs forever instead of raising an exception. () 2.5 backport candidate. ........ r53147 | andrew.kuchling | 2006-12-22 20:06:16 +0100 (Fri, 22 Dec 2006) | 1 line [Patch #827559 from Chris Gonnerman] Make SimpleHTTPServer redirect when a directory URL is missing the trailing slash; this lets relative links work. ........ r53149 | andrew.kuchling | 2006-12-22 20:21:27 +0100 (Fri, 22 Dec 2006) | 1 line Darn; this test works when you run test_pty.py directly, but fails when regrtest runs it (the os.read() raises os.error). I can't figure out the cause, so am commenting out the test. ........ r53150 | andrew.kuchling | 2006-12-22 22:48:19 +0100 (Fri, 22 Dec 2006) | 1 line Frak; this test also fails ........ r53153 | lars.gustaebel | 2006-12-23 17:40:13 +0100 (Sat, 23 Dec 2006) | 5 lines Patch #1230446: tarfile.py: fix ExFileObject so that read() and tell() work correctly together with readline(). Will backport to 2.5. ........ r53155 | lars.gustaebel | 2006-12-23 18:57:23 +0100 (Sat, 23 Dec 2006) | 5 lines Patch #1262036: Prevent TarFiles from being added to themselves under certain conditions. Will backport to 2.5. ........ r53159 | andrew.kuchling | 2006-12-27 04:25:31 +0100 (Wed, 27 Dec 2006) | 4 lines [Part of patch #1182394] Move the HMAC blocksize to be a class-level constant; this allows changing it in a subclass. To accommodate this, copy() now uses __class__. Also add some text to a comment. ........ r53160 | andrew.kuchling | 2006-12-27 04:31:24 +0100 (Wed, 27 Dec 2006) | 1 line [Rest of patch #1182394] Add ._current() method so that we can use the written-in-C .hexdigest() method ........ r53161 | lars.gustaebel | 2006-12-27 11:30:46 +0100 (Wed, 27 Dec 2006) | 4 lines Patch #1504073: Fix tarfile.open() for mode "r" with a fileobj argument. Will backport to 2.5. ........ r53165 | neal.norwitz | 2006-12-28 05:39:20 +0100 (Thu, 28 Dec 2006) | 1 line Remove a stray (old) macro name left around (I guess) ........ r53188 | neal.norwitz | 2006-12-29 04:01:53 +0100 (Fri, 29 Dec 2006) | 1 line SF bug #1623890, fix argument name in docstring ........ r53200 | raymond.hettinger | 2006-12-30 05:01:17 +0100 (Sat, 30 Dec 2006) | 1 line For sets with cyclical reprs, emit an ellipsis instead of infinitely recursing. ........ r53232 | brett.cannon | 2007-01-04 01:23:49 +0100 (Thu, 04 Jan 2007) | 3 lines Add EnvironmentVarGuard to test.test_support. Provides a context manager to temporarily set or unset environment variables. ........ r53235 | neal.norwitz | 2007-01-04 07:25:31 +0100 (Thu, 04 Jan 2007) | 1 line SF #1627373, fix typo in CarbonEvt. ........ r53244 | raymond.hettinger | 2007-01-04 18:53:34 +0100 (Thu, 04 Jan 2007) | 1 line Fix stability of heapq's nlargest() and nsmallest(). ........ r53249 | martin.v.loewis | 2007-01-04 22:06:12 +0100 (Thu, 04 Jan 2007) | 3 lines Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, to avoid relying on atexit. Will backport to 2.5. ........ r53252 | gregory.p.smith | 2007-01-05 02:59:42 +0100 (Fri, 05 Jan 2007) | 3 lines Support linking of the bsddb module against BerkeleyDB 4.5.x (will backport to 2.5) ........ r53253 | gregory.p.smith | 2007-01-05 03:06:17 +0100 (Fri, 05 Jan 2007) | 2 lines bump module version to match supported berkeleydb version ........ r53255 | neal.norwitz | 2007-01-05 06:25:22 +0100 (Fri, 05 Jan 2007) | 6 lines Prevent crash on shutdown which can occur if we are finalizing and the module dict has been cleared already and some object raises a warning (like in a __del__). Will backport. ........ r53258 | gregory.p.smith | 2007-01-05 08:21:35 +0100 (Fri, 05 Jan 2007) | 2 lines typo fix ........ r53260 | neal.norwitz | 2007-01-05 09:06:43 +0100 (Fri, 05 Jan 2007) | 1 line Add Collin Winter for access to update PEP 3107 ........ r53262 | andrew.kuchling | 2007-01-05 15:22:17 +0100 (Fri, 05 Jan 2007) | 1 line [Bug #1622533] Make docstrings raw strings because they contain control characters (\0, \1) ........ r53264 | andrew.kuchling | 2007-01-05 16:51:24 +0100 (Fri, 05 Jan 2007) | 1 line [Patch #1520904] Fix bsddb tests to write to the temp directory instead of the Lib/bsddb/test directory ........ r53279 | brett.cannon | 2007-01-05 22:45:09 +0100 (Fri, 05 Jan 2007) | 3 lines Silence a warning from gcc 4.0.1 by specifying a function's parameter list is 'void' instead of just a set of empty parentheses. ........ r53285 | raymond.hettinger | 2007-01-06 02:14:41 +0100 (Sat, 06 Jan 2007) | 2 lines SF# 1409443: Expand comment to cover the interaction between f->f_lasti and the PREDICT macros. ........ r53286 | anthony.baxter | 2007-01-06 05:45:54 +0100 (Sat, 06 Jan 2007) | 1 line update to (c) years to include 2007 ........ r53291 | neal.norwitz | 2007-01-06 22:24:35 +0100 (Sat, 06 Jan 2007) | 1 line Add Josiah to SF for maintaining asyncore/asynchat ........ r53293 | peter.astrand | 2007-01-07 09:53:46 +0100 (Sun, 07 Jan 2007) | 1 line Re-implemented fix for #1531862 once again, in a way that works with Python 2.2. Fixes bug #1603424. ........ r53295 | peter.astrand | 2007-01-07 15:34:16 +0100 (Sun, 07 Jan 2007) | 1 line Avoid O(N**2) bottleneck in _communicate_(). Fixes #1598181. ........ r53300 | raymond.hettinger | 2007-01-08 19:09:20 +0100 (Mon, 08 Jan 2007) | 1 line Fix zero-length corner case for iterating over a mutating deque. ........ r53301 | vinay.sajip | 2007-01-08 19:50:32 +0100 (Mon, 08 Jan 2007) | 4 lines Bare except clause removed from SMTPHandler.emit(). Now, only ImportError is trapped. Bare except clause removed from SocketHandler.createSocket(). Now, only socket.error is trapped. (SF #411881) ........ r53302 | vinay.sajip | 2007-01-08 19:51:46 +0100 (Mon, 08 Jan 2007) | 2 lines Bare except clause removed from LogRecord.__init__. Now, only ValueError, TypeError and AttributeError are trapped. (SF #411881) ........ r53303 | vinay.sajip | 2007-01-08 19:52:36 +0100 (Mon, 08 Jan 2007) | 1 line Added entries about removal of some bare except clauses from logging. ........ Modified: python/branches/p3yk/Doc/README ============================================================================== --- python/branches/p3yk/Doc/README (original) +++ python/branches/p3yk/Doc/README Wed Jan 10 00:18:33 2007 @@ -229,7 +229,7 @@ as long as you don't change or remove the copyright notice: ---------------------------------------------------------------------- -Copyright (c) 2000-2006 Python Software Foundation. +Copyright (c) 2000-2007 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/branches/p3yk/Doc/api/newtypes.tex ============================================================================== --- python/branches/p3yk/Doc/api/newtypes.tex (original) +++ python/branches/p3yk/Doc/api/newtypes.tex Wed Jan 10 00:18:33 2007 @@ -103,8 +103,6 @@ the value for the \var{methods} argument]{2.3} \end{cfuncdesc} -DL_IMPORT - \begin{cvardesc}{PyObject}{_Py_NoneStruct} Object which is visible in Python as \code{None}. This should only be accessed using the \code{Py_None} macro, which evaluates to a Modified: python/branches/p3yk/Doc/howto/functional.rst ============================================================================== --- python/branches/p3yk/Doc/howto/functional.rst (original) +++ python/branches/p3yk/Doc/howto/functional.rst Wed Jan 10 00:18:33 2007 @@ -1398,10 +1398,10 @@ ''''''''''''''''''''''''''' http://docs.python.org/lib/module-itertools.html: -Documentation ``for the itertools`` module. +Documentation for the ``itertools`` module. http://docs.python.org/lib/module-operator.html: -Documentation ``for the operator`` module. +Documentation for the ``operator`` module. http://www.python.org/dev/peps/pep-0289/: PEP 289: "Generator Expressions" Modified: python/branches/p3yk/Doc/lib/libbsddb.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libbsddb.tex (original) +++ python/branches/p3yk/Doc/lib/libbsddb.tex Wed Jan 10 00:18:33 2007 @@ -16,7 +16,7 @@ \function{pickle.dumps()}. The \module{bsddb} module requires a Berkeley DB library version from -3.3 thru 4.4. +3.3 thru 4.5. \begin{seealso} \seeurl{http://pybsddb.sourceforge.net/} Modified: python/branches/p3yk/Doc/lib/libbz2.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libbz2.tex (original) +++ python/branches/p3yk/Doc/lib/libbz2.tex Wed Jan 10 00:18:33 2007 @@ -81,10 +81,10 @@ \begin{methoddesc}[BZ2File]{seek}{offset\optional{, whence}} Move to new file position. Argument \var{offset} is a byte count. Optional -argument \var{whence} defaults to \code{0} (offset from start of file, -offset should be \code{>= 0}); other values are \code{1} (move relative to -current position, positive or negative), and \code{2} (move relative to end -of file, usually negative, although many platforms allow seeking beyond +argument \var{whence} defaults to \code{os.SEEK_SET} or \code{0} (offset from start of file; +offset should be \code{>= 0}); other values are \code{os.SEEK_CUR} or \code{1} (move relative to +current position; offset can be positive or negative), and \code{os.SEEK_END} or \code{2} (move relative to end +of file; offset is usually negative, although many platforms allow seeking beyond the end of a file). Note that seeking of bz2 files is emulated, and depending on the parameters Modified: python/branches/p3yk/Doc/lib/libctypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libctypes.tex (original) +++ python/branches/p3yk/Doc/lib/libctypes.tex Wed Jan 10 00:18:33 2007 @@ -2085,10 +2085,10 @@ the type. Some types accept other objects as well. \end{methoddesc} -\begin{methoddesc}{in_dll}{name, library} +\begin{methoddesc}{in_dll}{library, name} This method returns a ctypes type instance exported by a shared library. \var{name} is the name of the symbol that exports the data, -\code{library} is the loaded shared library. +\var{library} is the loaded shared library. \end{methoddesc} Common instance variables of ctypes data types: Modified: python/branches/p3yk/Doc/lib/libfuncs.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libfuncs.tex (original) +++ python/branches/p3yk/Doc/lib/libfuncs.tex Wed Jan 10 00:18:33 2007 @@ -237,11 +237,11 @@ \code{del \var{x}.\var{foobar}}. \end{funcdesc} -\begin{funcdesc}{dict}{\optional{mapping-or-sequence}} +\begin{funcdesc}{dict}{\optional{arg}} Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. - If the positional argument is a mapping object, return a dictionary + If the positional argument \var{arg} is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. Otherwise the positional argument must be a sequence, a container that supports iteration, or an iterator object. The elements of the argument @@ -448,18 +448,18 @@ \versionadded{2.2} \end{funcdesc} -\begin{funcdesc}{filter}{function, list} - Construct a list from those elements of \var{list} for which - \var{function} returns true. \var{list} may be either a sequence, a - container which supports iteration, or an iterator, If \var{list} +\begin{funcdesc}{filter}{function, iterable} + Construct a list from those elements of \var{iterable} for which + \var{function} returns true. \var{iterable} may be either a sequence, a + container which supports iteration, or an iterator, If \var{iterable} is a string or a tuple, the result also has that type; otherwise it is always a list. If \var{function} is \code{None}, the identity function is assumed, that is, all elements of - \var{list} that are false are removed. + \var{iterable} that are false are removed. - Note that \code{filter(function, \var{list})} is equivalent to - \code{[item for item in \var{list} if function(item)]} if function is - not \code{None} and \code{[item for item in \var{list} if item]} if + Note that \code{filter(function, \var{iterable})} is equivalent to + \code{[item for item in \var{iterable} if function(item)]} if function is + not \code{None} and \code{[item for item in \var{iterable} if item]} if function is \code{None}. \end{funcdesc} @@ -608,12 +608,12 @@ may be a sequence (string, tuple or list) or a mapping (dictionary). \end{funcdesc} -\begin{funcdesc}{list}{\optional{sequence}} +\begin{funcdesc}{list}{\optional{iterable}} Return a list whose items are the same and in the same order as - \var{sequence}'s items. \var{sequence} may be either a sequence, a + \var{iterable}'s items. \var{iterable} may be either a sequence, a container that supports iteration, or an iterator object. If - \var{sequence} is already a list, a copy is made and returned, - similar to \code{\var{sequence}[:]}. For instance, + \var{iterable} is already a list, a copy is made and returned, + similar to \code{\var{iterable}[:]}. For instance, \code{list('abc')} returns \code{['a', 'b', 'c']} and \code{list( (1, 2, 3) )} returns \code{[1, 2, 3]}. If no argument is given, returns a new empty list, \code{[]}. @@ -639,22 +639,22 @@ are given, returns \code{0L}. \end{funcdesc} -\begin{funcdesc}{map}{function, list, ...} - Apply \var{function} to every item of \var{list} and return a list - of the results. If additional \var{list} arguments are passed, +\begin{funcdesc}{map}{function, iterable, ...} + Apply \var{function} to every item of \var{iterable} and return a list + of the results. If additional \var{iterable} arguments are passed, \var{function} must take that many arguments and is applied to the - items of all lists in parallel; if a list is shorter than another it + items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with \code{None} items. If \var{function} is \code{None}, the identity function is assumed; if there are - multiple list arguments, \function{map()} returns a list consisting - of tuples containing the corresponding items from all lists (a kind - of transpose operation). The \var{list} arguments may be any kind - of sequence; the result is always a list. + multiple arguments, \function{map()} returns a list consisting + of tuples containing the corresponding items from all iterables (a kind + of transpose operation). The \var{iterable} arguments may be a sequence + or any iterable object; the result is always a list. \end{funcdesc} -\begin{funcdesc}{max}{s\optional{, args...}\optional{key}} - With a single argument \var{s}, return the largest item of a - non-empty sequence (such as a string, tuple or list). With more +\begin{funcdesc}{max}{iterable\optional{, args...}\optional{key}} + With a single argument \var{iterable}, return the largest item of a + non-empty iterable (such as a string, tuple or list). With more than one argument, return the largest of the arguments. The optional \var{key} argument specifies a one-argument ordering @@ -664,16 +664,16 @@ \versionchanged[Added support for the optional \var{key} argument]{2.5} \end{funcdesc} -\begin{funcdesc}{min}{s\optional{, args...}\optional{key}} - With a single argument \var{s}, return the smallest item of a - non-empty sequence (such as a string, tuple or list). With more +\begin{funcdesc}{min}{iterable\optional{, args...}\optional{key}} + With a single argument \var{iterable}, return the smallest item of a + non-empty iterable (such as a string, tuple or list). With more than one argument, return the smallest of the arguments. The optional \var{key} argument specifies a one-argument ordering function like that used for \method{list.sort()}. The \var{key} argument, if supplied, must be in keyword form (for example, \samp{min(a,b,c,key=func)}). - \versionchanged[Added support for the optional \var{key} argument]{2.5} + \versionchanged[Added support for the optional \var{key} argument]{2.5} \end{funcdesc} \begin{funcdesc}{object}{} @@ -1073,11 +1073,11 @@ string, \code{''}. \end{funcdesc} -\begin{funcdesc}{sum}{sequence\optional{, start}} - Sums \var{start} and the items of a \var{sequence}, from left to - right, and returns the total. \var{start} defaults to \code{0}. - The \var{sequence}'s items are normally numbers, and are not allowed - to be strings. The fast, correct way to concatenate sequence of +\begin{funcdesc}{sum}{iterable\optional{, start}} + Sums \var{start} and the items of an \var{iterable} from left to + right and returns the total. \var{start} defaults to \code{0}. + The \var{iterable}'s items are normally numbers, and are not allowed + to be strings. The fast, correct way to concatenate a sequence of strings is by calling \code{''.join(\var{sequence})}. \versionadded{2.3} \end{funcdesc} @@ -1105,11 +1105,11 @@ \versionadded{2.2} \end{funcdesc} -\begin{funcdesc}{tuple}{\optional{sequence}} +\begin{funcdesc}{tuple}{\optional{iterable}} Return a tuple whose items are the same and in the same order as - \var{sequence}'s items. \var{sequence} may be a sequence, a + \var{iterable}'s items. \var{iterable} may be a sequence, a container that supports iteration, or an iterator object. - If \var{sequence} is already a tuple, it + If \var{iterable} is already a tuple, it is returned unchanged. For instance, \code{tuple('abc')} returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns \code{(1, 2, 3)}. If no argument is given, returns a new empty Modified: python/branches/p3yk/Doc/lib/liblogging.tex ============================================================================== --- python/branches/p3yk/Doc/lib/liblogging.tex (original) +++ python/branches/p3yk/Doc/lib/liblogging.tex Wed Jan 10 00:18:33 2007 @@ -516,8 +516,10 @@ \end{methoddesc} \begin{methoddesc}{findCaller}{} -Finds the caller's source filename and line number. Returns the filename -and line number as a 2-element tuple. +Finds the caller's source filename and line number. Returns the filename, +line number and function name as a 3-element tuple. +\versionchanged[The function name was added. In earlier versions, the +filename and line number were returned as a 2-element tuple.]{2.5} \end{methoddesc} \begin{methoddesc}{handle}{record} Modified: python/branches/p3yk/Doc/lib/libmmap.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libmmap.tex (original) +++ python/branches/p3yk/Doc/lib/libmmap.tex Wed Jan 10 00:18:33 2007 @@ -140,8 +140,9 @@ \begin{methoddesc}{seek}{pos\optional{, whence}} Set the file's current position. \var{whence} argument is optional - and defaults to \code{0} (absolute file positioning); other values - are \code{1} (seek relative to the current position) and \code{2} + and defaults to \code{os.SEEK_SET} or \code{0} (absolute file + positioning); other values are \code{os.SEEK_CUR} or \code{1} (seek + relative to the current position) and \code{os.SEEK_END} or \code{2} (seek relative to the file's end). \end{methoddesc} Modified: python/branches/p3yk/Doc/lib/libsimplexmlrpc.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsimplexmlrpc.tex (original) +++ python/branches/p3yk/Doc/lib/libsimplexmlrpc.tex Wed Jan 10 00:18:33 2007 @@ -15,7 +15,7 @@ \begin{classdesc}{SimpleXMLRPCServer}{addr\optional{, requestHandler\optional{, - logRequests\optional{allow_none\optional{, encoding}}}}} + logRequests\optional{, allow_none\optional{, encoding}}}}} Create a new server instance. This class provides methods for registration of functions that can be called by Modified: python/branches/p3yk/Doc/lib/libsocket.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsocket.tex (original) +++ python/branches/p3yk/Doc/lib/libsocket.tex Wed Jan 10 00:18:33 2007 @@ -569,11 +569,32 @@ Receive data from the socket. The return value is a pair \code{(\var{string}, \var{address})} where \var{string} is a string representing the data received and \var{address} is the address of the -socket sending the data. The optional \var{flags} argument has the -same meaning as for \method{recv()} above. +socket sending the data. See the \UNIX{} manual page +\manpage{recv}{2} for the meaning of the optional argument +\var{flags}; it defaults to zero. (The format of \var{address} depends on the address family --- see above.) \end{methoddesc} +\begin{methoddesc}[socket]{recvfrom_into}{buffer\optional{, nbytes\optional{, flags}}} +Receive data from the socket, writing it into \var{buffer} instead of +creating a new string. The return value is a pair +\code{(\var{nbytes}, \var{address})} where \var{nbytes} is the number +of bytes received and \var{address} is the address of the socket +sending the data. See the \UNIX{} manual page +\manpage{recv}{2} for the meaning of the optional argument +\var{flags}; it defaults to zero. (The format of \var{address} +depends on the address family --- see above.) +\end{methoddesc} + +\begin{methoddesc}[socket]{recv_into}{buffer\optional{, nbytes\optional{, flags}}} +Receive up to \var{nbytes} bytes from the socket, +storing the data into a buffer rather than creating a new string. +If \var{nbytes} is not specified (or 0), +receive up to the size available in the given buffer. +See the \UNIX{} manual page \manpage{recv}{2} for the meaning of the +optional argument \var{flags}; it defaults to zero. +\end{methoddesc} + \begin{methoddesc}[socket]{send}{string\optional{, flags}} Send data to the socket. The socket must be connected to a remote socket. The optional \var{flags} argument has the same meaning as for Modified: python/branches/p3yk/Doc/lib/libsqlite3.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsqlite3.tex (original) +++ python/branches/p3yk/Doc/lib/libsqlite3.tex Wed Jan 10 00:18:33 2007 @@ -187,12 +187,12 @@ \end{funcdesc} \begin{funcdesc}{complete_statement}{sql} -Returns \constant{True} if the string \var{sql} one or more complete SQL -statements terminated by semicolons. It does not verify if the SQL is -syntactically correct, only if there are no unclosed string literals and if the +Returns \constant{True} if the string \var{sql} contains one or more complete SQL +statements terminated by semicolons. It does not verify that the SQL is +syntactically correct, only that there are no unclosed string literals and the statement is terminated by a semicolon. -This can be used to build a shell for SQLite, like in the following example: +This can be used to build a shell for SQLite, as in the following example: \verbatiminput{sqlite3/complete_statement.py} \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk/Doc/lib/libstdtypes.tex Wed Jan 10 00:18:33 2007 @@ -1660,9 +1660,12 @@ \begin{methoddesc}[file]{seek}{offset\optional{, whence}} Set the file's current position, like \code{stdio}'s \cfunction{fseek()}. - The \var{whence} argument is optional and defaults to \code{0} - (absolute file positioning); other values are \code{1} (seek - relative to the current position) and \code{2} (seek relative to the + The \var{whence} argument is optional and defaults to + \code{os.SEEK_SET} or \code{0} + (absolute file positioning); other values are \code{os.SEEK_CUR} or \code{1} + (seek + relative to the current position) and \code{os.SEEK_END} or \code{2} + (seek relative to the file's end). There is no return value. Note that if the file is opened for appending (mode \code{'a'} or \code{'a+'}), any \method{seek()} operations will be undone at the next write. If the Modified: python/branches/p3yk/Doc/lib/libtarfile.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtarfile.tex (original) +++ python/branches/p3yk/Doc/lib/libtarfile.tex Wed Jan 10 00:18:33 2007 @@ -124,6 +124,11 @@ only if \member{TarFile.errorlevel}\code{ == 2}. \end{excdesc} +\begin{excdesc}{HeaderError} + Is raised by \method{frombuf()} if the buffer it gets is invalid. + \versionadded{2.6} +\end{excdesc} + \begin{seealso} \seemodule{zipfile}{Documentation of the \refmodule{zipfile} standard module.} @@ -332,6 +337,8 @@ \begin{methoddesc}{frombuf}{} Create and return a \class{TarInfo} object from a string buffer. + \versionadded[Raises \exception{HeaderError} if the buffer is + invalid.]{2.6} \end{methoddesc} \begin{methoddesc}{tobuf}{posix} Modified: python/branches/p3yk/Doc/lib/libtest.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtest.tex (original) +++ python/branches/p3yk/Doc/lib/libtest.tex Wed Jan 10 00:18:33 2007 @@ -263,6 +263,12 @@ This does not equal a failure since it could be the path to the file. \end{funcdesc} +\begin{funcdesc}{guard_warnings_filter}{} +Returns a context manager that guards the \module{warnings} module's +filter settings. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{run_unittest}{*classes} Execute \class{unittest.TestCase} subclasses passed to the function. The function scans the classes for methods starting with the prefix @@ -275,4 +281,22 @@ The optional argument \var{testclass} accepts one of the test classes in the suite so as to print out more detailed information on where the testing suite originated from. + +The \module{test.test_support} module defines the following classes: + +\begin{classdesc}{EnvironmentVarGuard}{} +Class used to temporarily set or unset environment variables. Instances can be +used as a context manager. +\versionadded{2.6} +\end{classdesc} + +\begin{methoddesc}{set}{envvar, value} +Temporarily set the environment variable \code{envvar} to the value of +\code{value}. +\end{methoddesc} + +\begin{methoddesc}{unset}{envvar} +Temporarily unset the environment variable \code{envvar}. +\end{methoddesc} + \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/liburlparse.tex ============================================================================== --- python/branches/p3yk/Doc/lib/liburlparse.tex (original) +++ python/branches/p3yk/Doc/lib/liburlparse.tex Wed Jan 10 00:18:33 2007 @@ -89,7 +89,7 @@ \begin{funcdesc}{urlunparse}{parts} Construct a URL from a tuple as returned by \code{urlparse()}. -The \var{parts} argument be any six-item iterable. +The \var{parts} argument can be any six-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). @@ -133,7 +133,7 @@ \begin{funcdesc}{urlunsplit}{parts} Combine the elements of a tuple as returned by \function{urlsplit()} into a complete URL as a string. -The \var{parts} argument be any five-item iterable. +The \var{parts} argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). Modified: python/branches/p3yk/Doc/mac/toolbox.tex ============================================================================== --- python/branches/p3yk/Doc/mac/toolbox.tex (original) +++ python/branches/p3yk/Doc/mac/toolbox.tex Wed Jan 10 00:18:33 2007 @@ -65,7 +65,7 @@ \modulesynopsis{Interface to the Component Manager.} \section{\module{Carbon.CarbonEvt} --- Carbon Event Manager} -\declaremodule{standard}{Carbon.CaronEvt} +\declaremodule{standard}{Carbon.CarbonEvt} \platform{Mac} \modulesynopsis{Interface to the Carbon Event Manager.} Modified: python/branches/p3yk/Doc/whatsnew/whatsnew25.tex ============================================================================== --- python/branches/p3yk/Doc/whatsnew/whatsnew25.tex (original) +++ python/branches/p3yk/Doc/whatsnew/whatsnew25.tex Wed Jan 10 00:18:33 2007 @@ -5,7 +5,7 @@ % Fix XXX comments \title{What's New in Python 2.5} -\release{1.0} +\release{1.01} \author{A.M. Kuchling} \authoraddress{\email{amk at amk.ca}} @@ -556,13 +556,14 @@ where the generator's execution is paused. \item \method{close()} raises a new \exception{GeneratorExit} - exception inside the generator to terminate the iteration. - On receiving this - exception, the generator's code must either raise - \exception{GeneratorExit} or \exception{StopIteration}; catching the - exception and doing anything else is illegal and will trigger - a \exception{RuntimeError}. \method{close()} will also be called by - Python's garbage collector when the generator is garbage-collected. + exception inside the generator to terminate the iteration. On + receiving this exception, the generator's code must either raise + \exception{GeneratorExit} or \exception{StopIteration}. Catching + the \exception{GeneratorExit} exception and returning a value is + illegal and will trigger a \exception{RuntimeError}; if the function + raises some other exception, that exception is propagated to the + caller. \method{close()} will also be called by Python's garbage + collector when the generator is garbage-collected. If you need to run cleanup code when a \exception{GeneratorExit} occurs, I suggest using a \code{try: ... finally:} suite instead of @@ -1663,6 +1664,13 @@ \item The \module{pyexpat} module now uses version 2.0 of the Expat parser. (Contributed by Trent Mick.) +\item The \class{Queue} class provided by the \module{Queue} module +gained two new methods. \method{join()} blocks until all items in +the queue have been retrieved and all processing work on the items +have been completed. Worker threads call the other new method, +\method{task_done()}, to signal that processing for an item has been +completed. (Contributed by Raymond Hettinger.) + \item The old \module{regex} and \module{regsub} modules, which have been deprecated ever since Python 2.0, have finally been deleted. Other deleted modules: \module{statcache}, \module{tzparse}, Modified: python/branches/p3yk/LICENSE ============================================================================== --- python/branches/p3yk/LICENSE (original) +++ python/branches/p3yk/LICENSE Wed Jan 10 00:18:33 2007 @@ -88,9 +88,9 @@ prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) -2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights -Reserved" are retained in Python alone or in any derivative version -prepared by Licensee. +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make Modified: python/branches/p3yk/Lib/CGIHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/CGIHTTPServer.py (original) +++ python/branches/p3yk/Lib/CGIHTTPServer.py Wed Jan 10 00:18:33 2007 @@ -105,17 +105,36 @@ def run_cgi(self): """Execute a CGI script.""" + path = self.path dir, rest = self.cgi_info + + i = path.find('/', len(dir) + 1) + while i >= 0: + nextdir = path[:i] + nextrest = path[i+1:] + + scriptdir = self.translate_path(nextdir) + if os.path.isdir(scriptdir): + dir, rest = nextdir, nextrest + i = path.find('/', len(dir) + 1) + else: + break + + # find an explicit query string, if present. i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' + + # dissect the part after the directory name into a script name & + # a possible additional path, to be stored in PATH_INFO. i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' + scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): Modified: python/branches/p3yk/Lib/SimpleHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/SimpleHTTPServer.py (original) +++ python/branches/p3yk/Lib/SimpleHTTPServer.py Wed Jan 10 00:18:33 2007 @@ -66,6 +66,12 @@ path = self.translate_path(self.path) f = None if os.path.isdir(path): + if not self.path.endswith('/'): + # redirect browser - doing basically what apache does + self.send_response(301) + self.send_header("Location", self.path + "/") + self.end_headers() + return None for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): Modified: python/branches/p3yk/Lib/StringIO.py ============================================================================== --- python/branches/p3yk/Lib/StringIO.py (original) +++ python/branches/p3yk/Lib/StringIO.py Wed Jan 10 00:18:33 2007 @@ -139,7 +139,7 @@ return r def readline(self, length=None): - """Read one entire line from the file. + r"""Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is Modified: python/branches/p3yk/Lib/bsddb/dbobj.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbobj.py (original) +++ python/branches/p3yk/Lib/bsddb/dbobj.py Wed Jan 10 00:18:33 2007 @@ -55,8 +55,9 @@ return self._cobj.set_lg_max(*args, **kwargs) def set_lk_detect(self, *args, **kwargs): return self._cobj.set_lk_detect(*args, **kwargs) - def set_lk_max(self, *args, **kwargs): - return self._cobj.set_lk_max(*args, **kwargs) + if db.version() < (4,5): + def set_lk_max(self, *args, **kwargs): + return self._cobj.set_lk_max(*args, **kwargs) def set_lk_max_locks(self, *args, **kwargs): return self._cobj.set_lk_max_locks(*args, **kwargs) def set_lk_max_lockers(self, *args, **kwargs): Modified: python/branches/p3yk/Lib/bsddb/test/test_1413192.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_1413192.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_1413192.py Wed Jan 10 00:18:33 2007 @@ -14,7 +14,7 @@ env_name = '.' env = db.DBEnv() -env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN) +env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN | db.DB_INIT_MPOOL) the_txn = env.txn_begin() map = db.DB(env) Modified: python/branches/p3yk/Lib/bsddb/test/test_associate.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_associate.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_associate.py Wed Jan 10 00:18:33 2007 @@ -91,7 +91,7 @@ class AssociateErrorTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/p3yk/Lib/bsddb/test/test_basics.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_basics.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_basics.py Wed Jan 10 00:18:33 2007 @@ -54,7 +54,7 @@ def setUp(self): if self.useEnv: - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: shutil.rmtree(homeDir) Modified: python/branches/p3yk/Lib/bsddb/test/test_dbobj.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbobj.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbobj.py Wed Jan 10 00:18:33 2007 @@ -2,6 +2,7 @@ import sys, os, string import unittest import glob +import tempfile try: # For Pythons w/distutils pybsddb @@ -19,7 +20,7 @@ db_name = 'test-dbobj.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py Wed Jan 10 00:18:33 2007 @@ -242,7 +242,7 @@ class BasicEnvShelveTestCase(DBShelveTestCase): def do_open(self): self.homeDir = homeDir = os.path.join( - os.path.dirname(sys.argv[0]), 'db_home') + tempfile.gettempdir(), 'db_home') try: os.mkdir(homeDir) except os.error: pass self.env = db.DBEnv() Modified: python/branches/p3yk/Lib/bsddb/test/test_dbtables.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbtables.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbtables.py Wed Jan 10 00:18:33 2007 @@ -26,6 +26,7 @@ pickle = cPickle except ImportError: import pickle +import tempfile import unittest from .test_all import verbose @@ -46,7 +47,7 @@ db_name = 'test-table.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk/Lib/bsddb/test/test_env_close.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_env_close.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_env_close.py Wed Jan 10 00:18:33 2007 @@ -33,7 +33,7 @@ class DBEnvClosedEarlyCrash(unittest.TestCase): def setUp(self): - self.homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + self.homeDir = os.path.join(tempfile.gettempdir(), 'db_home') try: os.mkdir(self.homeDir) except os.error: pass tempfile.tempdir = self.homeDir Modified: python/branches/p3yk/Lib/bsddb/test/test_join.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_join.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_join.py Wed Jan 10 00:18:33 2007 @@ -49,7 +49,7 @@ def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk/Lib/bsddb/test/test_lock.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_lock.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_lock.py Wed Jan 10 00:18:33 2007 @@ -30,7 +30,7 @@ class LockingTestCase(unittest.TestCase): def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk/Lib/bsddb/test/test_misc.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_misc.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_misc.py Wed Jan 10 00:18:33 2007 @@ -4,6 +4,7 @@ import os import sys import unittest +import tempfile try: # For Pythons w/distutils pybsddb @@ -17,7 +18,7 @@ class MiscTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/p3yk/Lib/bsddb/test/test_recno.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_recno.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_recno.py Wed Jan 10 00:18:33 2007 @@ -203,10 +203,10 @@ just a line in the file, but you can set a different record delimiter if needed. """ - source = os.path.join(os.path.dirname(sys.argv[0]), - 'db_home/test_recno.txt') - if not os.path.isdir('db_home'): - os.mkdir('db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') + source = os.path.join(homeDir, 'test_recno.txt') + if not os.path.isdir(homeDir): + os.mkdir(homeDir) f = open(source, 'w') # create the file f.close() Modified: python/branches/p3yk/Lib/bsddb/test/test_thread.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_thread.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_thread.py Wed Jan 10 00:18:33 2007 @@ -53,7 +53,7 @@ if verbose: dbutils._deadlock_VerboseFile = sys.stdout - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/p3yk/Lib/cookielib.py ============================================================================== --- python/branches/p3yk/Lib/cookielib.py (original) +++ python/branches/p3yk/Lib/cookielib.py Wed Jan 10 00:18:33 2007 @@ -1316,26 +1316,28 @@ """ _debug("add_cookie_header") self._cookies_lock.acquire() + try: - self._policy._now = self._now = int(time.time()) - - cookies = self._cookies_for_request(request) + self._policy._now = self._now = int(time.time()) - attrs = self._cookie_attrs(cookies) - if attrs: - if not request.has_header("Cookie"): - request.add_unredirected_header( - "Cookie", "; ".join(attrs)) - - # if necessary, advertise that we know RFC 2965 - if (self._policy.rfc2965 and not self._policy.hide_cookie2 and - not request.has_header("Cookie2")): - for cookie in cookies: - if cookie.version != 1: - request.add_unredirected_header("Cookie2", '$Version="1"') - break + cookies = self._cookies_for_request(request) - self._cookies_lock.release() + attrs = self._cookie_attrs(cookies) + if attrs: + if not request.has_header("Cookie"): + request.add_unredirected_header( + "Cookie", "; ".join(attrs)) + + # if necessary, advertise that we know RFC 2965 + if (self._policy.rfc2965 and not self._policy.hide_cookie2 and + not request.has_header("Cookie2")): + for cookie in cookies: + if cookie.version != 1: + request.add_unredirected_header("Cookie2", '$Version="1"') + break + + finally: + self._cookies_lock.release() self.clear_expired_cookies() @@ -1602,12 +1604,15 @@ def set_cookie_if_ok(self, cookie, request): """Set a cookie if policy says it's OK to do so.""" self._cookies_lock.acquire() - self._policy._now = self._now = int(time.time()) + try: + self._policy._now = self._now = int(time.time()) - if self._policy.set_ok(cookie, request): - self.set_cookie(cookie) + if self._policy.set_ok(cookie, request): + self.set_cookie(cookie) + - self._cookies_lock.release() + finally: + self._cookies_lock.release() def set_cookie(self, cookie): """Set a cookie, without checking whether or not it should be set.""" @@ -1626,13 +1631,15 @@ """Extract cookies from response, where allowable given the request.""" _debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() - self._policy._now = self._now = int(time.time()) + try: + self._policy._now = self._now = int(time.time()) - for cookie in self.make_cookies(response, request): - if self._policy.set_ok(cookie, request): - _debug(" setting cookie: %s", cookie) - self.set_cookie(cookie) - self._cookies_lock.release() + for cookie in self.make_cookies(response, request): + if self._policy.set_ok(cookie, request): + _debug(" setting cookie: %s", cookie) + self.set_cookie(cookie) + finally: + self._cookies_lock.release() def clear(self, domain=None, path=None, name=None): """Clear some cookies. @@ -1669,10 +1676,12 @@ """ self._cookies_lock.acquire() - for cookie in self: - if cookie.discard: - self.clear(cookie.domain, cookie.path, cookie.name) - self._cookies_lock.release() + try: + for cookie in self: + if cookie.discard: + self.clear(cookie.domain, cookie.path, cookie.name) + finally: + self._cookies_lock.release() def clear_expired_cookies(self): """Discard all expired cookies. @@ -1685,11 +1694,13 @@ """ self._cookies_lock.acquire() - now = time.time() - for cookie in self: - if cookie.is_expired(now): - self.clear(cookie.domain, cookie.path, cookie.name) - self._cookies_lock.release() + try: + now = time.time() + for cookie in self: + if cookie.is_expired(now): + self.clear(cookie.domain, cookie.path, cookie.name) + finally: + self._cookies_lock.release() def __iter__(self): return deepvalues(self._cookies) @@ -1761,16 +1772,18 @@ else: raise ValueError(MISSING_FILENAME_TEXT) self._cookies_lock.acquire() - - old_state = copy.deepcopy(self._cookies) - self._cookies = {} try: - self.load(filename, ignore_discard, ignore_expires) - except (LoadError, IOError): - self._cookies = old_state - raise - self._cookies_lock.release() + old_state = copy.deepcopy(self._cookies) + self._cookies = {} + try: + self.load(filename, ignore_discard, ignore_expires) + except (LoadError, IOError): + self._cookies = old_state + raise + + finally: + self._cookies_lock.release() from _LWPCookieJar import LWPCookieJar, lwp_cookie_str from _MozillaCookieJar import MozillaCookieJar Modified: python/branches/p3yk/Lib/difflib.py ============================================================================== --- python/branches/p3yk/Lib/difflib.py (original) +++ python/branches/p3yk/Lib/difflib.py Wed Jan 10 00:18:33 2007 @@ -1310,7 +1310,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, charjunk=IS_CHARACTER_JUNK): - """Returns generator yielding marked up from/to side by side differences. + r"""Returns generator yielding marked up from/to side by side differences. Arguments: fromlines -- list of text lines to compared to tolines Modified: python/branches/p3yk/Lib/dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/dumbdbm.py (original) +++ python/branches/p3yk/Lib/dumbdbm.py Wed Jan 10 00:18:33 2007 @@ -68,7 +68,8 @@ try: f = _open(self._datfile, 'r') except IOError: - f = _open(self._datfile, 'w', self._mode) + f = _open(self._datfile, 'w') + self._chmod(self._datfile) f.close() self._update() @@ -106,7 +107,8 @@ except self._os.error: pass - f = self._open(self._dirfile, 'w', self._mode) + f = self._open(self._dirfile, 'w') + self._chmod(self._dirfile) for key, pos_and_siz_pair in self._index.iteritems(): f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -152,7 +154,8 @@ # the in-memory index dict, and append one to the directory file. def _addkey(self, key, pos_and_siz_pair): self._index[key] = pos_and_siz_pair - f = _open(self._dirfile, 'a', self._mode) + f = _open(self._dirfile, 'a') + self._chmod(self._dirfile) f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -211,6 +214,9 @@ __del__ = close + def _chmod (self, file): + if hasattr(self._os, 'chmod'): + self._os.chmod(file, self._mode) def open(file, flag=None, mode=0666): @@ -227,4 +233,15 @@ """ # flag argument is currently ignored + + # Modify mode depending on the umask + try: + um = _os.umask(0) + _os.umask(um) + except AttributeError: + pass + else: + # Turn off any bits that are set in the umask + mode = mode & (~um) + return _Database(file, mode) Modified: python/branches/p3yk/Lib/heapq.py ============================================================================== --- python/branches/p3yk/Lib/heapq.py (original) +++ python/branches/p3yk/Lib/heapq.py Wed Jan 10 00:18:33 2007 @@ -130,7 +130,7 @@ 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee -from operator import itemgetter +from operator import itemgetter, neg import bisect def heappush(heap, item): @@ -315,8 +315,6 @@ Equivalent to: sorted(iterable, key=key)[:n] """ - if key is None: - return _nsmallest(n, iterable) in1, in2 = tee(iterable) it = izip(imap(key, in1), count(), in2) # decorate result = _nsmallest(n, it) @@ -328,10 +326,8 @@ Equivalent to: sorted(iterable, key=key, reverse=True)[:n] """ - if key is None: - return _nlargest(n, iterable) in1, in2 = tee(iterable) - it = izip(imap(key, in1), count(), in2) # decorate + it = izip(imap(key, in1), imap(neg, count()), in2) # decorate result = _nlargest(n, it) return map(itemgetter(2), result) # undecorate Modified: python/branches/p3yk/Lib/hmac.py ============================================================================== --- python/branches/p3yk/Lib/hmac.py (original) +++ python/branches/p3yk/Lib/hmac.py Wed Jan 10 00:18:33 2007 @@ -3,13 +3,11 @@ Implements the HMAC algorithm as described by RFC 2104. """ -def _strxor(s1, s2): - """Utility method. XOR the two strings s1 and s2 (must have same length). - """ - return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) +trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)]) +trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)]) # The size of the digests returned by HMAC depends on the underlying -# hashing module used. +# hashing module used. Use digest_size from the instance of HMAC instead. digest_size = None # A unique object passed by HMAC.copy() to the HMAC constructor, in order @@ -22,6 +20,7 @@ This supports the API for Cryptographic Hash Functions (PEP 247). """ + blocksize = 64 # 512-bit HMAC; can be changed in subclasses. def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. @@ -49,16 +48,13 @@ self.inner = self.digest_cons() self.digest_size = self.inner.digest_size - blocksize = 64 - ipad = "\x36" * blocksize - opad = "\x5C" * blocksize - + blocksize = self.blocksize if len(key) > blocksize: key = self.digest_cons(key).digest() key = key + chr(0) * (blocksize - len(key)) - self.outer.update(_strxor(key, opad)) - self.inner.update(_strxor(key, ipad)) + self.outer.update(key.translate(trans_5C)) + self.inner.update(key.translate(trans_36)) if msg is not None: self.update(msg) @@ -75,13 +71,22 @@ An update to this copy won't affect the original object. """ - other = HMAC(_secret_backdoor_key) + other = self.__class__(_secret_backdoor_key) other.digest_cons = self.digest_cons other.digest_size = self.digest_size other.inner = self.inner.copy() other.outer = self.outer.copy() return other + def _current(self): + """Return a hash object for the current state. + + To be used only internally with digest() and hexdigest(). + """ + h = self.outer.copy() + h.update(self.inner.digest()) + return h + def digest(self): """Return the hash value of this hashing object. @@ -89,15 +94,14 @@ not altered in any way by this function; you can continue updating the object after calling this function. """ - h = self.outer.copy() - h.update(self.inner.digest()) + h = self._current() return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ - return "".join([hex(ord(x))[2:].zfill(2) - for x in tuple(self.digest())]) + h = self._current() + return h.hexdigest() def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. Modified: python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py Wed Jan 10 00:18:33 2007 @@ -118,8 +118,11 @@ i = 0 while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]: i += 1 - while cursel > 0 and selstart[:i] <= self.completions[cursel-1]: + previous_completion = self.completions[cursel - 1] + while cursel > 0 and selstart[:i] <= previous_completion: i += 1 + if selstart == previous_completion: + break # maybe we have a duplicate? newstart = selstart[:i] self._change_start(newstart) Modified: python/branches/p3yk/Lib/idlelib/NEWS.txt ============================================================================== --- python/branches/p3yk/Lib/idlelib/NEWS.txt (original) +++ python/branches/p3yk/Lib/idlelib/NEWS.txt Wed Jan 10 00:18:33 2007 @@ -3,9 +3,14 @@ *Release date: XX-XXX-200X* +- Avoid hang when encountering a duplicate in a completion list. Bug 1571112. + - Patch #1362975: Rework CodeContext indentation algorithm to avoid hard-coding pixel widths. +- Bug #813342: Start the IDLE subprocess with -Qnew if the parent + is started with that option. + - Some syntax errors were being caught by tokenize during the tabnanny check, resulting in obscure error messages. Do the syntax check first. Bug 1562716, 1562719 @@ -14,6 +19,12 @@ the Python release of which it's a part. +What's New in IDLE 1.2? +======================= + +*Release date: 19-SEP-2006* + + What's New in IDLE 1.2c1? ========================= @@ -44,6 +55,13 @@ *Release date: 03-AUG-2006* +- Bug #1525817: Don't truncate short lines in IDLE's tool tips. + +- Bug #1517990: IDLE keybindings on MacOS X now work correctly + +- Bug #1517996: IDLE now longer shows the default Tk menu when a + path browser, class browser or debugger is the frontmost window on MacOS X + - EditorWindow.test() was failing. Bug 1417598 - EditorWindow failed when used stand-alone if sys.ps1 not set. @@ -80,6 +98,8 @@ *Release date: 05-APR-2006* +- Patch #1162825: Support non-ASCII characters in IDLE window titles. + - Source file f.flush() after writing; trying to avoid lossage if user kills GUI. Modified: python/branches/p3yk/Lib/logging/__init__.py ============================================================================== --- python/branches/p3yk/Lib/logging/__init__.py (original) +++ python/branches/p3yk/Lib/logging/__init__.py Wed Jan 10 00:18:33 2007 @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.4.9.9" -__date__ = "06 February 2006" +__version__ = "0.5.0.0" +__date__ = "08 January 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -243,7 +243,7 @@ try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] - except: + except (TypeError, ValueError, AttributeError): self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info Modified: python/branches/p3yk/Lib/logging/handlers.py ============================================================================== --- python/branches/p3yk/Lib/logging/handlers.py (original) +++ python/branches/p3yk/Lib/logging/handlers.py Wed Jan 10 00:18:33 2007 @@ -347,7 +347,7 @@ try: self.sock = self.makeSocket() self.retryTime = None # next time, no delay before trying - except: + except socket.error: #Creation failed, so set the retry time and return. if self.retryTime is None: self.retryPeriod = self.retryStart @@ -738,7 +738,7 @@ import smtplib try: from email.Utils import formatdate - except: + except ImportError: formatdate = self.date_time port = self.mailport if not port: Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Wed Jan 10 00:18:33 2007 @@ -510,6 +510,7 @@ self._next_key = 0 self._pending = False # No changes require rewriting the file. self._locked = False + self._file_length = None # Used to record mailbox size def add(self, message): """Add message and return assigned key.""" @@ -563,7 +564,21 @@ """Write any pending changes to disk.""" if not self._pending: return - self._lookup() + + # In order to be writing anything out at all, self._toc must + # already have been generated (and presumably has been modified + # by adding or deleting an item). + assert self._toc is not None + + # Check length of self._file; if it's changed, some other process + # has modified the mailbox since we scanned it. + self._file.seek(0, 2) + cur_len = self._file.tell() + if cur_len != self._file_length: + raise ExternalClashError('Size of mailbox file changed ' + '(expected %i, found %i)' % + (self._file_length, cur_len)) + new_file = _create_temporary(self._path) try: new_toc = {} @@ -639,6 +654,7 @@ offsets = self._install_message(message) self._post_message_hook(self._file) self._file.flush() + self._file_length = self._file.tell() # Record current length of mailbox return offsets @@ -730,6 +746,7 @@ break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) + self._file_length = self._file.tell() class MMDF(_mboxMMDF): @@ -773,6 +790,8 @@ break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) + self._file.seek(0, 2) + self._file_length = self._file.tell() class MH(Mailbox): @@ -1198,7 +1217,9 @@ self._toc = dict(enumerate(zip(starts, stops))) self._labels = dict(enumerate(label_lists)) self._next_key = len(self._toc) - + self._file.seek(0, 2) + self._file_length = self._file.tell() + def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' % @@ -1884,7 +1905,8 @@ def _sync_flush(f): """Ensure changes to file f are physically on disk.""" f.flush() - os.fsync(f.fileno()) + if hasattr(os, 'fsync'): + os.fsync(f.fileno()) def _sync_close(f): """Close file f, ensuring all changes are physically on disk.""" Modified: python/branches/p3yk/Lib/pty.py ============================================================================== --- python/branches/p3yk/Lib/pty.py (original) +++ python/branches/p3yk/Lib/pty.py Wed Jan 10 00:18:33 2007 @@ -121,7 +121,9 @@ # Explicitly open the tty to make it become a controlling tty. tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) os.close(tmp_fd) - + else: + os.close(slave_fd) + # Parent and child process. return pid, master_fd Modified: python/branches/p3yk/Lib/pydoc.py ============================================================================== --- python/branches/p3yk/Lib/pydoc.py (original) +++ python/branches/p3yk/Lib/pydoc.py Wed Jan 10 00:18:33 2007 @@ -1741,6 +1741,9 @@ Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. + +On the Microsoft Windows operating system, the files can be built by +running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory. ''') return target = self.topics.get(topic, self.keywords.get(topic)) Modified: python/branches/p3yk/Lib/random.py ============================================================================== --- python/branches/p3yk/Lib/random.py (original) +++ python/branches/p3yk/Lib/random.py Wed Jan 10 00:18:33 2007 @@ -205,7 +205,7 @@ raise ValueError, "empty range for randrange()" if n >= maxwidth: - return istart + self._randbelow(n) + return istart + istep*self._randbelow(n) return istart + istep*int(self.random() * n) def randint(self, a, b): Modified: python/branches/p3yk/Lib/sre_parse.py ============================================================================== --- python/branches/p3yk/Lib/sre_parse.py (original) +++ python/branches/p3yk/Lib/sre_parse.py Wed Jan 10 00:18:33 2007 @@ -134,6 +134,8 @@ def __delitem__(self, index): del self.data[index] def __getitem__(self, index): + if isinstance(index, slice): + return SubPattern(self.pattern, self.data[index]) return self.data[index] def __setitem__(self, index, code): self.data[index] = code Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Wed Jan 10 00:18:33 2007 @@ -166,7 +166,7 @@ communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to - terminate. The optional stdin argument should be a string to be + terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. @@ -1005,8 +1005,12 @@ # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)): - if fd: os.close(fd) + if p2cread and p2cread not in (0,): + os.close(p2cread) + if c2pwrite and c2pwrite not in (p2cread, 1): + os.close(c2pwrite) + if errwrite and errwrite not in (p2cread, c2pwrite, 2): + os.close(errwrite) # Close all other fds, if asked for if close_fds: @@ -1108,6 +1112,7 @@ read_set.append(self.stderr) stderr = [] + input_offset = 0 while read_set or write_set: rlist, wlist, xlist = select.select(read_set, write_set, []) @@ -1115,9 +1120,9 @@ # When select has indicated that the file is writable, # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 - bytes_written = os.write(self.stdin.fileno(), input[:512]) - input = input[bytes_written:] - if not input: + bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) + input_offset += bytes_written + if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Wed Jan 10 00:18:33 2007 @@ -147,7 +147,10 @@ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0200): - n = int(s.rstrip(NUL + " ") or "0", 8) + try: + n = int(s.rstrip(NUL + " ") or "0", 8) + except ValueError: + raise HeaderError("invalid header") else: n = 0L for i in xrange(len(s) - 1): @@ -282,6 +285,9 @@ class StreamError(TarError): """Exception for unsupported operations on stream-like TarFiles.""" pass +class HeaderError(TarError): + """Exception for invalid headers.""" + pass #--------------------------- # internal stream interface @@ -624,140 +630,194 @@ #------------------------ # Extraction file object #------------------------ -class ExFileObject(object): - """File-like object for reading an archive member. - Is returned by TarFile.extractfile(). Support for - sparse files included. +class _FileInFile(object): + """A thin wrapper around an existing file object that + provides a part of its data as an individual file + object. """ - def __init__(self, tarfile, tarinfo): - self.fileobj = tarfile.fileobj - self.name = tarinfo.name - self.mode = "r" - self.closed = False - self.offset = tarinfo.offset_data - self.size = tarinfo.size - self.pos = 0L - self.linebuffer = "" - if tarinfo.issparse(): - self.sparse = tarinfo.sparse - self.read = self._readsparse - else: - self.read = self._readnormal + def __init__(self, fileobj, offset, size, sparse=None): + self.fileobj = fileobj + self.offset = offset + self.size = size + self.sparse = sparse + self.position = 0 - def __read(self, size): - """Overloadable read method. + def tell(self): + """Return the current file position. """ - return self.fileobj.read(size) + return self.position - def readline(self, size=-1): - """Read a line with approx. size. If size is negative, - read a whole line. readline() and read() must not - be mixed up (!). - """ - if size < 0: - size = sys.maxint - - nl = self.linebuffer.find("\n") - if nl >= 0: - nl = min(nl, size) - else: - size -= len(self.linebuffer) - while (nl < 0 and size > 0): - buf = self.read(min(size, 100)) - if not buf: - break - self.linebuffer += buf - size -= len(buf) - nl = self.linebuffer.find("\n") - if nl == -1: - s = self.linebuffer - self.linebuffer = "" - return s - buf = self.linebuffer[:nl] - self.linebuffer = self.linebuffer[nl + 1:] - while buf[-1:] == "\r": - buf = buf[:-1] - return buf + "\n" - - def readlines(self): - """Return a list with all (following) lines. + def seek(self, position): + """Seek to a position in the file. """ - result = [] - while True: - line = self.readline() - if not line: break - result.append(line) - return result + self.position = position - def _readnormal(self, size=None): - """Read operation for regular files. + def read(self, size=None): + """Read data from the file. """ - if self.closed: - raise ValueError("file is closed") - self.fileobj.seek(self.offset + self.pos) - bytesleft = self.size - self.pos if size is None: - bytestoread = bytesleft + size = self.size - self.position else: - bytestoread = min(size, bytesleft) - self.pos += bytestoread - return self.__read(bytestoread) + size = min(size, self.size - self.position) - def _readsparse(self, size=None): - """Read operation for sparse files. - """ - if self.closed: - raise ValueError("file is closed") + if self.sparse is None: + return self.readnormal(size) + else: + return self.readsparse(size) - if size is None: - size = self.size - self.pos + def readnormal(self, size): + """Read operation for regular files. + """ + self.fileobj.seek(self.offset + self.position) + self.position += size + return self.fileobj.read(size) + def readsparse(self, size): + """Read operation for sparse files. + """ data = [] while size > 0: - buf = self._readsparsesection(size) + buf = self.readsparsesection(size) if not buf: break size -= len(buf) data.append(buf) return "".join(data) - def _readsparsesection(self, size): + def readsparsesection(self, size): """Read a single section of a sparse file. """ - section = self.sparse.find(self.pos) + section = self.sparse.find(self.position) if section is None: return "" - toread = min(size, section.offset + section.size - self.pos) + size = min(size, section.offset + section.size - self.position) + if isinstance(section, _data): - realpos = section.realpos + self.pos - section.offset - self.pos += toread + realpos = section.realpos + self.position - section.offset self.fileobj.seek(self.offset + realpos) - return self.__read(toread) + self.position += size + return self.fileobj.read(size) + else: + self.position += size + return NUL * size +#class _FileInFile + + +class ExFileObject(object): + """File-like object for reading an archive member. + Is returned by TarFile.extractfile(). + """ + blocksize = 1024 + + def __init__(self, tarfile, tarinfo): + self.fileobj = _FileInFile(tarfile.fileobj, + tarinfo.offset_data, + tarinfo.size, + getattr(tarinfo, "sparse", None)) + self.name = tarinfo.name + self.mode = "r" + self.closed = False + self.size = tarinfo.size + + self.position = 0 + self.buffer = "" + + def read(self, size=None): + """Read at most size bytes from the file. If size is not + present or None, read all data until EOF is reached. + """ + if self.closed: + raise ValueError("I/O operation on closed file") + + buf = "" + if self.buffer: + if size is None: + buf = self.buffer + self.buffer = "" + else: + buf = self.buffer[:size] + self.buffer = self.buffer[size:] + + if size is None: + buf += self.fileobj.read() else: - self.pos += toread - return NUL * toread + buf += self.fileobj.read(size - len(buf)) + + self.position += len(buf) + return buf + + def readline(self, size=-1): + """Read one entire line from the file. If size is present + and non-negative, return a string with at most that + size, which may be an incomplete line. + """ + if self.closed: + raise ValueError("I/O operation on closed file") + + if "\n" in self.buffer: + pos = self.buffer.find("\n") + 1 + else: + buffers = [self.buffer] + while True: + buf = self.fileobj.read(self.blocksize) + buffers.append(buf) + if not buf or "\n" in buf: + self.buffer = "".join(buffers) + pos = self.buffer.find("\n") + 1 + if pos == 0: + # no newline found. + pos = len(self.buffer) + break + + if size != -1: + pos = min(size, pos) + + buf = self.buffer[:pos] + self.buffer = self.buffer[pos:] + self.position += len(buf) + return buf + + def readlines(self): + """Return a list with all remaining lines. + """ + result = [] + while True: + line = self.readline() + if not line: break + result.append(line) + return result def tell(self): """Return the current file position. """ - return self.pos + if self.closed: + raise ValueError("I/O operation on closed file") + + return self.position - def seek(self, pos, whence=0): + def seek(self, pos, whence=os.SEEK_SET): """Seek to a position in the file. """ - self.linebuffer = "" - if whence == 0: - self.pos = min(max(pos, 0), self.size) - if whence == 1: + if self.closed: + raise ValueError("I/O operation on closed file") + + if whence == os.SEEK_SET: + self.position = min(max(pos, 0), self.size) + elif whence == os.SEEK_CUR: if pos < 0: - self.pos = max(self.pos + pos, 0) + self.position = max(self.position + pos, 0) else: - self.pos = min(self.pos + pos, self.size) - if whence == 2: - self.pos = max(min(self.size + pos, self.size), 0) + self.position = min(self.position + pos, self.size) + elif whence == os.SEEK_END: + self.position = max(min(self.size + pos, self.size), 0) + else: + raise ValueError("Invalid argument") + + self.buffer = "" + self.fileobj.seek(self.position) def close(self): """Close the file object. @@ -765,20 +825,13 @@ self.closed = True def __iter__(self): - """Get an iterator over the file object. - """ - if self.closed: - raise ValueError("I/O operation on closed file") - return self - - def next(self): - """Get the next item from the file iterator. + """Get an iterator over the file's lines. """ - result = self.readline() - if not result: - raise StopIteration - return result - + while True: + line = self.readline() + if not line: + break + yield line #class ExFileObject #------------------ @@ -821,9 +874,13 @@ """Construct a TarInfo object from a 512 byte string buffer. """ if len(buf) != BLOCKSIZE: - raise ValueError("truncated header") + raise HeaderError("truncated header") if buf.count(NUL) == BLOCKSIZE: - raise ValueError("empty header") + raise HeaderError("empty header") + + chksum = nti(buf[148:156]) + if chksum not in calc_chksums(buf): + raise HeaderError("bad checksum") tarinfo = cls() tarinfo.buf = buf @@ -833,7 +890,7 @@ tarinfo.gid = nti(buf[116:124]) tarinfo.size = nti(buf[124:136]) tarinfo.mtime = nti(buf[136:148]) - tarinfo.chksum = nti(buf[148:156]) + tarinfo.chksum = chksum tarinfo.type = buf[156:157] tarinfo.linkname = buf[157:257].rstrip(NUL) tarinfo.uname = buf[265:297].rstrip(NUL) @@ -845,8 +902,6 @@ if prefix and not tarinfo.issparse(): tarinfo.name = prefix + "/" + tarinfo.name - if tarinfo.chksum not in calc_chksums(buf): - raise ValueError("invalid header") return tarinfo def tobuf(self, posix=False): @@ -999,7 +1054,7 @@ can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ - self.name = name + self.name = os.path.abspath(name) if len(mode) > 1 or mode not in "raw": raise ValueError("mode must be 'r', 'a' or 'w'") @@ -1011,7 +1066,7 @@ self._extfileobj = False else: if self.name is None and hasattr(fileobj, "name"): - self.name = fileobj.name + self.name = os.path.abspath(fileobj.name) if hasattr(fileobj, "mode"): self.mode = fileobj.mode self._extfileobj = True @@ -1088,9 +1143,13 @@ # Find out which *open() is appropriate for opening the file. for comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) + if fileobj is not None: + saved_pos = fileobj.tell() try: return func(name, "r", fileobj) except (ReadError, CompressionError): + if fileobj is not None: + fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") @@ -1147,24 +1206,12 @@ except (ImportError, AttributeError): raise CompressionError("gzip module is not available") - pre, ext = os.path.splitext(name) - pre = os.path.basename(pre) - if ext == ".tgz": - ext = ".tar" - if ext == ".gz": - ext = "" - tarname = pre + ext - if fileobj is None: fileobj = _open(name, mode + "b") - if mode != "r": - name = tarname - try: - t = cls.taropen(tarname, mode, - gzip.GzipFile(name, mode, compresslevel, fileobj) - ) + t = cls.taropen(name, mode, + gzip.GzipFile(name, mode, compresslevel, fileobj)) except IOError: raise ReadError("not a gzip file") t._extfileobj = False @@ -1183,21 +1230,13 @@ except ImportError: raise CompressionError("bz2 module is not available") - pre, ext = os.path.splitext(name) - pre = os.path.basename(pre) - if ext == ".tbz2": - ext = ".tar" - if ext == ".bz2": - ext = "" - tarname = pre + ext - if fileobj is not None: fileobj = _BZ2Proxy(fileobj, mode) else: fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel) try: - t = cls.taropen(tarname, mode, fileobj) + t = cls.taropen(name, mode, fileobj) except IOError: raise ReadError("not a bzip2 file") t._extfileobj = False @@ -1402,8 +1441,7 @@ arcname = name # Skip if somebody tries to archive the archive... - if self.name is not None \ - and os.path.abspath(name) == os.path.abspath(self.name): + if self.name is not None and os.path.abspath(name) == self.name: self._dbg(2, "tarfile: Skipped %r" % name) return @@ -1795,16 +1833,14 @@ tarinfo = self.proc_member(tarinfo) - except ValueError, e: + except HeaderError, e: if self.ignore_zeros: - self._dbg(2, "0x%X: empty or invalid block: %s" % - (self.offset, e)) + self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue else: if self.offset == 0: - raise ReadError("empty, unreadable or compressed " - "file: %s" % e) + raise ReadError(str(e)) return None break Modified: python/branches/p3yk/Lib/test/test_compile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compile.py (original) +++ python/branches/p3yk/Lib/test/test_compile.py Wed Jan 10 00:18:33 2007 @@ -1,5 +1,4 @@ import unittest -import warnings import sys from test import test_support Modified: python/branches/p3yk/Lib/test/test_deque.py ============================================================================== --- python/branches/p3yk/Lib/test/test_deque.py (original) +++ python/branches/p3yk/Lib/test/test_deque.py Wed Jan 10 00:18:33 2007 @@ -396,6 +396,12 @@ d.pop() self.assertRaises(RuntimeError, it.next) + def test_runtime_error_on_empty_deque(self): + d = deque() + it = iter(d) + d.append(10) + self.assertRaises(RuntimeError, it.next) + class Deque(deque): pass Modified: python/branches/p3yk/Lib/test/test_dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dumbdbm.py (original) +++ python/branches/p3yk/Lib/test/test_dumbdbm.py Wed Jan 10 00:18:33 2007 @@ -38,6 +38,24 @@ self.read_helper(f) f.close() + def test_dumbdbm_creation_mode(self): + # On platforms without chmod, don't do anything. + if not (hasattr(os, 'chmod') and hasattr(os, 'umask')): + return + + try: + old_umask = os.umask(0002) + f = dumbdbm.open(_fname, 'c', 0637) + f.close() + finally: + os.umask(old_umask) + + import stat + st = os.stat(_fname + '.dat') + self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + st = os.stat(_fname + '.dir') + self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + def test_close_twice(self): f = dumbdbm.open(_fname) f['a'] = 'b' Modified: python/branches/p3yk/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk/Lib/test/test_exceptions.py Wed Jan 10 00:18:33 2007 @@ -3,7 +3,6 @@ import os import sys import unittest -import warnings import pickle try: import cPickle Modified: python/branches/p3yk/Lib/test/test_heapq.py ============================================================================== --- python/branches/p3yk/Lib/test/test_heapq.py (original) +++ python/branches/p3yk/Lib/test/test_heapq.py Wed Jan 10 00:18:33 2007 @@ -104,20 +104,20 @@ self.assertEqual(heap_sorted, sorted(data)) def test_nsmallest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nsmallest(n, data), sorted(data)[:n]) - self.assertEqual(nsmallest(n, data, key=f), - sorted(data, key=f)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nsmallest(n, data), sorted(data)[:n]) + self.assertEqual(nsmallest(n, data, key=f), + sorted(data, key=f)[:n]) def test_nlargest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) - self.assertEqual(nlargest(n, data, key=f), - sorted(data, key=f, reverse=True)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) + self.assertEqual(nlargest(n, data, key=f), + sorted(data, key=f, reverse=True)[:n]) #============================================================================== Modified: python/branches/p3yk/Lib/test/test_import.py ============================================================================== --- python/branches/p3yk/Lib/test/test_import.py (original) +++ python/branches/p3yk/Lib/test/test_import.py Wed Jan 10 00:18:33 2007 @@ -1,10 +1,11 @@ -from test.test_support import TESTFN, run_unittest +from test.test_support import TESTFN, run_unittest, guard_warnings_filter import unittest import os import random import sys import py_compile +import warnings def remove_files(name): @@ -204,15 +205,11 @@ self.assert_(y is test.test_support, y.__name__) def test_import_initless_directory_warning(self): - import warnings - oldfilters = warnings.filters[:] - warnings.simplefilter('error', ImportWarning); - try: + with guard_warnings_filter(): # Just a random non-package directory we always expect to be # somewhere in sys.path... + warnings.simplefilter('error', ImportWarning) self.assertRaises(ImportWarning, __import__, "site-packages") - finally: - warnings.filters = oldfilters def test_main(verbose=None): run_unittest(ImportTest) Modified: python/branches/p3yk/Lib/test/test_pty.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pty.py (original) +++ python/branches/p3yk/Lib/test/test_pty.py Wed Jan 10 00:18:33 2007 @@ -115,6 +115,12 @@ os._exit(4) else: debug("Waiting for child (%d) to finish."%pid) + ##line = os.read(master_fd, 80) + ##lines = line.replace('\r\n', '\n').split('\n') + ##if False and lines != ['In child, calling os.setsid()', + ## 'Good: OSError was raised.', '']: + ## raise TestFailed("Unexpected output from child: %r" % line) + (pid, status) = os.waitpid(pid, 0) res = status >> 8 debug("Child (%d) exited with status %d (%d)."%(pid, res, status)) @@ -127,6 +133,15 @@ elif res != 4: raise TestFailed, "pty.fork() failed for unknown reasons." + ##debug("Reading from master_fd now that the child has exited") + ##try: + ## s1 = os.read(master_fd, 1024) + ##except os.error: + ## pass + ##else: + ## raise TestFailed("Read from master_fd did not raise exception") + + os.close(master_fd) # pty.fork() passed. Modified: python/branches/p3yk/Lib/test/test_random.py ============================================================================== --- python/branches/p3yk/Lib/test/test_random.py (original) +++ python/branches/p3yk/Lib/test/test_random.py Wed Jan 10 00:18:33 2007 @@ -180,10 +180,9 @@ def test_bigrand(self): # Verify warnings are raised when randrange is too large for random() - oldfilters = warnings.filters[:] - warnings.filterwarnings("error", "Underlying random") - self.assertRaises(UserWarning, self.gen.randrange, 2**60) - warnings.filters[:] = oldfilters + with test_support.guard_warnings_filter(): + warnings.filterwarnings("error", "Underlying random") + self.assertRaises(UserWarning, self.gen.randrange, 2**60) class SystemRandom_TestBasicOps(TestBasicOps): gen = random.SystemRandom() @@ -441,6 +440,14 @@ self.assertEqual(k, numbits) # note the stronger assertion self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion + def test_randrange_bug_1590891(self): + start = 1000000000000 + stop = -100000000000000000000 + step = -200 + x = self.gen.randrange(start, stop, step) + self.assert_(stop < x <= start) + self.assertEqual((x+stop)%step, 0) + _gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289, 771.3234287757674, -176.6150291498386, 12.50734324009056, -0.1385710331296526, 0.9934937113930748e-05, 0.1659470187408462e-06) Modified: python/branches/p3yk/Lib/test/test_repr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_repr.py (original) +++ python/branches/p3yk/Lib/test/test_repr.py Wed Jan 10 00:18:33 2007 @@ -136,7 +136,6 @@ '> fo, s, + fo.close() + fo = open(test_support.TESTFN, "rb") + self.assertEqual(fo.read(), repr(s)) + finally: + fo.close() + os.remove(test_support.TESTFN) + class TestSet(TestJointOps): thetype = set Modified: python/branches/p3yk/Lib/test/test_struct.py ============================================================================== --- python/branches/p3yk/Lib/test/test_struct.py (original) +++ python/branches/p3yk/Lib/test/test_struct.py Wed Jan 10 00:18:33 2007 @@ -50,22 +50,17 @@ def with_warning_restore(func): def _with_warning_restore(*args, **kw): - # The `warnings` module doesn't have an advertised way to restore - # its filter list. Cheat. - save_warnings_filters = warnings.filters[:] - # Grrr, we need this function to warn every time. Without removing - # the warningregistry, running test_tarfile then test_struct would fail - # on 64-bit platforms. - globals = func.func_globals - if '__warningregistry__' in globals: - del globals['__warningregistry__'] - warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) - warnings.filterwarnings("error", r""".*format requires.*""", - DeprecationWarning) - try: + with test.test_support.guard_warnings_filter(): + # Grrr, we need this function to warn every time. Without removing + # the warningregistry, running test_tarfile then test_struct would fail + # on 64-bit platforms. + globals = func.func_globals + if '__warningregistry__' in globals: + del globals['__warningregistry__'] + warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) + warnings.filterwarnings("error", r""".*format requires.*""", + DeprecationWarning) return func(*args, **kw) - finally: - warnings.filters[:] = save_warnings_filters[:] return _with_warning_restore def deprecated_err(func, *args): Modified: python/branches/p3yk/Lib/test/test_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_support.py (original) +++ python/branches/p3yk/Lib/test/test_support.py Wed Jan 10 00:18:33 2007 @@ -3,7 +3,9 @@ if __name__ != 'test.test_support': raise ImportError, 'test_support must be imported from the test package' +from contextlib import contextmanager import sys +import warnings class Error(Exception): """Base class for regression test exceptions.""" @@ -267,6 +269,48 @@ print >> get_original_stdout(), '\tfetching %s ...' % url fn, _ = urllib.urlretrieve(url, filename) return open(fn) + + at contextmanager +def guard_warnings_filter(): + """Guard the warnings filter from being permanently changed.""" + original_filters = warnings.filters[:] + try: + yield + finally: + warnings.filters = original_filters + +class EnvironmentVarGuard(object): + + """Class to help protect the environment variable properly. Can be used as + a context manager.""" + + def __init__(self): + from os import environ + self._environ = environ + self._unset = set() + self._reset = dict() + + def set(self, envvar, value): + if envvar not in self._environ: + self._unset.add(envvar) + else: + self._reset[envvar] = self._environ[envvar] + self._environ[envvar] = value + + def unset(self, envvar): + if envvar in self._environ: + self._reset[envvar] = self._environ[envvar] + del self._environ[envvar] + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + for envvar, value in self._reset.iteritems(): + self._environ[envvar] = value + for unset in self._unset: + del self._environ[unset] + #======================================================================= # Decorator for running a function in a different locale, correctly resetting Modified: python/branches/p3yk/Lib/test/test_tarfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tarfile.py (original) +++ python/branches/p3yk/Lib/test/test_tarfile.py Wed Jan 10 00:18:33 2007 @@ -110,7 +110,7 @@ """Test seek() method of _FileObject, incl. random reading. """ if self.sep != "|": - filename = "0-REGTYPE" + filename = "0-REGTYPE-TEXT" self.tar.extract(filename, dirname()) f = open(os.path.join(dirname(), filename), "rb") data = f.read() @@ -149,6 +149,16 @@ s2 = fobj.readlines() self.assert_(s1 == s2, "readlines() after seek failed") + fobj.seek(0) + self.assert_(len(fobj.readline()) == fobj.tell(), + "tell() after readline() failed") + fobj.seek(512) + self.assert_(len(fobj.readline()) + 512 == fobj.tell(), + "tell() after seek() and readline() failed") + fobj.seek(0) + line = fobj.readline() + self.assert_(fobj.read() == data[len(line):], + "read() after readline() failed") fobj.close() def test_old_dirtype(self): @@ -280,6 +290,20 @@ else: self.dst.addfile(tarinfo, f) + def test_add_self(self): + dstname = os.path.abspath(self.dstname) + + self.assertEqual(self.dst.name, dstname, "archive name must be absolute") + + self.dst.add(dstname) + self.assertEqual(self.dst.getnames(), [], "added the archive to itself") + + cwd = os.getcwd() + os.chdir(dirname()) + self.dst.add(dstname) + os.chdir(cwd) + self.assertEqual(self.dst.getnames(), [], "added the archive to itself") + class Write100Test(BaseTest): # The name field in a tar header stores strings of at most 100 chars. @@ -601,6 +625,38 @@ self.assertEqual(tarfile.filemode(0755), '-rwxr-xr-x') self.assertEqual(tarfile.filemode(07111), '---s--s--t') +class HeaderErrorTest(unittest.TestCase): + + def test_truncated_header(self): + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "") + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "filename\0") + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 511) + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 513) + + def test_empty_header(self): + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 512) + + def test_invalid_header(self): + buf = tarfile.TarInfo("filename").tobuf() + buf = buf[:148] + "foo\0\0\0\0\0" + buf[156:] # invalid number field. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, buf) + + def test_bad_checksum(self): + buf = tarfile.TarInfo("filename").tobuf() + b = buf[:148] + " " + buf[156:] # clear the checksum field. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b) + b = "a" + buf[1:] # manipulate the buffer, so checksum won't match. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b) + +class OpenFileobjTest(BaseTest): + # Test for SF bug #1496501. + + def test_opener(self): + fobj = StringIO.StringIO("foo\n") + try: + tarfile.open("", "r", fileobj=fobj) + except tarfile.ReadError: + self.assertEqual(fobj.tell(), 0, "fileobj's position has moved") if bz2: # Bzip2 TestCases @@ -646,6 +702,8 @@ tests = [ FileModeTest, + HeaderErrorTest, + OpenFileobjTest, ReadTest, ReadStreamTest, ReadDetectTest, Modified: python/branches/p3yk/Lib/test/test_uu.py ============================================================================== --- python/branches/p3yk/Lib/test/test_uu.py (original) +++ python/branches/p3yk/Lib/test/test_uu.py Wed Jan 10 00:18:33 2007 @@ -114,11 +114,11 @@ def test_encode(self): try: - fin = open(self.tmpin, 'wb') + fin = open(self.tmpin, 'w') fin.write(plaintext) fin.close() - fin = open(self.tmpin, 'rb') + fin = open(self.tmpin, 'r') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() @@ -130,7 +130,7 @@ self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) # in_file and out_file as filenames - uu.encode(self.tmpin, self.tmpout, mode=0644) + uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) fout = open(self.tmpout, 'r') s = fout.read() fout.close() @@ -142,11 +142,11 @@ def test_decode(self): try: - f = open(self.tmpin, 'wb') + f = open(self.tmpin, 'w') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close() - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') uu.decode(f) f.close() @@ -163,11 +163,11 @@ try: f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout)) - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') uu.decode(f) f.close() - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') self.assertRaises(uu.Error, uu.decode, f) f.close() finally: Modified: python/branches/p3yk/Lib/test/test_weakref.py ============================================================================== --- python/branches/p3yk/Lib/test/test_weakref.py (original) +++ python/branches/p3yk/Lib/test/test_weakref.py Wed Jan 10 00:18:33 2007 @@ -189,7 +189,7 @@ # None as the value for the callback, where either means "no # callback". The "no callback" ref and proxy objects are supposed # to be shared so long as they exist by all callers so long as - # they are active. In Python 2.3.3 and earlier, this guaranttee + # they are active. In Python 2.3.3 and earlier, this guarantee # was not honored, and was broken in different ways for # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.) Modified: python/branches/p3yk/Lib/threading.py ============================================================================== --- python/branches/p3yk/Lib/threading.py (original) +++ python/branches/p3yk/Lib/threading.py Wed Jan 10 00:18:33 2007 @@ -636,13 +636,11 @@ _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() - import atexit - atexit.register(self.__exitfunc) def _set_daemon(self): return False - def __exitfunc(self): + def _exitfunc(self): self._Thread__stop() t = _pickSomeNonDaemonThread() if t: @@ -715,9 +713,11 @@ from thread import stack_size -# Create the main thread object +# Create the main thread object, +# and make it available for the interpreter +# (Py_Main) as threading._shutdown. -_MainThread() +_shutdown = _MainThread()._exitfunc # get thread-local implementation, either from the thread # module, or from the python fallback Modified: python/branches/p3yk/Lib/urllib.py ============================================================================== --- python/branches/p3yk/Lib/urllib.py (original) +++ python/branches/p3yk/Lib/urllib.py Wed Jan 10 00:18:33 2007 @@ -405,8 +405,8 @@ h.putheader('Content-Length', '%d' % len(data)) else: h.putrequest('GET', selector) - if proxy_auth: h.putheader('Proxy-Authorization: Basic %s' % proxy_auth) - if auth: h.putheader('Authorization: Basic %s' % auth) + if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth) + if auth: h.putheader('Authorization', 'Basic %s' % auth) if realhost: h.putheader('Host', realhost) for args in self.addheaders: h.putheader(*args) h.endheaders() Modified: python/branches/p3yk/Misc/ACKS ============================================================================== --- python/branches/p3yk/Misc/ACKS (original) +++ python/branches/p3yk/Misc/ACKS Wed Jan 10 00:18:33 2007 @@ -285,6 +285,7 @@ Albert Hofkamp Jonathan Hogg Gerrit Holl +Shane Holloway Rune Holm Philip Homburg Naofumi Honda Modified: python/branches/p3yk/Misc/developers.txt ============================================================================== --- python/branches/p3yk/Misc/developers.txt (original) +++ python/branches/p3yk/Misc/developers.txt Wed Jan 10 00:18:33 2007 @@ -17,6 +17,15 @@ Permissions History ------------------- +- Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python + project 06 Jan 2007, by NCN, as a tracker tech. He will maintain asyncore. + +- Collin Winter was given SVN access on 05 Jan 2007 by NCN, for PEP + update access. + +- Lars Gustaebel was given SVN access on 20 Dec 2006 by NCN, for tarfile.py + related work. + - 2006 Summer of Code entries: SoC developers are expected to work primarily in nondist/sandbox or on a branch of their own, and will have their work reviewed before changes are accepted into the trunk. Modified: python/branches/p3yk/Modules/_bsddb.c ============================================================================== --- python/branches/p3yk/Modules/_bsddb.c (original) +++ python/branches/p3yk/Modules/_bsddb.c Wed Jan 10 00:18:33 2007 @@ -98,7 +98,7 @@ #error "eek! DBVER can't handle minor versions > 9" #endif -#define PY_BSDDB_VERSION "4.4.6" +#define PY_BSDDB_VERSION "4.5.0" static char *rcs_id = "$Id$"; @@ -4127,6 +4127,7 @@ } +#if (DBVER < 45) static PyObject* DBEnv_set_lk_max(DBEnvObject* self, PyObject* args) { @@ -4142,6 +4143,7 @@ RETURN_IF_ERR(); RETURN_NONE(); } +#endif #if (DBVER >= 32) @@ -5231,7 +5233,9 @@ {"set_lg_regionmax",(PyCFunction)DBEnv_set_lg_regionmax, METH_VARARGS}, #endif {"set_lk_detect", (PyCFunction)DBEnv_set_lk_detect, METH_VARARGS}, +#if (DBVER < 45) {"set_lk_max", (PyCFunction)DBEnv_set_lk_max, METH_VARARGS}, +#endif #if (DBVER >= 32) {"set_lk_max_locks", (PyCFunction)DBEnv_set_lk_max_locks, METH_VARARGS}, {"set_lk_max_lockers", (PyCFunction)DBEnv_set_lk_max_lockers, METH_VARARGS}, @@ -5833,7 +5837,9 @@ ADD_INT(d, DB_AFTER); ADD_INT(d, DB_APPEND); ADD_INT(d, DB_BEFORE); +#if (DBVER < 45) ADD_INT(d, DB_CACHED_COUNTS); +#endif #if (DBVER >= 41) _addIntToDict(d, "DB_CHECKPOINT", 0); #else @@ -5868,7 +5874,9 @@ ADD_INT(d, DB_POSITION); ADD_INT(d, DB_PREV); ADD_INT(d, DB_PREV_NODUP); +#if (DBVER < 45) ADD_INT(d, DB_RECORDCOUNT); +#endif ADD_INT(d, DB_SET); ADD_INT(d, DB_SET_RANGE); ADD_INT(d, DB_SET_RECNO); Modified: python/branches/p3yk/Modules/bz2module.c ============================================================================== --- python/branches/p3yk/Modules/bz2module.c (original) +++ python/branches/p3yk/Modules/bz2module.c Wed Jan 10 00:18:33 2007 @@ -989,7 +989,7 @@ char small_buffer[SMALLCHUNK]; char *buffer = small_buffer; size_t buffersize = SMALLCHUNK; - int bytesread = 0; + Py_off_t bytesread = 0; size_t readsize; int chunksize; int bzerror; Modified: python/branches/p3yk/Modules/collectionsmodule.c ============================================================================== --- python/branches/p3yk/Modules/collectionsmodule.c (original) +++ python/branches/p3yk/Modules/collectionsmodule.c Wed Jan 10 00:18:33 2007 @@ -911,15 +911,14 @@ { PyObject *item; - if (it->counter == 0) - return NULL; - if (it->deque->state != it->state) { it->counter = 0; PyErr_SetString(PyExc_RuntimeError, "deque mutated during iteration"); return NULL; } + if (it->counter == 0) + return NULL; assert (!(it->b == it->deque->rightblock && it->index > it->deque->rightindex)); Modified: python/branches/p3yk/Modules/main.c ============================================================================== --- python/branches/p3yk/Modules/main.c (original) +++ python/branches/p3yk/Modules/main.c Wed Jan 10 00:18:33 2007 @@ -175,6 +175,33 @@ return 0; } +/* Wait until threading._shutdown completes, provided + the threading module was imported in the first place. + The shutdown routine will wait until all non-daemon + "threading" threads have completed. */ +#include "abstract.h" +static void +WaitForThreadShutdown(void) +{ +#ifdef WITH_THREAD + PyObject *result; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_shutdown", ""); + if (result == NULL) + PyErr_WriteUnraisable(threading); + else + Py_DECREF(result); + Py_DECREF(threading); +#endif +} + /* Main program */ int @@ -483,6 +510,8 @@ /* XXX */ sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + WaitForThreadShutdown(); + Py_Finalize(); #ifdef RISCOS if (Py_RISCOSWimpFlag) Modified: python/branches/p3yk/Modules/socketmodule.c ============================================================================== --- python/branches/p3yk/Modules/socketmodule.c (original) +++ python/branches/p3yk/Modules/socketmodule.c Wed Jan 10 00:18:33 2007 @@ -2210,7 +2210,7 @@ /* * This is the guts of the recv() and recv_into() methods, which reads into a - * char buffer. If you have any inc/def ref to do to the objects that contain + * char buffer. If you have any inc/dec ref to do to the objects that contain * the buffer, do it in the caller. This function returns the number of bytes * succesfully read. If there was an error, it returns -1. Note that it is * also possible that we return a number of bytes smaller than the request Modified: python/branches/p3yk/Modules/timemodule.c ============================================================================== --- python/branches/p3yk/Modules/timemodule.c (original) +++ python/branches/p3yk/Modules/timemodule.c Wed Jan 10 00:18:33 2007 @@ -659,7 +659,7 @@ time_tzset. In the future, some parts of it can be moved back (for platforms that don't HAVE_WORKING_TZSET, when we know what they are), and the extranious calls to tzset(3) should be removed. - I havn't done this yet, as I don't want to change this code as + I haven't done this yet, as I don't want to change this code as little as possible when introducing the time.tzset and time.tzsetwall methods. This should simply be a method of doing the following once, at the top of this function and removing the call to tzset() from Modified: python/branches/p3yk/Objects/dictnotes.txt ============================================================================== --- python/branches/p3yk/Objects/dictnotes.txt (original) +++ python/branches/p3yk/Objects/dictnotes.txt Wed Jan 10 00:18:33 2007 @@ -44,7 +44,7 @@ d.setdefault(word, []).append(pagenumber) Note, the second example is a use case characterized by a get and set - to the same key. There are similar used cases with a __contains__ + to the same key. There are similar use cases with a __contains__ followed by a get, set, or del to the same key. Part of the justification for d.setdefault is combining the two lookups into one. Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Wed Jan 10 00:18:33 2007 @@ -573,8 +573,17 @@ char *emit = ""; /* No separator emitted on first pass */ char *separator = ", "; int literalform = 0; + int status = Py_ReprEnter((PyObject*)so); + + if (status != 0) { + if (status < 0) + return status; + fprintf(fp, "%s(...)", so->ob_type->tp_name); + return 0; + } if (!so->used) { + Py_ReprLeave((PyObject*)so); fprintf(fp, "%s()", so->ob_type->tp_name); return 0; } @@ -587,32 +596,44 @@ while (set_next(so, &pos, &entry)) { fputs(emit, fp); emit = separator; - if (PyObject_Print(entry->key, fp, 0) != 0) + if (PyObject_Print(entry->key, fp, 0) != 0) { + Py_ReprLeave((PyObject*)so); return -1; + } } if (literalform) fputs("}", fp); else fputs("])", fp); + Py_ReprLeave((PyObject*)so); return 0; } static PyObject * set_repr(PySetObject *so) { - PyObject *keys, *result, *listrepr; + PyObject *keys, *result=NULL, *listrepr; + int status = Py_ReprEnter((PyObject*)so); + + if (status != 0) { + if (status < 0) + return NULL; + return PyString_FromFormat("%s(...)", so->ob_type->tp_name); + } /* shortcut for the empty set */ - if (!so->used) + if (!so->used) { + Py_ReprLeave((PyObject*)so); return PyString_FromFormat("%s()", so->ob_type->tp_name); + } keys = PySequence_List((PyObject *)so); if (keys == NULL) - return NULL; + goto done; listrepr = PyObject_Repr(keys); Py_DECREF(keys); if (listrepr == NULL) - return NULL; + goto done; if (so->ob_type == &PySet_Type) { char *s = PyString_AS_STRING(listrepr); @@ -624,6 +645,8 @@ PyString_AS_STRING(listrepr)); } Py_DECREF(listrepr); +done: + Py_ReprLeave((PyObject*)so); return result; } Modified: python/branches/p3yk/PC/python_nt.rc ============================================================================== --- python/branches/p3yk/PC/python_nt.rc (original) +++ python/branches/p3yk/PC/python_nt.rc Wed Jan 10 00:18:33 2007 @@ -61,7 +61,7 @@ VALUE "FileDescription", "Python Core\0" VALUE "FileVersion", PYTHON_VERSION VALUE "InternalName", "Python DLL\0" - VALUE "LegalCopyright", "Copyright ? 2001-2006 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" + VALUE "LegalCopyright", "Copyright ? 2001-2007 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" VALUE "OriginalFilename", PYTHON_DLL_NAME "\0" VALUE "ProductName", "Python\0" VALUE "ProductVersion", PYTHON_VERSION Modified: python/branches/p3yk/PCbuild/python20.wse ============================================================================== --- python/branches/p3yk/PCbuild/python20.wse (original) +++ python/branches/p3yk/PCbuild/python20.wse Wed Jan 10 00:18:33 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/branches/p3yk/PCbuild8/python20.wse ============================================================================== --- python/branches/p3yk/PCbuild8/python20.wse (original) +++ python/branches/p3yk/PCbuild8/python20.wse Wed Jan 10 00:18:33 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Wed Jan 10 00:18:33 2007 @@ -738,7 +738,16 @@ this wasn't always true before 2.3! PyFrame_New now sets f->f_lasti to -1 (i.e. the index *before* the first instruction) and YIELD_VALUE doesn't fiddle with f_lasti any more. So this - does work. Promise. */ + does work. Promise. + + When the PREDICT() macros are enabled, some opcode pairs follow in + direct succession without updating f->f_lasti. A successful + prediction effectively links the two codes together as if they + were a single new opcode; accordingly,f->f_lasti will point to + the first code in the pair (for instance, GET_ITER followed by + FOR_ITER is effectively a single opcode and f->f_lasti will point + at to the beginning of the combined pair.) + */ next_instr = first_instr + f->f_lasti + 1; stack_pointer = f->f_stacktop; assert(stack_pointer != NULL); Modified: python/branches/p3yk/Python/errors.c ============================================================================== --- python/branches/p3yk/Python/errors.c (original) +++ python/branches/p3yk/Python/errors.c Wed Jan 10 00:18:33 2007 @@ -649,7 +649,8 @@ if (warnings_module != NULL) { dict = PyModule_GetDict(warnings_module); - func = PyDict_GetItemString(dict, "warn"); + if (dict != NULL) + func = PyDict_GetItemString(dict, "warn"); } if (func == NULL) { PySys_WriteStderr("warning: %s\n", message); Modified: python/branches/p3yk/Python/getcopyright.c ============================================================================== --- python/branches/p3yk/Python/getcopyright.c (original) +++ python/branches/p3yk/Python/getcopyright.c Wed Jan 10 00:18:33 2007 @@ -4,7 +4,7 @@ static char cprt[] = "\ -Copyright (c) 2001-2006 Python Software Foundation.\n\ +Copyright (c) 2001-2007 Python Software Foundation.\n\ All Rights Reserved.\n\ \n\ Copyright (c) 2000 BeOpen.com.\n\ Modified: python/branches/p3yk/README ============================================================================== --- python/branches/p3yk/README (original) +++ python/branches/p3yk/README Wed Jan 10 00:18:33 2007 @@ -1,7 +1,8 @@ This is Python 3000 -- unversioned (branched off 2.5 in various beta stages) ================================================================= -Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 +Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Wed Jan 10 00:18:33 2007 @@ -606,7 +606,7 @@ # a release. Most open source OSes come with one or more # versions of BerkeleyDB already installed. - max_db_ver = (4, 4) + max_db_ver = (4, 5) min_db_ver = (3, 3) db_setup_debug = False # verbose debug prints from this script? @@ -623,7 +623,7 @@ '/sw/include/db3', ] # 4.x minor number specific paths - for x in (0,1,2,3,4): + for x in (0,1,2,3,4,5): db_inc_paths.append('/usr/include/db4%d' % x) db_inc_paths.append('/usr/include/db4.%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x) @@ -631,7 +631,7 @@ db_inc_paths.append('/pkg/db-4.%d/include' % x) db_inc_paths.append('/opt/db-4.%d/include' % x) # 3.x minor number specific paths - for x in (2,3): + for x in (3,): db_inc_paths.append('/usr/include/db3%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x) db_inc_paths.append('/usr/local/include/db3%d' % x) From python-checkins at python.org Wed Jan 10 00:21:29 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 10 Jan 2007 00:21:29 +0100 (CET) Subject: [Python-checkins] r53333 - in python/branches/bcannon-objcap: Lib/importlib.py Message-ID: <20070109232129.C9E541E4007@bag.python.org> Author: brett.cannon Date: Wed Jan 10 00:21:29 2007 New Revision: 53333 Added: python/branches/bcannon-objcap/Lib/importlib.py (contents, props changed) Modified: python/branches/bcannon-objcap/ (props changed) Log: Fix screw-up in adding importlib from the sandbox as an external definition. Also create a symlink in Lib for the module. Added: python/branches/bcannon-objcap/Lib/importlib.py ============================================================================== --- (empty file) +++ python/branches/bcannon-objcap/Lib/importlib.py Wed Jan 10 00:21:29 2007 @@ -0,0 +1 @@ +link ../importlib/importlib.py \ No newline at end of file From python-checkins at python.org Wed Jan 10 00:34:33 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 10 Jan 2007 00:34:33 +0100 (CET) Subject: [Python-checkins] r53334 - python/branches/bcannon-objcap/BRANCHNEWS Message-ID: <20070109233433.BB7661E4007@bag.python.org> Author: brett.cannon Date: Wed Jan 10 00:34:33 2007 New Revision: 53334 Modified: python/branches/bcannon-objcap/BRANCHNEWS Log: Add comment about the external definition for importlib. Also note that ``svn blame`` can be used to figure out when a comment was added (and thus what revision it pertains to). Modified: python/branches/bcannon-objcap/BRANCHNEWS ============================================================================== --- python/branches/bcannon-objcap/BRANCHNEWS (original) +++ python/branches/bcannon-objcap/BRANCHNEWS Wed Jan 10 00:34:33 2007 @@ -2,6 +2,9 @@ Branch News +++++++++++ +If a comment lacks an explicit revision number then use ``svn blame`` on this +file to find out what revision number introduced the feature. + Core and builtins ----------------- @@ -41,3 +44,9 @@ * rev. 51880: Add access to the 'sys' modules data dict to Interpreter objects. * rev. 51875: Introduced the interpreter module. + + +Library +------- + +* rev. 53333: External definition of importlib (from the sandbox) added. From python-checkins at python.org Wed Jan 10 02:30:34 2007 From: python-checkins at python.org (guido.van.rossum) Date: Wed, 10 Jan 2007 02:30:34 +0100 (CET) Subject: [Python-checkins] r53337 - peps/trunk/pep-3100.txt Message-ID: <20070110013034.833DF1E4008@bag.python.org> Author: guido.van.rossum Date: Wed Jan 10 02:30:33 2007 New Revision: 53337 Modified: peps/trunk/pep-3100.txt Log: Note that the sets module has been removed. Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Wed Jan 10 02:30:33 2007 @@ -199,6 +199,7 @@ To be removed: +* The sets module. [done] * stdlib modules to be removed + see docstrings and comments in the source - ``macfs``, ``new``, ``reconvert``, ``stringold``, ``xmllib``, From python-checkins at python.org Wed Jan 10 02:40:18 2007 From: python-checkins at python.org (guido.van.rossum) Date: Wed, 10 Jan 2007 02:40:18 +0100 (CET) Subject: [Python-checkins] r53338 - sandbox/trunk/2to3/fixes/fix_except.py Message-ID: <20070110014018.673821E4008@bag.python.org> Author: guido.van.rossum Date: Wed Jan 10 02:40:17 2007 New Revision: 53338 Modified: sandbox/trunk/2to3/fixes/fix_except.py Log: Patch by Collin Winter: Python 2 excepts could take the form except E,V: (no space) That doesn't work for the new version. Modified: sandbox/trunk/2to3/fixes/fix_except.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_except.py (original) +++ sandbox/trunk/2to3/fixes/fix_except.py Wed Jan 10 02:40:17 2007 @@ -35,7 +35,12 @@ return node as_leaf = pytree.Leaf(token.NAME, "as") - as_leaf.set_prefix(' ') + as_leaf.set_prefix(" ") + + # Python 2 excepts could take the form except E,V: (no space) + # That doesn't work for the new version + if not b.get_prefix(): + b.set_prefix(" ") new = pytree.Node(syms.except_clause, [pytree.Leaf(token.NAME, "except"), From python-checkins at python.org Wed Jan 10 04:39:54 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 10 Jan 2007 04:39:54 +0100 (CET) Subject: [Python-checkins] r53339 - peps/trunk/pep-3108.txt Message-ID: <20070110033954.93AE61E4009@bag.python.org> Author: brett.cannon Date: Wed Jan 10 04:39:53 2007 New Revision: 53339 Modified: peps/trunk/pep-3108.txt Log: 'sets' module was removed from Py3K, so remove all mention of it. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 10 04:39:53 2007 @@ -515,13 +515,11 @@ + heapq + Queue - + sets + UserDist (?) + UserList (?) * Python implementations of built-in data types - + sets + UserDict + UserList + UserString From python-checkins at python.org Wed Jan 10 17:13:41 2007 From: python-checkins at python.org (gustavo.niemeyer) Date: Wed, 10 Jan 2007 17:13:41 +0100 (CET) Subject: [Python-checkins] r53340 - python/trunk/Objects/intobject.c Message-ID: <20070110161341.744681E400B@bag.python.org> Author: gustavo.niemeyer Date: Wed Jan 10 17:13:40 2007 New Revision: 53340 Modified: python/trunk/Objects/intobject.c Log: 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. Modified: python/trunk/Objects/intobject.c ============================================================================== --- python/trunk/Objects/intobject.c (original) +++ python/trunk/Objects/intobject.c Wed Jan 10 17:13:40 2007 @@ -1070,8 +1070,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*/ From python-checkins at python.org Wed Jan 10 17:15:49 2007 From: python-checkins at python.org (gustavo.niemeyer) Date: Wed, 10 Jan 2007 17:15:49 +0100 (CET) Subject: [Python-checkins] r53341 - python/trunk/Objects/intobject.c Message-ID: <20070110161549.32B0A1E4026@bag.python.org> Author: gustavo.niemeyer Date: Wed Jan 10 17:15:48 2007 New Revision: 53341 Modified: python/trunk/Objects/intobject.c Log: Minor change in int() docstring for proper spacing. Modified: python/trunk/Objects/intobject.c ============================================================================== --- python/trunk/Objects/intobject.c (original) +++ python/trunk/Objects/intobject.c Wed Jan 10 17:15:48 2007 @@ -1070,7 +1070,7 @@ 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 base is zero, the proper base is guessed based on the\n\ +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."); From python-checkins at python.org Wed Jan 10 17:21:49 2007 From: python-checkins at python.org (georg.brandl) Date: Wed, 10 Jan 2007 17:21:49 +0100 (CET) Subject: [Python-checkins] r53343 - peps/trunk/pep-3100.txt Message-ID: <20070110162149.AD9791E4014@bag.python.org> Author: georg.brandl Date: Wed Jan 10 17:21:49 2007 New Revision: 53343 Modified: peps/trunk/pep-3100.txt Log: Reference markup fix. Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Wed Jan 10 17:21:49 2007 @@ -65,7 +65,7 @@ * True division becomes default behavior [#pep238]_ [done] * ``exec`` as a statement is not worth it -- make it a function [done] -* (Maybe) add optional declarations for static typing [#pep3107] [10]_ +* (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]_ * Use ``except E1, E2, E3 as err:`` if you want the error variable. [3]_ From buildbot at python.org Wed Jan 10 18:05:08 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 17:05:08 +0000 Subject: [Python-checkins] buildbot failure in x86 cygwin trunk Message-ID: <20070110170508.60C3B1E4014@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/2 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: gustavo.niemeyer BUILD FAILED: failed failed slave lost sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 19:17:39 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 18:17:39 +0000 Subject: [Python-checkins] buildbot warnings in alpha Debian trunk Message-ID: <20070110181739.EF69E1E400A@bag.python.org> The Buildbot has detected a new failure of alpha Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Debian%2520trunk/builds/2 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: gustavo.niemeyer Build had warnings: warnings failed slave lost sincerely, -The Buildbot From python-checkins at python.org Wed Jan 10 19:59:30 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 10 Jan 2007 19:59:30 +0100 (CET) Subject: [Python-checkins] r53350 - peps/trunk/pep-0004.txt Message-ID: <20070110185930.CCDB71E400A@bag.python.org> Author: brett.cannon Date: Wed Jan 10 19:59:30 2007 New Revision: 53350 Modified: peps/trunk/pep-0004.txt Log: Fix a typo. Modified: peps/trunk/pep-0004.txt ============================================================================== --- peps/trunk/pep-0004.txt (original) +++ peps/trunk/pep-0004.txt Wed Jan 10 19:59:30 2007 @@ -71,7 +71,7 @@ All these modules have been declared as obsolete in Python 2.0, some even earlier. - The following obsolte modules were removed in Python 2.5: + The following obsolete modules were removed in Python 2.5: addpack, cmp, cmpcache, codehack, dircmp, dump, find, fmt, grep, lockfile, newdir, ni, packmail, Para, poly, From python-checkins at python.org Wed Jan 10 20:01:48 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 10 Jan 2007 20:01:48 +0100 (CET) Subject: [Python-checkins] r53351 - peps/trunk/pep-3100.txt Message-ID: <20070110190148.22B291E400A@bag.python.org> Author: brett.cannon Date: Wed Jan 10 20:01:46 2007 New Revision: 53351 Modified: peps/trunk/pep-3100.txt Log: Add a missing comma. Modified: peps/trunk/pep-3100.txt ============================================================================== --- peps/trunk/pep-3100.txt (original) +++ peps/trunk/pep-3100.txt Wed Jan 10 20:01:46 2007 @@ -206,7 +206,7 @@ ``pcre``, ``pypcre``, ``strop`` + see PEP 4 [#pep4]_ - ``posixfile``, ``pre``, ``regsub``, ``rfc822``, - ``statcache``, ``string``, ``TERMIOS`` ``mimetools``, + ``statcache``, ``string``, ``TERMIOS``, ``mimetools``, ``MimeWriter``, ``mimify``, ``mpz``, ``rgbimage`` + Everything in lib-old [#pep4]_ - ``Para``, ``addpack``, ``cmp``, ``cmpcache``, ``codehack``, From python-checkins at python.org Wed Jan 10 20:30:05 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 10 Jan 2007 20:30:05 +0100 (CET) Subject: [Python-checkins] r53355 - peps/trunk/pep-3108.txt Message-ID: <20070110193005.EE6FE1E400C@bag.python.org> Author: brett.cannon Date: Wed Jan 10 20:30:05 2007 New Revision: 53355 Modified: peps/trunk/pep-3108.txt Log: Clean up the discussion of the removal of modules based on PEP 4 or documentation (a discrepency that will hopefully get fixed soon). Part of the clean up is to no longer explicitly list modules slated for removal that are mentioned in PEP 4 so as to not keep a duplicate copy of that list. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 10 20:30:05 2007 @@ -54,29 +54,28 @@ Previously deprecated --------------------- -Modules in this section have been deprecated at some point in the -Python 2.x release series but are currently still distributed with -Python. Deprecation information is gathered either from PEP 4 or the -Global Module Index [#pep-0004]_, [#module-index]_. Each module is -listed with the Python version of initial deprecation. - -============== ========== -Module Deprecated -============== ========== -buildtools 2.3 -cfmfile 2.4 -gopherlib 2.5 -macfs 2.3 -md5 2.5 -mimetools 2.3 -MimeWriter 2.3 -mimefy 2.3 -multifile 2.3 -posixfile 1.5 -rfc822 2.3 -rgbimg 2.5 -sha 2.5 -============== ========== +PEP 4 lists all modules that have been deprecated in the stdlib +[#pep-0004]_. All modules listed in the PEP at the time of the first +alpha release of Python 3.0 will be removed. + +The entire contents of libold will also be removed. These modules +have already been removed from being imported but are kept in the +distribution for Python for users that rely upon the code. + +On top of the modules listed in PEP 4, other modules have been +documented as deprecated but have yet to be added to PEP 4. + +============== ========== +Module Deprecated +============== ========== +buildtools 2.3 +cfmfile 2.4 +macfs 2.3 +md5 2.5 +sha 2.5 +strop unknown +xmllib unknown +============== ========== Platform-specific with minimal use @@ -134,13 +133,6 @@ - Third-party libraries provide better support (Python Imaging Library [#pil]_). - + sv - - - Wrapper for Indigo video card. - - Harware is no longer manufactured. - - Undocumented. - - Code not uniquely edited in 13 years. - * Solaris + SUNAUDIODEV/sunaudiodev @@ -228,6 +220,13 @@ + String slicing and string interpolation can do similar work. + Used by pdb, but do not need to expose API. +* stringold + + + Function versions of the methods on string objects. + + Obsolete since Python 1.6. + + Any functionality not in the string object or module will be moved + to the string module (mostly constants). + * symtable/_symtable + Undocumented. @@ -246,6 +245,8 @@ + Just a rebinding of names from the 'types' module. + Can also call ``type`` built-in to get most types easily. + + Docstring states the module is no longer useful as of revision + 27241 (2002-06-15). * pure @@ -312,11 +313,6 @@ + ``os.statvfs`` now returns a tuple with attributes. -* strop - - + Implements functions used by 'string' module that have now - become methods on the str type. - * thread + People should use 'threading' instead. @@ -328,11 +324,6 @@ + Guido has previously supported the deprecation [#thread-deprecation]_. -* timing - - + Use timeit or time. - + Documentation says the module is obsolete [#timing-module]_. - Modules to Rename ================= From python-checkins at python.org Wed Jan 10 20:57:10 2007 From: python-checkins at python.org (brett.cannon) Date: Wed, 10 Jan 2007 20:57:10 +0100 (CET) Subject: [Python-checkins] r53356 - peps/trunk/pep-3108.txt Message-ID: <20070110195710.E23731E400A@bag.python.org> Author: brett.cannon Date: Wed Jan 10 20:57:10 2007 New Revision: 53356 Modified: peps/trunk/pep-3108.txt Log: Add sqlite3 to the suggested database package. Also comment that the servers package could be broken up separately into socket and HTTP server packages. Modified: peps/trunk/pep-3108.txt ============================================================================== --- peps/trunk/pep-3108.txt (original) +++ peps/trunk/pep-3108.txt Wed Jan 10 20:57:10 2007 @@ -567,6 +567,7 @@ + bsddb + dumbdbm + gdbm + + sqlite3 + whichdb * Audio @@ -611,7 +612,7 @@ + webbrowser + wsgiref -* Servers +* Servers (each sub-grouping can be their own package) + HTTP From python-checkins at python.org Wed Jan 10 21:07:30 2007 From: python-checkins at python.org (thomas.heller) Date: Wed, 10 Jan 2007 21:07:30 +0100 (CET) Subject: [Python-checkins] r53357 - in python/branches/release25-maint: Lib/ctypes/__init__.py Misc/NEWS Message-ID: <20070110200730.CCFCF1E401C@bag.python.org> Author: thomas.heller Date: Wed Jan 10 21:07:29 2007 New Revision: 53357 Modified: python/branches/release25-maint/Lib/ctypes/__init__.py python/branches/release25-maint/Misc/NEWS Log: Change the ctypes version number to "1.0.2". Modified: python/branches/release25-maint/Lib/ctypes/__init__.py ============================================================================== --- python/branches/release25-maint/Lib/ctypes/__init__.py (original) +++ python/branches/release25-maint/Lib/ctypes/__init__.py Wed Jan 10 21:07:29 2007 @@ -5,7 +5,7 @@ import os as _os, sys as _sys -__version__ = "1.0.1" +__version__ = "1.0.2" from _ctypes import Union, Structure, Array from _ctypes import _Pointer Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Wed Jan 10 21:07:29 2007 @@ -89,6 +89,8 @@ Extension Modules ----------------- +- The version number of the ctypes package was changed to "1.0.2". + - Patch #1544279: Improve thread-safety of the socket module by moving the sock_addr_t storage out of the socket object. From python-checkins at python.org Wed Jan 10 21:12:13 2007 From: python-checkins at python.org (thomas.heller) Date: Wed, 10 Jan 2007 21:12:13 +0100 (CET) Subject: [Python-checkins] r53358 - in python/trunk: Lib/ctypes/__init__.py Misc/NEWS Message-ID: <20070110201213.E2FF11E400A@bag.python.org> Author: thomas.heller Date: Wed Jan 10 21:12:13 2007 New Revision: 53358 Modified: python/trunk/Lib/ctypes/__init__.py python/trunk/Misc/NEWS Log: Change the ctypes version number to "1.1.0". Modified: python/trunk/Lib/ctypes/__init__.py ============================================================================== --- python/trunk/Lib/ctypes/__init__.py (original) +++ python/trunk/Lib/ctypes/__init__.py Wed Jan 10 21:12:13 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 Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed Jan 10 21:12:13 2007 @@ -109,6 +109,8 @@ Library ------- +- The version number of the ctypes package changed to "1.1.0". + - Bug #1627575: logging: 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". From buildbot at python.org Wed Jan 10 21:17:24 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:17:24 +0000 Subject: [Python-checkins] buildbot failure in x86 Ubuntu edgy (icc) 2.5 Message-ID: <20070110201724.65F111E400A@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/135 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller BUILD FAILED: failed failed slave lost sincerely, -The Buildbot From python-checkins at python.org Wed Jan 10 21:24:14 2007 From: python-checkins at python.org (georg.brandl) Date: Wed, 10 Jan 2007 21:24:14 +0100 (CET) Subject: [Python-checkins] r53359 - peps/trunk/pep-3099.txt Message-ID: <20070110202414.7D4851E400A@bag.python.org> Author: georg.brandl Date: Wed Jan 10 21:24:13 2007 New Revision: 53359 Modified: peps/trunk/pep-3099.txt Log: Patch #1627052 (backticks in PEP3099). Modified: peps/trunk/pep-3099.txt ============================================================================== --- peps/trunk/pep-3099.txt (original) +++ peps/trunk/pep-3099.txt Wed Jan 10 21:24:13 2007 @@ -120,6 +120,17 @@ list. Do ``from __future__ import braces`` to get a definitive answer on this subject. +* No more backticks. + + Backticks (\`) will no longer be used as shorthand for ``repr`` -- + but that doesn't mean they are available for other uses. Even + ignoring the backwards compatibility confusion, the character + itself causes too many problems (in some fonts, on some keyboards, + when typesetting a book, etc). + + Thread: "new operators via backquoting", + http://mail.python.org/pipermail/python-ideas/2007-January/000054.html + * Referencing the global name ``foo`` will not be spelled ``globals.foo``. The ``global`` statement will stay. From buildbot at python.org Wed Jan 10 21:31:26 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:31:26 +0000 Subject: [Python-checkins] buildbot warnings in amd64 gentoo 2.5 Message-ID: <20070110203126.9CB5F1E400A@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/169 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/home/buildslave/buildslave/python/2.5.norwitz-amd64/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/home/buildslave/buildslave/python/2.5.norwitz-amd64/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildslave/buildslave/python/2.5.norwitz-amd64/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/home/buildslave/buildslave/python/2.5.norwitz-amd64/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:31:56 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:31:56 +0000 Subject: [Python-checkins] buildbot warnings in x86 gentoo 2.5 Message-ID: <20070110203156.767991E400A@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/168 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller 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') 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') 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') 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') 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') 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/home/buildslave/python-trunk/2.5.norwitz-x86/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:31:56 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:31:56 +0000 Subject: [Python-checkins] buildbot warnings in x86 mvlgcc 2.5 Message-ID: <20070110203156.8D4E01E400B@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/80 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/home2/buildbot/slave/2.5.loewis-linux/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/home2/buildbot/slave/2.5.loewis-linux/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home2/buildbot/slave/2.5.loewis-linux/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/home2/buildbot/slave/2.5.loewis-linux/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:33:56 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:33:56 +0000 Subject: [Python-checkins] buildbot warnings in x86 W2k 2.5 Message-ID: <20070110203356.E47C71E400A@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/0 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "../lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "C:\trentm\data\buildbot\python-slave\2.5.mick-windows\build\lib\test\test_ctypes.py", line 4, in import ctypes.test File "C:\trentm\data\buildbot\python-slave\2.5.mick-windows\build\lib\ctypes\__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\trentm\data\buildbot\python-slave\2.5.mick-windows\build\lib\test\test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "C:\trentm\data\buildbot\python-slave\2.5.mick-windows\build\lib\ctypes\__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:43:02 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:43:02 +0000 Subject: [Python-checkins] buildbot warnings in x86 OpenBSD 2.5 Message-ID: <20070110204302.F2FD51E400A@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/149 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/home/buildbot/buildarea/2.5.cortesi/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/home/buildbot/buildarea/2.5.cortesi/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildbot/buildarea/2.5.cortesi/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/home/buildbot/buildarea/2.5.cortesi/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From python-checkins at python.org Wed Jan 10 21:44:21 2007 From: python-checkins at python.org (thomas.heller) Date: Wed, 10 Jan 2007 21:44:21 +0100 (CET) Subject: [Python-checkins] r53360 - python/branches/release25-maint/Modules/_ctypes/_ctypes.c Message-ID: <20070110204421.CBB871E400A@bag.python.org> Author: thomas.heller Date: Wed Jan 10 21:44:21 2007 New Revision: 53360 Modified: python/branches/release25-maint/Modules/_ctypes/_ctypes.c Log: Must update the version number on the extension module as well. Modified: python/branches/release25-maint/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/release25-maint/Modules/_ctypes/_ctypes.c (original) +++ python/branches/release25-maint/Modules/_ctypes/_ctypes.c Wed Jan 10 21:44:21 2007 @@ -4744,7 +4744,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.0.2"); PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); From buildbot at python.org Wed Jan 10 21:45:08 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:45:08 +0000 Subject: [Python-checkins] buildbot warnings in ppc Debian unstable 2.5 Message-ID: <20070110204508.BF8491E4011@bag.python.org> The Buildbot has detected a new failure of ppc Debian unstable 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/ppc%2520Debian%2520unstable%25202.5/builds/0 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/home/pybot/buildarea/2.5.klose-debian-ppc/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/home/pybot/buildarea/2.5.klose-debian-ppc/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pybot/buildarea/2.5.klose-debian-ppc/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/home/pybot/buildarea/2.5.klose-debian-ppc/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:46:49 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:46:49 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian 2.5 Message-ID: <20070110204650.059C11E400A@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/0 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/home/pybot/buildarea64/2.5.klose-debian-ppc64/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/home/pybot/buildarea64/2.5.klose-debian-ppc64/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/pybot/buildarea64/2.5.klose-debian-ppc64/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/home/pybot/buildarea64/2.5.klose-debian-ppc64/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:49:47 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:49:47 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP 2.5 Message-ID: <20070110204947.84B751E400A@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/71 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "../lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "C:\buildbot_py25\2.5.mcintyre-windows\build\lib\test\test_ctypes.py", line 4, in import ctypes.test File "C:\buildbot_py25\2.5.mcintyre-windows\build\lib\ctypes\__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\buildbot_py25\2.5.mcintyre-windows\build\lib\test\test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "C:\buildbot_py25\2.5.mcintyre-windows\build\lib\ctypes\__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:50:23 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:50:23 +0000 Subject: [Python-checkins] buildbot warnings in x86 gentoo trunk Message-ID: <20070110205023.A78E11E4019@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/1833 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.1.0', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/home/buildslave/python-trunk/trunk.norwitz-x86/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.1.0', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:50:39 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:50:39 +0000 Subject: [Python-checkins] buildbot warnings in amd64 gentoo trunk Message-ID: <20070110205039.3C67A1E4017@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/1751 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.1.0', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/home/buildslave/buildslave/python/trunk.norwitz-amd64/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.1.0', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:50:41 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:50:41 +0000 Subject: [Python-checkins] buildbot warnings in sparc solaris10 gcc 2.5 Message-ID: <20070110205042.4C7931E400A@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/161 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/opt/users/buildbot/slave/2.5.loewis-sun/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/opt/users/buildbot/slave/2.5.loewis-sun/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/users/buildbot/slave/2.5.loewis-sun/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/opt/users/buildbot/slave/2.5.loewis-sun/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From python-checkins at python.org Wed Jan 10 21:51:20 2007 From: python-checkins at python.org (thomas.heller) Date: Wed, 10 Jan 2007 21:51:20 +0100 (CET) Subject: [Python-checkins] r53361 - python/trunk/Modules/_ctypes/_ctypes.c Message-ID: <20070110205120.093F71E400D@bag.python.org> Author: thomas.heller Date: Wed Jan 10 21:51:19 2007 New Revision: 53361 Modified: python/trunk/Modules/_ctypes/_ctypes.c Log: Must change the version number in the _ctypes extension as well. Modified: python/trunk/Modules/_ctypes/_ctypes.c ============================================================================== --- python/trunk/Modules/_ctypes/_ctypes.c (original) +++ python/trunk/Modules/_ctypes/_ctypes.c Wed Jan 10 21:51:19 2007 @@ -4751,7 +4751,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)); From buildbot at python.org Wed Jan 10 21:51:38 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:51:38 +0000 Subject: [Python-checkins] buildbot warnings in x86 mvlgcc trunk Message-ID: <20070110205138.825FD1E400A@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/157 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: Traceback (most recent call last): File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home2/buildbot/slave/trunk.loewis-linux/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 "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/threading.py", line 460, in __bootstrap self.run() File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/bsddb/test/test_thread.py", line 281, in readerThread rec = dbutils.DeadlockWrap(c.next, max_retries=10) File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) DBLockDeadlockError: (-30995, 'DB_LOCK_DEADLOCK: Locker killed to resolve a deadlock') 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.1.0', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/home2/buildbot/slave/trunk.loewis-linux/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.1.0', '1.0.1') sincerely, -The Buildbot From buildbot at python.org Wed Jan 10 21:52:13 2007 From: buildbot at python.org (buildbot at python.org) Date: Wed, 10 Jan 2007 20:52:13 +0000 Subject: [Python-checkins] buildbot warnings in g4 osx.4 2.5 Message-ID: <20070110205213.C23C61E400A@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/160 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_ctypes test_threading Traceback (most recent call last): File "./Lib/test/regrtest.py", line 546, in runtest_inner the_package = __import__(abstest, globals(), locals(), []) File "/Users/buildslave/bb/2.5.psf-g4/build/Lib/test/test_ctypes.py", line 4, in import ctypes.test File "/Users/buildslave/bb/2.5.psf-g4/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') ====================================================================== ERROR: test_PyThreadState_SetAsyncExc (test.test_threading.ThreadTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/buildslave/bb/2.5.psf-g4/build/Lib/test/test_threading.py", line 138, in test_PyThreadState_SetAsyncExc import ctypes File "/Users/buildslave/bb/2.5.psf-g4/build/Lib/ctypes/__init__.py", line 20, in raise Exception, ("Version number mismatch", __version__, _ctypes_version) Exception: ('Version number mismatch', '1.0.2', '1.0.1') sincerely, -The Buildbot From python-checkins at python.org Thu Jan 11 00:12:57 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 11 Jan 2007 00:12:57 +0100 (CET) Subject: [Python-checkins] r53362 - python/trunk/Lib/BaseHTTPServer.py Message-ID: <20070110231257.97B1A1E400A@bag.python.org> Author: guido.van.rossum Date: Thu Jan 11 00:12:56 2007 New Revision: 53362 Modified: python/trunk/Lib/BaseHTTPServer.py Log: Fix the signature of log_error(). (A subclass that did the right thing was getting complaints from pychecker.) Modified: python/trunk/Lib/BaseHTTPServer.py ============================================================================== --- python/trunk/Lib/BaseHTTPServer.py (original) +++ python/trunk/Lib/BaseHTTPServer.py Thu Jan 11 00:12:56 2007 @@ -396,7 +396,7 @@ self.log_message('"%s" %s %s', self.requestline, str(code), str(size)) - def log_error(self, *args): + def log_error(self, format, *args): """Log an error. This is called when a request cannot be fulfilled. By @@ -408,7 +408,7 @@ """ - self.log_message(*args) + self.log_message(format, *args) def log_message(self, format, *args): """Log an arbitrary message. From python-checkins at python.org Thu Jan 11 00:21:50 2007 From: python-checkins at python.org (thomas.wouters) Date: Thu, 11 Jan 2007 00:21:50 +0100 (CET) Subject: [Python-checkins] r53363 - in python/branches/p3yk-noslice: Doc/README Doc/api/newtypes.tex Doc/howto/functional.rst Doc/html/style.css Doc/lib/libbsddb.tex Doc/lib/libbz2.tex Doc/lib/libctypes.tex Doc/lib/libfuncs.tex Doc/lib/liblogging.tex Doc/lib/libmmap.tex Doc/lib/libsimplexmlrpc.tex Doc/lib/libsocket.tex Doc/lib/libsqlite3.tex Doc/lib/libstdtypes.tex Doc/lib/libsys.tex Doc/lib/libtarfile.tex Doc/lib/libtest.tex Doc/lib/liburlparse.tex Doc/mac/toolbox.tex Doc/perl/python.perl Doc/tut/tut.tex Doc/whatsnew/whatsnew25.tex Grammar/Grammar Include/Python-ast.h Include/Python.h Include/floatobject.h Include/funcobject.h Include/graminit.h Include/pyport.h Include/stringobject.h Include/token.h LICENSE Lib/CGIHTTPServer.py Lib/SimpleHTTPServer.py Lib/StringIO.py Lib/bsddb/dbobj.py Lib/bsddb/test/test_1413192.py Lib/bsddb/test/test_associate.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_dbobj.py Lib/bsddb/test/test_dbshelve.py Lib/bsddb/test/test_dbtables.py Lib/bsddb/test/test_env_close.py Lib/bsddb/test/test_join.py Lib/bsddb/test/test_lock.py Lib/bsddb/test/test_misc.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_thread.py Lib/compiler/ast.py Lib/compiler/pyassem.py Lib/compiler/pycodegen.py Lib/compiler/symbols.py Lib/compiler/transformer.py Lib/cookielib.py Lib/difflib.py Lib/dumbdbm.py Lib/heapq.py Lib/hmac.py Lib/idlelib/AutoCompleteWindow.py Lib/idlelib/NEWS.txt Lib/logging/__init__.py Lib/logging/handlers.py Lib/mailbox.py Lib/pty.py Lib/pydoc.py Lib/random.py Lib/subprocess.py Lib/symbol.py Lib/tarfile.py Lib/test/output/test_tokenize Lib/test/test_ast.py Lib/test/test_builtin.py Lib/test/test_compile.py Lib/test/test_compiler.py Lib/test/test_deque.py Lib/test/test_dumbdbm.py Lib/test/test_exceptions.py Lib/test/test_grammar.py Lib/test/test_heapq.py Lib/test/test_import.py Lib/test/test_pty.py Lib/test/test_random.py Lib/test/test_repr.py Lib/test/test_set.py Lib/test/test_struct.py Lib/test/test_support.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/test_tokenize.py Lib/test/test_uu.py Lib/test/test_weakref.py Lib/test/tokenize_tests.txt Lib/threading.py Lib/token.py Lib/tokenize.py Lib/urllib.py Misc/ACKS Misc/NEWS Misc/developers.txt Misc/python-mode.el Modules/_bsddb.c Modules/_ctypes/_ctypes_test.c Modules/_elementtree.c Modules/addrinfo.h Modules/bz2module.c Modules/collectionsmodule.c Modules/main.c Modules/parsermodule.c Modules/socketmodule.c Modules/timemodule.c Objects/bytesobject.c Objects/dictnotes.txt Objects/floatobject.c Objects/funcobject.c Objects/object.c Objects/setobject.c PC/python_nt.rc PCbuild/python20.wse PCbuild/pythoncore.vcproj PCbuild8/python20.wse Parser/Python.asdl Parser/asdl.py Parser/spark.py Parser/tokenizer.c Python/Python-ast.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/compile.c Python/errors.c Python/getcopyright.c Python/graminit.c Python/import.c Python/marshal.c Python/symtable.c Python/sysmodule.c README Tools/compiler/ast.txt Tools/compiler/astgen.py Tools/pybench/Strings.py Tools/scripts/fixdiv.py setup.py Message-ID: <20070110232150.CDDB51E400A@bag.python.org> Author: thomas.wouters Date: Thu Jan 11 00:21:28 2007 New Revision: 53363 Modified: python/branches/p3yk-noslice/ (props changed) python/branches/p3yk-noslice/Doc/README python/branches/p3yk-noslice/Doc/api/newtypes.tex python/branches/p3yk-noslice/Doc/howto/functional.rst python/branches/p3yk-noslice/Doc/html/style.css python/branches/p3yk-noslice/Doc/lib/libbsddb.tex python/branches/p3yk-noslice/Doc/lib/libbz2.tex python/branches/p3yk-noslice/Doc/lib/libctypes.tex python/branches/p3yk-noslice/Doc/lib/libfuncs.tex python/branches/p3yk-noslice/Doc/lib/liblogging.tex python/branches/p3yk-noslice/Doc/lib/libmmap.tex python/branches/p3yk-noslice/Doc/lib/libsimplexmlrpc.tex python/branches/p3yk-noslice/Doc/lib/libsocket.tex python/branches/p3yk-noslice/Doc/lib/libsqlite3.tex python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex python/branches/p3yk-noslice/Doc/lib/libsys.tex python/branches/p3yk-noslice/Doc/lib/libtarfile.tex python/branches/p3yk-noslice/Doc/lib/libtest.tex python/branches/p3yk-noslice/Doc/lib/liburlparse.tex python/branches/p3yk-noslice/Doc/mac/toolbox.tex python/branches/p3yk-noslice/Doc/perl/python.perl python/branches/p3yk-noslice/Doc/tut/tut.tex python/branches/p3yk-noslice/Doc/whatsnew/whatsnew25.tex python/branches/p3yk-noslice/Grammar/Grammar python/branches/p3yk-noslice/Include/Python-ast.h python/branches/p3yk-noslice/Include/Python.h python/branches/p3yk-noslice/Include/floatobject.h python/branches/p3yk-noslice/Include/funcobject.h python/branches/p3yk-noslice/Include/graminit.h python/branches/p3yk-noslice/Include/pyport.h python/branches/p3yk-noslice/Include/stringobject.h python/branches/p3yk-noslice/Include/token.h python/branches/p3yk-noslice/LICENSE python/branches/p3yk-noslice/Lib/CGIHTTPServer.py python/branches/p3yk-noslice/Lib/SimpleHTTPServer.py python/branches/p3yk-noslice/Lib/StringIO.py python/branches/p3yk-noslice/Lib/bsddb/dbobj.py python/branches/p3yk-noslice/Lib/bsddb/test/test_1413192.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_dbobj.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_env_close.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_misc.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/compiler/ast.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/transformer.py python/branches/p3yk-noslice/Lib/cookielib.py python/branches/p3yk-noslice/Lib/difflib.py python/branches/p3yk-noslice/Lib/dumbdbm.py python/branches/p3yk-noslice/Lib/heapq.py python/branches/p3yk-noslice/Lib/hmac.py python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt python/branches/p3yk-noslice/Lib/logging/__init__.py python/branches/p3yk-noslice/Lib/logging/handlers.py python/branches/p3yk-noslice/Lib/mailbox.py python/branches/p3yk-noslice/Lib/pty.py python/branches/p3yk-noslice/Lib/pydoc.py python/branches/p3yk-noslice/Lib/random.py python/branches/p3yk-noslice/Lib/subprocess.py python/branches/p3yk-noslice/Lib/symbol.py python/branches/p3yk-noslice/Lib/tarfile.py python/branches/p3yk-noslice/Lib/test/output/test_tokenize python/branches/p3yk-noslice/Lib/test/test_ast.py python/branches/p3yk-noslice/Lib/test/test_builtin.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_deque.py python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py python/branches/p3yk-noslice/Lib/test/test_exceptions.py python/branches/p3yk-noslice/Lib/test/test_grammar.py python/branches/p3yk-noslice/Lib/test/test_heapq.py python/branches/p3yk-noslice/Lib/test/test_import.py python/branches/p3yk-noslice/Lib/test/test_pty.py python/branches/p3yk-noslice/Lib/test/test_random.py python/branches/p3yk-noslice/Lib/test/test_repr.py python/branches/p3yk-noslice/Lib/test/test_set.py python/branches/p3yk-noslice/Lib/test/test_struct.py python/branches/p3yk-noslice/Lib/test/test_support.py python/branches/p3yk-noslice/Lib/test/test_sys.py python/branches/p3yk-noslice/Lib/test/test_tarfile.py python/branches/p3yk-noslice/Lib/test/test_tokenize.py python/branches/p3yk-noslice/Lib/test/test_uu.py python/branches/p3yk-noslice/Lib/test/test_weakref.py python/branches/p3yk-noslice/Lib/test/tokenize_tests.txt python/branches/p3yk-noslice/Lib/threading.py python/branches/p3yk-noslice/Lib/token.py python/branches/p3yk-noslice/Lib/tokenize.py python/branches/p3yk-noslice/Lib/urllib.py python/branches/p3yk-noslice/Misc/ACKS python/branches/p3yk-noslice/Misc/NEWS python/branches/p3yk-noslice/Misc/developers.txt python/branches/p3yk-noslice/Misc/python-mode.el python/branches/p3yk-noslice/Modules/_bsddb.c python/branches/p3yk-noslice/Modules/_ctypes/_ctypes_test.c python/branches/p3yk-noslice/Modules/_elementtree.c python/branches/p3yk-noslice/Modules/addrinfo.h python/branches/p3yk-noslice/Modules/bz2module.c python/branches/p3yk-noslice/Modules/collectionsmodule.c python/branches/p3yk-noslice/Modules/main.c python/branches/p3yk-noslice/Modules/parsermodule.c python/branches/p3yk-noslice/Modules/socketmodule.c python/branches/p3yk-noslice/Modules/timemodule.c python/branches/p3yk-noslice/Objects/bytesobject.c python/branches/p3yk-noslice/Objects/dictnotes.txt python/branches/p3yk-noslice/Objects/floatobject.c python/branches/p3yk-noslice/Objects/funcobject.c python/branches/p3yk-noslice/Objects/object.c python/branches/p3yk-noslice/Objects/setobject.c python/branches/p3yk-noslice/PC/python_nt.rc python/branches/p3yk-noslice/PCbuild/python20.wse python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj python/branches/p3yk-noslice/PCbuild8/python20.wse python/branches/p3yk-noslice/Parser/Python.asdl python/branches/p3yk-noslice/Parser/asdl.py python/branches/p3yk-noslice/Parser/spark.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/errors.c python/branches/p3yk-noslice/Python/getcopyright.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/symtable.c python/branches/p3yk-noslice/Python/sysmodule.c python/branches/p3yk-noslice/README python/branches/p3yk-noslice/Tools/compiler/ast.txt python/branches/p3yk-noslice/Tools/compiler/astgen.py python/branches/p3yk-noslice/Tools/pybench/Strings.py python/branches/p3yk-noslice/Tools/scripts/fixdiv.py python/branches/p3yk-noslice/setup.py Log: Merge noslice branch with p3yk branch. Merged revisions 53040-53333 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/p3yk ................ r53064 | thomas.wouters | 2006-12-19 09:30:14 +0100 (Tue, 19 Dec 2006) | 4 lines Implement extended slicing in bytes objects. ................ r53080 | georg.brandl | 2006-12-19 21:50:34 +0100 (Tue, 19 Dec 2006) | 3 lines Patch #1601678: move intern() to sys.intern(). ................ r53087 | guido.van.rossum | 2006-12-19 22:35:46 +0100 (Tue, 19 Dec 2006) | 2 lines The opstrings table was backwards. Add an XXX comment. ................ r53089 | fred.drake | 2006-12-19 23:06:09 +0100 (Tue, 19 Dec 2006) | 1 line hide version notes for 1.x and 2.x from the HTML version ................ r53167 | neal.norwitz | 2006-12-28 05:45:06 +0100 (Thu, 28 Dec 2006) | 3 lines Remove PyFloat_AsReprString() and PyFloat_AsString() which should not have been public due to passing buffers without lengths. ................ r53168 | neal.norwitz | 2006-12-28 05:47:50 +0100 (Thu, 28 Dec 2006) | 5 lines Cruft removal: * DL_IMPORT/DL_EXPORT * #if 0'd code * Py_PROTO which was obsolete, but still used in one place in addrinfo.h ................ r53170 | neal.norwitz | 2006-12-28 07:47:50 +0100 (Thu, 28 Dec 2006) | 1 line PEP 3107 - Function Annotations thanks to Tony Lownds ................ r53171 | guido.van.rossum | 2006-12-28 22:03:31 +0100 (Thu, 28 Dec 2006) | 2 lines Update the magic number now that signature annotations were added. ................ r53189 | fred.drake | 2006-12-29 05:42:48 +0100 (Fri, 29 Dec 2006) | 3 lines avoid dict.has_key, since this might get used by a Py3K built in the working copy ................ r53288 | martin.v.loewis | 2007-01-06 14:29:14 +0100 (Sat, 06 Jan 2007) | 2 lines Commit __version__ change. ................ r53289 | martin.v.loewis | 2007-01-06 14:49:08 +0100 (Sat, 06 Jan 2007) | 2 lines Add the bytes type to the build process. ................ r53332 | thomas.wouters | 2007-01-10 00:18:33 +0100 (Wed, 10 Jan 2007) | 377 lines Merged revisions 53005-53303 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53012 | walter.doerwald | 2006-12-12 22:55:31 +0100 (Tue, 12 Dec 2006) | 2 lines Fix typo. ........ r53023 | brett.cannon | 2006-12-13 23:31:37 +0100 (Wed, 13 Dec 2006) | 2 lines Remove an unneeded import of 'warnings'. ........ r53025 | brett.cannon | 2006-12-14 00:02:38 +0100 (Thu, 14 Dec 2006) | 2 lines Remove unneeded imports of 'warnings'. ........ r53026 | brett.cannon | 2006-12-14 00:09:53 +0100 (Thu, 14 Dec 2006) | 4 lines Add test.test_support.guard_warnings_filter . This function returns a context manager that protects warnings.filter from being modified once the context is exited. ........ r53029 | george.yoshida | 2006-12-14 03:22:44 +0100 (Thu, 14 Dec 2006) | 2 lines Note that guard_warnings_filter was added in 2.6 ........ r53031 | vinay.sajip | 2006-12-14 09:53:55 +0100 (Thu, 14 Dec 2006) | 1 line Added news on recent changes to logging ........ r53032 | andrew.kuchling | 2006-12-14 19:57:53 +0100 (Thu, 14 Dec 2006) | 1 line [Patch #1599256 from David Watson] check that os.fsync is available before using it ........ r53042 | kurt.kaiser | 2006-12-15 06:13:11 +0100 (Fri, 15 Dec 2006) | 6 lines 1. Avoid hang when encountering a duplicate in a completion list. Bug 1571112. 2. Duplicate some old entries from Python's NEWS to IDLE's NEWS.txt M AutoCompleteWindow.py M NEWS.txt ........ r53048 | andrew.kuchling | 2006-12-18 18:12:31 +0100 (Mon, 18 Dec 2006) | 1 line [Bug #1618083] Add missing word; make a few grammar fixes ........ r53050 | andrew.kuchling | 2006-12-18 18:16:05 +0100 (Mon, 18 Dec 2006) | 1 line Bump version ........ r53051 | andrew.kuchling | 2006-12-18 18:22:07 +0100 (Mon, 18 Dec 2006) | 1 line [Bug #1616726] Fix description of generator.close(); if you raise some random exception, the exception is raised and doesn't trigger a RuntimeError ........ r53052 | andrew.kuchling | 2006-12-18 18:38:14 +0100 (Mon, 18 Dec 2006) | 1 line Describe new methods in Queue module ........ r53053 | andrew.kuchling | 2006-12-18 20:22:24 +0100 (Mon, 18 Dec 2006) | 1 line [Patch #1615868 by Lars Gustaebel] Use Py_off_t to fix BZ2File.seek() for offsets > 2Gb ........ r53057 | andrew.kuchling | 2006-12-18 22:29:07 +0100 (Mon, 18 Dec 2006) | 1 line Fix markup ........ r53063 | thomas.wouters | 2006-12-19 09:17:50 +0100 (Tue, 19 Dec 2006) | 5 lines Make sre's SubPattern objects accept slice objects like it already accepts simple slices. ........ r53065 | andrew.kuchling | 2006-12-19 15:13:05 +0100 (Tue, 19 Dec 2006) | 6 lines [Patch #1618455 by Ben Maurer] Improve speed of HMAC by using str.translate() instead of a more general XOR that has to construct a list. Slightly modified from Maurer's patch: the _strxor() function is no longer necessary at all. ........ r53066 | andrew.kuchling | 2006-12-19 15:28:23 +0100 (Tue, 19 Dec 2006) | 9 lines [Bug #1613651] Document socket.recv_into, socket.recvfrom_into Also, the text for recvfrom told you to read recv() for an explanation of the 'flags' argument, but recv() just pointed you at the man page. Copied the man-page text to recvfrom(), recvfrom_into, recv_into to avoid the pointless redirection. I don't have LaTeX on this machine; hope my markup is OK. ........ r53067 | andrew.kuchling | 2006-12-19 15:29:04 +0100 (Tue, 19 Dec 2006) | 1 line Comment typo ........ r53068 | andrew.kuchling | 2006-12-19 16:11:41 +0100 (Tue, 19 Dec 2006) | 1 line [Patch #1617413 from Dug Song] Fix HTTP Basic authentication via HTTPS ........ r53071 | andrew.kuchling | 2006-12-19 16:18:12 +0100 (Tue, 19 Dec 2006) | 1 line [Patch #1600491 from Jim Jewett] Describe how to build help files on Windows ........ r53073 | andrew.kuchling | 2006-12-19 16:43:10 +0100 (Tue, 19 Dec 2006) | 6 lines [Patch #1587139 by kxroberto] Protect lock acquisition/release with try...finally to ensure the lock is always released. This could use the 'with' statement, but the patch uses 'finally'. 2.5 backport candidate. ........ r53074 | vinay.sajip | 2006-12-19 19:29:11 +0100 (Tue, 19 Dec 2006) | 1 line Updated documentation for findCaller() to indicate that a 3-tuple is now returned, rather than a 2-tuple. ........ r53090 | georg.brandl | 2006-12-19 23:06:46 +0100 (Tue, 19 Dec 2006) | 3 lines Patch #1484695: The tarfile module now raises a HeaderError exception if a buffer given to frombuf() is invalid. ........ r53099 | raymond.hettinger | 2006-12-20 07:42:06 +0100 (Wed, 20 Dec 2006) | 5 lines Bug #1590891: random.randrange don't return correct value for big number Needs to be backported. ........ r53106 | georg.brandl | 2006-12-20 12:55:16 +0100 (Wed, 20 Dec 2006) | 3 lines Testcase for patch #1484695. ........ r53110 | andrew.kuchling | 2006-12-20 20:48:20 +0100 (Wed, 20 Dec 2006) | 17 lines [Apply length-checking.diff from bug #1599254] Add length checking to single-file mailbox formats: before doing a flush() on a mailbox, seek to the end and verify its length is unchanged, raising ExternalClashError if the file's length has changed. This fix avoids potential data loss if some other process appends to the mailbox file after the table of contents has been generated; instead of overwriting the modified file, you'll get the exception. I also noticed that the self._lookup() call in self.flush() wasn't necessary (everything that sets self._pending to True also calls self.lookup()), and replaced it by an assertion. 2.5 backport candidate. ........ r53112 | andrew.kuchling | 2006-12-20 20:57:10 +0100 (Wed, 20 Dec 2006) | 1 line [Bug #1619674] Make sum() use the term iterable, not sequence ........ r53113 | andrew.kuchling | 2006-12-20 20:58:11 +0100 (Wed, 20 Dec 2006) | 1 line Two grammar fixes ........ r53115 | andrew.kuchling | 2006-12-20 21:11:12 +0100 (Wed, 20 Dec 2006) | 5 lines Some other built-in functions are described with 'sequence' arguments that should really be 'iterable'; this commit changes them. Did I miss any? Did I introduce any errors? ........ r53117 | andrew.kuchling | 2006-12-20 21:20:42 +0100 (Wed, 20 Dec 2006) | 1 line [Bug #1619680] in_dll() arguments are documented in the wrong order ........ r53120 | neal.norwitz | 2006-12-21 05:38:00 +0100 (Thu, 21 Dec 2006) | 1 line Lars asked for permission on on python-dev for work on tarfile.py ........ r53125 | andrew.kuchling | 2006-12-21 14:40:29 +0100 (Thu, 21 Dec 2006) | 1 line Mention the os.SEEK_* constants ........ r53129 | walter.doerwald | 2006-12-21 19:06:30 +0100 (Thu, 21 Dec 2006) | 2 lines Fix typo. ........ r53131 | thomas.heller | 2006-12-21 19:30:56 +0100 (Thu, 21 Dec 2006) | 3 lines Fix wrong markup of an argument in a method signature. Will backport. ........ r53137 | andrew.kuchling | 2006-12-22 01:50:56 +0100 (Fri, 22 Dec 2006) | 1 line Typo fix ........ r53139 | andrew.kuchling | 2006-12-22 14:25:02 +0100 (Fri, 22 Dec 2006) | 1 line [Bug #737202; fix from Titus Brown] Make CGIHTTPServer work for scripts in sub-directories ........ r53141 | andrew.kuchling | 2006-12-22 16:04:45 +0100 (Fri, 22 Dec 2006) | 6 lines [Bug #802128] Make the mode argument of dumbdbm actually work the way it's described, and add a test for it. 2.5 bugfix candidate, maybe; arguably this patch changes the API of dumbdbm and shouldn't be added in a point-release. ........ r53142 | andrew.kuchling | 2006-12-22 16:16:58 +0100 (Fri, 22 Dec 2006) | 6 lines [Bug #802128 continued] Modify mode depending on the process umask. Is there really no other way to read the umask than to set it? Hope this works on Windows... ........ r53145 | andrew.kuchling | 2006-12-22 17:43:26 +0100 (Fri, 22 Dec 2006) | 1 line [Bug #776202] Apply Walter Doerwald's patch to use text mode for encoded files ........ r53146 | andrew.kuchling | 2006-12-22 19:41:42 +0100 (Fri, 22 Dec 2006) | 9 lines [Patch #783050 from Patrick Lynch] The emulation of forkpty() is incorrect; the master should close the slave fd. Added a test to test_pty.py that reads from the master_fd after doing a pty.fork(); without the fix it hangs forever instead of raising an exception. () 2.5 backport candidate. ........ r53147 | andrew.kuchling | 2006-12-22 20:06:16 +0100 (Fri, 22 Dec 2006) | 1 line [Patch #827559 from Chris Gonnerman] Make SimpleHTTPServer redirect when a directory URL is missing the trailing slash; this lets relative links work. ........ r53149 | andrew.kuchling | 2006-12-22 20:21:27 +0100 (Fri, 22 Dec 2006) | 1 line Darn; this test works when you run test_pty.py directly, but fails when regrtest runs it (the os.read() raises os.error). I can't figure out the cause, so am commenting out the test. ........ r53150 | andrew.kuchling | 2006-12-22 22:48:19 +0100 (Fri, 22 Dec 2006) | 1 line Frak; this test also fails ........ r53153 | lars.gustaebel | 2006-12-23 17:40:13 +0100 (Sat, 23 Dec 2006) | 5 lines Patch #1230446: tarfile.py: fix ExFileObject so that read() and tell() work correctly together with readline(). Will backport to 2.5. ........ r53155 | lars.gustaebel | 2006-12-23 18:57:23 +0100 (Sat, 23 Dec 2006) | 5 lines Patch #1262036: Prevent TarFiles from being added to themselves under certain conditions. Will backport to 2.5. ........ r53159 | andrew.kuchling | 2006-12-27 04:25:31 +0100 (Wed, 27 Dec 2006) | 4 lines [Part of patch #1182394] Move the HMAC blocksize to be a class-level constant; this allows changing it in a subclass. To accommodate this, copy() now uses __class__. Also add some text to a comment. ........ r53160 | andrew.kuchling | 2006-12-27 04:31:24 +0100 (Wed, 27 Dec 2006) | 1 line [Rest of patch #1182394] Add ._current() method so that we can use the written-in-C .hexdigest() method ........ r53161 | lars.gustaebel | 2006-12-27 11:30:46 +0100 (Wed, 27 Dec 2006) | 4 lines Patch #1504073: Fix tarfile.open() for mode "r" with a fileobj argument. Will backport to 2.5. ........ r53165 | neal.norwitz | 2006-12-28 05:39:20 +0100 (Thu, 28 Dec 2006) | 1 line Remove a stray (old) macro name left around (I guess) ........ r53188 | neal.norwitz | 2006-12-29 04:01:53 +0100 (Fri, 29 Dec 2006) | 1 line SF bug #1623890, fix argument name in docstring ........ r53200 | raymond.hettinger | 2006-12-30 05:01:17 +0100 (Sat, 30 Dec 2006) | 1 line For sets with cyclical reprs, emit an ellipsis instead of infinitely recursing. ........ r53232 | brett.cannon | 2007-01-04 01:23:49 +0100 (Thu, 04 Jan 2007) | 3 lines Add EnvironmentVarGuard to test.test_support. Provides a context manager to temporarily set or unset environment variables. ........ r53235 | neal.norwitz | 2007-01-04 07:25:31 +0100 (Thu, 04 Jan 2007) | 1 line SF #1627373, fix typo in CarbonEvt. ........ r53244 | raymond.hettinger | 2007-01-04 18:53:34 +0100 (Thu, 04 Jan 2007) | 1 line Fix stability of heapq's nlargest() and nsmallest(). ........ r53249 | martin.v.loewis | 2007-01-04 22:06:12 +0100 (Thu, 04 Jan 2007) | 3 lines Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, to avoid relying on atexit. Will backport to 2.5. ........ r53252 | gregory.p.smith | 2007-01-05 02:59:42 +0100 (Fri, 05 Jan 2007) | 3 lines Support linking of the bsddb module against BerkeleyDB 4.5.x (will backport to 2.5) ........ r53253 | gregory.p.smith | 2007-01-05 03:06:17 +0100 (Fri, 05 Jan 2007) | 2 lines bump module version to match supported berkeleydb version ........ r53255 | neal.norwitz | 2007-01-05 06:25:22 +0100 (Fri, 05 Jan 2007) | 6 lines Prevent crash on shutdown which can occur if we are finalizing and the module dict has been cleared already and some object raises a warning (like in a __del__). Will backport. ........ r53258 | gregory.p.smith | 2007-01-05 08:21:35 +0100 (Fri, 05 Jan 2007) | 2 lines typo fix ........ r53260 | neal.norwitz | 2007-01-05 09:06:43 +0100 (Fri, 05 Jan 2007) | 1 line Add Collin Winter for access to update PEP 3107 ........ r53262 | andrew.kuchling | 2007-01-05 15:22:17 +0100 (Fri, 05 Jan 2007) | 1 line [Bug #1622533] Make docstrings raw strings because they contain control characters (\0, \1) ........ r53264 | andrew.kuchling | 2007-01-05 16:51:24 +0100 (Fri, 05 Jan 2007) | 1 line [Patch #1520904] Fix bsddb tests to write to the temp directory instead of the Lib/bsddb/test directory ........ r53279 | brett.cannon | 2007-01-05 22:45:09 +0100 (Fri, 05 Jan 2007) | 3 lines Silence a warning from gcc 4.0.1 by specifying a function's parameter list is 'void' instead of just a set of empty parentheses. ........ r53285 | raymond.hettinger | 2007-01-06 02:14:41 +0100 (Sat, 06 Jan 2007) | 2 lines SF# 1409443: Expand comment to cover the interaction between f->f_lasti and the PREDICT macros. ........ r53286 | anthony.baxter | 2007-01-06 05:45:54 +0100 (Sat, 06 Jan 2007) | 1 line update to (c) years to include 2007 ........ r53291 | neal.norwitz | 2007-01-06 22:24:35 +0100 (Sat, 06 Jan 2007) | 1 line Add Josiah to SF for maintaining asyncore/asynchat ........ r53293 | peter.astrand | 2007-01-07 09:53:46 +0100 (Sun, 07 Jan 2007) | 1 line Re-implemented fix for #1531862 once again, in a way that works with Python 2.2. Fixes bug #1603424. ........ r53295 | peter.astrand | 2007-01-07 15:34:16 +0100 (Sun, 07 Jan 2007) | 1 line Avoid O(N**2) bottleneck in _communicate_(). Fixes #1598181. ........ r53300 | raymond.hettinger | 2007-01-08 19:09:20 +0100 (Mon, 08 Jan 2007) | 1 line Fix zero-length corner case for iterating over a mutating deque. ........ r53301 | vinay.sajip | 2007-01-08 19:50:32 +0100 (Mon, 08 Jan 2007) | 4 lines Bare except clause removed from SMTPHandler.emit(). Now, only ImportError is trapped. Bare except clause removed from SocketHandler.createSocket(). Now, only socket.error is trapped. (SF #411881) ........ r53302 | vinay.sajip | 2007-01-08 19:51:46 +0100 (Mon, 08 Jan 2007) | 2 lines Bare except clause removed from LogRecord.__init__. Now, only ValueError, TypeError and AttributeError are trapped. (SF #411881) ........ r53303 | vinay.sajip | 2007-01-08 19:52:36 +0100 (Mon, 08 Jan 2007) | 1 line Added entries about removal of some bare except clauses from logging. ........ ................ Modified: python/branches/p3yk-noslice/Doc/README ============================================================================== --- python/branches/p3yk-noslice/Doc/README (original) +++ python/branches/p3yk-noslice/Doc/README Thu Jan 11 00:21:28 2007 @@ -229,7 +229,7 @@ as long as you don't change or remove the copyright notice: ---------------------------------------------------------------------- -Copyright (c) 2000-2006 Python Software Foundation. +Copyright (c) 2000-2007 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/branches/p3yk-noslice/Doc/api/newtypes.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/api/newtypes.tex (original) +++ python/branches/p3yk-noslice/Doc/api/newtypes.tex Thu Jan 11 00:21:28 2007 @@ -103,8 +103,6 @@ the value for the \var{methods} argument]{2.3} \end{cfuncdesc} -DL_IMPORT - \begin{cvardesc}{PyObject}{_Py_NoneStruct} Object which is visible in Python as \code{None}. This should only be accessed using the \code{Py_None} macro, which evaluates to a Modified: python/branches/p3yk-noslice/Doc/howto/functional.rst ============================================================================== --- python/branches/p3yk-noslice/Doc/howto/functional.rst (original) +++ python/branches/p3yk-noslice/Doc/howto/functional.rst Thu Jan 11 00:21:28 2007 @@ -1398,10 +1398,10 @@ ''''''''''''''''''''''''''' http://docs.python.org/lib/module-itertools.html: -Documentation ``for the itertools`` module. +Documentation for the ``itertools`` module. http://docs.python.org/lib/module-operator.html: -Documentation ``for the operator`` module. +Documentation for the ``operator`` module. http://www.python.org/dev/peps/pep-0289/: PEP 289: "Generator Expressions" Modified: python/branches/p3yk-noslice/Doc/html/style.css ============================================================================== --- python/branches/p3yk-noslice/Doc/html/style.css (original) +++ python/branches/p3yk-noslice/Doc/html/style.css Thu Jan 11 00:21:28 2007 @@ -99,6 +99,9 @@ div.note .label { margin-right: 0.5em; font-family: sans-serif; } +.versionnote1 { display: none; } +.versionnote2 { display: none; } + address { font-size: 80%; } .release-info { font-style: italic; font-size: 80%; } Modified: python/branches/p3yk-noslice/Doc/lib/libbsddb.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libbsddb.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libbsddb.tex Thu Jan 11 00:21:28 2007 @@ -16,7 +16,7 @@ \function{pickle.dumps()}. The \module{bsddb} module requires a Berkeley DB library version from -3.3 thru 4.4. +3.3 thru 4.5. \begin{seealso} \seeurl{http://pybsddb.sourceforge.net/} Modified: python/branches/p3yk-noslice/Doc/lib/libbz2.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libbz2.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libbz2.tex Thu Jan 11 00:21:28 2007 @@ -81,10 +81,10 @@ \begin{methoddesc}[BZ2File]{seek}{offset\optional{, whence}} Move to new file position. Argument \var{offset} is a byte count. Optional -argument \var{whence} defaults to \code{0} (offset from start of file, -offset should be \code{>= 0}); other values are \code{1} (move relative to -current position, positive or negative), and \code{2} (move relative to end -of file, usually negative, although many platforms allow seeking beyond +argument \var{whence} defaults to \code{os.SEEK_SET} or \code{0} (offset from start of file; +offset should be \code{>= 0}); other values are \code{os.SEEK_CUR} or \code{1} (move relative to +current position; offset can be positive or negative), and \code{os.SEEK_END} or \code{2} (move relative to end +of file; offset is usually negative, although many platforms allow seeking beyond the end of a file). Note that seeking of bz2 files is emulated, and depending on the parameters Modified: python/branches/p3yk-noslice/Doc/lib/libctypes.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libctypes.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libctypes.tex Thu Jan 11 00:21:28 2007 @@ -2085,10 +2085,10 @@ the type. Some types accept other objects as well. \end{methoddesc} -\begin{methoddesc}{in_dll}{name, library} +\begin{methoddesc}{in_dll}{library, name} This method returns a ctypes type instance exported by a shared library. \var{name} is the name of the symbol that exports the data, -\code{library} is the loaded shared library. +\var{library} is the loaded shared library. \end{methoddesc} Common instance variables of ctypes data types: Modified: python/branches/p3yk-noslice/Doc/lib/libfuncs.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libfuncs.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libfuncs.tex Thu Jan 11 00:21:28 2007 @@ -237,11 +237,11 @@ \code{del \var{x}.\var{foobar}}. \end{funcdesc} -\begin{funcdesc}{dict}{\optional{mapping-or-sequence}} +\begin{funcdesc}{dict}{\optional{arg}} Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. - If the positional argument is a mapping object, return a dictionary + If the positional argument \var{arg} is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. Otherwise the positional argument must be a sequence, a container that supports iteration, or an iterator object. The elements of the argument @@ -448,18 +448,18 @@ \versionadded{2.2} \end{funcdesc} -\begin{funcdesc}{filter}{function, list} - Construct a list from those elements of \var{list} for which - \var{function} returns true. \var{list} may be either a sequence, a - container which supports iteration, or an iterator, If \var{list} +\begin{funcdesc}{filter}{function, iterable} + Construct a list from those elements of \var{iterable} for which + \var{function} returns true. \var{iterable} may be either a sequence, a + container which supports iteration, or an iterator, If \var{iterable} is a string or a tuple, the result also has that type; otherwise it is always a list. If \var{function} is \code{None}, the identity function is assumed, that is, all elements of - \var{list} that are false are removed. + \var{iterable} that are false are removed. - Note that \code{filter(function, \var{list})} is equivalent to - \code{[item for item in \var{list} if function(item)]} if function is - not \code{None} and \code{[item for item in \var{list} if item]} if + Note that \code{filter(function, \var{iterable})} is equivalent to + \code{[item for item in \var{iterable} if function(item)]} if function is + not \code{None} and \code{[item for item in \var{iterable} if item]} if function is \code{None}. \end{funcdesc} @@ -608,12 +608,12 @@ may be a sequence (string, tuple or list) or a mapping (dictionary). \end{funcdesc} -\begin{funcdesc}{list}{\optional{sequence}} +\begin{funcdesc}{list}{\optional{iterable}} Return a list whose items are the same and in the same order as - \var{sequence}'s items. \var{sequence} may be either a sequence, a + \var{iterable}'s items. \var{iterable} may be either a sequence, a container that supports iteration, or an iterator object. If - \var{sequence} is already a list, a copy is made and returned, - similar to \code{\var{sequence}[:]}. For instance, + \var{iterable} is already a list, a copy is made and returned, + similar to \code{\var{iterable}[:]}. For instance, \code{list('abc')} returns \code{['a', 'b', 'c']} and \code{list( (1, 2, 3) )} returns \code{[1, 2, 3]}. If no argument is given, returns a new empty list, \code{[]}. @@ -639,22 +639,22 @@ are given, returns \code{0L}. \end{funcdesc} -\begin{funcdesc}{map}{function, list, ...} - Apply \var{function} to every item of \var{list} and return a list - of the results. If additional \var{list} arguments are passed, +\begin{funcdesc}{map}{function, iterable, ...} + Apply \var{function} to every item of \var{iterable} and return a list + of the results. If additional \var{iterable} arguments are passed, \var{function} must take that many arguments and is applied to the - items of all lists in parallel; if a list is shorter than another it + items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with \code{None} items. If \var{function} is \code{None}, the identity function is assumed; if there are - multiple list arguments, \function{map()} returns a list consisting - of tuples containing the corresponding items from all lists (a kind - of transpose operation). The \var{list} arguments may be any kind - of sequence; the result is always a list. + multiple arguments, \function{map()} returns a list consisting + of tuples containing the corresponding items from all iterables (a kind + of transpose operation). The \var{iterable} arguments may be a sequence + or any iterable object; the result is always a list. \end{funcdesc} -\begin{funcdesc}{max}{s\optional{, args...}\optional{key}} - With a single argument \var{s}, return the largest item of a - non-empty sequence (such as a string, tuple or list). With more +\begin{funcdesc}{max}{iterable\optional{, args...}\optional{key}} + With a single argument \var{iterable}, return the largest item of a + non-empty iterable (such as a string, tuple or list). With more than one argument, return the largest of the arguments. The optional \var{key} argument specifies a one-argument ordering @@ -664,16 +664,16 @@ \versionchanged[Added support for the optional \var{key} argument]{2.5} \end{funcdesc} -\begin{funcdesc}{min}{s\optional{, args...}\optional{key}} - With a single argument \var{s}, return the smallest item of a - non-empty sequence (such as a string, tuple or list). With more +\begin{funcdesc}{min}{iterable\optional{, args...}\optional{key}} + With a single argument \var{iterable}, return the smallest item of a + non-empty iterable (such as a string, tuple or list). With more than one argument, return the smallest of the arguments. The optional \var{key} argument specifies a one-argument ordering function like that used for \method{list.sort()}. The \var{key} argument, if supplied, must be in keyword form (for example, \samp{min(a,b,c,key=func)}). - \versionchanged[Added support for the optional \var{key} argument]{2.5} + \versionchanged[Added support for the optional \var{key} argument]{2.5} \end{funcdesc} \begin{funcdesc}{object}{} @@ -1073,11 +1073,11 @@ string, \code{''}. \end{funcdesc} -\begin{funcdesc}{sum}{sequence\optional{, start}} - Sums \var{start} and the items of a \var{sequence}, from left to - right, and returns the total. \var{start} defaults to \code{0}. - The \var{sequence}'s items are normally numbers, and are not allowed - to be strings. The fast, correct way to concatenate sequence of +\begin{funcdesc}{sum}{iterable\optional{, start}} + Sums \var{start} and the items of an \var{iterable} from left to + right and returns the total. \var{start} defaults to \code{0}. + The \var{iterable}'s items are normally numbers, and are not allowed + to be strings. The fast, correct way to concatenate a sequence of strings is by calling \code{''.join(\var{sequence})}. \versionadded{2.3} \end{funcdesc} @@ -1105,11 +1105,11 @@ \versionadded{2.2} \end{funcdesc} -\begin{funcdesc}{tuple}{\optional{sequence}} +\begin{funcdesc}{tuple}{\optional{iterable}} Return a tuple whose items are the same and in the same order as - \var{sequence}'s items. \var{sequence} may be a sequence, a + \var{iterable}'s items. \var{iterable} may be a sequence, a container that supports iteration, or an iterator object. - If \var{sequence} is already a tuple, it + If \var{iterable} is already a tuple, it is returned unchanged. For instance, \code{tuple('abc')} returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns \code{(1, 2, 3)}. If no argument is given, returns a new empty @@ -1262,17 +1262,3 @@ argument). \end{funcdesc} -\begin{funcdesc}{intern}{string} - Enter \var{string} in the table of ``interned'' strings and return - the interned string -- which is \var{string} itself or a copy. - Interning strings is useful to gain a little performance on - dictionary lookup -- if the keys in a dictionary are interned, and - the lookup key is interned, the key comparisons (after hashing) can - be done by a pointer compare instead of a string compare. Normally, - the names used in Python programs are automatically interned, and - the dictionaries used to hold module, class or instance attributes - have interned keys. \versionchanged[Interned strings are not - immortal (like they used to be in Python 2.2 and before); - you must keep a reference to the return value of \function{intern()} - around to benefit from it]{2.3} -\end{funcdesc} 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 Thu Jan 11 00:21:28 2007 @@ -516,8 +516,10 @@ \end{methoddesc} \begin{methoddesc}{findCaller}{} -Finds the caller's source filename and line number. Returns the filename -and line number as a 2-element tuple. +Finds the caller's source filename and line number. Returns the filename, +line number and function name as a 3-element tuple. +\versionchanged[The function name was added. In earlier versions, the +filename and line number were returned as a 2-element tuple.]{2.5} \end{methoddesc} \begin{methoddesc}{handle}{record} Modified: python/branches/p3yk-noslice/Doc/lib/libmmap.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libmmap.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libmmap.tex Thu Jan 11 00:21:28 2007 @@ -140,8 +140,9 @@ \begin{methoddesc}{seek}{pos\optional{, whence}} Set the file's current position. \var{whence} argument is optional - and defaults to \code{0} (absolute file positioning); other values - are \code{1} (seek relative to the current position) and \code{2} + and defaults to \code{os.SEEK_SET} or \code{0} (absolute file + positioning); other values are \code{os.SEEK_CUR} or \code{1} (seek + relative to the current position) and \code{os.SEEK_END} or \code{2} (seek relative to the file's end). \end{methoddesc} Modified: python/branches/p3yk-noslice/Doc/lib/libsimplexmlrpc.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libsimplexmlrpc.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libsimplexmlrpc.tex Thu Jan 11 00:21:28 2007 @@ -15,7 +15,7 @@ \begin{classdesc}{SimpleXMLRPCServer}{addr\optional{, requestHandler\optional{, - logRequests\optional{allow_none\optional{, encoding}}}}} + logRequests\optional{, allow_none\optional{, encoding}}}}} Create a new server instance. This class provides methods for registration of functions that can be called by Modified: python/branches/p3yk-noslice/Doc/lib/libsocket.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libsocket.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libsocket.tex Thu Jan 11 00:21:28 2007 @@ -569,11 +569,32 @@ Receive data from the socket. The return value is a pair \code{(\var{string}, \var{address})} where \var{string} is a string representing the data received and \var{address} is the address of the -socket sending the data. The optional \var{flags} argument has the -same meaning as for \method{recv()} above. +socket sending the data. See the \UNIX{} manual page +\manpage{recv}{2} for the meaning of the optional argument +\var{flags}; it defaults to zero. (The format of \var{address} depends on the address family --- see above.) \end{methoddesc} +\begin{methoddesc}[socket]{recvfrom_into}{buffer\optional{, nbytes\optional{, flags}}} +Receive data from the socket, writing it into \var{buffer} instead of +creating a new string. The return value is a pair +\code{(\var{nbytes}, \var{address})} where \var{nbytes} is the number +of bytes received and \var{address} is the address of the socket +sending the data. See the \UNIX{} manual page +\manpage{recv}{2} for the meaning of the optional argument +\var{flags}; it defaults to zero. (The format of \var{address} +depends on the address family --- see above.) +\end{methoddesc} + +\begin{methoddesc}[socket]{recv_into}{buffer\optional{, nbytes\optional{, flags}}} +Receive up to \var{nbytes} bytes from the socket, +storing the data into a buffer rather than creating a new string. +If \var{nbytes} is not specified (or 0), +receive up to the size available in the given buffer. +See the \UNIX{} manual page \manpage{recv}{2} for the meaning of the +optional argument \var{flags}; it defaults to zero. +\end{methoddesc} + \begin{methoddesc}[socket]{send}{string\optional{, flags}} Send data to the socket. The socket must be connected to a remote socket. The optional \var{flags} argument has the same meaning as for Modified: python/branches/p3yk-noslice/Doc/lib/libsqlite3.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libsqlite3.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libsqlite3.tex Thu Jan 11 00:21:28 2007 @@ -187,12 +187,12 @@ \end{funcdesc} \begin{funcdesc}{complete_statement}{sql} -Returns \constant{True} if the string \var{sql} one or more complete SQL -statements terminated by semicolons. It does not verify if the SQL is -syntactically correct, only if there are no unclosed string literals and if the +Returns \constant{True} if the string \var{sql} contains one or more complete SQL +statements terminated by semicolons. It does not verify that the SQL is +syntactically correct, only that there are no unclosed string literals and the statement is terminated by a semicolon. -This can be used to build a shell for SQLite, like in the following example: +This can be used to build a shell for SQLite, as in the following example: \verbatiminput{sqlite3/complete_statement.py} \end{funcdesc} Modified: python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex Thu Jan 11 00:21:28 2007 @@ -1660,9 +1660,12 @@ \begin{methoddesc}[file]{seek}{offset\optional{, whence}} Set the file's current position, like \code{stdio}'s \cfunction{fseek()}. - The \var{whence} argument is optional and defaults to \code{0} - (absolute file positioning); other values are \code{1} (seek - relative to the current position) and \code{2} (seek relative to the + The \var{whence} argument is optional and defaults to + \code{os.SEEK_SET} or \code{0} + (absolute file positioning); other values are \code{os.SEEK_CUR} or \code{1} + (seek + relative to the current position) and \code{os.SEEK_END} or \code{2} + (seek relative to the file's end). There is no return value. Note that if the file is opened for appending (mode \code{'a'} or \code{'a+'}), any \method{seek()} operations will be undone at the next write. If the Modified: python/branches/p3yk-noslice/Doc/lib/libsys.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libsys.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libsys.tex Thu Jan 11 00:21:28 2007 @@ -340,6 +340,21 @@ \versionadded{1.5.2} \end{datadesc} +\begin{funcdesc}{intern}{string} + Enter \var{string} in the table of ``interned'' strings and return + the interned string -- which is \var{string} itself or a copy. + Interning strings is useful to gain a little performance on + dictionary lookup -- if the keys in a dictionary are interned, and + the lookup key is interned, the key comparisons (after hashing) can + be done by a pointer compare instead of a string compare. Normally, + the names used in Python programs are automatically interned, and + the dictionaries used to hold module, class or instance attributes + have interned keys. \versionchanged[Interned strings are not + immortal (like they used to be in Python 2.2 and before); + you must keep a reference to the return value of \function{intern()} + around to benefit from it]{2.3} +\end{funcdesc} + \begin{datadesc}{last_type} \dataline{last_value} \dataline{last_traceback} 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 Thu Jan 11 00:21:28 2007 @@ -124,6 +124,11 @@ only if \member{TarFile.errorlevel}\code{ == 2}. \end{excdesc} +\begin{excdesc}{HeaderError} + Is raised by \method{frombuf()} if the buffer it gets is invalid. + \versionadded{2.6} +\end{excdesc} + \begin{seealso} \seemodule{zipfile}{Documentation of the \refmodule{zipfile} standard module.} @@ -332,6 +337,8 @@ \begin{methoddesc}{frombuf}{} Create and return a \class{TarInfo} object from a string buffer. + \versionadded[Raises \exception{HeaderError} if the buffer is + invalid.]{2.6} \end{methoddesc} \begin{methoddesc}{tobuf}{posix} Modified: python/branches/p3yk-noslice/Doc/lib/libtest.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libtest.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libtest.tex Thu Jan 11 00:21:28 2007 @@ -263,6 +263,12 @@ This does not equal a failure since it could be the path to the file. \end{funcdesc} +\begin{funcdesc}{guard_warnings_filter}{} +Returns a context manager that guards the \module{warnings} module's +filter settings. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{run_unittest}{*classes} Execute \class{unittest.TestCase} subclasses passed to the function. The function scans the classes for methods starting with the prefix @@ -275,4 +281,22 @@ The optional argument \var{testclass} accepts one of the test classes in the suite so as to print out more detailed information on where the testing suite originated from. + +The \module{test.test_support} module defines the following classes: + +\begin{classdesc}{EnvironmentVarGuard}{} +Class used to temporarily set or unset environment variables. Instances can be +used as a context manager. +\versionadded{2.6} +\end{classdesc} + +\begin{methoddesc}{set}{envvar, value} +Temporarily set the environment variable \code{envvar} to the value of +\code{value}. +\end{methoddesc} + +\begin{methoddesc}{unset}{envvar} +Temporarily unset the environment variable \code{envvar}. +\end{methoddesc} + \end{funcdesc} Modified: python/branches/p3yk-noslice/Doc/lib/liburlparse.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/liburlparse.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/liburlparse.tex Thu Jan 11 00:21:28 2007 @@ -89,7 +89,7 @@ \begin{funcdesc}{urlunparse}{parts} Construct a URL from a tuple as returned by \code{urlparse()}. -The \var{parts} argument be any six-item iterable. +The \var{parts} argument can be any six-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). @@ -133,7 +133,7 @@ \begin{funcdesc}{urlunsplit}{parts} Combine the elements of a tuple as returned by \function{urlsplit()} into a complete URL as a string. -The \var{parts} argument be any five-item iterable. +The \var{parts} argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). Modified: python/branches/p3yk-noslice/Doc/mac/toolbox.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/mac/toolbox.tex (original) +++ python/branches/p3yk-noslice/Doc/mac/toolbox.tex Thu Jan 11 00:21:28 2007 @@ -65,7 +65,7 @@ \modulesynopsis{Interface to the Component Manager.} \section{\module{Carbon.CarbonEvt} --- Carbon Event Manager} -\declaremodule{standard}{Carbon.CaronEvt} +\declaremodule{standard}{Carbon.CarbonEvt} \platform{Mac} \modulesynopsis{Interface to the Carbon Event Manager.} Modified: python/branches/p3yk-noslice/Doc/perl/python.perl ============================================================================== --- python/branches/p3yk-noslice/Doc/perl/python.perl (original) +++ python/branches/p3yk-noslice/Doc/perl/python.perl Thu Jan 11 00:21:28 2007 @@ -422,11 +422,15 @@ local $_ = $_[1]; my $explanation = next_optional_argument(); my $release = next_argument(); + my $classes = "versionnote"; + if ($release =~ /^(\d+)\./) { + $classes .= " versionnote$1"; + } my $text = "$type in version $release."; if ($explanation) { $text = "$type in version $release:\n$explanation."; } - return "\n$text\n" . $_; + return "\n$text\n" . $_; } sub do_cmd_versionadded{ 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 Thu Jan 11 00:21:28 2007 @@ -2700,7 +2700,7 @@ 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'execfile', 'exit', 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', - 'id', 'int', 'intern', 'isinstance', 'issubclass', 'iter', + 'id', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'reload', 'repr', 'reversed', 'round', 'set', Modified: python/branches/p3yk-noslice/Doc/whatsnew/whatsnew25.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/whatsnew/whatsnew25.tex (original) +++ python/branches/p3yk-noslice/Doc/whatsnew/whatsnew25.tex Thu Jan 11 00:21:28 2007 @@ -5,7 +5,7 @@ % Fix XXX comments \title{What's New in Python 2.5} -\release{1.0} +\release{1.01} \author{A.M. Kuchling} \authoraddress{\email{amk at amk.ca}} @@ -556,13 +556,14 @@ where the generator's execution is paused. \item \method{close()} raises a new \exception{GeneratorExit} - exception inside the generator to terminate the iteration. - On receiving this - exception, the generator's code must either raise - \exception{GeneratorExit} or \exception{StopIteration}; catching the - exception and doing anything else is illegal and will trigger - a \exception{RuntimeError}. \method{close()} will also be called by - Python's garbage collector when the generator is garbage-collected. + exception inside the generator to terminate the iteration. On + receiving this exception, the generator's code must either raise + \exception{GeneratorExit} or \exception{StopIteration}. Catching + the \exception{GeneratorExit} exception and returning a value is + illegal and will trigger a \exception{RuntimeError}; if the function + raises some other exception, that exception is propagated to the + caller. \method{close()} will also be called by Python's garbage + collector when the generator is garbage-collected. If you need to run cleanup code when a \exception{GeneratorExit} occurs, I suggest using a \code{try: ... finally:} suite instead of @@ -1663,6 +1664,13 @@ \item The \module{pyexpat} module now uses version 2.0 of the Expat parser. (Contributed by Trent Mick.) +\item The \class{Queue} class provided by the \module{Queue} module +gained two new methods. \method{join()} blocks until all items in +the queue have been retrieved and all processing work on the items +have been completed. Worker threads call the other new method, +\method{task_done()}, to signal that processing for an item has been +completed. (Contributed by Raymond Hettinger.) + \item The old \module{regex} and \module{regsub} modules, which have been deprecated ever since Python 2.0, have finally been deleted. Other deleted modules: \module{statcache}, \module{tzparse}, Modified: python/branches/p3yk-noslice/Grammar/Grammar ============================================================================== --- python/branches/p3yk-noslice/Grammar/Grammar (original) +++ python/branches/p3yk-noslice/Grammar/Grammar Thu Jan 11 00:21:28 2007 @@ -21,13 +21,20 @@ decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE decorators: decorator+ -funcdef: [decorators] 'def' NAME parameters ':' suite -parameters: '(' [varargslist] ')' -varargslist: ((fpdef ['=' test] ',')* - ('*' [NAME] (',' NAME ['=' test])* [',' '**' 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 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 Thu Jan 11 00:21:28 2007 @@ -30,6 +30,8 @@ typedef struct _arguments *arguments_ty; +typedef struct _arg *arg_ty; + typedef struct _keyword *keyword_ty; typedef struct _alias *alias_ty; @@ -74,6 +76,7 @@ arguments_ty args; asdl_seq *body; asdl_seq *decorators; + expr_ty returns; } FunctionDef; struct { @@ -328,12 +331,30 @@ struct _arguments { asdl_seq *args; identifier vararg; + expr_ty varargannotation; asdl_seq *kwonlyargs; identifier kwarg; + expr_ty kwargannotation; asdl_seq *defaults; asdl_seq *kw_defaults; }; +enum _arg_kind {SimpleArg_kind=1, NestedArgs_kind=2}; +struct _arg { + enum _arg_kind kind; + union { + struct { + identifier arg; + expr_ty annotation; + } SimpleArg; + + struct { + asdl_seq *args; + } NestedArgs; + + } v; +}; + struct _keyword { identifier arg; expr_ty value; @@ -350,8 +371,8 @@ 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, int lineno, int col_offset, PyArena - *arena); + 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); @@ -429,9 +450,12 @@ PyArena *arena); excepthandler_ty excepthandler(expr_ty type, expr_ty name, asdl_seq * body, int lineno, int col_offset, PyArena *arena); -arguments_ty arguments(asdl_seq * args, identifier vararg, asdl_seq * - kwonlyargs, identifier kwarg, asdl_seq * defaults, +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); Modified: python/branches/p3yk-noslice/Include/Python.h ============================================================================== --- python/branches/p3yk-noslice/Include/Python.h (original) +++ python/branches/p3yk-noslice/Include/Python.h Thu Jan 11 00:21:28 2007 @@ -48,14 +48,6 @@ #include "pyport.h" -/* pyconfig.h or pyport.h may or may not define DL_IMPORT */ -#ifndef DL_IMPORT /* declarations for DLL import/export */ -#define DL_IMPORT(RTYPE) RTYPE -#endif -#ifndef DL_EXPORT /* declarations for DLL import/export */ -#define DL_EXPORT(RTYPE) RTYPE -#endif - /* Debug-mode build with pymalloc implies PYMALLOC_DEBUG. * PYMALLOC_DEBUG is in error if pymalloc is not in use. */ Modified: python/branches/p3yk-noslice/Include/floatobject.h ============================================================================== --- python/branches/p3yk-noslice/Include/floatobject.h (original) +++ python/branches/p3yk-noslice/Include/floatobject.h Thu Jan 11 00:21:28 2007 @@ -34,19 +34,6 @@ PyAPI_FUNC(double) PyFloat_AsDouble(PyObject *); #define PyFloat_AS_DOUBLE(op) (((PyFloatObject *)(op))->ob_fval) -/* Write repr(v) into the char buffer argument, followed by null byte. The - buffer must be "big enough"; >= 100 is very safe. - PyFloat_AsReprString(buf, x) strives to print enough digits so that - PyFloat_FromString(buf) then reproduces x exactly. */ -PyAPI_FUNC(void) PyFloat_AsReprString(char*, PyFloatObject *v); - -/* Write str(v) into the char buffer argument, followed by null byte. The - buffer must be "big enough"; >= 100 is very safe. Note that it's - unusual to be able to get back the float you started with from - PyFloat_AsString's result -- use PyFloat_AsReprString() if you want to - preserve precision across conversions. */ -PyAPI_FUNC(void) PyFloat_AsString(char*, PyFloatObject *v); - /* _PyFloat_{Pack,Unpack}{4,8} * * The struct and pickle (at least) modules need an efficient platform- @@ -82,6 +69,11 @@ PyAPI_FUNC(int) _PyFloat_Pack4(double x, unsigned char *p, int le); PyAPI_FUNC(int) _PyFloat_Pack8(double x, unsigned char *p, int le); +/* Needed for the old way for marshal to store a floating point number. + Returns the string length copied into p, -1 on error. + */ +PyAPI_FUNC(int) _PyFloat_Repr(double x, char *p, size_t len); + /* The unpack routines read 4 or 8 bytes, starting at p. le is a bool * argument, true if the string is in little-endian format (exponent * last, at p+3 or p+7), false if big-endian (exponent first, at p). @@ -93,7 +85,6 @@ PyAPI_FUNC(double) _PyFloat_Unpack4(const unsigned char *p, int le); PyAPI_FUNC(double) _PyFloat_Unpack8(const unsigned char *p, int le); - #ifdef __cplusplus } #endif Modified: python/branches/p3yk-noslice/Include/funcobject.h ============================================================================== --- python/branches/p3yk-noslice/Include/funcobject.h (original) +++ python/branches/p3yk-noslice/Include/funcobject.h Thu Jan 11 00:21:28 2007 @@ -30,6 +30,7 @@ PyObject *func_dict; /* The __dict__ attribute, a dict or NULL */ PyObject *func_weakreflist; /* List of weak references */ PyObject *func_module; /* The __module__ attribute, can be anything */ + PyObject *func_annotations; /* Annotations, a dict or NULL */ /* Invariant: * func_closure contains the bindings for func_code->co_freevars, so @@ -52,6 +53,8 @@ PyAPI_FUNC(int) PyFunction_SetKwDefaults(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyFunction_GetClosure(PyObject *); PyAPI_FUNC(int) PyFunction_SetClosure(PyObject *, PyObject *); +PyAPI_FUNC(PyObject *) PyFunction_GetAnnotations(PyObject *); +PyAPI_FUNC(int) PyFunction_SetAnnotations(PyObject *, PyObject *); /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ @@ -67,6 +70,8 @@ (((PyFunctionObject *)func) -> func_kwdefaults) #define PyFunction_GET_CLOSURE(func) \ (((PyFunctionObject *)func) -> func_closure) +#define PyFunction_GET_ANNOTATIONS(func) \ + (((PyFunctionObject *)func) -> func_annotations) /* The classmethod and staticmethod types lives here, too */ PyAPI_DATA(PyTypeObject) PyClassMethod_Type; Modified: python/branches/p3yk-noslice/Include/graminit.h ============================================================================== --- python/branches/p3yk-noslice/Include/graminit.h (original) +++ python/branches/p3yk-noslice/Include/graminit.h Thu Jan 11 00:21:28 2007 @@ -5,79 +5,84 @@ #define decorators 260 #define funcdef 261 #define parameters 262 -#define varargslist 263 -#define fpdef 264 -#define fplist 265 -#define stmt 266 -#define simple_stmt 267 -#define small_stmt 268 -#define expr_stmt 269 -#define augassign 270 -#define print_stmt 271 -#define del_stmt 272 -#define pass_stmt 273 -#define flow_stmt 274 -#define break_stmt 275 -#define continue_stmt 276 -#define return_stmt 277 -#define yield_stmt 278 -#define raise_stmt 279 -#define import_stmt 280 -#define import_name 281 -#define import_from 282 -#define import_as_name 283 -#define dotted_as_name 284 -#define import_as_names 285 -#define dotted_as_names 286 -#define dotted_name 287 -#define global_stmt 288 -#define assert_stmt 289 -#define compound_stmt 290 -#define if_stmt 291 -#define while_stmt 292 -#define for_stmt 293 -#define try_stmt 294 -#define with_stmt 295 -#define with_var 296 -#define except_clause 297 -#define suite 298 -#define testlist_safe 299 -#define old_test 300 -#define old_lambdef 301 -#define test 302 -#define or_test 303 -#define and_test 304 -#define not_test 305 -#define comparison 306 -#define comp_op 307 -#define expr 308 -#define xor_expr 309 -#define and_expr 310 -#define shift_expr 311 -#define arith_expr 312 -#define term 313 -#define factor 314 -#define power 315 -#define atom 316 -#define listmaker 317 -#define testlist_gexp 318 -#define lambdef 319 -#define trailer 320 -#define subscriptlist 321 -#define subscript 322 -#define sliceop 323 -#define exprlist 324 -#define testlist 325 -#define dictsetmaker 326 -#define classdef 327 -#define arglist 328 -#define argument 329 -#define list_iter 330 -#define list_for 331 -#define list_if 332 -#define gen_iter 333 -#define gen_for 334 -#define gen_if 335 -#define testlist1 336 -#define encoding_decl 337 -#define yield_expr 338 +#define typedargslist 263 +#define tname 264 +#define tfpdef 265 +#define tfplist 266 +#define varargslist 267 +#define vname 268 +#define vfpdef 269 +#define vfplist 270 +#define stmt 271 +#define simple_stmt 272 +#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 Modified: python/branches/p3yk-noslice/Include/pyport.h ============================================================================== --- python/branches/p3yk-noslice/Include/pyport.h (original) +++ python/branches/p3yk-noslice/Include/pyport.h Thu Jan 11 00:21:28 2007 @@ -35,17 +35,6 @@ **************************************************************************/ - -/* For backward compatibility only. Obsolete, do not use. */ -#ifdef HAVE_PROTOTYPES -#define Py_PROTO(x) x -#else -#define Py_PROTO(x) () -#endif -#ifndef Py_FPROTO -#define Py_FPROTO(x) Py_PROTO(x) -#endif - /* typedefs for some C9X-defined synonyms for integral types. * * The names in Python are exactly the same as the C9X names, except with a @@ -226,9 +215,7 @@ /* NB caller must include */ #ifdef HAVE_SYS_SELECT_H - #include - #endif /* !HAVE_SYS_SELECT_H */ /******************************* @@ -504,7 +491,7 @@ #ifdef __BEOS__ /* Unchecked */ /* It's in the libs, but not the headers... - [cjh] */ -int shutdown( int, int ); +int shutdown(int, int); #endif #ifdef HAVE__GETPTY @@ -523,25 +510,6 @@ #endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) */ -/* These are pulled from various places. It isn't obvious on what platforms - they are necessary, nor what the exact prototype should look like (which - is likely to vary between platforms!) If you find you need one of these - declarations, please move them to a platform-specific block and include - proper prototypes. */ -#if 0 - -/* From Modules/resource.c */ -extern int getrusage(); -extern int getpagesize(); - -/* From Python/sysmodule.c and Modules/posixmodule.c */ -extern int fclose(FILE *); - -/* From Modules/posixmodule.c */ -extern int fdatasync(int); -#endif /* 0 */ - - /************************ * WRAPPER FOR * ************************/ @@ -651,56 +619,6 @@ # endif /* __cplusplus */ #endif -/* Deprecated DL_IMPORT and DL_EXPORT macros */ -#if defined(Py_ENABLE_SHARED) && defined (HAVE_DECLSPEC_DLL) -# if defined(Py_BUILD_CORE) -# define DL_IMPORT(RTYPE) __declspec(dllexport) RTYPE -# define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE -# else -# define DL_IMPORT(RTYPE) __declspec(dllimport) RTYPE -# define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE -# endif -#endif -#ifndef DL_EXPORT -# define DL_EXPORT(RTYPE) RTYPE -#endif -#ifndef DL_IMPORT -# define DL_IMPORT(RTYPE) RTYPE -#endif -/* End of deprecated DL_* macros */ - -/* If the fd manipulation macros aren't defined, - here is a set that should do the job */ - -#if 0 /* disabled and probably obsolete */ - -#ifndef FD_SETSIZE -#define FD_SETSIZE 256 -#endif - -#ifndef FD_SET - -typedef long fd_mask; - -#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */ -#ifndef howmany -#define howmany(x, y) (((x)+((y)-1))/(y)) -#endif /* howmany */ - -typedef struct fd_set { - fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)]; -} fd_set; - -#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS))) -#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS))) -#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS))) -#define FD_ZERO(p) memset((char *)(p), '\0', sizeof(*(p))) - -#endif /* FD_SET */ - -#endif /* fd manipulation macros */ - - /* limits.h constants that may be missing */ #ifndef INT_MAX Modified: python/branches/p3yk-noslice/Include/stringobject.h ============================================================================== --- python/branches/p3yk-noslice/Include/stringobject.h (original) +++ python/branches/p3yk-noslice/Include/stringobject.h Thu Jan 11 00:21:28 2007 @@ -28,7 +28,7 @@ Interning strings (ob_sstate) tries to ensure that only one string object with a given value exists, so equality tests can be one pointer comparison. This is generally restricted to strings that "look like" - Python identifiers, although the intern() builtin can be used to force + Python identifiers, although the sys.intern() function can be used to force interning of any string. Together, these sped the interpreter by up to 20%. */ Modified: python/branches/p3yk-noslice/Include/token.h ============================================================================== --- python/branches/p3yk-noslice/Include/token.h (original) +++ python/branches/p3yk-noslice/Include/token.h Thu Jan 11 00:21:28 2007 @@ -58,10 +58,11 @@ #define DOUBLESLASH 48 #define DOUBLESLASHEQUAL 49 #define AT 50 +#define RARROW 51 /* Don't forget to update the table _PyParser_TokenNames in tokenizer.c! */ -#define OP 51 -#define ERRORTOKEN 52 -#define N_TOKENS 53 +#define OP 52 +#define ERRORTOKEN 53 +#define N_TOKENS 54 /* Special definitions for cooperation with parser */ Modified: python/branches/p3yk-noslice/LICENSE ============================================================================== --- python/branches/p3yk-noslice/LICENSE (original) +++ python/branches/p3yk-noslice/LICENSE Thu Jan 11 00:21:28 2007 @@ -88,9 +88,9 @@ prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) -2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights -Reserved" are retained in Python alone or in any derivative version -prepared by Licensee. +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make Modified: python/branches/p3yk-noslice/Lib/CGIHTTPServer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/CGIHTTPServer.py (original) +++ python/branches/p3yk-noslice/Lib/CGIHTTPServer.py Thu Jan 11 00:21:28 2007 @@ -105,17 +105,36 @@ def run_cgi(self): """Execute a CGI script.""" + path = self.path dir, rest = self.cgi_info + + i = path.find('/', len(dir) + 1) + while i >= 0: + nextdir = path[:i] + nextrest = path[i+1:] + + scriptdir = self.translate_path(nextdir) + if os.path.isdir(scriptdir): + dir, rest = nextdir, nextrest + i = path.find('/', len(dir) + 1) + else: + break + + # find an explicit query string, if present. i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' + + # dissect the part after the directory name into a script name & + # a possible additional path, to be stored in PATH_INFO. i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' + scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): Modified: python/branches/p3yk-noslice/Lib/SimpleHTTPServer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/SimpleHTTPServer.py (original) +++ python/branches/p3yk-noslice/Lib/SimpleHTTPServer.py Thu Jan 11 00:21:28 2007 @@ -66,6 +66,12 @@ path = self.translate_path(self.path) f = None if os.path.isdir(path): + if not self.path.endswith('/'): + # redirect browser - doing basically what apache does + self.send_response(301) + self.send_header("Location", self.path + "/") + self.end_headers() + return None for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): Modified: python/branches/p3yk-noslice/Lib/StringIO.py ============================================================================== --- python/branches/p3yk-noslice/Lib/StringIO.py (original) +++ python/branches/p3yk-noslice/Lib/StringIO.py Thu Jan 11 00:21:28 2007 @@ -139,7 +139,7 @@ return r def readline(self, length=None): - """Read one entire line from the file. + r"""Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is Modified: python/branches/p3yk-noslice/Lib/bsddb/dbobj.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/dbobj.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/dbobj.py Thu Jan 11 00:21:28 2007 @@ -55,8 +55,9 @@ return self._cobj.set_lg_max(*args, **kwargs) def set_lk_detect(self, *args, **kwargs): return self._cobj.set_lk_detect(*args, **kwargs) - def set_lk_max(self, *args, **kwargs): - return self._cobj.set_lk_max(*args, **kwargs) + if db.version() < (4,5): + def set_lk_max(self, *args, **kwargs): + return self._cobj.set_lk_max(*args, **kwargs) def set_lk_max_locks(self, *args, **kwargs): return self._cobj.set_lk_max_locks(*args, **kwargs) def set_lk_max_lockers(self, *args, **kwargs): Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_1413192.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_1413192.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_1413192.py Thu Jan 11 00:21:28 2007 @@ -14,7 +14,7 @@ env_name = '.' env = db.DBEnv() -env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN) +env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN | db.DB_INIT_MPOOL) the_txn = env.txn_begin() map = db.DB(env) Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -91,7 +91,7 @@ class AssociateErrorTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -54,7 +54,7 @@ def setUp(self): if self.useEnv: - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: shutil.rmtree(homeDir) Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_dbobj.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_dbobj.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_dbobj.py Thu Jan 11 00:21:28 2007 @@ -2,6 +2,7 @@ import sys, os, string import unittest import glob +import tempfile try: # For Pythons w/distutils pybsddb @@ -19,7 +20,7 @@ db_name = 'test-dbobj.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -242,7 +242,7 @@ class BasicEnvShelveTestCase(DBShelveTestCase): def do_open(self): self.homeDir = homeDir = os.path.join( - os.path.dirname(sys.argv[0]), 'db_home') + tempfile.gettempdir(), 'db_home') try: os.mkdir(homeDir) except os.error: pass self.env = db.DBEnv() Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -26,6 +26,7 @@ pickle = cPickle except ImportError: import pickle +import tempfile import unittest from .test_all import verbose @@ -46,7 +47,7 @@ db_name = 'test-table.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_env_close.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_env_close.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_env_close.py Thu Jan 11 00:21:28 2007 @@ -33,7 +33,7 @@ class DBEnvClosedEarlyCrash(unittest.TestCase): def setUp(self): - self.homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + self.homeDir = os.path.join(tempfile.gettempdir(), 'db_home') try: os.mkdir(self.homeDir) except os.error: pass tempfile.tempdir = self.homeDir Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -49,7 +49,7 @@ def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -30,7 +30,7 @@ class LockingTestCase(unittest.TestCase): def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_misc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_misc.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_misc.py Thu Jan 11 00:21:28 2007 @@ -4,6 +4,7 @@ import os import sys import unittest +import tempfile try: # For Pythons w/distutils pybsddb @@ -17,7 +18,7 @@ class MiscTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -203,10 +203,10 @@ just a line in the file, but you can set a different record delimiter if needed. """ - source = os.path.join(os.path.dirname(sys.argv[0]), - 'db_home/test_recno.txt') - if not os.path.isdir('db_home'): - os.mkdir('db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') + source = os.path.join(homeDir, 'test_recno.txt') + if not os.path.isdir(homeDir): + os.mkdir(homeDir) f = open(source, 'w') # create the file f.close() Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -53,7 +53,7 @@ if verbose: dbutils._deadlock_VerboseFile = sys.stdout - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/p3yk-noslice/Lib/compiler/ast.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/ast.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/ast.py Thu Jan 11 00:21:28 2007 @@ -33,7 +33,10 @@ pass # implemented by subclasses class EmptyNode(Node): - pass + def getChildNodes(self): + return () + def getChildren(self): + return () class Expression(Node): # Expression is an artificial node class to support "eval" @@ -487,12 +490,13 @@ return "From(%s, %s, %s)" % (repr(self.modname), repr(self.names), repr(self.level)) class Function(Node): - def __init__(self, decorators, name, argnames, defaults, kwonlyargs, flags, doc, code, lineno=None): + def __init__(self, decorators, name, arguments, defaults, kwonlyargs, returns, flags, doc, code, lineno=None): self.decorators = decorators self.name = name - self.argnames = argnames + self.arguments = arguments self.defaults = defaults self.kwonlyargs = kwonlyargs + self.returns = returns self.flags = flags self.doc = doc self.code = code @@ -508,9 +512,10 @@ children = [] children.append(self.decorators) children.append(self.name) - children.append(self.argnames) + children.extend(flatten(self.arguments)) children.extend(flatten(self.defaults)) - children.append(self.kwonlyargs) + children.extend(flatten(self.kwonlyargs)) + children.append(self.returns) children.append(self.flags) children.append(self.doc) children.append(self.code) @@ -520,18 +525,22 @@ nodelist = [] if self.decorators is not None: nodelist.append(self.decorators) + nodelist.extend(flatten_nodes(self.arguments)) nodelist.extend(flatten_nodes(self.defaults)) + nodelist.extend(flatten_nodes(self.kwonlyargs)) + if self.returns is not None: + nodelist.append(self.returns) nodelist.append(self.code) return tuple(nodelist) def __repr__(self): - return "Function(%s, %s, %s, %s, %s, %s, %s, %s)" % (repr(self.decorators), repr(self.name), repr(self.argnames), repr(self.defaults), repr(self.kwonlyargs), repr(self.flags), repr(self.doc), repr(self.code)) + return "Function(%s, %s, %s, %s, %s, %s, %s, %s, %s)" % (repr(self.decorators), repr(self.name), repr(self.arguments), repr(self.defaults), repr(self.kwonlyargs), repr(self.returns), repr(self.flags), repr(self.doc), repr(self.code)) class GenExpr(Node): def __init__(self, code, lineno=None): self.code = code self.lineno = lineno - self.argnames = ['.0'] + self.arguments = [SimpleArg('.0', None)] self.varargs = self.kwargs = None self.kwonlyargs = () @@ -715,9 +724,24 @@ def __repr__(self): return "Keyword(%s, %s)" % (repr(self.name), repr(self.expr)) +class Kwarg(Node): + def __init__(self, arg, expr, lineno=None): + self.arg = arg + self.expr = expr + self.lineno = lineno + + def getChildren(self): + return self.arg, self.expr + + def getChildNodes(self): + return self.arg, self.expr + + def __repr__(self): + return "Kwarg(%s, %s)" % (repr(self.arg), repr(self.expr)) + class Lambda(Node): - def __init__(self, argnames, defaults, kwonlyargs, flags, code, lineno=None): - self.argnames = argnames + def __init__(self, arguments, defaults, kwonlyargs, flags, code, lineno=None): + self.arguments = arguments self.defaults = defaults self.kwonlyargs = kwonlyargs self.flags = flags @@ -728,25 +752,28 @@ self.varargs = 1 if flags & CO_VARKEYWORDS: self.kwargs = 1 + self.returns = None def getChildren(self): children = [] - children.append(self.argnames) + children.extend(flatten(self.arguments)) children.extend(flatten(self.defaults)) - children.append(self.kwonlyargs) + children.extend(flatten(self.kwonlyargs)) children.append(self.flags) children.append(self.code) return tuple(children) def getChildNodes(self): nodelist = [] + nodelist.extend(flatten_nodes(self.arguments)) nodelist.extend(flatten_nodes(self.defaults)) + nodelist.extend(flatten_nodes(self.kwonlyargs)) nodelist.append(self.code) return tuple(nodelist) def __repr__(self): - return "Lambda(%s, %s, %s, %s, %s)" % (repr(self.argnames), repr(self.defaults), repr(self.kwonlyargs), repr(self.flags), repr(self.code)) + return "Lambda(%s, %s, %s, %s, %s)" % (repr(self.arguments), repr(self.defaults), repr(self.kwonlyargs), repr(self.flags), repr(self.code)) class LeftShift(Node): def __init__(self, (left, right), lineno=None): @@ -897,6 +924,22 @@ def __repr__(self): return "Name(%s)" % (repr(self.name),) +class NestedArgs(Node): + def __init__(self, args, lineno=None): + self.args = args + self.lineno = lineno + + def getChildren(self): + return tuple(flatten(self.args)) + + def getChildNodes(self): + nodelist = [] + nodelist.extend(flatten_nodes(self.args)) + return tuple(nodelist) + + def __repr__(self): + return "NestedArgs(%s)" % (repr(self.args),) + class Not(Node): def __init__(self, expr, lineno=None): self.expr = expr @@ -1071,6 +1114,27 @@ def __repr__(self): return "Set(%s)" % (repr(self.items),) +class SimpleArg(Node): + def __init__(self, name, annotation, lineno=None): + self.name = name + self.annotation = annotation + self.lineno = lineno + + def getChildren(self): + children = [] + children.append(self.name) + children.append(self.annotation) + return tuple(children) + + def getChildNodes(self): + nodelist = [] + if self.annotation is not None: + nodelist.append(self.annotation) + return tuple(nodelist) + + def __repr__(self): + return "SimpleArg(%s, %s)" % (repr(self.name), repr(self.annotation)) + class Slice(Node): def __init__(self, expr, flags, lower, upper, lineno=None): self.expr = expr 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 Thu Jan 11 00:21:28 2007 @@ -314,7 +314,7 @@ super_init = FlowGraph.__init__ def __init__(self, name, filename, - args=(), kwonlyargs={}, optimized=0, klass=None): + args=(), kwonlyargs=(), optimized=0, klass=None): self.super_init() self.name = name self.filename = filename @@ -338,24 +338,40 @@ # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] - self.varnames = list(args) or [] - for i in range(len(self.varnames)): + # The varnames list needs to be computed after flags have been set + self.varnames = [] + self.stage = RAW + + def computeVarnames(self): + # self.args is positional, vararg, kwarg, kwonly, unpacked. This + # order is due to the visit order in symbol module and could change. + # argcount is # len(self.args) - len(unpacked). We want + # self.varnames to be positional, kwonly, vararg, kwarg, unpacked + # and argcount to be len(positional). + + # determine starting index of unpacked, kwonly, vararg + u = self.argcount # starting index of unpacked + k = u - len(self.kwonlyargs) # starting index of kwonly + v = k - self.checkFlag(CO_VARARGS) - self.checkFlag(CO_VARKEYWORDS) + + vars = list(self.args) + self.varnames = vars[:v] + vars[k:u] + vars[v:k] + vars[u:] + self.argcount = v + + # replace TupleArgs with calculated var name + for i in range(self.argcount): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() - self.stage = RAW def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag - if flag == CO_VARARGS: - self.argcount = self.argcount - 1 def checkFlag(self, flag): - if self.flags & flag: - return 1 + return (self.flags & flag) == flag def setFreeVars(self, names): self.freevars = list(names) @@ -366,6 +382,7 @@ def getCode(self): """Get a Python code object""" assert self.stage == RAW + self.computeVarnames() self.computeStackDepth() self.flattenGraph() assert self.stage == FLAT @@ -575,6 +592,12 @@ lnotab.nextLine(oparg) continue hi, lo = twobyte(oparg) + + extended, hi = twobyte(hi) + if extended: + ehi, elo = twobyte(extended) + lnotab.addCode(self.opnum['EXTENDED_ARG'], elo, ehi) + try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: @@ -595,8 +618,6 @@ else: nlocals = len(self.varnames) argcount = self.argcount - if self.flags & CO_VARKEYWORDS: - argcount = argcount - 1 kwonlyargcount = len(self.kwonlyargs) return new.code(argcount, kwonlyargcount, nlocals, self.stacksize, self.flags, @@ -798,7 +819,8 @@ return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): hi, lo = divmod(argc, 256) - return -(lo + hi * 2) + ehi, hi = divmod(hi, 256) + return -(lo + hi * 2 + ehi) def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc 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 Thu Jan 11 00:21:28 2007 @@ -378,18 +378,57 @@ walk(node.code, gen) gen.finish() self.set_lineno(node) + num_kwargs = 0 for keyword in node.kwonlyargs: default = keyword.expr if isinstance(default, ast.EmptyNode): continue - self.emit('LOAD_CONST', keyword.name) + self.emit('LOAD_CONST', keyword.arg.name) self.visit(default) + num_kwargs += 1 for default in node.defaults: self.visit(default) - self._makeClosure(gen, len(node.defaults)) + + num_annotations = self._visit_annotations(node) + + oparg = len(node.defaults) + oparg |= num_kwargs << 8 + oparg |= num_annotations << 16 + + self._makeClosure(gen, oparg) for i in range(ndecorators): self.emit('CALL_FUNCTION', 1) + def _visit_annotations(self, node): + # emit code, return num_annotations + annotations = [] + annotations.extend(self._visit_argument_annotations(node.arguments)) + annotations.extend(self._visit_kwarg_annotations(node.kwonlyargs)) + if node.returns: + self.visit(node.returns) + annotations.append('return') + if not annotations: + return 0 + self.emit('LOAD_CONST', tuple(annotations)) + return len(annotations) + 1 + + def _visit_argument_annotations(self, arguments): + for arg in arguments: + if isinstance(arg, ast.SimpleArg): + if arg.annotation: + self.visit(arg.annotation) + yield arg.name + else: + for name in self._visit_argument_annotations(arg.args): + yield name + + def _visit_kwarg_annotations(self, kwargs): + for kwarg in kwargs: + arg = kwarg.arg + if arg.annotation: + self.visit(arg.annotation) + yield arg.name + def visitClass(self, node): gen = self.ClassGen(node, self.scopes, self.get_module()) @@ -1279,7 +1318,7 @@ else: name = func.name - args, hasTupleArg = generateArgList(func.argnames) + args, hasTupleArg = generateArgList(func.arguments) kwonlyargs = generateKwonlyArgList(func.kwonlyargs) self.graph = pyassem.PyFlowGraph(name, func.filename, args, kwonlyargs=kwonlyargs, @@ -1290,7 +1329,7 @@ if not isLambda and func.doc: self.setDocstring(func.doc) - lnf = walk(func.code, self.NameFinder(args), verbose=0) + lnf = walk(func.code, self.NameFinder(args+kwonlyargs), verbose=0) self.locals.push(lnf.getLocals()) if func.varargs: self.graph.setFlag(CO_VARARGS) @@ -1298,7 +1337,7 @@ self.graph.setFlag(CO_VARKEYWORDS) self.set_lineno(func) if hasTupleArg: - self.generateArgUnpack(func.argnames) + self.generateArgUnpack(func.arguments) def get_module(self): return self.module @@ -1312,9 +1351,9 @@ def generateArgUnpack(self, args): for i in range(len(args)): arg = args[i] - if isinstance(arg, tuple): + if isinstance(arg, ast.NestedArgs): self.emit('LOAD_FAST', '.%d' % (i * 2)) - self.unpackSequence(arg) + self.unpackSequence(tuple(_nested_names(arg))) def unpackSequence(self, tup): if VERSION > 1: @@ -1408,21 +1447,29 @@ count = 0 for i in range(len(arglist)): elt = arglist[i] - if isinstance(elt, str): - args.append(elt) - elif isinstance(elt, tuple): - args.append(TupleArg(i * 2, elt)) - extra.extend(misc.flatten(elt)) + if isinstance(elt, ast.SimpleArg): + args.append(elt.name) + elif isinstance(elt, ast.NestedArgs): + t = tuple(_nested_names(elt)) + args.append(TupleArg(i * 2, t)) + extra.extend(misc.flatten(t)) count = count + 1 else: raise ValueError, "unexpect argument type:", elt return args + extra, count +def _nested_names(elt): + for arg in elt.args: + if isinstance(arg, ast.SimpleArg): + yield arg.name + elif isinstance(arg, ast.NestedArgs): + yield tuple(_nested_names(arg)) + def generateKwonlyArgList(keywordOnlyArgs): - kwonlyargs = {} + kwonlyargs = [] for elt in keywordOnlyArgs: - assert isinstance(elt, ast.Keyword) - kwonlyargs[elt.name] = elt.expr + assert isinstance(elt, ast.Kwarg) + kwonlyargs.append(elt.arg.name) return kwonlyargs def findOp(node): 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 Thu Jan 11 00:21:28 2007 @@ -233,7 +233,12 @@ if parent.nested or isinstance(parent, FunctionScope): scope.nested = 1 self.scopes[node] = scope - self._do_args(scope, node.argnames) + + args = node.arguments + for kwonly in node.kwonlyargs: + args.append(kwonly.arg) + self._do_arguments(scope, args) + self.visit(node.code, scope) self.handle_free_vars(scope, parent) @@ -275,16 +280,18 @@ if parent.nested or isinstance(parent, FunctionScope): scope.nested = 1 self.scopes[node] = scope - self._do_args(scope, node.argnames) + self._do_arguments(scope, node.arguments) self.visit(node.code, scope) self.handle_free_vars(scope, parent) - def _do_args(self, scope, args): - for name in args: - if type(name) == types.TupleType: - self._do_args(scope, name) + def _do_arguments(self, scope, arguments): + for node in arguments: + if isinstance(node, ast.SimpleArg): + scope.add_param(node.name) + if node.annotation: + self.visit(node.annotation, scope) else: - scope.add_param(name) + self._do_arguments(scope, node.args) def handle_free_vars(self, scope, parent): parent.add_child(scope) 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 Thu Jan 11 00:21:28 2007 @@ -234,25 +234,24 @@ return Decorators(items) def funcdef(self, nodelist): - # -6 -5 -4 -3 -2 -1 - # funcdef: [decorators] 'def' NAME parameters ':' suite - # parameters: '(' [varargslist] ')' - - if len(nodelist) == 6: - assert nodelist[0][0] == symbol.decorators + # 0 1 2 4 -1 + # funcdef: [decorators] 'def' NAME parameters ['->' test] ':' suite + # parameters: '(' [typedargslist] ')' + if nodelist[0][0] == symbol.decorators: decorators = self.decorators(nodelist[0][1:]) + nodelist = nodelist[1:] else: - assert len(nodelist) == 5 decorators = None + assert len(nodelist) in (5, 7) - lineno = nodelist[-4][2] - name = nodelist[-4][1] - args = nodelist[-3][2] + lineno = nodelist[0][2] + name = nodelist[1][1] + args = nodelist[2][2] - if args[0] == symbol.varargslist: - names, defaults, kwonlyargs, flags = self.com_arglist(args[1:]) + if args[0] == symbol.varargslist or args[0] == symbol.typedargslist: + arguments, defaults, kwonly, flags = self.com_arglist(args[1:]) else: - names = defaults = kwonlyargs = () + arguments = defaults = kwonly = () flags = 0 doc = self.get_docstring(nodelist[-1]) @@ -263,22 +262,28 @@ assert isinstance(code, Stmt) assert isinstance(code.nodes[0], Discard) del code.nodes[0] - return Function(decorators, name, names, defaults, - kwonlyargs, flags, doc, code, lineno=lineno) + + if len(nodelist) == 7: + returns = self.com_node(nodelist[4]) + else: + returns = None + + return Function(decorators, name, arguments, defaults, + kwonly, returns, flags, doc, code, lineno=lineno) def lambdef(self, nodelist): # lambdef: 'lambda' [varargslist] ':' test if nodelist[2][0] == symbol.varargslist: - names, defaults, kwonlyargs, flags = \ + arguments, defaults, kwonlyargs, flags = \ self.com_arglist(nodelist[2][1:]) else: - names = defaults = kwonlyargs = () + arguments = defaults = kwonlyargs = () flags = 0 # code for lambda code = self.com_node(nodelist[-1]) - return Lambda(names, defaults, kwonlyargs, + return Lambda(arguments, defaults, kwonlyargs, flags, code, lineno=nodelist[1][2]) old_lambdef = lambdef @@ -324,10 +329,25 @@ def varargslist(self, nodelist): raise WalkerError - def fpdef(self, nodelist): + def vfpdef(self, nodelist): raise WalkerError - def fplist(self, nodelist): + def vfplist(self, nodelist): + raise WalkerError + + def vname(self, nodelist): + raise WalkerError + + def typedargslist(self, nodelist): + raise WalkerError + + def tfpdef(self, nodelist): + raise WalkerError + + def tfplist(self, nodelist): + raise WalkerError + + def tname(self, nodelist): raise WalkerError def dotted_name(self, nodelist): @@ -786,9 +806,10 @@ return Discard(Const(None)) def keywordonlyargs(self, nodelist): - # (',' NAME ['=' test])* + # (',' tname ['=' test])* # ^^^ # ------+ + # tname and vname are handled. kwonlyargs = [] i = 0 while i < len(nodelist): @@ -802,10 +823,25 @@ i += 2 if node[0] == token.DOUBLESTAR: return kwonlyargs, i - elif node[0] == token.NAME: - kwonlyargs.append(Keyword(node[1], default, lineno=node[2])) + elif node[0] in (symbol.vname, symbol.tname): + lineno = extractLineNo(node) + kwarg = Kwarg(self._simplearg(node), default, lineno=lineno) + kwonlyargs.append(kwarg) i += 2 return kwonlyargs, i + + def _simplearg(self, node): + # tname: NAME [':' test] + # vname: NAME + assert node[0] == symbol.vname or node[0] == symbol.tname + name = node[1][1] + lineno = node[1][2] + assert isinstance(name, str) + if len(node) > 2: + annotation = self.com_node(node[3]) + else: + annotation = None + return SimpleArg(name, annotation, lineno) def com_arglist(self, nodelist): # varargslist: @@ -814,7 +850,7 @@ # | fpdef ['=' test] (',' fpdef ['=' test])* [','] # fpdef: NAME | '(' fplist ')' # fplist: fpdef (',' fpdef)* [','] - names = [] + arguments = [] kwonlyargs = [] defaults = [] flags = 0 @@ -825,14 +861,15 @@ if node[0] == token.STAR or node[0] == token.DOUBLESTAR: if node[0] == token.STAR: node = nodelist[i+1] - if node[0] == token.NAME: # vararg - names.append(node[1]) + if node[0] in (symbol.tname, symbol.vname): # vararg + arguments.append(self._simplearg(node)) flags = flags | CO_VARARGS i = i + 3 else: # no vararg assert node[0] == token.COMMA i += 2 - if i < len(nodelist) and nodelist[i][0] == token.NAME: + if i < len(nodelist) and \ + nodelist[i][0] in (symbol.tname, symbol.vname): kwonlyargs, skip = self.keywordonlyargs(nodelist[i:]) i += skip @@ -843,13 +880,13 @@ node = nodelist[i+1] else: raise ValueError, "unexpected token: %s" % t - names.append(node[1]) + arguments.append(self._simplearg(node)) flags = flags | CO_VARKEYWORDS break - # fpdef: NAME | '(' fplist ')' - names.append(self.com_fpdef(node)) + # tfpdef: tname | '(' tfplist ')' + arguments.append(self.com_tfpdef(node)) i = i + 1 if i < len(nodelist) and nodelist[i][0] == token.EQUAL: @@ -863,21 +900,24 @@ # skip the comma i = i + 1 - return names, defaults, kwonlyargs, flags + return arguments, defaults, kwonlyargs, flags - def com_fpdef(self, node): - # fpdef: NAME | '(' fplist ')' + def com_tfpdef(self, node): + # tfpdef: tname | '(' tfplist ')' + # def f((x)): -- x is not nested + while node[1][0] == token.LPAR and len(node[2]) == 2: + node = node[2][1] if node[1][0] == token.LPAR: - return self.com_fplist(node[2]) - return node[1][1] + return NestedArgs(self.com_tfplist(node[2])) + return self._simplearg(node[1]) - def com_fplist(self, node): - # fplist: fpdef (',' fpdef)* [','] + def com_tfplist(self, node): + # tfplist: tfpdef (',' tfpdef)* [','] if len(node) == 2: - return self.com_fpdef(node[1]) + return self.com_tfpdef(node[1]), list = [] for i in range(1, len(node), 2): - list.append(self.com_fpdef(node[i])) + list.append(self.com_tfpdef(node[i])) return tuple(list) def com_dotted_name(self, node): Modified: python/branches/p3yk-noslice/Lib/cookielib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/cookielib.py (original) +++ python/branches/p3yk-noslice/Lib/cookielib.py Thu Jan 11 00:21:28 2007 @@ -1316,26 +1316,28 @@ """ _debug("add_cookie_header") self._cookies_lock.acquire() + try: - self._policy._now = self._now = int(time.time()) - - cookies = self._cookies_for_request(request) + self._policy._now = self._now = int(time.time()) - attrs = self._cookie_attrs(cookies) - if attrs: - if not request.has_header("Cookie"): - request.add_unredirected_header( - "Cookie", "; ".join(attrs)) - - # if necessary, advertise that we know RFC 2965 - if (self._policy.rfc2965 and not self._policy.hide_cookie2 and - not request.has_header("Cookie2")): - for cookie in cookies: - if cookie.version != 1: - request.add_unredirected_header("Cookie2", '$Version="1"') - break + cookies = self._cookies_for_request(request) - self._cookies_lock.release() + attrs = self._cookie_attrs(cookies) + if attrs: + if not request.has_header("Cookie"): + request.add_unredirected_header( + "Cookie", "; ".join(attrs)) + + # if necessary, advertise that we know RFC 2965 + if (self._policy.rfc2965 and not self._policy.hide_cookie2 and + not request.has_header("Cookie2")): + for cookie in cookies: + if cookie.version != 1: + request.add_unredirected_header("Cookie2", '$Version="1"') + break + + finally: + self._cookies_lock.release() self.clear_expired_cookies() @@ -1602,12 +1604,15 @@ def set_cookie_if_ok(self, cookie, request): """Set a cookie if policy says it's OK to do so.""" self._cookies_lock.acquire() - self._policy._now = self._now = int(time.time()) + try: + self._policy._now = self._now = int(time.time()) - if self._policy.set_ok(cookie, request): - self.set_cookie(cookie) + if self._policy.set_ok(cookie, request): + self.set_cookie(cookie) + - self._cookies_lock.release() + finally: + self._cookies_lock.release() def set_cookie(self, cookie): """Set a cookie, without checking whether or not it should be set.""" @@ -1626,13 +1631,15 @@ """Extract cookies from response, where allowable given the request.""" _debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() - self._policy._now = self._now = int(time.time()) + try: + self._policy._now = self._now = int(time.time()) - for cookie in self.make_cookies(response, request): - if self._policy.set_ok(cookie, request): - _debug(" setting cookie: %s", cookie) - self.set_cookie(cookie) - self._cookies_lock.release() + for cookie in self.make_cookies(response, request): + if self._policy.set_ok(cookie, request): + _debug(" setting cookie: %s", cookie) + self.set_cookie(cookie) + finally: + self._cookies_lock.release() def clear(self, domain=None, path=None, name=None): """Clear some cookies. @@ -1669,10 +1676,12 @@ """ self._cookies_lock.acquire() - for cookie in self: - if cookie.discard: - self.clear(cookie.domain, cookie.path, cookie.name) - self._cookies_lock.release() + try: + for cookie in self: + if cookie.discard: + self.clear(cookie.domain, cookie.path, cookie.name) + finally: + self._cookies_lock.release() def clear_expired_cookies(self): """Discard all expired cookies. @@ -1685,11 +1694,13 @@ """ self._cookies_lock.acquire() - now = time.time() - for cookie in self: - if cookie.is_expired(now): - self.clear(cookie.domain, cookie.path, cookie.name) - self._cookies_lock.release() + try: + now = time.time() + for cookie in self: + if cookie.is_expired(now): + self.clear(cookie.domain, cookie.path, cookie.name) + finally: + self._cookies_lock.release() def __iter__(self): return deepvalues(self._cookies) @@ -1761,16 +1772,18 @@ else: raise ValueError(MISSING_FILENAME_TEXT) self._cookies_lock.acquire() - - old_state = copy.deepcopy(self._cookies) - self._cookies = {} try: - self.load(filename, ignore_discard, ignore_expires) - except (LoadError, IOError): - self._cookies = old_state - raise - self._cookies_lock.release() + old_state = copy.deepcopy(self._cookies) + self._cookies = {} + try: + self.load(filename, ignore_discard, ignore_expires) + except (LoadError, IOError): + self._cookies = old_state + raise + + finally: + self._cookies_lock.release() from _LWPCookieJar import LWPCookieJar, lwp_cookie_str from _MozillaCookieJar import MozillaCookieJar Modified: python/branches/p3yk-noslice/Lib/difflib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/difflib.py (original) +++ python/branches/p3yk-noslice/Lib/difflib.py Thu Jan 11 00:21:28 2007 @@ -1310,7 +1310,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, charjunk=IS_CHARACTER_JUNK): - """Returns generator yielding marked up from/to side by side differences. + r"""Returns generator yielding marked up from/to side by side differences. Arguments: fromlines -- list of text lines to compared to tolines Modified: python/branches/p3yk-noslice/Lib/dumbdbm.py ============================================================================== --- python/branches/p3yk-noslice/Lib/dumbdbm.py (original) +++ python/branches/p3yk-noslice/Lib/dumbdbm.py Thu Jan 11 00:21:28 2007 @@ -68,7 +68,8 @@ try: f = _open(self._datfile, 'r') except IOError: - f = _open(self._datfile, 'w', self._mode) + f = _open(self._datfile, 'w') + self._chmod(self._datfile) f.close() self._update() @@ -106,7 +107,8 @@ except self._os.error: pass - f = self._open(self._dirfile, 'w', self._mode) + f = self._open(self._dirfile, 'w') + self._chmod(self._dirfile) for key, pos_and_siz_pair in self._index.iteritems(): f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -152,7 +154,8 @@ # the in-memory index dict, and append one to the directory file. def _addkey(self, key, pos_and_siz_pair): self._index[key] = pos_and_siz_pair - f = _open(self._dirfile, 'a', self._mode) + f = _open(self._dirfile, 'a') + self._chmod(self._dirfile) f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -211,6 +214,9 @@ __del__ = close + def _chmod (self, file): + if hasattr(self._os, 'chmod'): + self._os.chmod(file, self._mode) def open(file, flag=None, mode=0666): @@ -227,4 +233,15 @@ """ # flag argument is currently ignored + + # Modify mode depending on the umask + try: + um = _os.umask(0) + _os.umask(um) + except AttributeError: + pass + else: + # Turn off any bits that are set in the umask + mode = mode & (~um) + return _Database(file, mode) Modified: python/branches/p3yk-noslice/Lib/heapq.py ============================================================================== --- python/branches/p3yk-noslice/Lib/heapq.py (original) +++ python/branches/p3yk-noslice/Lib/heapq.py Thu Jan 11 00:21:28 2007 @@ -130,7 +130,7 @@ 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee -from operator import itemgetter +from operator import itemgetter, neg import bisect def heappush(heap, item): @@ -315,8 +315,6 @@ Equivalent to: sorted(iterable, key=key)[:n] """ - if key is None: - return _nsmallest(n, iterable) in1, in2 = tee(iterable) it = izip(imap(key, in1), count(), in2) # decorate result = _nsmallest(n, it) @@ -328,10 +326,8 @@ Equivalent to: sorted(iterable, key=key, reverse=True)[:n] """ - if key is None: - return _nlargest(n, iterable) in1, in2 = tee(iterable) - it = izip(imap(key, in1), count(), in2) # decorate + it = izip(imap(key, in1), imap(neg, count()), in2) # decorate result = _nlargest(n, it) return map(itemgetter(2), result) # undecorate Modified: python/branches/p3yk-noslice/Lib/hmac.py ============================================================================== --- python/branches/p3yk-noslice/Lib/hmac.py (original) +++ python/branches/p3yk-noslice/Lib/hmac.py Thu Jan 11 00:21:28 2007 @@ -3,13 +3,11 @@ Implements the HMAC algorithm as described by RFC 2104. """ -def _strxor(s1, s2): - """Utility method. XOR the two strings s1 and s2 (must have same length). - """ - return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) +trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)]) +trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)]) # The size of the digests returned by HMAC depends on the underlying -# hashing module used. +# hashing module used. Use digest_size from the instance of HMAC instead. digest_size = None # A unique object passed by HMAC.copy() to the HMAC constructor, in order @@ -22,6 +20,7 @@ This supports the API for Cryptographic Hash Functions (PEP 247). """ + blocksize = 64 # 512-bit HMAC; can be changed in subclasses. def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. @@ -49,16 +48,13 @@ self.inner = self.digest_cons() self.digest_size = self.inner.digest_size - blocksize = 64 - ipad = "\x36" * blocksize - opad = "\x5C" * blocksize - + blocksize = self.blocksize if len(key) > blocksize: key = self.digest_cons(key).digest() key = key + chr(0) * (blocksize - len(key)) - self.outer.update(_strxor(key, opad)) - self.inner.update(_strxor(key, ipad)) + self.outer.update(key.translate(trans_5C)) + self.inner.update(key.translate(trans_36)) if msg is not None: self.update(msg) @@ -75,13 +71,22 @@ An update to this copy won't affect the original object. """ - other = HMAC(_secret_backdoor_key) + other = self.__class__(_secret_backdoor_key) other.digest_cons = self.digest_cons other.digest_size = self.digest_size other.inner = self.inner.copy() other.outer = self.outer.copy() return other + def _current(self): + """Return a hash object for the current state. + + To be used only internally with digest() and hexdigest(). + """ + h = self.outer.copy() + h.update(self.inner.digest()) + return h + def digest(self): """Return the hash value of this hashing object. @@ -89,15 +94,14 @@ not altered in any way by this function; you can continue updating the object after calling this function. """ - h = self.outer.copy() - h.update(self.inner.digest()) + h = self._current() return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ - return "".join([hex(ord(x))[2:].zfill(2) - for x in tuple(self.digest())]) + h = self._current() + return h.hexdigest() def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. Modified: python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py Thu Jan 11 00:21:28 2007 @@ -118,8 +118,11 @@ i = 0 while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]: i += 1 - while cursel > 0 and selstart[:i] <= self.completions[cursel-1]: + previous_completion = self.completions[cursel - 1] + while cursel > 0 and selstart[:i] <= previous_completion: i += 1 + if selstart == previous_completion: + break # maybe we have a duplicate? newstart = selstart[:i] self._change_start(newstart) Modified: python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt (original) +++ python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt Thu Jan 11 00:21:28 2007 @@ -3,9 +3,14 @@ *Release date: XX-XXX-200X* +- Avoid hang when encountering a duplicate in a completion list. Bug 1571112. + - Patch #1362975: Rework CodeContext indentation algorithm to avoid hard-coding pixel widths. +- Bug #813342: Start the IDLE subprocess with -Qnew if the parent + is started with that option. + - Some syntax errors were being caught by tokenize during the tabnanny check, resulting in obscure error messages. Do the syntax check first. Bug 1562716, 1562719 @@ -14,6 +19,12 @@ the Python release of which it's a part. +What's New in IDLE 1.2? +======================= + +*Release date: 19-SEP-2006* + + What's New in IDLE 1.2c1? ========================= @@ -44,6 +55,13 @@ *Release date: 03-AUG-2006* +- Bug #1525817: Don't truncate short lines in IDLE's tool tips. + +- Bug #1517990: IDLE keybindings on MacOS X now work correctly + +- Bug #1517996: IDLE now longer shows the default Tk menu when a + path browser, class browser or debugger is the frontmost window on MacOS X + - EditorWindow.test() was failing. Bug 1417598 - EditorWindow failed when used stand-alone if sys.ps1 not set. @@ -80,6 +98,8 @@ *Release date: 05-APR-2006* +- Patch #1162825: Support non-ASCII characters in IDLE window titles. + - Source file f.flush() after writing; trying to avoid lossage if user kills GUI. Modified: python/branches/p3yk-noslice/Lib/logging/__init__.py ============================================================================== --- python/branches/p3yk-noslice/Lib/logging/__init__.py (original) +++ python/branches/p3yk-noslice/Lib/logging/__init__.py Thu Jan 11 00:21:28 2007 @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.4.9.9" -__date__ = "06 February 2006" +__version__ = "0.5.0.0" +__date__ = "08 January 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -243,7 +243,7 @@ try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] - except: + except (TypeError, ValueError, AttributeError): self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info Modified: python/branches/p3yk-noslice/Lib/logging/handlers.py ============================================================================== --- python/branches/p3yk-noslice/Lib/logging/handlers.py (original) +++ python/branches/p3yk-noslice/Lib/logging/handlers.py Thu Jan 11 00:21:28 2007 @@ -347,7 +347,7 @@ try: self.sock = self.makeSocket() self.retryTime = None # next time, no delay before trying - except: + except socket.error: #Creation failed, so set the retry time and return. if self.retryTime is None: self.retryPeriod = self.retryStart @@ -738,7 +738,7 @@ import smtplib try: from email.Utils import formatdate - except: + except ImportError: formatdate = self.date_time port = self.mailport if not port: Modified: python/branches/p3yk-noslice/Lib/mailbox.py ============================================================================== --- python/branches/p3yk-noslice/Lib/mailbox.py (original) +++ python/branches/p3yk-noslice/Lib/mailbox.py Thu Jan 11 00:21:28 2007 @@ -510,6 +510,7 @@ self._next_key = 0 self._pending = False # No changes require rewriting the file. self._locked = False + self._file_length = None # Used to record mailbox size def add(self, message): """Add message and return assigned key.""" @@ -563,7 +564,21 @@ """Write any pending changes to disk.""" if not self._pending: return - self._lookup() + + # In order to be writing anything out at all, self._toc must + # already have been generated (and presumably has been modified + # by adding or deleting an item). + assert self._toc is not None + + # Check length of self._file; if it's changed, some other process + # has modified the mailbox since we scanned it. + self._file.seek(0, 2) + cur_len = self._file.tell() + if cur_len != self._file_length: + raise ExternalClashError('Size of mailbox file changed ' + '(expected %i, found %i)' % + (self._file_length, cur_len)) + new_file = _create_temporary(self._path) try: new_toc = {} @@ -639,6 +654,7 @@ offsets = self._install_message(message) self._post_message_hook(self._file) self._file.flush() + self._file_length = self._file.tell() # Record current length of mailbox return offsets @@ -730,6 +746,7 @@ break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) + self._file_length = self._file.tell() class MMDF(_mboxMMDF): @@ -773,6 +790,8 @@ break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) + self._file.seek(0, 2) + self._file_length = self._file.tell() class MH(Mailbox): @@ -1198,7 +1217,9 @@ self._toc = dict(enumerate(zip(starts, stops))) self._labels = dict(enumerate(label_lists)) self._next_key = len(self._toc) - + self._file.seek(0, 2) + self._file_length = self._file.tell() + def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' % @@ -1884,7 +1905,8 @@ def _sync_flush(f): """Ensure changes to file f are physically on disk.""" f.flush() - os.fsync(f.fileno()) + if hasattr(os, 'fsync'): + os.fsync(f.fileno()) def _sync_close(f): """Close file f, ensuring all changes are physically on disk.""" Modified: python/branches/p3yk-noslice/Lib/pty.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pty.py (original) +++ python/branches/p3yk-noslice/Lib/pty.py Thu Jan 11 00:21:28 2007 @@ -121,7 +121,9 @@ # Explicitly open the tty to make it become a controlling tty. tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) os.close(tmp_fd) - + else: + os.close(slave_fd) + # Parent and child process. return pid, master_fd Modified: python/branches/p3yk-noslice/Lib/pydoc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pydoc.py (original) +++ python/branches/p3yk-noslice/Lib/pydoc.py Thu Jan 11 00:21:28 2007 @@ -1741,6 +1741,9 @@ Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. + +On the Microsoft Windows operating system, the files can be built by +running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory. ''') return target = self.topics.get(topic, self.keywords.get(topic)) Modified: python/branches/p3yk-noslice/Lib/random.py ============================================================================== --- python/branches/p3yk-noslice/Lib/random.py (original) +++ python/branches/p3yk-noslice/Lib/random.py Thu Jan 11 00:21:28 2007 @@ -205,7 +205,7 @@ raise ValueError, "empty range for randrange()" if n >= maxwidth: - return istart + self._randbelow(n) + return istart + istep*self._randbelow(n) return istart + istep*int(self.random() * n) def randint(self, a, b): Modified: python/branches/p3yk-noslice/Lib/subprocess.py ============================================================================== --- python/branches/p3yk-noslice/Lib/subprocess.py (original) +++ python/branches/p3yk-noslice/Lib/subprocess.py Thu Jan 11 00:21:28 2007 @@ -166,7 +166,7 @@ communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to - terminate. The optional stdin argument should be a string to be + terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. @@ -1005,8 +1005,12 @@ # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)): - if fd: os.close(fd) + if p2cread and p2cread not in (0,): + os.close(p2cread) + if c2pwrite and c2pwrite not in (p2cread, 1): + os.close(c2pwrite) + if errwrite and errwrite not in (p2cread, c2pwrite, 2): + os.close(errwrite) # Close all other fds, if asked for if close_fds: @@ -1108,6 +1112,7 @@ read_set.append(self.stderr) stderr = [] + input_offset = 0 while read_set or write_set: rlist, wlist, xlist = select.select(read_set, write_set, []) @@ -1115,9 +1120,9 @@ # When select has indicated that the file is writable, # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 - bytes_written = os.write(self.stdin.fileno(), input[:512]) - input = input[bytes_written:] - if not input: + bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) + input_offset += bytes_written + if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) Modified: python/branches/p3yk-noslice/Lib/symbol.py ============================================================================== --- python/branches/p3yk-noslice/Lib/symbol.py (original) +++ python/branches/p3yk-noslice/Lib/symbol.py Thu Jan 11 00:21:28 2007 @@ -17,82 +17,87 @@ decorators = 260 funcdef = 261 parameters = 262 -varargslist = 263 -fpdef = 264 -fplist = 265 -stmt = 266 -simple_stmt = 267 -small_stmt = 268 -expr_stmt = 269 -augassign = 270 -print_stmt = 271 -del_stmt = 272 -pass_stmt = 273 -flow_stmt = 274 -break_stmt = 275 -continue_stmt = 276 -return_stmt = 277 -yield_stmt = 278 -raise_stmt = 279 -import_stmt = 280 -import_name = 281 -import_from = 282 -import_as_name = 283 -dotted_as_name = 284 -import_as_names = 285 -dotted_as_names = 286 -dotted_name = 287 -global_stmt = 288 -assert_stmt = 289 -compound_stmt = 290 -if_stmt = 291 -while_stmt = 292 -for_stmt = 293 -try_stmt = 294 -with_stmt = 295 -with_var = 296 -except_clause = 297 -suite = 298 -testlist_safe = 299 -old_test = 300 -old_lambdef = 301 -test = 302 -or_test = 303 -and_test = 304 -not_test = 305 -comparison = 306 -comp_op = 307 -expr = 308 -xor_expr = 309 -and_expr = 310 -shift_expr = 311 -arith_expr = 312 -term = 313 -factor = 314 -power = 315 -atom = 316 -listmaker = 317 -testlist_gexp = 318 -lambdef = 319 -trailer = 320 -subscriptlist = 321 -subscript = 322 -sliceop = 323 -exprlist = 324 -testlist = 325 -dictsetmaker = 326 -classdef = 327 -arglist = 328 -argument = 329 -list_iter = 330 -list_for = 331 -list_if = 332 -gen_iter = 333 -gen_for = 334 -gen_if = 335 -testlist1 = 336 -encoding_decl = 337 -yield_expr = 338 +typedargslist = 263 +tname = 264 +tfpdef = 265 +tfplist = 266 +varargslist = 267 +vname = 268 +vfpdef = 269 +vfplist = 270 +stmt = 271 +simple_stmt = 272 +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 #--end constants-- sym_name = {} Modified: python/branches/p3yk-noslice/Lib/tarfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/tarfile.py (original) +++ python/branches/p3yk-noslice/Lib/tarfile.py Thu Jan 11 00:21:28 2007 @@ -147,7 +147,10 @@ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0200): - n = int(s.rstrip(NUL + " ") or "0", 8) + try: + n = int(s.rstrip(NUL + " ") or "0", 8) + except ValueError: + raise HeaderError("invalid header") else: n = 0L for i in xrange(len(s) - 1): @@ -282,6 +285,9 @@ class StreamError(TarError): """Exception for unsupported operations on stream-like TarFiles.""" pass +class HeaderError(TarError): + """Exception for invalid headers.""" + pass #--------------------------- # internal stream interface @@ -624,140 +630,194 @@ #------------------------ # Extraction file object #------------------------ -class ExFileObject(object): - """File-like object for reading an archive member. - Is returned by TarFile.extractfile(). Support for - sparse files included. +class _FileInFile(object): + """A thin wrapper around an existing file object that + provides a part of its data as an individual file + object. """ - def __init__(self, tarfile, tarinfo): - self.fileobj = tarfile.fileobj - self.name = tarinfo.name - self.mode = "r" - self.closed = False - self.offset = tarinfo.offset_data - self.size = tarinfo.size - self.pos = 0L - self.linebuffer = "" - if tarinfo.issparse(): - self.sparse = tarinfo.sparse - self.read = self._readsparse - else: - self.read = self._readnormal + def __init__(self, fileobj, offset, size, sparse=None): + self.fileobj = fileobj + self.offset = offset + self.size = size + self.sparse = sparse + self.position = 0 - def __read(self, size): - """Overloadable read method. + def tell(self): + """Return the current file position. """ - return self.fileobj.read(size) + return self.position - def readline(self, size=-1): - """Read a line with approx. size. If size is negative, - read a whole line. readline() and read() must not - be mixed up (!). - """ - if size < 0: - size = sys.maxint - - nl = self.linebuffer.find("\n") - if nl >= 0: - nl = min(nl, size) - else: - size -= len(self.linebuffer) - while (nl < 0 and size > 0): - buf = self.read(min(size, 100)) - if not buf: - break - self.linebuffer += buf - size -= len(buf) - nl = self.linebuffer.find("\n") - if nl == -1: - s = self.linebuffer - self.linebuffer = "" - return s - buf = self.linebuffer[:nl] - self.linebuffer = self.linebuffer[nl + 1:] - while buf[-1:] == "\r": - buf = buf[:-1] - return buf + "\n" - - def readlines(self): - """Return a list with all (following) lines. + def seek(self, position): + """Seek to a position in the file. """ - result = [] - while True: - line = self.readline() - if not line: break - result.append(line) - return result + self.position = position - def _readnormal(self, size=None): - """Read operation for regular files. + def read(self, size=None): + """Read data from the file. """ - if self.closed: - raise ValueError("file is closed") - self.fileobj.seek(self.offset + self.pos) - bytesleft = self.size - self.pos if size is None: - bytestoread = bytesleft + size = self.size - self.position else: - bytestoread = min(size, bytesleft) - self.pos += bytestoread - return self.__read(bytestoread) + size = min(size, self.size - self.position) - def _readsparse(self, size=None): - """Read operation for sparse files. - """ - if self.closed: - raise ValueError("file is closed") + if self.sparse is None: + return self.readnormal(size) + else: + return self.readsparse(size) - if size is None: - size = self.size - self.pos + def readnormal(self, size): + """Read operation for regular files. + """ + self.fileobj.seek(self.offset + self.position) + self.position += size + return self.fileobj.read(size) + def readsparse(self, size): + """Read operation for sparse files. + """ data = [] while size > 0: - buf = self._readsparsesection(size) + buf = self.readsparsesection(size) if not buf: break size -= len(buf) data.append(buf) return "".join(data) - def _readsparsesection(self, size): + def readsparsesection(self, size): """Read a single section of a sparse file. """ - section = self.sparse.find(self.pos) + section = self.sparse.find(self.position) if section is None: return "" - toread = min(size, section.offset + section.size - self.pos) + size = min(size, section.offset + section.size - self.position) + if isinstance(section, _data): - realpos = section.realpos + self.pos - section.offset - self.pos += toread + realpos = section.realpos + self.position - section.offset self.fileobj.seek(self.offset + realpos) - return self.__read(toread) + self.position += size + return self.fileobj.read(size) + else: + self.position += size + return NUL * size +#class _FileInFile + + +class ExFileObject(object): + """File-like object for reading an archive member. + Is returned by TarFile.extractfile(). + """ + blocksize = 1024 + + def __init__(self, tarfile, tarinfo): + self.fileobj = _FileInFile(tarfile.fileobj, + tarinfo.offset_data, + tarinfo.size, + getattr(tarinfo, "sparse", None)) + self.name = tarinfo.name + self.mode = "r" + self.closed = False + self.size = tarinfo.size + + self.position = 0 + self.buffer = "" + + def read(self, size=None): + """Read at most size bytes from the file. If size is not + present or None, read all data until EOF is reached. + """ + if self.closed: + raise ValueError("I/O operation on closed file") + + buf = "" + if self.buffer: + if size is None: + buf = self.buffer + self.buffer = "" + else: + buf = self.buffer[:size] + self.buffer = self.buffer[size:] + + if size is None: + buf += self.fileobj.read() else: - self.pos += toread - return NUL * toread + buf += self.fileobj.read(size - len(buf)) + + self.position += len(buf) + return buf + + def readline(self, size=-1): + """Read one entire line from the file. If size is present + and non-negative, return a string with at most that + size, which may be an incomplete line. + """ + if self.closed: + raise ValueError("I/O operation on closed file") + + if "\n" in self.buffer: + pos = self.buffer.find("\n") + 1 + else: + buffers = [self.buffer] + while True: + buf = self.fileobj.read(self.blocksize) + buffers.append(buf) + if not buf or "\n" in buf: + self.buffer = "".join(buffers) + pos = self.buffer.find("\n") + 1 + if pos == 0: + # no newline found. + pos = len(self.buffer) + break + + if size != -1: + pos = min(size, pos) + + buf = self.buffer[:pos] + self.buffer = self.buffer[pos:] + self.position += len(buf) + return buf + + def readlines(self): + """Return a list with all remaining lines. + """ + result = [] + while True: + line = self.readline() + if not line: break + result.append(line) + return result def tell(self): """Return the current file position. """ - return self.pos + if self.closed: + raise ValueError("I/O operation on closed file") + + return self.position - def seek(self, pos, whence=0): + def seek(self, pos, whence=os.SEEK_SET): """Seek to a position in the file. """ - self.linebuffer = "" - if whence == 0: - self.pos = min(max(pos, 0), self.size) - if whence == 1: + if self.closed: + raise ValueError("I/O operation on closed file") + + if whence == os.SEEK_SET: + self.position = min(max(pos, 0), self.size) + elif whence == os.SEEK_CUR: if pos < 0: - self.pos = max(self.pos + pos, 0) + self.position = max(self.position + pos, 0) else: - self.pos = min(self.pos + pos, self.size) - if whence == 2: - self.pos = max(min(self.size + pos, self.size), 0) + self.position = min(self.position + pos, self.size) + elif whence == os.SEEK_END: + self.position = max(min(self.size + pos, self.size), 0) + else: + raise ValueError("Invalid argument") + + self.buffer = "" + self.fileobj.seek(self.position) def close(self): """Close the file object. @@ -765,20 +825,13 @@ self.closed = True def __iter__(self): - """Get an iterator over the file object. - """ - if self.closed: - raise ValueError("I/O operation on closed file") - return self - - def next(self): - """Get the next item from the file iterator. + """Get an iterator over the file's lines. """ - result = self.readline() - if not result: - raise StopIteration - return result - + while True: + line = self.readline() + if not line: + break + yield line #class ExFileObject #------------------ @@ -821,9 +874,13 @@ """Construct a TarInfo object from a 512 byte string buffer. """ if len(buf) != BLOCKSIZE: - raise ValueError("truncated header") + raise HeaderError("truncated header") if buf.count(NUL) == BLOCKSIZE: - raise ValueError("empty header") + raise HeaderError("empty header") + + chksum = nti(buf[148:156]) + if chksum not in calc_chksums(buf): + raise HeaderError("bad checksum") tarinfo = cls() tarinfo.buf = buf @@ -833,7 +890,7 @@ tarinfo.gid = nti(buf[116:124]) tarinfo.size = nti(buf[124:136]) tarinfo.mtime = nti(buf[136:148]) - tarinfo.chksum = nti(buf[148:156]) + tarinfo.chksum = chksum tarinfo.type = buf[156:157] tarinfo.linkname = buf[157:257].rstrip(NUL) tarinfo.uname = buf[265:297].rstrip(NUL) @@ -845,8 +902,6 @@ if prefix and not tarinfo.issparse(): tarinfo.name = prefix + "/" + tarinfo.name - if tarinfo.chksum not in calc_chksums(buf): - raise ValueError("invalid header") return tarinfo def tobuf(self, posix=False): @@ -999,7 +1054,7 @@ can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ - self.name = name + self.name = os.path.abspath(name) if len(mode) > 1 or mode not in "raw": raise ValueError("mode must be 'r', 'a' or 'w'") @@ -1011,7 +1066,7 @@ self._extfileobj = False else: if self.name is None and hasattr(fileobj, "name"): - self.name = fileobj.name + self.name = os.path.abspath(fileobj.name) if hasattr(fileobj, "mode"): self.mode = fileobj.mode self._extfileobj = True @@ -1088,9 +1143,13 @@ # Find out which *open() is appropriate for opening the file. for comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) + if fileobj is not None: + saved_pos = fileobj.tell() try: return func(name, "r", fileobj) except (ReadError, CompressionError): + if fileobj is not None: + fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") @@ -1147,24 +1206,12 @@ except (ImportError, AttributeError): raise CompressionError("gzip module is not available") - pre, ext = os.path.splitext(name) - pre = os.path.basename(pre) - if ext == ".tgz": - ext = ".tar" - if ext == ".gz": - ext = "" - tarname = pre + ext - if fileobj is None: fileobj = _open(name, mode + "b") - if mode != "r": - name = tarname - try: - t = cls.taropen(tarname, mode, - gzip.GzipFile(name, mode, compresslevel, fileobj) - ) + t = cls.taropen(name, mode, + gzip.GzipFile(name, mode, compresslevel, fileobj)) except IOError: raise ReadError("not a gzip file") t._extfileobj = False @@ -1183,21 +1230,13 @@ except ImportError: raise CompressionError("bz2 module is not available") - pre, ext = os.path.splitext(name) - pre = os.path.basename(pre) - if ext == ".tbz2": - ext = ".tar" - if ext == ".bz2": - ext = "" - tarname = pre + ext - if fileobj is not None: fileobj = _BZ2Proxy(fileobj, mode) else: fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel) try: - t = cls.taropen(tarname, mode, fileobj) + t = cls.taropen(name, mode, fileobj) except IOError: raise ReadError("not a bzip2 file") t._extfileobj = False @@ -1402,8 +1441,7 @@ arcname = name # Skip if somebody tries to archive the archive... - if self.name is not None \ - and os.path.abspath(name) == os.path.abspath(self.name): + if self.name is not None and os.path.abspath(name) == self.name: self._dbg(2, "tarfile: Skipped %r" % name) return @@ -1795,16 +1833,14 @@ tarinfo = self.proc_member(tarinfo) - except ValueError, e: + except HeaderError, e: if self.ignore_zeros: - self._dbg(2, "0x%X: empty or invalid block: %s" % - (self.offset, e)) + self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue else: if self.offset == 0: - raise ReadError("empty, unreadable or compressed " - "file: %s" % e) + raise ReadError(str(e)) return None break Modified: python/branches/p3yk-noslice/Lib/test/output/test_tokenize ============================================================================== --- python/branches/p3yk-noslice/Lib/test/output/test_tokenize (original) +++ python/branches/p3yk-noslice/Lib/test/output/test_tokenize Thu Jan 11 00:21:28 2007 @@ -682,4 +682,20 @@ 177,11-177,15: NAME 'pass' 177,15-177,16: NEWLINE '\n' 178,0-178,1: NL '\n' -179,0-179,0: ENDMARKER '' +179,0-179,1: OP '@' +179,1-179,13: NAME 'staticmethod' +179,13-179,14: NEWLINE '\n' +180,0-180,3: NAME 'def' +180,4-180,7: NAME 'foo' +180,7-180,8: OP '(' +180,8-180,9: NAME 'x' +180,9-180,10: OP ':' +180,10-180,11: NUMBER '1' +180,11-180,12: OP ')' +180,12-180,14: OP '->' +180,14-180,15: NUMBER '1' +180,15-180,16: OP ':' +180,17-180,21: NAME 'pass' +180,21-180,22: NEWLINE '\n' +181,0-181,1: NL '\n' +182,0-182,0: ENDMARKER '' 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 Thu Jan 11 00:21:28 2007 @@ -151,9 +151,9 @@ #### EVERYTHING BELOW IS GENERATED ##### exec_results = [ -('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], None, [], []), [('Pass', (1, 9))], [])]), +('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]), ('Module', [('ClassDef', (1, 0), 'C', [], [('Pass', (1, 8))])]), -('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], None, [], []), [('Return', (1, 8), ('Num', (1, 15), 1))], [])]), +('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Return', (1, 8), ('Num', (1, 15), 1))], [], None)]), ('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))]), @@ -180,13 +180,13 @@ ('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])), ('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))), ('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))), -('Expression', ('Lambda', (1, 0), ('arguments', [], None, [], None, [], []), ('Name', (1, 7), 'None', ('Load',)))), +('Expression', ('Lambda', (1, 0), ('arguments', [], None, None, [], None, None, [], []), ('Name', (1, 7), 'None', ('Load',)))), ('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])), ('Expression', ('ListComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))])])), ('Expression', ('GeneratorExp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))])])), ('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])), ('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('Num', (1, 2), 1), ('Num', (1, 4), 2)], [('keyword', 'c', ('Num', (1, 8), 3))], ('Name', (1, 11), 'd', ('Load',)), ('Name', (1, 15), 'e', ('Load',)))), -('Expression', ('Num', (1, 0), 10L)), +('Expression', ('Num', (1, 0), 10)), ('Expression', ('Str', (1, 0), 'string')), ('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))), ('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))), 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 Thu Jan 11 00:21:28 2007 @@ -845,30 +845,6 @@ self.assertEqual(int(Foo4()), 42L) self.assertRaises(TypeError, int, Foo5()) - def test_intern(self): - self.assertRaises(TypeError, intern) - s = "never interned before" - self.assert_(intern(s) is s) - s2 = s.swapcase().swapcase() - self.assert_(intern(s2) is s) - - # Subclasses of string can't be interned, because they - # provide too much opportunity for insane things to happen. - # We don't want them in the interned dict and if they aren't - # actually interned, we don't want to create the appearance - # that they are by allowing intern() to succeeed. - class S(str): - def __hash__(self): - return 123 - - self.assertRaises(TypeError, intern, S("abc")) - - # It's still safe to pass these strings to routines that - # call intern internally, e.g. PyObject_SetAttr(). - s = S("abc") - setattr(s, s, s) - self.assertEqual(getattr(s, s), s) - def test_iter(self): self.assertRaises(TypeError, iter) self.assertRaises(TypeError, iter, 42, 42) 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 Thu Jan 11 00:21:28 2007 @@ -1,5 +1,4 @@ import unittest -import warnings import sys from test import test_support 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 Thu Jan 11 00:21:28 2007 @@ -115,6 +115,24 @@ dct = {} exec(c, dct) self.assertEquals(dct.get('result'), 3) + c = compiler.compile('def g(a):\n' + ' def f(): return a + 2\n' + ' return f()\n' + 'result = g(1)', + '', + 'exec') + dct = {} + exec(c, dct) + self.assertEquals(dct.get('result'), 3) + c = compiler.compile('def g((a, b)):\n' + ' def f(): return a + b\n' + ' return f()\n' + 'result = g((1, 2))', + '', + 'exec') + dct = {} + exec(c, dct) + self.assertEquals(dct.get('result'), 3) def testGenExp(self): c = compiler.compile('list((i,j) for i in range(3) if i < 3' @@ -123,6 +141,22 @@ 'eval') self.assertEquals(eval(c), [(0, 3), (1, 3), (2, 3)]) + def testFuncAnnotations(self): + testdata = [ + ('def f(a: 1): pass', {'a': 1}), + ('''def f(a, (b:1, c:2, d), e:3=4, f=5, + *g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass + ''', {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, + 'k': 11, 'return': 12}), + ] + for sourcecode, expected in testdata: + # avoid IndentationError: unexpected indent from trailing lines + sourcecode = sourcecode.rstrip()+'\n' + c = compiler.compile(sourcecode, '', 'exec') + dct = {} + exec(c, dct) + self.assertEquals(dct['f'].func_annotations, expected) + NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard, compiler.ast.Const) @@ -168,10 +202,11 @@ ############################################################################### -def test_main(): +def test_main(all=False): global TEST_ALL - TEST_ALL = test.test_support.is_resource_enabled("compiler") + TEST_ALL = all or test.test_support.is_resource_enabled("compiler") test.test_support.run_unittest(CompilerTest) if __name__ == "__main__": - test_main() + import sys + test_main('all' in sys.argv) 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 Thu Jan 11 00:21:28 2007 @@ -396,6 +396,12 @@ d.pop() self.assertRaises(RuntimeError, it.next) + def test_runtime_error_on_empty_deque(self): + d = deque() + it = iter(d) + d.append(10) + self.assertRaises(RuntimeError, it.next) + class Deque(deque): pass Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -38,6 +38,24 @@ self.read_helper(f) f.close() + def test_dumbdbm_creation_mode(self): + # On platforms without chmod, don't do anything. + if not (hasattr(os, 'chmod') and hasattr(os, 'umask')): + return + + try: + old_umask = os.umask(0002) + f = dumbdbm.open(_fname, 'c', 0637) + f.close() + finally: + os.umask(old_umask) + + import stat + st = os.stat(_fname + '.dat') + self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + st = os.stat(_fname + '.dir') + self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + def test_close_twice(self): f = dumbdbm.open(_fname) f['a'] = 'b' Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -3,7 +3,6 @@ import os import sys import unittest -import warnings import pickle try: import cPickle 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 Thu Jan 11 00:21:28 2007 @@ -138,16 +138,22 @@ x = eval('1, 0 or 1') def testFuncdef(self): - ### 'def' NAME parameters ':' suite - ### parameters: '(' [varargslist] ')' - ### varargslist: (fpdef ['=' test] ',')* - ### ('*' (NAME|',' fpdef ['=' test]) [',' ('**'|'*' '*') NAME] - ### | ('**'|'*' '*') NAME) - ### | fpdef ['=' test] (',' fpdef ['=' test])* [','] - ### fpdef: NAME | '(' fplist ')' - ### fplist: fpdef (',' fpdef)* [','] - ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test) - ### argument: [test '='] test # Really [keyword '='] test + ### [decorators] 'def' NAME parameters ['->' test] ':' suite + ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE + ### decorators: decorator+ + ### 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)* [','] def f1(): pass f1() f1(*()) @@ -294,6 +300,28 @@ pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200) pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100) + # argument annotation tests + def f(x) -> list: pass + self.assertEquals(f.func_annotations, {'return': list}) + def f(x:int): pass + self.assertEquals(f.func_annotations, {'x': int}) + def f(*x:str): pass + self.assertEquals(f.func_annotations, {'x': str}) + def f(**x:float): pass + self.assertEquals(f.func_annotations, {'x': float}) + def f(x, y:1+2): pass + self.assertEquals(f.func_annotations, {'y': 3}) + def f(a, (b:1, c:2, d)): pass + self.assertEquals(f.func_annotations, {'b': 1, 'c': 2}) + def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6): pass + self.assertEquals(f.func_annotations, + {'b': 1, 'c': 2, 'e': 3, 'g': 6}) + def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6, h:7, i=8, j:9=10, + **k:11) -> 12: pass + self.assertEquals(f.func_annotations, + {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, + 'k': 11, 'return': 12}) + def testLambdef(self): ### lambdef: 'lambda' [varargslist] ':' test l1 = lambda : 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 Thu Jan 11 00:21:28 2007 @@ -104,20 +104,20 @@ self.assertEqual(heap_sorted, sorted(data)) def test_nsmallest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nsmallest(n, data), sorted(data)[:n]) - self.assertEqual(nsmallest(n, data, key=f), - sorted(data, key=f)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nsmallest(n, data), sorted(data)[:n]) + self.assertEqual(nsmallest(n, data, key=f), + sorted(data, key=f)[:n]) def test_nlargest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) - self.assertEqual(nlargest(n, data, key=f), - sorted(data, key=f, reverse=True)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) + self.assertEqual(nlargest(n, data, key=f), + sorted(data, key=f, reverse=True)[:n]) #============================================================================== Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -1,10 +1,11 @@ -from test.test_support import TESTFN, run_unittest +from test.test_support import TESTFN, run_unittest, guard_warnings_filter import unittest import os import random import sys import py_compile +import warnings def remove_files(name): @@ -204,15 +205,11 @@ self.assert_(y is test.test_support, y.__name__) def test_import_initless_directory_warning(self): - import warnings - oldfilters = warnings.filters[:] - warnings.simplefilter('error', ImportWarning); - try: + with guard_warnings_filter(): # Just a random non-package directory we always expect to be # somewhere in sys.path... + warnings.simplefilter('error', ImportWarning) self.assertRaises(ImportWarning, __import__, "site-packages") - finally: - warnings.filters = oldfilters def test_main(verbose=None): run_unittest(ImportTest) Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -115,6 +115,12 @@ os._exit(4) else: debug("Waiting for child (%d) to finish."%pid) + ##line = os.read(master_fd, 80) + ##lines = line.replace('\r\n', '\n').split('\n') + ##if False and lines != ['In child, calling os.setsid()', + ## 'Good: OSError was raised.', '']: + ## raise TestFailed("Unexpected output from child: %r" % line) + (pid, status) = os.waitpid(pid, 0) res = status >> 8 debug("Child (%d) exited with status %d (%d)."%(pid, res, status)) @@ -127,6 +133,15 @@ elif res != 4: raise TestFailed, "pty.fork() failed for unknown reasons." + ##debug("Reading from master_fd now that the child has exited") + ##try: + ## s1 = os.read(master_fd, 1024) + ##except os.error: + ## pass + ##else: + ## raise TestFailed("Read from master_fd did not raise exception") + + os.close(master_fd) # pty.fork() passed. Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -180,10 +180,9 @@ def test_bigrand(self): # Verify warnings are raised when randrange is too large for random() - oldfilters = warnings.filters[:] - warnings.filterwarnings("error", "Underlying random") - self.assertRaises(UserWarning, self.gen.randrange, 2**60) - warnings.filters[:] = oldfilters + with test_support.guard_warnings_filter(): + warnings.filterwarnings("error", "Underlying random") + self.assertRaises(UserWarning, self.gen.randrange, 2**60) class SystemRandom_TestBasicOps(TestBasicOps): gen = random.SystemRandom() @@ -441,6 +440,14 @@ self.assertEqual(k, numbits) # note the stronger assertion self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion + def test_randrange_bug_1590891(self): + start = 1000000000000 + stop = -100000000000000000000 + step = -200 + x = self.gen.randrange(start, stop, step) + self.assert_(stop < x <= start) + self.assertEqual((x+stop)%step, 0) + _gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289, 771.3234287757674, -176.6150291498386, 12.50734324009056, -0.1385710331296526, 0.9934937113930748e-05, 0.1659470187408462e-06) Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -136,7 +136,6 @@ '> fo, s, + fo.close() + fo = open(test_support.TESTFN, "rb") + self.assertEqual(fo.read(), repr(s)) + finally: + fo.close() + os.remove(test_support.TESTFN) + class TestSet(TestJointOps): thetype = set Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -50,22 +50,17 @@ def with_warning_restore(func): def _with_warning_restore(*args, **kw): - # The `warnings` module doesn't have an advertised way to restore - # its filter list. Cheat. - save_warnings_filters = warnings.filters[:] - # Grrr, we need this function to warn every time. Without removing - # the warningregistry, running test_tarfile then test_struct would fail - # on 64-bit platforms. - globals = func.func_globals - if '__warningregistry__' in globals: - del globals['__warningregistry__'] - warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) - warnings.filterwarnings("error", r""".*format requires.*""", - DeprecationWarning) - try: + with test.test_support.guard_warnings_filter(): + # Grrr, we need this function to warn every time. Without removing + # the warningregistry, running test_tarfile then test_struct would fail + # on 64-bit platforms. + globals = func.func_globals + if '__warningregistry__' in globals: + del globals['__warningregistry__'] + warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) + warnings.filterwarnings("error", r""".*format requires.*""", + DeprecationWarning) return func(*args, **kw) - finally: - warnings.filters[:] = save_warnings_filters[:] return _with_warning_restore def deprecated_err(func, *args): Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -3,7 +3,9 @@ if __name__ != 'test.test_support': raise ImportError, 'test_support must be imported from the test package' +from contextlib import contextmanager import sys +import warnings class Error(Exception): """Base class for regression test exceptions.""" @@ -267,6 +269,48 @@ print >> get_original_stdout(), '\tfetching %s ...' % url fn, _ = urllib.urlretrieve(url, filename) return open(fn) + + at contextmanager +def guard_warnings_filter(): + """Guard the warnings filter from being permanently changed.""" + original_filters = warnings.filters[:] + try: + yield + finally: + warnings.filters = original_filters + +class EnvironmentVarGuard(object): + + """Class to help protect the environment variable properly. Can be used as + a context manager.""" + + def __init__(self): + from os import environ + self._environ = environ + self._unset = set() + self._reset = dict() + + def set(self, envvar, value): + if envvar not in self._environ: + self._unset.add(envvar) + else: + self._reset[envvar] = self._environ[envvar] + self._environ[envvar] = value + + def unset(self, envvar): + if envvar in self._environ: + self._reset[envvar] = self._environ[envvar] + del self._environ[envvar] + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + for envvar, value in self._reset.iteritems(): + self._environ[envvar] = value + for unset in self._unset: + del self._environ[unset] + #======================================================================= # Decorator for running a function in a different locale, correctly resetting Modified: python/branches/p3yk-noslice/Lib/test/test_sys.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_sys.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_sys.py Thu Jan 11 00:21:28 2007 @@ -350,6 +350,31 @@ # the test runs under regrtest. self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding) + def test_intern(self): + self.assertRaises(TypeError, sys.intern) + s = "never interned before" + self.assert_(sys.intern(s) is s) + s2 = s.swapcase().swapcase() + self.assert_(sys.intern(s2) is s) + + # Subclasses of string can't be interned, because they + # provide too much opportunity for insane things to happen. + # We don't want them in the interned dict and if they aren't + # actually interned, we don't want to create the appearance + # that they are by allowing intern() to succeeed. + class S(str): + def __hash__(self): + return 123 + + self.assertRaises(TypeError, sys.intern, S("abc")) + + # It's still safe to pass these strings to routines that + # call intern internally, e.g. PyObject_SetAttr(). + s = S("abc") + setattr(s, s, s) + self.assertEqual(getattr(s, s), s) + + def test_main(): test.test_support.run_unittest(SysModuleTest) 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 Thu Jan 11 00:21:28 2007 @@ -110,7 +110,7 @@ """Test seek() method of _FileObject, incl. random reading. """ if self.sep != "|": - filename = "0-REGTYPE" + filename = "0-REGTYPE-TEXT" self.tar.extract(filename, dirname()) f = open(os.path.join(dirname(), filename), "rb") data = f.read() @@ -149,6 +149,16 @@ s2 = fobj.readlines() self.assert_(s1 == s2, "readlines() after seek failed") + fobj.seek(0) + self.assert_(len(fobj.readline()) == fobj.tell(), + "tell() after readline() failed") + fobj.seek(512) + self.assert_(len(fobj.readline()) + 512 == fobj.tell(), + "tell() after seek() and readline() failed") + fobj.seek(0) + line = fobj.readline() + self.assert_(fobj.read() == data[len(line):], + "read() after readline() failed") fobj.close() def test_old_dirtype(self): @@ -280,6 +290,20 @@ else: self.dst.addfile(tarinfo, f) + def test_add_self(self): + dstname = os.path.abspath(self.dstname) + + self.assertEqual(self.dst.name, dstname, "archive name must be absolute") + + self.dst.add(dstname) + self.assertEqual(self.dst.getnames(), [], "added the archive to itself") + + cwd = os.getcwd() + os.chdir(dirname()) + self.dst.add(dstname) + os.chdir(cwd) + self.assertEqual(self.dst.getnames(), [], "added the archive to itself") + class Write100Test(BaseTest): # The name field in a tar header stores strings of at most 100 chars. @@ -601,6 +625,38 @@ self.assertEqual(tarfile.filemode(0755), '-rwxr-xr-x') self.assertEqual(tarfile.filemode(07111), '---s--s--t') +class HeaderErrorTest(unittest.TestCase): + + def test_truncated_header(self): + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "") + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "filename\0") + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 511) + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 513) + + def test_empty_header(self): + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 512) + + def test_invalid_header(self): + buf = tarfile.TarInfo("filename").tobuf() + buf = buf[:148] + "foo\0\0\0\0\0" + buf[156:] # invalid number field. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, buf) + + def test_bad_checksum(self): + buf = tarfile.TarInfo("filename").tobuf() + b = buf[:148] + " " + buf[156:] # clear the checksum field. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b) + b = "a" + buf[1:] # manipulate the buffer, so checksum won't match. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b) + +class OpenFileobjTest(BaseTest): + # Test for SF bug #1496501. + + def test_opener(self): + fobj = StringIO.StringIO("foo\n") + try: + tarfile.open("", "r", fileobj=fobj) + except tarfile.ReadError: + self.assertEqual(fobj.tell(), 0, "fileobj's position has moved") if bz2: # Bzip2 TestCases @@ -646,6 +702,8 @@ tests = [ FileModeTest, + HeaderErrorTest, + OpenFileobjTest, ReadTest, ReadStreamTest, ReadDetectTest, Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -219,5 +219,15 @@ if verbose: print 'finished' +def test_rarrow(): + """ + This function exists solely to test the tokenization of the RARROW + operator. + + >>> tokenize(iter(['->']).next) #doctest: +NORMALIZE_WHITESPACE + 1,0-1,2:\tOP\t'->' + 2,0-2,0:\tENDMARKER\t'' + """ + if __name__ == "__main__": test_main() 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 Thu Jan 11 00:21:28 2007 @@ -114,11 +114,11 @@ def test_encode(self): try: - fin = open(self.tmpin, 'wb') + fin = open(self.tmpin, 'w') fin.write(plaintext) fin.close() - fin = open(self.tmpin, 'rb') + fin = open(self.tmpin, 'r') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() @@ -130,7 +130,7 @@ self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) # in_file and out_file as filenames - uu.encode(self.tmpin, self.tmpout, mode=0644) + uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) fout = open(self.tmpout, 'r') s = fout.read() fout.close() @@ -142,11 +142,11 @@ def test_decode(self): try: - f = open(self.tmpin, 'wb') + f = open(self.tmpin, 'w') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close() - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') uu.decode(f) f.close() @@ -163,11 +163,11 @@ try: f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout)) - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') uu.decode(f) f.close() - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') self.assertRaises(uu.Error, uu.decode, f) f.close() finally: Modified: python/branches/p3yk-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 Thu Jan 11 00:21:28 2007 @@ -189,7 +189,7 @@ # None as the value for the callback, where either means "no # callback". The "no callback" ref and proxy objects are supposed # to be shared so long as they exist by all callers so long as - # they are active. In Python 2.3.3 and earlier, this guaranttee + # they are active. In Python 2.3.3 and earlier, this guarantee # was not honored, and was broken in different ways for # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.) Modified: python/branches/p3yk-noslice/Lib/test/tokenize_tests.txt ============================================================================== --- python/branches/p3yk-noslice/Lib/test/tokenize_tests.txt (original) +++ python/branches/p3yk-noslice/Lib/test/tokenize_tests.txt Thu Jan 11 00:21:28 2007 @@ -176,3 +176,6 @@ @staticmethod def foo(): pass + at staticmethod +def foo(x:1)->1: pass + Modified: python/branches/p3yk-noslice/Lib/threading.py ============================================================================== --- python/branches/p3yk-noslice/Lib/threading.py (original) +++ python/branches/p3yk-noslice/Lib/threading.py Thu Jan 11 00:21:28 2007 @@ -636,13 +636,11 @@ _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() - import atexit - atexit.register(self.__exitfunc) def _set_daemon(self): return False - def __exitfunc(self): + def _exitfunc(self): self._Thread__stop() t = _pickSomeNonDaemonThread() if t: @@ -715,9 +713,11 @@ from thread import stack_size -# Create the main thread object +# Create the main thread object, +# and make it available for the interpreter +# (Py_Main) as threading._shutdown. -_MainThread() +_shutdown = _MainThread()._exitfunc # get thread-local implementation, either from the thread # module, or from the python fallback Modified: python/branches/p3yk-noslice/Lib/token.py ============================================================================== --- python/branches/p3yk-noslice/Lib/token.py (original) +++ python/branches/p3yk-noslice/Lib/token.py Thu Jan 11 00:21:28 2007 @@ -60,9 +60,10 @@ DOUBLESLASH = 48 DOUBLESLASHEQUAL = 49 AT = 50 -OP = 51 -ERRORTOKEN = 52 -N_TOKENS = 53 +RARROW = 51 +OP = 52 +ERRORTOKEN = 53 +N_TOKENS = 54 NT_OFFSET = 256 #--end constants-- Modified: python/branches/p3yk-noslice/Lib/tokenize.py ============================================================================== --- python/branches/p3yk-noslice/Lib/tokenize.py (original) +++ python/branches/p3yk-noslice/Lib/tokenize.py Thu Jan 11 00:21:28 2007 @@ -78,7 +78,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"~") Modified: python/branches/p3yk-noslice/Lib/urllib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/urllib.py (original) +++ python/branches/p3yk-noslice/Lib/urllib.py Thu Jan 11 00:21:28 2007 @@ -405,8 +405,8 @@ h.putheader('Content-Length', '%d' % len(data)) else: h.putrequest('GET', selector) - if proxy_auth: h.putheader('Proxy-Authorization: Basic %s' % proxy_auth) - if auth: h.putheader('Authorization: Basic %s' % auth) + if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth) + if auth: h.putheader('Authorization', 'Basic %s' % auth) if realhost: h.putheader('Host', realhost) for args in self.addheaders: h.putheader(*args) h.endheaders() Modified: python/branches/p3yk-noslice/Misc/ACKS ============================================================================== --- python/branches/p3yk-noslice/Misc/ACKS (original) +++ python/branches/p3yk-noslice/Misc/ACKS Thu Jan 11 00:21:28 2007 @@ -285,6 +285,7 @@ Albert Hofkamp Jonathan Hogg Gerrit Holl +Shane Holloway Rune Holm Philip Homburg Naofumi Honda Modified: python/branches/p3yk-noslice/Misc/NEWS ============================================================================== --- python/branches/p3yk-noslice/Misc/NEWS (original) +++ python/branches/p3yk-noslice/Misc/NEWS Thu Jan 11 00:21:28 2007 @@ -12,7 +12,7 @@ TO DO ----- -- See PEP 3000. +- See PEP 3000, 3100. - Test merging certain changes from the 2.5 HEAD code. @@ -36,7 +36,13 @@ Core and Builtins ----------------- -- Renamed nb_nonzero to nb_bool and __nonzero__ to __bool__ +- Added function annotations per PEP 3107. + +- Moved intern() to sys.intern(). + +- exec is now a function. + +- Renamed nb_nonzero to nb_bool and __nonzero__ to __bool__. - Classic classes are a thing of the past. All classes are new style. @@ -90,7 +96,7 @@ - zip returns an iterator - Additions: - set literals + set literals, ellipsis literal Extension Modules Modified: python/branches/p3yk-noslice/Misc/developers.txt ============================================================================== --- python/branches/p3yk-noslice/Misc/developers.txt (original) +++ python/branches/p3yk-noslice/Misc/developers.txt Thu Jan 11 00:21:28 2007 @@ -17,6 +17,15 @@ Permissions History ------------------- +- Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python + project 06 Jan 2007, by NCN, as a tracker tech. He will maintain asyncore. + +- Collin Winter was given SVN access on 05 Jan 2007 by NCN, for PEP + update access. + +- Lars Gustaebel was given SVN access on 20 Dec 2006 by NCN, for tarfile.py + related work. + - 2006 Summer of Code entries: SoC developers are expected to work primarily in nondist/sandbox or on a branch of their own, and will have their work reviewed before changes are accepted into the trunk. Modified: python/branches/p3yk-noslice/Misc/python-mode.el ============================================================================== --- python/branches/p3yk-noslice/Misc/python-mode.el (original) +++ python/branches/p3yk-noslice/Misc/python-mode.el Thu Jan 11 00:21:28 2007 @@ -382,7 +382,7 @@ "delattr" "dict" "dir" "divmod" "enumerate" "eval" "execfile" "exit" "file" "filter" "float" "getattr" "globals" "hasattr" - "hash" "hex" "id" "int" "intern" + "hash" "hex" "id" "int" "isinstance" "issubclass" "iter" "len" "license" "list" "locals" "long" "map" "max" "min" "object" "oct" "open" "ord" "pow" "property" "range" Modified: python/branches/p3yk-noslice/Modules/_bsddb.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_bsddb.c (original) +++ python/branches/p3yk-noslice/Modules/_bsddb.c Thu Jan 11 00:21:28 2007 @@ -98,7 +98,7 @@ #error "eek! DBVER can't handle minor versions > 9" #endif -#define PY_BSDDB_VERSION "4.4.6" +#define PY_BSDDB_VERSION "4.5.0" static char *rcs_id = "$Id$"; @@ -4127,6 +4127,7 @@ } +#if (DBVER < 45) static PyObject* DBEnv_set_lk_max(DBEnvObject* self, PyObject* args) { @@ -4142,6 +4143,7 @@ RETURN_IF_ERR(); RETURN_NONE(); } +#endif #if (DBVER >= 32) @@ -5231,7 +5233,9 @@ {"set_lg_regionmax",(PyCFunction)DBEnv_set_lg_regionmax, METH_VARARGS}, #endif {"set_lk_detect", (PyCFunction)DBEnv_set_lk_detect, METH_VARARGS}, +#if (DBVER < 45) {"set_lk_max", (PyCFunction)DBEnv_set_lk_max, METH_VARARGS}, +#endif #if (DBVER >= 32) {"set_lk_max_locks", (PyCFunction)DBEnv_set_lk_max_locks, METH_VARARGS}, {"set_lk_max_lockers", (PyCFunction)DBEnv_set_lk_max_lockers, METH_VARARGS}, @@ -5627,7 +5631,7 @@ #define MODULE_NAME_MAX_LEN 11 static char _bsddbModuleName[MODULE_NAME_MAX_LEN+1] = "_bsddb"; -DL_EXPORT(void) init_bsddb(void) +PyMODINIT_FUNC init_bsddb(void) { PyObject* m; PyObject* d; @@ -5833,7 +5837,9 @@ ADD_INT(d, DB_AFTER); ADD_INT(d, DB_APPEND); ADD_INT(d, DB_BEFORE); +#if (DBVER < 45) ADD_INT(d, DB_CACHED_COUNTS); +#endif #if (DBVER >= 41) _addIntToDict(d, "DB_CHECKPOINT", 0); #else @@ -5868,7 +5874,9 @@ ADD_INT(d, DB_POSITION); ADD_INT(d, DB_PREV); ADD_INT(d, DB_PREV_NODUP); +#if (DBVER < 45) ADD_INT(d, DB_RECORDCOUNT); +#endif ADD_INT(d, DB_SET); ADD_INT(d, DB_SET_RANGE); ADD_INT(d, DB_SET_RECNO); @@ -6032,7 +6040,7 @@ /* allow this module to be named _pybsddb so that it can be installed * and imported on top of python >= 2.3 that includes its own older * copy of the library named _bsddb without importing the old version. */ -DL_EXPORT(void) init_pybsddb(void) +PyMODINIT_FUNC init_pybsddb(void) { strncpy(_bsddbModuleName, "_pybsddb", MODULE_NAME_MAX_LEN); init_bsddb(); 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 Thu Jan 11 00:21:28 2007 @@ -330,7 +330,7 @@ short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7; }; -DL_EXPORT(void) set_bitfields(struct BITS *bits, char name, int value) +PyAPI_FUNC(void) set_bitfields(struct BITS *bits, char name, int value) { switch (name) { case 'A': bits->A = value; break; @@ -353,7 +353,7 @@ } } -DL_EXPORT(int) unpack_bitfields(struct BITS *bits, char name) +PyAPI_FUNC(int) unpack_bitfields(struct BITS *bits, char name) { switch (name) { case 'A': return bits->A; @@ -547,7 +547,7 @@ #endif -DL_EXPORT(void) +PyMODINIT_FUNC init_ctypes_test(void) { Py_InitModule("_ctypes_test", module_methods); Modified: python/branches/p3yk-noslice/Modules/_elementtree.c ============================================================================== --- python/branches/p3yk-noslice/Modules/_elementtree.c (original) +++ python/branches/p3yk-noslice/Modules/_elementtree.c Thu Jan 11 00:21:28 2007 @@ -2612,7 +2612,7 @@ {NULL, NULL} }; -DL_EXPORT(void) +PyMODINIT_FUNC init_elementtree(void) { PyObject* m; Modified: python/branches/p3yk-noslice/Modules/addrinfo.h ============================================================================== --- python/branches/p3yk-noslice/Modules/addrinfo.h (original) +++ python/branches/p3yk-noslice/Modules/addrinfo.h Thu Jan 11 00:21:28 2007 @@ -170,7 +170,7 @@ #ifdef __cplusplus extern "C" { #endif -extern void freehostent Py_PROTO((struct hostent *)); +extern void freehostent(struct hostent *); #ifdef __cplusplus } #endif Modified: python/branches/p3yk-noslice/Modules/bz2module.c ============================================================================== --- python/branches/p3yk-noslice/Modules/bz2module.c (original) +++ python/branches/p3yk-noslice/Modules/bz2module.c Thu Jan 11 00:21:28 2007 @@ -989,7 +989,7 @@ char small_buffer[SMALLCHUNK]; char *buffer = small_buffer; size_t buffersize = SMALLCHUNK; - int bytesread = 0; + Py_off_t bytesread = 0; size_t readsize; int chunksize; int bzerror; Modified: python/branches/p3yk-noslice/Modules/collectionsmodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/collectionsmodule.c (original) +++ python/branches/p3yk-noslice/Modules/collectionsmodule.c Thu Jan 11 00:21:28 2007 @@ -911,15 +911,14 @@ { PyObject *item; - if (it->counter == 0) - return NULL; - if (it->deque->state != it->state) { it->counter = 0; PyErr_SetString(PyExc_RuntimeError, "deque mutated during iteration"); return NULL; } + if (it->counter == 0) + return NULL; assert (!(it->b == it->deque->rightblock && it->index > it->deque->rightindex)); Modified: python/branches/p3yk-noslice/Modules/main.c ============================================================================== --- python/branches/p3yk-noslice/Modules/main.c (original) +++ python/branches/p3yk-noslice/Modules/main.c Thu Jan 11 00:21:28 2007 @@ -175,6 +175,33 @@ return 0; } +/* Wait until threading._shutdown completes, provided + the threading module was imported in the first place. + The shutdown routine will wait until all non-daemon + "threading" threads have completed. */ +#include "abstract.h" +static void +WaitForThreadShutdown(void) +{ +#ifdef WITH_THREAD + PyObject *result; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_shutdown", ""); + if (result == NULL) + PyErr_WriteUnraisable(threading); + else + Py_DECREF(result); + Py_DECREF(threading); +#endif +} + /* Main program */ int @@ -483,6 +510,8 @@ /* XXX */ sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + WaitForThreadShutdown(); + Py_Finalize(); #ifdef RISCOS if (Py_RISCOSWimpFlag) Modified: python/branches/p3yk-noslice/Modules/parsermodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/parsermodule.c (original) +++ python/branches/p3yk-noslice/Modules/parsermodule.c Thu Jan 11 00:21:28 2007 @@ -854,7 +854,7 @@ VALIDATER(class); VALIDATER(node); VALIDATER(parameters); VALIDATER(suite); VALIDATER(testlist); VALIDATER(varargslist); -VALIDATER(fpdef); VALIDATER(fplist); +VALIDATER(vfpdef); VALIDATER(vfplist); VALIDATER(stmt); VALIDATER(simple_stmt); VALIDATER(expr_stmt); VALIDATER(power); VALIDATER(print_stmt); VALIDATER(del_stmt); @@ -863,7 +863,7 @@ VALIDATER(import_name); VALIDATER(import_from); VALIDATER(global_stmt); VALIDATER(list_if); VALIDATER(assert_stmt); VALIDATER(list_for); -VALIDATER(compound_stmt); +VALIDATER(compound_stmt); VALIDATER(vname); VALIDATER(while); VALIDATER(for); VALIDATER(try); VALIDATER(except_clause); VALIDATER(test); VALIDATER(and_test); @@ -1120,7 +1120,32 @@ } -/* '*' [NAME] (',' NAME ['=' test])* [',' '**' NAME] | '**' NAME +/* validate either vname or tname. + * vname: NAME + * tname: NAME [':' test] + */ +static int +validate_vname(node *tree) +{ + int nch = NCH(tree); + if (TYPE(tree) == vname) { + return nch == 1 && validate_name(CHILD(tree, 0), NULL); + } + else if (TYPE(tree) == tname) { + if (nch == 1) { + return validate_name(CHILD(tree, 0), NULL); + } + else if (nch == 3) { + return validate_name(CHILD(tree, 0), NULL) && + validate_colon(CHILD(tree, 1)) && + validate_test(CHILD(tree, 2)); + } + } + return 0; +} + +/* '*' vname (',' vname ['=' test])* [',' '**' vname] | '**' vname + * ..or tname in place of vname. vname: NAME; tname: NAME [':' test] */ static int validate_varargslist_trailer(node *tree, int start) @@ -1136,26 +1161,27 @@ sym = TYPE(CHILD(tree, start)); if (sym == STAR) { /* - * '*' [NAME] (',' NAME ['=' test])* [',' '**' NAME] | '**' NAME + * '*' vname (',' vname ['=' test])* [',' '**' vname] | '**' vname */ if (nch-start == 2) - res = validate_name(CHILD(tree, start+1), NULL); + res = validate_vname(CHILD(tree, start+1)); else if (nch-start == 5 && TYPE(CHILD(tree, start+2)) == COMMA) - res = (validate_name(CHILD(tree, start+1), NULL) + res = (validate_vname(CHILD(tree, start+1)) && validate_comma(CHILD(tree, start+2)) && validate_doublestar(CHILD(tree, start+3)) - && validate_name(CHILD(tree, start+4), NULL)); + && validate_vname(CHILD(tree, start+4))); else { - /* skip over [NAME] (',' NAME ['=' test])* */ + /* skip over vname (',' vname ['=' test])* */ i = start + 1; - if (TYPE(CHILD(tree, i)) == NAME) { /* skip over [NAME] */ + if (TYPE(CHILD(tree, i)) == vname || + TYPE(CHILD(tree, i)) == tname) { /* skip over vname or tname */ i += 1; } - while (res && i+1 < nch) { /* validate (',' NAME ['=' test])* */ + while (res && i+1 < nch) { /* validate (',' vname ['=' test])* */ res = validate_comma(CHILD(tree, i)); if (TYPE(CHILD(tree, i+1)) == DOUBLESTAR) break; - res = res && validate_name(CHILD(tree, i+1), NULL); + res = res && validate_vname(CHILD(tree, i+1)); if (res && i+2 < nch && TYPE(CHILD(tree, i+2)) == EQUAL) { res = res && (i+3 < nch) && validate_test(CHILD(tree, i+3)); @@ -1165,9 +1191,9 @@ i += 2; } } - /* [',' '**' NAME] */ + /* [',' '**' vname] */ if (res && i+1 < nch && TYPE(CHILD(tree, i+1)) == DOUBLESTAR) { - res = validate_name(CHILD(tree, i+2), NULL); + res = validate_vname(CHILD(tree, i+2)); } } } @@ -1176,7 +1202,7 @@ * '**' NAME */ if (nch-start == 2) - res = validate_name(CHILD(tree, start+1), NULL); + res = validate_vname(CHILD(tree, start+1)); } if (!res) err_string("illegal variable argument trailer for varargslist"); @@ -1184,21 +1210,34 @@ } -/* validate_varargslist() +/* validate_varargslist() * - * varargslist: - * (fpdef ['=' test] ',')* - * ('*' [NAME] (',' NAME ['=' test])* [',' '**' NAME] | '**' NAME) - * | fpdef ['=' test] (',' fpdef ['=' test])* [','] + * Validate typedargslist or varargslist. + * + * 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)* [','] * */ static int validate_varargslist(node *tree) { int nch = NCH(tree); - int res = validate_ntype(tree, varargslist) && (nch != 0); + int res = (TYPE(tree) == varargslist || + TYPE(tree) == typedargslist) && + (nch != 0); int sym; - if (!res) return 0; if (nch < 1) { @@ -1211,19 +1250,19 @@ * '*' [NAME] (',' NAME ['=' test])* [',' '**' NAME] | '**' NAME */ res = validate_varargslist_trailer(tree, 0); - else if (sym == fpdef) { + else if (sym == vfpdef || sym == tfpdef) { int i = 0; sym = TYPE(CHILD(tree, nch-1)); - if (sym == NAME) { + if (sym == vname || sym == tname) { /* - * (fpdef ['=' test] ',')+ - * ('*' NAME [',' '**' NAME] - * | '**' NAME) + * (vfpdef ['=' test] ',')+ + * ('*' vname [',' '**' vname] + * | '**' vname) */ - /* skip over (fpdef ['=' test] ',')+ */ + /* skip over (vfpdef ['=' test] ',')+ */ while (res && (i+2 <= nch)) { - res = validate_fpdef(CHILD(tree, i)); + res = validate_vfpdef(CHILD(tree, i)); ++i; if (res && TYPE(CHILD(tree, i)) == EQUAL && (i+2 <= nch)) { res = (validate_equal(CHILD(tree, i)) @@ -1248,7 +1287,7 @@ } else { /* - * fpdef ['=' test] (',' fpdef ['=' test])* [','] + * vfpdef ['=' test] (',' vfpdef ['=' test])* [','] */ /* strip trailing comma node */ if (sym == COMMA) { @@ -1258,9 +1297,9 @@ --nch; } /* - * fpdef ['=' test] (',' fpdef ['=' test])* + * vfpdef ['=' test] (',' vfpdef ['=' test])* */ - res = validate_fpdef(CHILD(tree, 0)); + res = validate_vfpdef(CHILD(tree, 0)); ++i; if (res && (i+2 <= nch) && TYPE(CHILD(tree, i)) == EQUAL) { res = (validate_equal(CHILD(tree, i)) @@ -1268,12 +1307,12 @@ i += 2; } /* - * ... (',' fpdef ['=' test])* + * ... (',' vfpdef ['=' test])* * i ---^^^ */ while (res && (nch - i) >= 2) { res = (validate_comma(CHILD(tree, i)) - && validate_fpdef(CHILD(tree, i+1))); + && validate_vfpdef(CHILD(tree, i+1))); i += 2; if (res && (nch - i) >= 2 && TYPE(CHILD(tree, i)) == EQUAL) { res = (validate_equal(CHILD(tree, i)) @@ -1405,24 +1444,32 @@ return res; } -/* validate_fpdef() +/* validate_vfpdef() + * + * Validate vfpdef or tfpdef. + * + * vname: NAME + * vfpdef: vname | '(' vfplist ')' + * vfplist: vfpdef (',' vfpdef)* [','] + * + * tname: NAME [':' test] + * tfpdef: tname | '(' tfplist ')' + * tfplist: tfpdef (',' tfpdef)* [','] * - * fpdef: - * NAME - * | '(' fplist ')' */ static int -validate_fpdef(node *tree) +validate_vfpdef(node *tree) { int nch = NCH(tree); - int res = validate_ntype(tree, fpdef); + int typ = TYPE(tree); + int res = typ == vfpdef || typ == tfpdef; if (res) { if (nch == 1) - res = validate_ntype(CHILD(tree, 0), NAME); + res = validate_vname(CHILD(tree, 0)); else if (nch == 3) res = (validate_lparen(CHILD(tree, 0)) - && validate_fplist(CHILD(tree, 1)) + && validate_vfplist(CHILD(tree, 1)) && validate_rparen(CHILD(tree, 2))); else res = validate_numnodes(tree, 1, "fpdef"); @@ -1432,10 +1479,10 @@ static int -validate_fplist(node *tree) +validate_vfplist(node *tree) { - return (validate_repeating_list(tree, fplist, - validate_fpdef, "fplist")); + return (validate_repeating_list(tree, vfplist, + validate_vfpdef, "vfplist")); } Modified: python/branches/p3yk-noslice/Modules/socketmodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/socketmodule.c (original) +++ python/branches/p3yk-noslice/Modules/socketmodule.c Thu Jan 11 00:21:28 2007 @@ -2210,7 +2210,7 @@ /* * This is the guts of the recv() and recv_into() methods, which reads into a - * char buffer. If you have any inc/def ref to do to the objects that contain + * char buffer. If you have any inc/dec ref to do to the objects that contain * the buffer, do it in the caller. This function returns the number of bytes * succesfully read. If there was an error, it returns -1. Note that it is * also possible that we return a number of bytes smaller than the request Modified: python/branches/p3yk-noslice/Modules/timemodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/timemodule.c (original) +++ python/branches/p3yk-noslice/Modules/timemodule.c Thu Jan 11 00:21:28 2007 @@ -659,7 +659,7 @@ time_tzset. In the future, some parts of it can be moved back (for platforms that don't HAVE_WORKING_TZSET, when we know what they are), and the extranious calls to tzset(3) should be removed. - I havn't done this yet, as I don't want to change this code as + I haven't done this yet, as I don't want to change this code as little as possible when introducing the time.tzset and time.tzsetwall methods. This should simply be a method of doing the following once, at the top of this function and removing the call to tzset() from Modified: python/branches/p3yk-noslice/Objects/bytesobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/bytesobject.c (original) +++ python/branches/p3yk-noslice/Objects/bytesobject.c Thu Jan 11 00:21:28 2007 @@ -324,7 +324,7 @@ } static int -bytes_setslice(PyBytesObject *self, Py_ssize_t lo, Py_ssize_t hi, +bytes_setslice(PyBytesObject *self, Py_ssize_t lo, Py_ssize_t hi, PyObject *values) { int avail; @@ -373,7 +373,7 @@ memmove(self->ob_bytes + lo + needed, self->ob_bytes + hi, self->ob_size - hi); } - if (PyBytes_Resize((PyObject *)self, + if (PyBytes_Resize((PyObject *)self, self->ob_size + needed - avail) < 0) return -1; if (avail < needed) { @@ -510,7 +510,7 @@ memmove(self->ob_bytes + start + needed, self->ob_bytes + stop, self->ob_size - stop); } - if (PyBytes_Resize((PyObject *)self, + if (PyBytes_Resize((PyObject *)self, self->ob_size + needed - slicelen) < 0) return -1; if (slicelen < needed) { @@ -557,7 +557,7 @@ self->ob_bytes + cur, PyBytes_GET_SIZE(self) - cur); } - if (PyBytes_Resize((PyObject *)self, + if (PyBytes_Resize((PyObject *)self, PyBytes_GET_SIZE(self) - slicelen) < 0) return -1; @@ -1034,7 +1034,7 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &bytes_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ /* bytes is 'final' or 'sealed' */ bytes_doc, /* tp_doc */ 0, /* tp_traverse */ Modified: python/branches/p3yk-noslice/Objects/dictnotes.txt ============================================================================== --- python/branches/p3yk-noslice/Objects/dictnotes.txt (original) +++ python/branches/p3yk-noslice/Objects/dictnotes.txt Thu Jan 11 00:21:28 2007 @@ -44,7 +44,7 @@ d.setdefault(word, []).append(pagenumber) Note, the second example is a use case characterized by a get and set - to the same key. There are similar used cases with a __contains__ + to the same key. There are similar use cases with a __contains__ followed by a get, set, or del to the same key. Part of the justification for d.setdefault is combining the two lookups into one. Modified: python/branches/p3yk-noslice/Objects/floatobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/floatobject.c (original) +++ python/branches/p3yk-noslice/Objects/floatobject.c Thu Jan 11 00:21:28 2007 @@ -220,19 +220,18 @@ /* Methods */ static void -format_float(char *buf, size_t buflen, PyFloatObject *v, int precision) +format_double(char *buf, size_t buflen, double ob_fval, int precision) { register char *cp; char format[32]; - /* Subroutine for float_repr and float_print. + /* Subroutine for float_repr, float_str, float_print and others. We want float numbers to be recognizable as such, i.e., they should contain a decimal point or an exponent. However, %g may print the number as an integer; in such cases, we append ".0" to the string. */ - assert(PyFloat_Check(v)); PyOS_snprintf(format, 32, "%%.%ig", precision); - PyOS_ascii_formatd(buf, buflen, format, v->ob_fval); + PyOS_ascii_formatd(buf, buflen, format, ob_fval); cp = buf; if (*cp == '-') cp++; @@ -249,14 +248,11 @@ } } -/* XXX PyFloat_AsStringEx should not be a public API function (for one - XXX thing, its signature passes a buffer without a length; for another, - XXX it isn't useful outside this file). -*/ -void -PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision) +static void +format_float(char *buf, size_t buflen, PyFloatObject *v, int precision) { - format_float(buf, 100, v, precision); + assert(PyFloat_Check(v)); + format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision); } /* Macro and helper that convert PyObject obj to a C double and store @@ -312,21 +308,6 @@ #define PREC_REPR 17 #define PREC_STR 12 -/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated: - XXX they pass a char buffer without passing a length. -*/ -void -PyFloat_AsString(char *buf, PyFloatObject *v) -{ - format_float(buf, 100, v, PREC_STR); -} - -void -PyFloat_AsReprString(char *buf, PyFloatObject *v) -{ - format_float(buf, 100, v, PREC_REPR); -} - /* ARGSUSED */ static int float_print(PyFloatObject *v, FILE *fp, int flags) @@ -1275,7 +1256,7 @@ if (PyFloat_CheckExact(p) && p->ob_refcnt != 0) { char buf[100]; - PyFloat_AsString(buf, p); + format_float(buf, sizeof(buf), p, PREC_STR); /* XXX(twouters) cast refcount to long until %zd is universally available @@ -1527,6 +1508,14 @@ } } +/* Should only be used by marshal. */ +int +_PyFloat_Repr(double x, char *p, size_t len) +{ + format_double(p, len, x, PREC_REPR); + return (int)strlen(p); +} + double _PyFloat_Unpack4(const unsigned char *p, int le) { Modified: python/branches/p3yk-noslice/Objects/funcobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/funcobject.c (original) +++ python/branches/p3yk-noslice/Objects/funcobject.c Thu Jan 11 00:21:28 2007 @@ -38,6 +38,7 @@ op->func_doc = doc; op->func_dict = NULL; op->func_module = NULL; + op->func_annotations = NULL; /* __module__: If module name is in globals, use it. Otherwise, use None. @@ -187,6 +188,38 @@ return 0; } +PyObject * +PyFunction_GetAnnotations(PyObject *op) +{ + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_annotations; +} + +int +PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) +{ + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (annotations == Py_None) + annotations = NULL; + else if (annotations && PyDict_Check(annotations)) { + Py_INCREF(annotations); + } + else { + PyErr_SetString(PyExc_SystemError, + "non-dict annotations"); + return -1; + } + Py_XDECREF(((PyFunctionObject *)op) -> func_annotations); + ((PyFunctionObject *) op) -> func_annotations = annotations; + return 0; +} + /* Methods */ #define OFF(x) offsetof(PyFunctionObject, x) @@ -395,12 +428,48 @@ return 0; } +static PyObject * +func_get_annotations(PyFunctionObject *op) +{ + if (op->func_annotations == NULL) { + op->func_annotations = PyDict_New(); + if (op->func_annotations == NULL) + return NULL; + } + Py_INCREF(op->func_annotations); + return op->func_annotations; +} + +static int +func_set_annotations(PyFunctionObject *op, PyObject *value) +{ + PyObject *tmp; + + if (value == Py_None) + value = NULL; + /* Legal to del f.func_annotations. + * Can only set func_annotations to NULL (through C api) + * or a dict. */ + if (value != NULL && !PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "func_annotations must be set to a dict object"); + return -1; + } + tmp = op->func_annotations; + Py_XINCREF(value); + op->func_annotations = value; + Py_XDECREF(tmp); + return 0; +} + static PyGetSetDef func_getsetlist[] = { {"func_code", (getter)func_get_code, (setter)func_set_code}, {"func_defaults", (getter)func_get_defaults, (setter)func_set_defaults}, {"func_kwdefaults", (getter)func_get_kwdefaults, (setter)func_set_kwdefaults}, + {"func_annotations", (getter)func_get_annotations, + (setter)func_set_annotations}, {"func_dict", (getter)func_get_dict, (setter)func_set_dict}, {"__dict__", (getter)func_get_dict, (setter)func_set_dict}, {"func_name", (getter)func_get_name, (setter)func_set_name}, @@ -524,6 +593,7 @@ Py_XDECREF(op->func_doc); Py_XDECREF(op->func_dict); Py_XDECREF(op->func_closure); + Py_XDECREF(op->func_annotations); PyObject_GC_Del(op); } @@ -546,6 +616,7 @@ Py_VISIT(f->func_name); Py_VISIT(f->func_dict); Py_VISIT(f->func_closure); + Py_VISIT(f->func_annotations); return 0; } Modified: python/branches/p3yk-noslice/Objects/object.c ============================================================================== --- python/branches/p3yk-noslice/Objects/object.c (original) +++ python/branches/p3yk-noslice/Objects/object.c Thu Jan 11 00:21:28 2007 @@ -619,7 +619,7 @@ /* Map rich comparison operators to their swapped version, e.g. LT <--> GT */ int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE}; -static char *opstrings[] = {">", ">=", "==", "!=", "<", "<="}; +static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="}; /* Perform a rich comparison, raising TypeError when the requested comparison operator is not supported. */ @@ -659,6 +659,7 @@ res = (v != w) ? Py_True : Py_False; break; default: + /* XXX Special-case None so it doesn't show as NoneType() */ PyErr_Format(PyExc_TypeError, "unorderable types: %.100s() %s %.100s()", v->ob_type->tp_name, Modified: python/branches/p3yk-noslice/Objects/setobject.c ============================================================================== --- python/branches/p3yk-noslice/Objects/setobject.c (original) +++ python/branches/p3yk-noslice/Objects/setobject.c Thu Jan 11 00:21:28 2007 @@ -573,8 +573,17 @@ char *emit = ""; /* No separator emitted on first pass */ char *separator = ", "; int literalform = 0; + int status = Py_ReprEnter((PyObject*)so); + + if (status != 0) { + if (status < 0) + return status; + fprintf(fp, "%s(...)", so->ob_type->tp_name); + return 0; + } if (!so->used) { + Py_ReprLeave((PyObject*)so); fprintf(fp, "%s()", so->ob_type->tp_name); return 0; } @@ -587,32 +596,44 @@ while (set_next(so, &pos, &entry)) { fputs(emit, fp); emit = separator; - if (PyObject_Print(entry->key, fp, 0) != 0) + if (PyObject_Print(entry->key, fp, 0) != 0) { + Py_ReprLeave((PyObject*)so); return -1; + } } if (literalform) fputs("}", fp); else fputs("])", fp); + Py_ReprLeave((PyObject*)so); return 0; } static PyObject * set_repr(PySetObject *so) { - PyObject *keys, *result, *listrepr; + PyObject *keys, *result=NULL, *listrepr; + int status = Py_ReprEnter((PyObject*)so); + + if (status != 0) { + if (status < 0) + return NULL; + return PyString_FromFormat("%s(...)", so->ob_type->tp_name); + } /* shortcut for the empty set */ - if (!so->used) + if (!so->used) { + Py_ReprLeave((PyObject*)so); return PyString_FromFormat("%s()", so->ob_type->tp_name); + } keys = PySequence_List((PyObject *)so); if (keys == NULL) - return NULL; + goto done; listrepr = PyObject_Repr(keys); Py_DECREF(keys); if (listrepr == NULL) - return NULL; + goto done; if (so->ob_type == &PySet_Type) { char *s = PyString_AS_STRING(listrepr); @@ -624,6 +645,8 @@ PyString_AS_STRING(listrepr)); } Py_DECREF(listrepr); +done: + Py_ReprLeave((PyObject*)so); return result; } Modified: python/branches/p3yk-noslice/PC/python_nt.rc ============================================================================== --- python/branches/p3yk-noslice/PC/python_nt.rc (original) +++ python/branches/p3yk-noslice/PC/python_nt.rc Thu Jan 11 00:21:28 2007 @@ -61,7 +61,7 @@ VALUE "FileDescription", "Python Core\0" VALUE "FileVersion", PYTHON_VERSION VALUE "InternalName", "Python DLL\0" - VALUE "LegalCopyright", "Copyright ? 2001-2006 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" + VALUE "LegalCopyright", "Copyright ? 2001-2007 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" VALUE "OriginalFilename", PYTHON_DLL_NAME "\0" VALUE "ProductName", "Python\0" VALUE "ProductVersion", PYTHON_VERSION Modified: python/branches/p3yk-noslice/PCbuild/python20.wse ============================================================================== --- python/branches/p3yk-noslice/PCbuild/python20.wse (original) +++ python/branches/p3yk-noslice/PCbuild/python20.wse Thu Jan 11 00:21:28 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj (original) +++ python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj Thu Jan 11 00:21:28 2007 @@ -437,6 +437,9 @@ RelativePath="..\Objects\bufferobject.c"> + + ", @@ -998,6 +999,7 @@ case '-': switch (c2) { case '=': return MINEQUAL; + case '>': return RARROW; } break; case '*': 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 Thu Jan 11 00:21:28 2007 @@ -34,6 +34,7 @@ "args", "body", "decorators", + "returns", }; static PyTypeObject *ClassDef_type; static char *ClassDef_fields[]={ @@ -333,11 +334,24 @@ static char *arguments_fields[]={ "args", "vararg", + "varargannotation", "kwonlyargs", "kwarg", + "kwargannotation", "defaults", "kw_defaults", }; +static PyTypeObject *arg_type; +static PyObject* ast2obj_arg(void*); +static PyTypeObject *SimpleArg_type; +static char *SimpleArg_fields[]={ + "arg", + "annotation", +}; +static PyTypeObject *NestedArgs_type; +static char *NestedArgs_fields[]={ + "args", +}; static PyTypeObject *keyword_type; static PyObject* ast2obj_keyword(void*); static char *keyword_fields[]={ @@ -454,7 +468,7 @@ if (!stmt_type) return 0; if (!add_attributes(stmt_type, stmt_attributes, 2)) return 0; FunctionDef_type = make_type("FunctionDef", stmt_type, - FunctionDef_fields, 4); + FunctionDef_fields, 5); if (!FunctionDef_type) return 0; ClassDef_type = make_type("ClassDef", stmt_type, ClassDef_fields, 3); if (!ClassDef_type) return 0; @@ -710,8 +724,16 @@ excepthandler_type = make_type("excepthandler", AST_type, excepthandler_fields, 5); if (!excepthandler_type) return 0; - arguments_type = make_type("arguments", AST_type, arguments_fields, 6); + arguments_type = make_type("arguments", AST_type, arguments_fields, 8); if (!arguments_type) return 0; + arg_type = make_type("arg", AST_type, NULL, 0); + if (!arg_type) return 0; + if (!add_attributes(arg_type, NULL, 0)) return 0; + SimpleArg_type = make_type("SimpleArg", arg_type, SimpleArg_fields, 2); + if (!SimpleArg_type) return 0; + NestedArgs_type = make_type("NestedArgs", arg_type, NestedArgs_fields, + 1); + if (!NestedArgs_type) return 0; keyword_type = make_type("keyword", AST_type, keyword_fields, 2); if (!keyword_type) return 0; alias_type = make_type("alias", AST_type, alias_fields, 2); @@ -783,7 +805,8 @@ stmt_ty FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq * - decorators, int lineno, int col_offset, PyArena *arena) + decorators, expr_ty returns, int lineno, int col_offset, PyArena + *arena) { stmt_ty p; if (!name) { @@ -806,6 +829,7 @@ p->v.FunctionDef.args = args; p->v.FunctionDef.body = body; p->v.FunctionDef.decorators = decorators; + p->v.FunctionDef.returns = returns; p->lineno = lineno; p->col_offset = col_offset; return p; @@ -1830,8 +1854,9 @@ } arguments_ty -arguments(asdl_seq * args, identifier vararg, asdl_seq * kwonlyargs, identifier - kwarg, asdl_seq * defaults, asdl_seq * kw_defaults, PyArena *arena) +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) { arguments_ty p; p = (arguments_ty)PyArena_Malloc(arena, sizeof(*p)); @@ -1841,13 +1866,49 @@ } p->args = args; p->vararg = vararg; + p->varargannotation = varargannotation; p->kwonlyargs = kwonlyargs; p->kwarg = kwarg; + p->kwargannotation = kwargannotation; p->defaults = defaults; p->kw_defaults = kw_defaults; return p; } +arg_ty +SimpleArg(identifier arg, expr_ty annotation, PyArena *arena) +{ + arg_ty p; + if (!arg) { + PyErr_SetString(PyExc_ValueError, + "field arg is required for SimpleArg"); + return NULL; + } + p = (arg_ty)PyArena_Malloc(arena, sizeof(*p)); + if (!p) { + PyErr_NoMemory(); + return NULL; + } + p->kind = SimpleArg_kind; + p->v.SimpleArg.arg = arg; + p->v.SimpleArg.annotation = annotation; + return p; +} + +arg_ty +NestedArgs(asdl_seq * args, PyArena *arena) +{ + arg_ty p; + p = (arg_ty)PyArena_Malloc(arena, sizeof(*p)); + if (!p) { + PyErr_NoMemory(); + return NULL; + } + p->kind = NestedArgs_kind; + p->v.NestedArgs.args = args; + return p; +} + keyword_ty keyword(identifier arg, expr_ty value, PyArena *arena) { @@ -1981,6 +2042,11 @@ if (PyObject_SetAttrString(result, "decorators", value) == -1) goto failed; Py_DECREF(value); + value = ast2obj_expr(o->v.FunctionDef.returns); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "returns", value) == -1) + goto failed; + Py_DECREF(value); break; case ClassDef_kind: result = PyType_GenericNew(ClassDef_type, NULL, NULL); @@ -2901,7 +2967,7 @@ result = PyType_GenericNew(arguments_type, NULL, NULL); if (!result) return NULL; - value = ast2obj_list(o->args, ast2obj_expr); + value = ast2obj_list(o->args, ast2obj_arg); if (!value) goto failed; if (PyObject_SetAttrString(result, "args", value) == -1) goto failed; @@ -2911,7 +2977,12 @@ if (PyObject_SetAttrString(result, "vararg", value) == -1) goto failed; Py_DECREF(value); - value = ast2obj_list(o->kwonlyargs, ast2obj_expr); + value = ast2obj_expr(o->varargannotation); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "varargannotation", value) == -1) + goto failed; + Py_DECREF(value); + value = ast2obj_list(o->kwonlyargs, ast2obj_arg); if (!value) goto failed; if (PyObject_SetAttrString(result, "kwonlyargs", value) == -1) goto failed; @@ -2921,6 +2992,11 @@ if (PyObject_SetAttrString(result, "kwarg", value) == -1) goto failed; Py_DECREF(value); + value = ast2obj_expr(o->kwargannotation); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "kwargannotation", value) == -1) + goto failed; + Py_DECREF(value); value = ast2obj_list(o->defaults, ast2obj_expr); if (!value) goto failed; if (PyObject_SetAttrString(result, "defaults", value) == -1) @@ -2939,6 +3015,48 @@ } PyObject* +ast2obj_arg(void* _o) +{ + arg_ty o = (arg_ty)_o; + PyObject *result = NULL, *value = NULL; + if (!o) { + Py_INCREF(Py_None); + return Py_None; + } + + switch (o->kind) { + case SimpleArg_kind: + result = PyType_GenericNew(SimpleArg_type, NULL, NULL); + if (!result) goto failed; + value = ast2obj_identifier(o->v.SimpleArg.arg); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "arg", value) == -1) + goto failed; + Py_DECREF(value); + value = ast2obj_expr(o->v.SimpleArg.annotation); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "annotation", value) == -1) + goto failed; + Py_DECREF(value); + break; + case NestedArgs_kind: + result = PyType_GenericNew(NestedArgs_type, NULL, NULL); + if (!result) goto failed; + value = ast2obj_list(o->v.NestedArgs.args, ast2obj_arg); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "args", value) == -1) + goto failed; + Py_DECREF(value); + break; + } + return result; +failed: + Py_XDECREF(value); + Py_XDECREF(result); + return NULL; +} + +PyObject* ast2obj_keyword(void* _o) { keyword_ty o = (keyword_ty)_o; @@ -3008,7 +3126,7 @@ if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) return; - if (PyModule_AddStringConstant(m, "__version__", "53040") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53170") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) @@ -3146,6 +3264,11 @@ (PyObject*)excepthandler_type) < 0) return; if (PyDict_SetItemString(d, "arguments", (PyObject*)arguments_type) < 0) return; + if (PyDict_SetItemString(d, "arg", (PyObject*)arg_type) < 0) return; + if (PyDict_SetItemString(d, "SimpleArg", (PyObject*)SimpleArg_type) < + 0) return; + if (PyDict_SetItemString(d, "NestedArgs", (PyObject*)NestedArgs_type) < + 0) return; if (PyDict_SetItemString(d, "keyword", (PyObject*)keyword_type) < 0) return; if (PyDict_SetItemString(d, "alias", (PyObject*)alias_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 Thu Jan 11 00:21:28 2007 @@ -388,14 +388,14 @@ expr_name = "list comprehension"; break; case Dict_kind: - case Set_kind: + case Set_kind: case Num_kind: case Str_kind: expr_name = "literal"; break; - case Ellipsis_kind: - expr_name = "Ellipsis"; - break; + case Ellipsis_kind: + expr_name = "Ellipsis"; + break; case Compare_kind: expr_name = "comparison"; break; @@ -553,59 +553,74 @@ return seq; } -static expr_ty +static arg_ty +compiler_simple_arg(struct compiling *c, const node *n) +{ + identifier name; + expr_ty annotation = NULL; + node *ch; + + assert(TYPE(n) == tname || TYPE(n) == vname); + ch = CHILD(n, 0); + if (!strcmp(STR(ch), "None")) { + ast_error(ch, "assignment to None"); + return NULL; + } + name = NEW_IDENTIFIER(ch); + if (!name) + return NULL; + + if (NCH(n) == 3 && TYPE(CHILD(n, 1)) == COLON) { + annotation = ast_for_expr(c, CHILD(n, 2)); + if (!annotation) + return NULL; + } + + return SimpleArg(name, annotation, c->c_arena); +} + +static arg_ty compiler_complex_args(struct compiling *c, const node *n) { int i, len = (NCH(n) + 1) / 2; - expr_ty result; + arg_ty arg; asdl_seq *args = asdl_seq_new(len, c->c_arena); if (!args) return NULL; - /* fpdef: NAME | '(' fplist ')' - fplist: fpdef (',' fpdef)* [','] - */ - REQ(n, fplist); + assert(TYPE(n) == tfplist || TYPE(n) == vfplist); for (i = 0; i < len; i++) { - 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); + const node *child = CHILD(n, 2*i); + /* def foo(((x), y)): -- x is not nested complex, special case. */ + while (NCH(child) == 3 && NCH(CHILD(child, 1)) == 1) + child = CHILD(CHILD(child, 1), 0); + + /* child either holds a tname or '(', a tfplist, ')' */ + switch (TYPE(CHILD(child, 0))) { + case tname: + case vname: + arg = compiler_simple_arg(c, CHILD(child, 0)); + break; + case LPAR: + arg = compiler_complex_args(c, CHILD(child, 1)); + break; + default: + PyErr_Format(PyExc_SystemError, + "unexpected node in args: %d @ %d", + TYPE(CHILD(child, 0)), i); + arg = NULL; } + if (!arg) + return NULL; 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 result; + return NestedArgs(args, c->c_arena); } /* returns -1 if failed to handle keyword only arguments returns new position to keep processing if successful - (',' NAME ['=' test])* + (',' tname ['=' test])* ^^^ start pointing here */ @@ -614,7 +629,8 @@ asdl_seq *kwonlyargs, asdl_seq *kwdefaults) { node *ch; - expr_ty name; + expr_ty expression, annotation; + arg_ty arg; int i = start; int j = 0; /* index for kwdefaults and kwonlyargs */ assert(kwonlyargs != NULL); @@ -622,9 +638,10 @@ while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { - case NAME: + case vname: + case tname: if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { - expr_ty expression = ast_for_expr(c, CHILD(n, i + 2)); + expression = ast_for_expr(c, CHILD(n, i + 2)); if (!expression) { ast_error(ch, "assignment to None"); goto error; @@ -635,18 +652,28 @@ else { /* setting NULL if no default value exists */ asdl_seq_SET(kwdefaults, j, NULL); } + if (NCH(ch) == 3) { + /* ch is NAME ':' test */ + annotation = ast_for_expr(c, CHILD(ch, 2)); + if (!annotation) { + ast_error(ch, "expected expression"); + goto error; + } + } + else { + annotation = NULL; + } + ch = CHILD(ch, 0); if (!strcmp(STR(ch), "None")) { ast_error(ch, "assignment to None"); goto error; } - name = Name(NEW_IDENTIFIER(ch), - Param, LINENO(ch), ch->n_col_offset, - c->c_arena); - if (!name) { + arg = SimpleArg(NEW_IDENTIFIER(ch), annotation, c->c_arena); + if (!arg) { ast_error(ch, "expecting name"); goto error; } - asdl_seq_SET(kwonlyargs, j++, name); + asdl_seq_SET(kwonlyargs, j++, arg); i += 2; /* the name and the comma */ break; case DOUBLESTAR: @@ -666,29 +693,41 @@ static arguments_ty ast_for_arguments(struct compiling *c, const node *n) { - /* parameters: '(' [varargslist] ')' - varargslist: (fpdef ['=' test] ',')* - ('*' [NAME] (',' fpdef ['=' test])* [',' '**' NAME] | '**' NAME) - | fpdef ['=' test] (',' fpdef ['=' test])* [','] + /* This function handles both typedargslist (function definition) + and varargslist (lambda definition). + + parameters: '(' [typedargslist] ')' + typedargslist: ((tfpdef ['=' test] ',')* + ('*' [tname] (',' tname ['=' test])* [',' '**' tname] + | '**' tname) + | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) + varargslist: ((vfpdef ['=' test] ',')* + ('*' [vname] (',' vname ['=' test])* [',' '**' vname] + | '**' vname) + | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) */ int i, j, k, nposargs = 0, nkwonlyargs = 0; int nposdefaults = 0, found_default = 0; asdl_seq *posargs, *posdefaults, *kwonlyargs, *kwdefaults; identifier vararg = NULL, kwarg = NULL; + arg_ty arg; + expr_ty varargannotation = NULL, kwargannotation = NULL; node *ch; if (TYPE(n) == parameters) { if (NCH(n) == 2) /* () as argument list */ - return arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena); + return arguments(NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, c->c_arena); n = CHILD(n, 1); } - REQ(n, varargslist); + assert(TYPE(n) == typedargslist || TYPE(n) == varargslist); /* first count the number of positional args & defaults */ for (i = 0; i < NCH(n); i++) { ch = CHILD(n, i); if (TYPE(ch) == STAR) { - if (TYPE(CHILD(n, i+1)) == NAME) { + if (TYPE(CHILD(n, i+1)) == tname + || TYPE(CHILD(n, i+1)) == vname) { /* skip NAME of vararg */ /* so that following can count only keyword only args */ i += 2; @@ -698,7 +737,7 @@ } break; } - if (TYPE(ch) == fpdef) nposargs++; + if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++; if (TYPE(ch) == EQUAL) nposdefaults++; } /* count the number of keyword only args & @@ -706,35 +745,39 @@ for ( ; i < NCH(n); ++i) { ch = CHILD(n, i); if (TYPE(ch) == DOUBLESTAR) break; - if (TYPE(ch) == NAME) nkwonlyargs++; + if (TYPE(ch) == tname || TYPE(ch) == vname) nkwonlyargs++; } posargs = (nposargs ? asdl_seq_new(nposargs, c->c_arena) : NULL); if (!posargs && nposargs) - return NULL; /* Don't need to goto error; no objects allocated */ + goto error; kwonlyargs = (nkwonlyargs ? asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwonlyargs && nkwonlyargs) - return NULL; /* Don't need to goto error; no objects allocated */ + goto error; posdefaults = (nposdefaults ? asdl_seq_new(nposdefaults, c->c_arena) : NULL); if (!posdefaults && nposdefaults) - return NULL; /* Don't need to goto error; no objects allocated */ + goto error; /* The length of kwonlyargs and kwdefaults are same since we set NULL as default for keyword only argument w/o default - we have sequence data structure, but no dictionary */ - kwdefaults = (nkwonlyargs ? + kwdefaults = (nkwonlyargs ? asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwdefaults && nkwonlyargs) - return NULL; /* Don't need to goto error; no objects allocated */ + goto error; if (nposargs + nkwonlyargs > 255) { - ast_error(n, "more than 255 arguments"); - return NULL; + ast_error(n, "more than 255 arguments"); + return NULL; } - /* fpdef: NAME | '(' fplist ')' - fplist: fpdef (',' fpdef)* [','] + /* tname: NAME [':' test] + tfpdef: tname | '(' tfplist ')' + tfplist: tfpdef (',' tfpdef)* [','] + vname: NAME + vfpdef: NAME | '(' vfplist ')' + vfplist: vfpdef (',' vfpdef)* [','] */ i = 0; j = 0; /* index for defaults */ @@ -742,8 +785,8 @@ while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { - case fpdef: - handle_fpdef: + case tfpdef: + case vfpdef: /* 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? */ @@ -753,7 +796,6 @@ goto error; assert(posdefaults != NULL); asdl_seq_SET(posdefaults, j++, expression); - i += 2; found_default = 1; } @@ -762,59 +804,47 @@ "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(posargs, 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(posargs, k++, name); + /* def foo((x)): is not complex, special case. */ + while (NCH(ch) == 3 && NCH(CHILD(ch, 1)) == 1) + ch = CHILD(CHILD(ch, 1), 0); + + if (NCH(ch) != 1) + arg = compiler_complex_args(c, CHILD(ch, 1)); + else + arg = compiler_simple_arg(c, CHILD(ch, 0)); + if (!arg) + goto error; + asdl_seq_SET(posargs, k++, arg); - } i += 2; /* the name and the comma */ break; case STAR: if (i+1 >= NCH(n)) { ast_error(CHILD(n, i), "no name for vararg"); - goto error; - } - if (!strcmp(STR(CHILD(n, i+1)), "None")) { - ast_error(CHILD(n, i+1), "assignment to None"); - goto error; + goto error; } - if (TYPE(CHILD(n, i+1)) == COMMA) { - int res = 0; + ch = CHILD(n, i+1); /* tname or COMMA */ + if (TYPE(ch) == COMMA) { + int res = 0; i += 2; /* now follows keyword only arguments */ res = handle_keywordonly_args(c, n, i, kwonlyargs, kwdefaults); if (res == -1) goto error; i = res; /* res has new position to process */ } + else if (!strcmp(STR(CHILD(ch, 0)), "None")) { + ast_error(CHILD(ch, 0), "assignment to None"); + goto error; + } else { - vararg = NEW_IDENTIFIER(CHILD(n, i+1)); + vararg = NEW_IDENTIFIER(CHILD(ch, 0)); + if (NCH(ch) > 1) { + /* there is an annotation on the vararg */ + varargannotation = ast_for_expr(c, CHILD(ch, 2)); + } i += 3; - if (i < NCH(n) && TYPE(CHILD(n, i)) == NAME) { + if (i < NCH(n) && (TYPE(CHILD(n, i)) == tname + || TYPE(CHILD(n, i)) == vname)) { int res = 0; res = handle_keywordonly_args(c, n, i, kwonlyargs, kwdefaults); @@ -824,11 +854,17 @@ } break; case DOUBLESTAR: - if (!strcmp(STR(CHILD(n, i+1)), "None")) { - ast_error(CHILD(n, i+1), "assignment to None"); + ch = CHILD(n, i+1); /* tname */ + assert(TYPE(ch) == tname || TYPE(ch) == vname); + if (!strcmp(STR(CHILD(ch, 0)), "None")) { + ast_error(CHILD(ch, 0), "assignment to None"); goto error; } - kwarg = NEW_IDENTIFIER(CHILD(n, i+1)); + kwarg = NEW_IDENTIFIER(CHILD(ch, 0)); + if (NCH(ch) > 1) { + /* there is an annotation on the kwarg */ + kwargannotation = ast_for_expr(c, CHILD(ch, 2)); + } i += 3; break; default: @@ -838,8 +874,8 @@ goto error; } } - return arguments(posargs, vararg, kwonlyargs, kwarg, - posdefaults, kwdefaults, c->c_arena); + return arguments(posargs, vararg, varargannotation, kwonlyargs, kwarg, + kwargannotation, posdefaults, kwdefaults, c->c_arena); error: Py_XDECREF(vararg); Py_XDECREF(kwarg); @@ -938,11 +974,12 @@ static stmt_ty ast_for_funcdef(struct compiling *c, const node *n) { - /* funcdef: 'def' [decorators] NAME parameters ':' suite */ + /* funcdef: 'def' [decorators] NAME parameters ['->' test] ':' suite */ identifier name; arguments_ty args; asdl_seq *body; asdl_seq *decorator_seq = NULL; + expr_ty returns = NULL; int name_i; REQ(n, funcdef); @@ -967,11 +1004,17 @@ args = ast_for_arguments(c, CHILD(n, name_i + 1)); if (!args) return NULL; + if (TYPE(CHILD(n, name_i+2)) == RARROW) { + returns = ast_for_expr(c, CHILD(n, name_i + 3)); + if (!returns) + return NULL; + name_i += 2; + } body = ast_for_suite(c, CHILD(n, name_i + 3)); if (!body) return NULL; - return FunctionDef(name, args, body, decorator_seq, LINENO(n), + return FunctionDef(name, args, body, decorator_seq, returns, LINENO(n), n->n_col_offset, c->c_arena); } @@ -983,7 +1026,8 @@ expr_ty expression; if (NCH(n) == 3) { - args = arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena); + args = arguments(NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, c->c_arena); if (!args) return NULL; expression = ast_for_expr(c, CHILD(n, 2)); @@ -1361,9 +1405,8 @@ PyArena_AddPyObject(c->c_arena, pynum); return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena); } - case DOT: - /* Ellipsis */ - return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena); + case DOT: /* Ellipsis */ + return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena); case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); @@ -1394,13 +1437,13 @@ else return ast_for_listcomp(c, ch); case LBRACE: { - /* dictsetmaker: test ':' test (',' test ':' test)* [','] | - * test (',' test)* [','] */ - int i, size; - asdl_seq *keys, *values; - - ch = CHILD(n, 1); - if (NCH(ch) == 1 || (NCH(ch) > 0 && STR(CHILD(ch, 1))[0] == ',')) { + /* dictsetmaker: test ':' test (',' test ':' test)* [','] | + * test (',' test)* [','] */ + int i, size; + asdl_seq *keys, *values; + + ch = CHILD(n, 1); + if (NCH(ch) == 1 || (NCH(ch) > 0 && STR(CHILD(ch, 1))[0] == ',')) { /* it's a set */ size = (NCH(ch) + 1) / 2; /* +1 in case no trailing comma */ keys = asdl_seq_new(size, c->c_arena); @@ -3046,10 +3089,10 @@ 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 | assert_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 | assert_stmt */ switch (TYPE(n)) { case expr_stmt: Modified: python/branches/p3yk-noslice/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk-noslice/Python/bltinmodule.c (original) +++ python/branches/p3yk-noslice/Python/bltinmodule.c Thu Jan 11 00:21:28 2007 @@ -1119,31 +1119,6 @@ static PyObject * -builtin_intern(PyObject *self, PyObject *args) -{ - PyObject *s; - if (!PyArg_ParseTuple(args, "S:intern", &s)) - return NULL; - if (!PyString_CheckExact(s)) { - PyErr_SetString(PyExc_TypeError, - "can't intern subclass of string"); - return NULL; - } - Py_INCREF(s); - PyString_InternInPlace(&s); - return s; -} - -PyDoc_STRVAR(intern_doc, -"intern(string) -> string\n\ -\n\ -``Intern'' the given string. This enters the string in the (global)\n\ -table of interned strings whose purpose is to speed up dictionary lookups.\n\ -Return the string itself or the previously interned string object with the\n\ -same value."); - - -static PyObject * builtin_iter(PyObject *self, PyObject *args) { PyObject *v, *w = NULL; @@ -2069,7 +2044,6 @@ {"hash", builtin_hash, METH_O, hash_doc}, {"hex", builtin_hex, METH_O, hex_doc}, {"id", builtin_id, METH_O, id_doc}, - {"intern", builtin_intern, METH_VARARGS, intern_doc}, {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, {"iter", builtin_iter, METH_VARARGS, iter_doc}, Modified: python/branches/p3yk-noslice/Python/ceval.c ============================================================================== --- python/branches/p3yk-noslice/Python/ceval.c (original) +++ python/branches/p3yk-noslice/Python/ceval.c Thu Jan 11 00:21:28 2007 @@ -734,7 +734,16 @@ this wasn't always true before 2.3! PyFrame_New now sets f->f_lasti to -1 (i.e. the index *before* the first instruction) and YIELD_VALUE doesn't fiddle with f_lasti any more. So this - does work. Promise. */ + does work. Promise. + + When the PREDICT() macros are enabled, some opcode pairs follow in + direct succession without updating f->f_lasti. A successful + prediction effectively links the two codes together as if they + were a single new opcode; accordingly,f->f_lasti will point to + the first code in the pair (for instance, GET_ITER followed by + FOR_ITER is effectively a single opcode and f->f_lasti will point + at to the beginning of the combined pair.) + */ next_instr = first_instr + f->f_lasti + 1; stack_pointer = f->f_stacktop; assert(stack_pointer != NULL); @@ -2225,10 +2234,38 @@ { int posdefaults = oparg & 0xff; int kwdefaults = (oparg>>8) & 0xff; + int num_annotations = (oparg >> 16) & 0x7fff; + PyObject *t; v = POP(); /* code object */ x = PyFunction_New(v, f->f_globals); Py_DECREF(v); + + if (x != NULL && num_annotations > 0) { + Py_ssize_t name_ix; + u = POP(); /* names of args with annotations */ + v = PyDict_New(); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + name_ix = PyTuple_Size(u); + assert(num_annotations == name_ix+1); + while (name_ix > 0) { + --name_ix; + t = PyTuple_GET_ITEM(u, name_ix); + w = POP(); + /* XXX(nnorwitz): check for errors */ + PyDict_SetItem(v, t, w); + Py_DECREF(w); + } + + err = PyFunction_SetAnnotations(x, v); + Py_DECREF(v); + Py_DECREF(u); + } + /* XXX Maybe this should be a separate opcode? */ if (x != NULL && posdefaults > 0) { v = PyTuple_New(posdefaults); @@ -2254,6 +2291,7 @@ while (--kwdefaults >= 0) { w = POP(); /* default value */ u = POP(); /* kw only arg name */ + /* XXX(nnorwitz): check for errors */ PyDict_SetItem(v, u, w); } err = PyFunction_SetKwDefaults(x, v); Modified: python/branches/p3yk-noslice/Python/compile.c ============================================================================== --- python/branches/p3yk-noslice/Python/compile.c (original) +++ python/branches/p3yk-noslice/Python/compile.c Thu Jan 11 00:21:28 2007 @@ -805,7 +805,7 @@ case RAISE_VARARGS: return -oparg; -#define NARGS(o) (((o) % 256) + 2*((o) / 256)) +#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256)) case CALL_FUNCTION: return -NARGS(oparg); case CALL_FUNCTION_VAR: @@ -814,7 +814,7 @@ case CALL_FUNCTION_VAR_KW: return -NARGS(oparg)-2; case MAKE_FUNCTION: - return -NARGS(oparg); + return -NARGS(oparg) - ((oparg >> 16) & 0xffff); #undef NARGS case BUILD_SLICE: if (oparg == 3) @@ -1240,14 +1240,37 @@ } static int +compiler_unpack_nested(struct compiler *c, asdl_seq *args) { + int i, len; + len = asdl_seq_LEN(args); + ADDOP_I(c, UNPACK_SEQUENCE, len); + for (i = 0; i < len; i++) { + arg_ty elt = (arg_ty)asdl_seq_GET(args, i); + switch (elt->kind) { + case SimpleArg_kind: + if (!compiler_nameop(c, elt->v.SimpleArg.arg, Store)) + return 0; + break; + case NestedArgs_kind: + if (!compiler_unpack_nested(c, elt->v.NestedArgs.args)) + return 0; + break; + default: + return 0; + } + } + return 1; +} + +static int compiler_arguments(struct compiler *c, arguments_ty args) { int i; int n = asdl_seq_LEN(args->args); - /* Correctly handle nested argument lists */ + for (i = 0; i < n; i++) { - expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i); - if (arg->kind == Tuple_kind) { + arg_ty arg = (arg_ty)asdl_seq_GET(args->args, i); + if (arg->kind == NestedArgs_kind) { PyObject *id = PyString_FromFormat(".%d", i); if (id == NULL) { return 0; @@ -1257,7 +1280,8 @@ return 0; } Py_DECREF(id); - VISIT(c, expr, arg); + if (!compiler_unpack_nested(c, arg->v.NestedArgs.args)) + return 0; } } return 1; @@ -1269,10 +1293,10 @@ { int i, default_count = 0; for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { - expr_ty arg = asdl_seq_GET(kwonlyargs, i); + arg_ty arg = asdl_seq_GET(kwonlyargs, i); expr_ty default_ = asdl_seq_GET(kw_defaults, i); if (default_) { - ADDOP_O(c, LOAD_CONST, arg->v.Name.id, consts); + ADDOP_O(c, LOAD_CONST, arg->v.SimpleArg.arg, consts); if (!compiler_visit_expr(c, default_)) { return -1; } @@ -1283,14 +1307,112 @@ } static int +compiler_visit_argannotation(struct compiler *c, identifier id, + expr_ty annotation, PyObject *names) +{ + if (annotation) { + VISIT(c, expr, annotation); + if (PyList_Append(names, id)) + return -1; + } + return 0; +} + +static int +compiler_visit_argannotations(struct compiler *c, asdl_seq* args, + PyObject *names) +{ + int i, error; + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + if (arg->kind == NestedArgs_kind) + error = compiler_visit_argannotations( + c, + arg->v.NestedArgs.args, + names); + else + error = compiler_visit_argannotation( + c, + arg->v.SimpleArg.arg, + arg->v.SimpleArg.annotation, + names); + if (error) + return error; + } + return 0; +} + +static int +compiler_visit_annotations(struct compiler *c, arguments_ty args, + expr_ty returns) +{ + /* push arg annotations and a list of the argument names. return the # + of items pushed. this is out-of-order wrt the source code. */ + static identifier return_str; + PyObject *names; + int len; + names = PyList_New(0); + if (!names) + return -1; + + if (compiler_visit_argannotations(c, args->args, names)) + goto error; + if (args->varargannotation && + compiler_visit_argannotation(c, args->vararg, + args->varargannotation, names)) + goto error; + if (compiler_visit_argannotations(c, args->kwonlyargs, names)) + goto error; + if (args->kwargannotation && + compiler_visit_argannotation(c, args->kwarg, + args->kwargannotation, names)) + goto error; + + if (!return_str) { + return_str = PyString_InternFromString("return"); + if (!return_str) + goto error; + } + if (compiler_visit_argannotation(c, return_str, returns, names)) { + goto error; + } + + len = PyList_GET_SIZE(names); + if (len) { + /* convert names to a tuple and place on stack */ + PyObject *elt; + int i; + PyObject *s = PyTuple_New(len); + if (!s) + goto error; + for (i = 0; i < len; i++) { + elt = PyList_GET_ITEM(names, i); + Py_INCREF(elt); + PyTuple_SET_ITEM(s, i, elt); + } + ADDOP_O(c, LOAD_CONST, s, consts); + Py_DECREF(s); + len++; /* include the just-pushed tuple */ + } + Py_DECREF(names); + return len; + +error: + Py_DECREF(names); + return -1; +} + +static int compiler_function(struct compiler *c, stmt_ty s) { PyCodeObject *co; PyObject *first_const = Py_None; arguments_ty args = s->v.FunctionDef.args; + expr_ty returns = s->v.FunctionDef.returns; asdl_seq* decos = s->v.FunctionDef.decorators; stmt_ty st; int i, n, docstring, kw_default_count = 0, arglength; + int num_annotations; assert(s->kind == FunctionDef_kind); @@ -1305,6 +1427,7 @@ } if (args->defaults) VISIT_SEQ(c, expr, args->defaults); + num_annotations = compiler_visit_annotations(c, args, returns); if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s, s->lineno)) @@ -1337,9 +1460,11 @@ arglength = asdl_seq_LEN(args->defaults); arglength |= kw_default_count << 8; + arglength |= num_annotations << 16; compiler_make_closure(c, co, arglength); Py_DECREF(co); + /* decorators */ for (i = 0; i < asdl_seq_LEN(decos); i++) { ADDOP_I(c, CALL_FUNCTION, 1); } Modified: python/branches/p3yk-noslice/Python/errors.c ============================================================================== --- python/branches/p3yk-noslice/Python/errors.c (original) +++ python/branches/p3yk-noslice/Python/errors.c Thu Jan 11 00:21:28 2007 @@ -649,7 +649,8 @@ if (warnings_module != NULL) { dict = PyModule_GetDict(warnings_module); - func = PyDict_GetItemString(dict, "warn"); + if (dict != NULL) + func = PyDict_GetItemString(dict, "warn"); } if (func == NULL) { PySys_WriteStderr("warning: %s\n", message); Modified: python/branches/p3yk-noslice/Python/getcopyright.c ============================================================================== --- python/branches/p3yk-noslice/Python/getcopyright.c (original) +++ python/branches/p3yk-noslice/Python/getcopyright.c Thu Jan 11 00:21:28 2007 @@ -4,7 +4,7 @@ static char cprt[] = "\ -Copyright (c) 2001-2006 Python Software Foundation.\n\ +Copyright (c) 2001-2007 Python Software Foundation.\n\ All Rights Reserved.\n\ \n\ Copyright (c) 2000 BeOpen.com.\n\ Modified: python/branches/p3yk-noslice/Python/graminit.c ============================================================================== --- python/branches/p3yk-noslice/Python/graminit.c (original) +++ python/branches/p3yk-noslice/Python/graminit.c Thu Jan 11 00:21:28 2007 @@ -99,29 +99,38 @@ static arc arcs_5_3[1] = { {20, 4}, }; -static arc arcs_5_4[1] = { +static arc arcs_5_4[2] = { {21, 5}, + {23, 6}, }; static arc arcs_5_5[1] = { - {22, 6}, + {22, 7}, }; static arc arcs_5_6[1] = { - {0, 6}, + {24, 8}, +}; +static arc arcs_5_7[1] = { + {23, 6}, }; -static state states_5[7] = { +static arc arcs_5_8[1] = { + {0, 8}, +}; +static state states_5[9] = { {2, arcs_5_0}, {1, arcs_5_1}, {1, arcs_5_2}, {1, arcs_5_3}, - {1, arcs_5_4}, + {2, arcs_5_4}, {1, arcs_5_5}, {1, arcs_5_6}, + {1, arcs_5_7}, + {1, arcs_5_8}, }; static arc arcs_6_0[1] = { {13, 1}, }; static arc arcs_6_1[2] = { - {23, 2}, + {25, 2}, {15, 3}, }; static arc arcs_6_2[1] = { @@ -137,54 +146,54 @@ {1, arcs_6_3}, }; static arc arcs_7_0[3] = { - {24, 1}, - {28, 2}, - {29, 3}, + {26, 1}, + {29, 2}, + {31, 3}, }; static arc arcs_7_1[3] = { - {25, 4}, - {27, 5}, + {27, 4}, + {28, 5}, {0, 1}, }; static arc arcs_7_2[3] = { - {19, 6}, - {27, 7}, + {30, 6}, + {28, 7}, {0, 2}, }; static arc arcs_7_3[1] = { - {19, 8}, + {30, 8}, }; static arc arcs_7_4[1] = { - {26, 9}, + {22, 9}, }; static arc arcs_7_5[4] = { - {24, 1}, - {28, 2}, - {29, 3}, + {26, 1}, + {29, 2}, + {31, 3}, {0, 5}, }; static arc arcs_7_6[2] = { - {27, 7}, + {28, 7}, {0, 6}, }; static arc arcs_7_7[2] = { - {19, 10}, - {29, 3}, + {30, 10}, + {31, 3}, }; static arc arcs_7_8[1] = { {0, 8}, }; static arc arcs_7_9[2] = { - {27, 5}, + {28, 5}, {0, 9}, }; static arc arcs_7_10[3] = { - {27, 7}, - {25, 11}, + {28, 7}, + {27, 11}, {0, 10}, }; static arc arcs_7_11[1] = { - {26, 6}, + {22, 6}, }; static state states_7[12] = { {3, arcs_7_0}, @@ -200,261 +209,330 @@ {3, arcs_7_10}, {1, arcs_7_11}, }; -static arc arcs_8_0[2] = { +static arc arcs_8_0[1] = { {19, 1}, - {13, 2}, }; -static arc arcs_8_1[1] = { +static arc arcs_8_1[2] = { + {23, 2}, {0, 1}, }; static arc arcs_8_2[1] = { - {30, 3}, + {22, 3}, }; static arc arcs_8_3[1] = { - {15, 1}, + {0, 3}, }; static state states_8[4] = { - {2, arcs_8_0}, - {1, arcs_8_1}, + {1, arcs_8_0}, + {2, arcs_8_1}, {1, arcs_8_2}, {1, arcs_8_3}, }; -static arc arcs_9_0[1] = { - {24, 1}, +static arc arcs_9_0[2] = { + {30, 1}, + {13, 2}, }; -static arc arcs_9_1[2] = { - {27, 2}, +static arc arcs_9_1[1] = { {0, 1}, }; -static arc arcs_9_2[2] = { - {24, 1}, - {0, 2}, +static arc arcs_9_2[1] = { + {32, 3}, }; -static state states_9[3] = { - {1, arcs_9_0}, - {2, arcs_9_1}, - {2, arcs_9_2}, +static arc arcs_9_3[1] = { + {15, 1}, }; -static arc arcs_10_0[2] = { - {3, 1}, - {4, 1}, +static state states_9[4] = { + {2, arcs_9_0}, + {1, arcs_9_1}, + {1, arcs_9_2}, + {1, arcs_9_3}, }; -static arc arcs_10_1[1] = { +static arc arcs_10_0[1] = { + {26, 1}, +}; +static arc arcs_10_1[2] = { + {28, 2}, {0, 1}, }; -static state states_10[2] = { - {2, arcs_10_0}, - {1, arcs_10_1}, +static arc arcs_10_2[2] = { + {26, 1}, + {0, 2}, +}; +static state states_10[3] = { + {1, arcs_10_0}, + {2, arcs_10_1}, + {2, arcs_10_2}, }; -static arc arcs_11_0[1] = { - {31, 1}, +static arc arcs_11_0[3] = { + {34, 1}, + {29, 2}, + {31, 3}, }; -static arc arcs_11_1[2] = { - {32, 2}, - {2, 3}, +static arc arcs_11_1[3] = { + {27, 4}, + {28, 5}, + {0, 1}, }; -static arc arcs_11_2[2] = { - {31, 1}, - {2, 3}, +static arc arcs_11_2[3] = { + {35, 6}, + {28, 7}, + {0, 2}, }; static arc arcs_11_3[1] = { - {0, 3}, + {35, 8}, }; -static state states_11[4] = { - {1, arcs_11_0}, - {2, arcs_11_1}, - {2, arcs_11_2}, - {1, arcs_11_3}, +static arc arcs_11_4[1] = { + {22, 9}, }; -static arc arcs_12_0[8] = { - {33, 1}, +static arc arcs_11_5[4] = { {34, 1}, - {35, 1}, - {36, 1}, - {37, 1}, - {38, 1}, - {39, 1}, - {40, 1}, -}; -static arc arcs_12_1[1] = { - {0, 1}, -}; -static state states_12[2] = { - {8, arcs_12_0}, - {1, arcs_12_1}, + {29, 2}, + {31, 3}, + {0, 5}, }; -static arc arcs_13_0[1] = { - {9, 1}, +static arc arcs_11_6[2] = { + {28, 7}, + {0, 6}, }; -static arc arcs_13_1[3] = { - {41, 2}, - {25, 3}, - {0, 1}, +static arc arcs_11_7[2] = { + {35, 10}, + {31, 3}, }; -static arc arcs_13_2[2] = { - {42, 4}, - {9, 4}, +static arc arcs_11_8[1] = { + {0, 8}, }; -static arc arcs_13_3[2] = { - {42, 5}, - {9, 5}, +static arc arcs_11_9[2] = { + {28, 5}, + {0, 9}, }; -static arc arcs_13_4[1] = { - {0, 4}, +static arc arcs_11_10[3] = { + {28, 7}, + {27, 11}, + {0, 10}, }; -static arc arcs_13_5[2] = { - {25, 3}, - {0, 5}, +static arc arcs_11_11[1] = { + {22, 6}, }; -static state states_13[6] = { - {1, arcs_13_0}, - {3, arcs_13_1}, - {2, arcs_13_2}, - {2, arcs_13_3}, - {1, arcs_13_4}, - {2, arcs_13_5}, +static state states_11[12] = { + {3, arcs_11_0}, + {3, arcs_11_1}, + {3, arcs_11_2}, + {1, arcs_11_3}, + {1, arcs_11_4}, + {4, arcs_11_5}, + {2, arcs_11_6}, + {2, arcs_11_7}, + {1, arcs_11_8}, + {2, arcs_11_9}, + {3, arcs_11_10}, + {1, arcs_11_11}, }; -static arc arcs_14_0[12] = { - {43, 1}, - {44, 1}, - {45, 1}, - {46, 1}, - {47, 1}, - {48, 1}, - {49, 1}, - {50, 1}, - {51, 1}, - {52, 1}, - {53, 1}, - {54, 1}, +static arc arcs_12_0[1] = { + {19, 1}, }; -static arc arcs_14_1[1] = { +static arc arcs_12_1[1] = { {0, 1}, }; -static state states_14[2] = { - {12, arcs_14_0}, - {1, arcs_14_1}, +static state states_12[2] = { + {1, arcs_12_0}, + {1, arcs_12_1}, }; -static arc arcs_15_0[1] = { - {55, 1}, +static arc arcs_13_0[2] = { + {35, 1}, + {13, 2}, }; -static arc arcs_15_1[3] = { - {26, 2}, - {56, 3}, +static arc arcs_13_1[1] = { {0, 1}, }; -static arc arcs_15_2[2] = { - {27, 4}, - {0, 2}, +static arc arcs_13_2[1] = { + {36, 3}, }; -static arc arcs_15_3[1] = { - {26, 5}, +static arc arcs_13_3[1] = { + {15, 1}, }; -static arc arcs_15_4[2] = { - {26, 2}, - {0, 4}, +static state states_13[4] = { + {2, arcs_13_0}, + {1, arcs_13_1}, + {1, arcs_13_2}, + {1, arcs_13_3}, }; -static arc arcs_15_5[2] = { - {27, 6}, - {0, 5}, +static arc arcs_14_0[1] = { + {34, 1}, +}; +static arc arcs_14_1[2] = { + {28, 2}, + {0, 1}, }; -static arc arcs_15_6[1] = { - {26, 7}, +static arc arcs_14_2[2] = { + {34, 1}, + {0, 2}, }; -static arc arcs_15_7[2] = { - {27, 8}, - {0, 7}, +static state states_14[3] = { + {1, arcs_14_0}, + {2, arcs_14_1}, + {2, arcs_14_2}, }; -static arc arcs_15_8[2] = { - {26, 7}, - {0, 8}, +static arc arcs_15_0[2] = { + {3, 1}, + {4, 1}, +}; +static arc arcs_15_1[1] = { + {0, 1}, }; -static state states_15[9] = { - {1, arcs_15_0}, - {3, arcs_15_1}, - {2, arcs_15_2}, - {1, arcs_15_3}, - {2, arcs_15_4}, - {2, arcs_15_5}, - {1, arcs_15_6}, - {2, arcs_15_7}, - {2, arcs_15_8}, +static state states_15[2] = { + {2, arcs_15_0}, + {1, arcs_15_1}, }; static arc arcs_16_0[1] = { - {57, 1}, + {37, 1}, +}; +static arc arcs_16_1[2] = { + {38, 2}, + {2, 3}, }; -static arc arcs_16_1[1] = { - {58, 2}, +static arc arcs_16_2[2] = { + {37, 1}, + {2, 3}, }; -static arc arcs_16_2[1] = { - {0, 2}, +static arc arcs_16_3[1] = { + {0, 3}, }; -static state states_16[3] = { +static state states_16[4] = { {1, arcs_16_0}, - {1, arcs_16_1}, - {1, arcs_16_2}, + {2, arcs_16_1}, + {2, arcs_16_2}, + {1, arcs_16_3}, }; -static arc arcs_17_0[1] = { - {59, 1}, +static arc arcs_17_0[8] = { + {39, 1}, + {40, 1}, + {41, 1}, + {42, 1}, + {43, 1}, + {44, 1}, + {45, 1}, + {46, 1}, }; static arc arcs_17_1[1] = { {0, 1}, }; static state states_17[2] = { - {1, arcs_17_0}, + {8, arcs_17_0}, {1, arcs_17_1}, }; -static arc arcs_18_0[5] = { - {60, 1}, - {61, 1}, - {62, 1}, - {63, 1}, - {64, 1}, +static arc arcs_18_0[1] = { + {9, 1}, }; -static arc arcs_18_1[1] = { +static arc arcs_18_1[3] = { + {47, 2}, + {27, 3}, {0, 1}, }; -static state states_18[2] = { - {5, arcs_18_0}, - {1, arcs_18_1}, +static arc arcs_18_2[2] = { + {48, 4}, + {9, 4}, }; -static arc arcs_19_0[1] = { - {65, 1}, +static arc arcs_18_3[2] = { + {48, 5}, + {9, 5}, +}; +static arc arcs_18_4[1] = { + {0, 4}, +}; +static arc arcs_18_5[2] = { + {27, 3}, + {0, 5}, +}; +static state states_18[6] = { + {1, arcs_18_0}, + {3, arcs_18_1}, + {2, arcs_18_2}, + {2, arcs_18_3}, + {1, arcs_18_4}, + {2, arcs_18_5}, +}; +static arc arcs_19_0[12] = { + {49, 1}, + {50, 1}, + {51, 1}, + {52, 1}, + {53, 1}, + {54, 1}, + {55, 1}, + {56, 1}, + {57, 1}, + {58, 1}, + {59, 1}, + {60, 1}, }; static arc arcs_19_1[1] = { {0, 1}, }; static state states_19[2] = { - {1, arcs_19_0}, + {12, arcs_19_0}, {1, arcs_19_1}, }; static arc arcs_20_0[1] = { - {66, 1}, + {61, 1}, }; -static arc arcs_20_1[1] = { +static arc arcs_20_1[3] = { + {22, 2}, + {62, 3}, {0, 1}, }; -static state states_20[2] = { +static arc arcs_20_2[2] = { + {28, 4}, + {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] = { {1, arcs_20_0}, - {1, arcs_20_1}, + {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}, }; static arc arcs_21_0[1] = { - {67, 1}, + {63, 1}, }; -static arc arcs_21_1[2] = { - {9, 2}, - {0, 1}, +static arc arcs_21_1[1] = { + {64, 2}, }; static arc arcs_21_2[1] = { {0, 2}, }; static state states_21[3] = { {1, arcs_21_0}, - {2, arcs_21_1}, + {1, arcs_21_1}, {1, arcs_21_2}, }; static arc arcs_22_0[1] = { - {42, 1}, + {65, 1}, }; static arc arcs_22_1[1] = { {0, 1}, @@ -463,662 +541,646 @@ {1, arcs_22_0}, {1, arcs_22_1}, }; -static arc arcs_23_0[1] = { +static arc arcs_23_0[5] = { + {66, 1}, + {67, 1}, {68, 1}, + {69, 1}, + {70, 1}, }; -static arc arcs_23_1[2] = { - {26, 2}, +static arc arcs_23_1[1] = { {0, 1}, }; -static arc arcs_23_2[2] = { - {27, 3}, - {0, 2}, -}; -static arc arcs_23_3[1] = { - {26, 4}, +static state states_23[2] = { + {5, arcs_23_0}, + {1, arcs_23_1}, }; -static arc arcs_23_4[2] = { - {27, 5}, - {0, 4}, -}; -static arc arcs_23_5[1] = { - {26, 6}, -}; -static arc arcs_23_6[1] = { - {0, 6}, -}; -static state states_23[7] = { - {1, arcs_23_0}, - {2, arcs_23_1}, - {2, arcs_23_2}, - {1, arcs_23_3}, - {2, arcs_23_4}, - {1, arcs_23_5}, - {1, arcs_23_6}, -}; -static arc arcs_24_0[2] = { - {69, 1}, - {70, 1}, +static arc arcs_24_0[1] = { + {71, 1}, }; static arc arcs_24_1[1] = { {0, 1}, }; static state states_24[2] = { - {2, arcs_24_0}, + {1, arcs_24_0}, {1, arcs_24_1}, }; static arc arcs_25_0[1] = { - {71, 1}, + {72, 1}, }; static arc arcs_25_1[1] = { - {72, 2}, -}; -static arc arcs_25_2[1] = { - {0, 2}, + {0, 1}, }; -static state states_25[3] = { +static state states_25[2] = { {1, arcs_25_0}, {1, arcs_25_1}, - {1, arcs_25_2}, }; static arc arcs_26_0[1] = { {73, 1}, }; static arc arcs_26_1[2] = { - {74, 2}, - {12, 3}, -}; -static arc arcs_26_2[3] = { - {74, 2}, - {12, 3}, - {71, 4}, -}; -static arc arcs_26_3[1] = { - {71, 4}, -}; -static arc arcs_26_4[3] = { - {28, 5}, - {13, 6}, - {75, 5}, -}; -static arc arcs_26_5[1] = { - {0, 5}, -}; -static arc arcs_26_6[1] = { - {75, 7}, + {9, 2}, + {0, 1}, }; -static arc arcs_26_7[1] = { - {15, 5}, +static arc arcs_26_2[1] = { + {0, 2}, }; -static state states_26[8] = { +static state states_26[3] = { {1, arcs_26_0}, {2, arcs_26_1}, - {3, arcs_26_2}, - {1, arcs_26_3}, - {3, arcs_26_4}, - {1, arcs_26_5}, - {1, arcs_26_6}, - {1, arcs_26_7}, + {1, arcs_26_2}, }; static arc arcs_27_0[1] = { - {19, 1}, + {48, 1}, }; -static arc arcs_27_1[2] = { - {77, 2}, +static arc arcs_27_1[1] = { {0, 1}, }; -static arc arcs_27_2[1] = { - {19, 3}, -}; -static arc arcs_27_3[1] = { - {0, 3}, -}; -static state states_27[4] = { +static state states_27[2] = { {1, arcs_27_0}, - {2, arcs_27_1}, - {1, arcs_27_2}, - {1, arcs_27_3}, + {1, arcs_27_1}, }; static arc arcs_28_0[1] = { - {12, 1}, + {74, 1}, }; static arc arcs_28_1[2] = { - {77, 2}, + {22, 2}, {0, 1}, }; -static arc arcs_28_2[1] = { - {19, 3}, +static arc arcs_28_2[2] = { + {28, 3}, + {0, 2}, }; static arc arcs_28_3[1] = { - {0, 3}, + {22, 4}, +}; +static arc arcs_28_4[2] = { + {28, 5}, + {0, 4}, +}; +static arc arcs_28_5[1] = { + {22, 6}, +}; +static arc arcs_28_6[1] = { + {0, 6}, }; -static state states_28[4] = { +static state states_28[7] = { {1, arcs_28_0}, {2, arcs_28_1}, - {1, arcs_28_2}, + {2, arcs_28_2}, {1, arcs_28_3}, + {2, arcs_28_4}, + {1, arcs_28_5}, + {1, arcs_28_6}, }; -static arc arcs_29_0[1] = { +static arc arcs_29_0[2] = { + {75, 1}, {76, 1}, }; -static arc arcs_29_1[2] = { - {27, 2}, +static arc arcs_29_1[1] = { {0, 1}, }; -static arc arcs_29_2[2] = { - {76, 1}, - {0, 2}, -}; -static state states_29[3] = { - {1, arcs_29_0}, - {2, arcs_29_1}, - {2, arcs_29_2}, +static state states_29[2] = { + {2, arcs_29_0}, + {1, arcs_29_1}, }; static arc arcs_30_0[1] = { - {78, 1}, + {77, 1}, }; -static arc arcs_30_1[2] = { - {27, 0}, - {0, 1}, +static arc arcs_30_1[1] = { + {78, 2}, +}; +static arc arcs_30_2[1] = { + {0, 2}, }; -static state states_30[2] = { +static state states_30[3] = { {1, arcs_30_0}, - {2, arcs_30_1}, + {1, arcs_30_1}, + {1, arcs_30_2}, }; static arc arcs_31_0[1] = { - {19, 1}, + {79, 1}, }; static arc arcs_31_1[2] = { - {74, 0}, - {0, 1}, + {80, 2}, + {12, 3}, +}; +static arc arcs_31_2[3] = { + {80, 2}, + {12, 3}, + {77, 4}, +}; +static arc arcs_31_3[1] = { + {77, 4}, +}; +static arc arcs_31_4[3] = { + {29, 5}, + {13, 6}, + {81, 5}, +}; +static arc arcs_31_5[1] = { + {0, 5}, }; -static state states_31[2] = { +static arc arcs_31_6[1] = { + {81, 7}, +}; +static arc arcs_31_7[1] = { + {15, 5}, +}; +static state states_31[8] = { {1, arcs_31_0}, {2, arcs_31_1}, + {3, 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] = { - {79, 1}, + {19, 1}, }; -static arc arcs_32_1[1] = { - {19, 2}, +static arc arcs_32_1[2] = { + {83, 2}, + {0, 1}, }; -static arc arcs_32_2[2] = { - {27, 1}, - {0, 2}, +static arc arcs_32_2[1] = { + {19, 3}, +}; +static arc arcs_32_3[1] = { + {0, 3}, }; -static state states_32[3] = { +static state states_32[4] = { {1, arcs_32_0}, - {1, arcs_32_1}, - {2, arcs_32_2}, + {2, arcs_32_1}, + {1, arcs_32_2}, + {1, arcs_32_3}, }; static arc arcs_33_0[1] = { - {80, 1}, + {12, 1}, }; -static arc arcs_33_1[1] = { - {26, 2}, +static arc arcs_33_1[2] = { + {83, 2}, + {0, 1}, }; -static arc arcs_33_2[2] = { - {27, 3}, - {0, 2}, +static arc arcs_33_2[1] = { + {19, 3}, }; static arc arcs_33_3[1] = { - {26, 4}, -}; -static arc arcs_33_4[1] = { - {0, 4}, + {0, 3}, }; -static state states_33[5] = { +static state states_33[4] = { {1, arcs_33_0}, - {1, arcs_33_1}, - {2, arcs_33_2}, + {2, arcs_33_1}, + {1, arcs_33_2}, {1, arcs_33_3}, - {1, arcs_33_4}, }; -static arc arcs_34_0[7] = { - {81, 1}, +static arc arcs_34_0[1] = { {82, 1}, - {83, 1}, - {84, 1}, - {85, 1}, - {17, 1}, - {86, 1}, }; -static arc arcs_34_1[1] = { +static arc arcs_34_1[2] = { + {28, 2}, {0, 1}, }; -static state states_34[2] = { - {7, arcs_34_0}, - {1, arcs_34_1}, -}; -static arc arcs_35_0[1] = { - {87, 1}, -}; -static arc arcs_35_1[1] = { - {26, 2}, -}; -static arc arcs_35_2[1] = { - {21, 3}, -}; -static arc arcs_35_3[1] = { - {22, 4}, -}; -static arc arcs_35_4[3] = { - {88, 1}, - {89, 5}, - {0, 4}, +static arc arcs_34_2[2] = { + {82, 1}, + {0, 2}, }; -static arc arcs_35_5[1] = { - {21, 6}, +static state states_34[3] = { + {1, arcs_34_0}, + {2, arcs_34_1}, + {2, arcs_34_2}, }; -static arc arcs_35_6[1] = { - {22, 7}, +static arc arcs_35_0[1] = { + {84, 1}, }; -static arc arcs_35_7[1] = { - {0, 7}, +static arc arcs_35_1[2] = { + {28, 0}, + {0, 1}, }; -static state states_35[8] = { +static state states_35[2] = { {1, arcs_35_0}, - {1, arcs_35_1}, - {1, arcs_35_2}, - {1, arcs_35_3}, - {3, arcs_35_4}, - {1, arcs_35_5}, - {1, arcs_35_6}, - {1, arcs_35_7}, + {2, arcs_35_1}, }; static arc arcs_36_0[1] = { - {90, 1}, -}; -static arc arcs_36_1[1] = { - {26, 2}, -}; -static arc arcs_36_2[1] = { - {21, 3}, -}; -static arc arcs_36_3[1] = { - {22, 4}, -}; -static arc arcs_36_4[2] = { - {89, 5}, - {0, 4}, -}; -static arc arcs_36_5[1] = { - {21, 6}, -}; -static arc arcs_36_6[1] = { - {22, 7}, + {19, 1}, }; -static arc arcs_36_7[1] = { - {0, 7}, +static arc arcs_36_1[2] = { + {80, 0}, + {0, 1}, }; -static state states_36[8] = { +static state states_36[2] = { {1, arcs_36_0}, - {1, arcs_36_1}, - {1, arcs_36_2}, - {1, arcs_36_3}, - {2, arcs_36_4}, - {1, arcs_36_5}, - {1, arcs_36_6}, - {1, arcs_36_7}, + {2, arcs_36_1}, }; static arc arcs_37_0[1] = { - {91, 1}, + {85, 1}, }; static arc arcs_37_1[1] = { - {58, 2}, -}; -static arc arcs_37_2[1] = { - {92, 3}, -}; -static arc arcs_37_3[1] = { - {9, 4}, -}; -static arc arcs_37_4[1] = { - {21, 5}, -}; -static arc arcs_37_5[1] = { - {22, 6}, -}; -static arc arcs_37_6[2] = { - {89, 7}, - {0, 6}, -}; -static arc arcs_37_7[1] = { - {21, 8}, -}; -static arc arcs_37_8[1] = { - {22, 9}, + {19, 2}, }; -static arc arcs_37_9[1] = { - {0, 9}, +static arc arcs_37_2[2] = { + {28, 1}, + {0, 2}, }; -static state states_37[10] = { +static state states_37[3] = { {1, arcs_37_0}, {1, arcs_37_1}, - {1, arcs_37_2}, - {1, arcs_37_3}, - {1, arcs_37_4}, - {1, arcs_37_5}, - {2, arcs_37_6}, - {1, arcs_37_7}, - {1, arcs_37_8}, - {1, arcs_37_9}, + {2, arcs_37_2}, }; static arc arcs_38_0[1] = { - {93, 1}, + {86, 1}, }; static arc arcs_38_1[1] = { - {21, 2}, + {22, 2}, }; -static arc arcs_38_2[1] = { - {22, 3}, +static arc arcs_38_2[2] = { + {28, 3}, + {0, 2}, }; -static arc arcs_38_3[2] = { - {94, 4}, - {95, 5}, +static arc arcs_38_3[1] = { + {22, 4}, }; static arc arcs_38_4[1] = { - {21, 6}, -}; -static arc arcs_38_5[1] = { - {21, 7}, -}; -static arc arcs_38_6[1] = { - {22, 8}, -}; -static arc arcs_38_7[1] = { - {22, 9}, -}; -static arc arcs_38_8[4] = { - {94, 4}, - {89, 10}, - {95, 5}, - {0, 8}, -}; -static arc arcs_38_9[1] = { - {0, 9}, -}; -static arc arcs_38_10[1] = { - {21, 11}, -}; -static arc arcs_38_11[1] = { - {22, 12}, -}; -static arc arcs_38_12[2] = { - {95, 5}, - {0, 12}, + {0, 4}, }; -static state states_38[13] = { +static state states_38[5] = { {1, arcs_38_0}, {1, arcs_38_1}, - {1, arcs_38_2}, - {2, arcs_38_3}, + {2, arcs_38_2}, + {1, arcs_38_3}, {1, arcs_38_4}, - {1, arcs_38_5}, - {1, arcs_38_6}, - {1, arcs_38_7}, - {4, arcs_38_8}, - {1, arcs_38_9}, - {1, arcs_38_10}, - {1, arcs_38_11}, - {2, arcs_38_12}, }; -static arc arcs_39_0[1] = { - {96, 1}, +static arc arcs_39_0[7] = { + {87, 1}, + {88, 1}, + {89, 1}, + {90, 1}, + {91, 1}, + {17, 1}, + {92, 1}, }; static arc arcs_39_1[1] = { - {26, 2}, -}; -static arc arcs_39_2[2] = { - {97, 3}, - {21, 4}, -}; -static arc arcs_39_3[1] = { - {21, 4}, -}; -static arc arcs_39_4[1] = { - {22, 5}, -}; -static arc arcs_39_5[1] = { - {0, 5}, + {0, 1}, }; -static state states_39[6] = { - {1, arcs_39_0}, +static state states_39[2] = { + {7, arcs_39_0}, {1, arcs_39_1}, - {2, arcs_39_2}, - {1, arcs_39_3}, - {1, arcs_39_4}, - {1, arcs_39_5}, }; static arc arcs_40_0[1] = { - {77, 1}, + {93, 1}, }; static arc arcs_40_1[1] = { - {98, 2}, + {22, 2}, }; static arc arcs_40_2[1] = { - {0, 2}, + {23, 3}, +}; +static arc arcs_40_3[1] = { + {24, 4}, }; -static state states_40[3] = { +static arc arcs_40_4[3] = { + {94, 1}, + {95, 5}, + {0, 4}, +}; +static arc arcs_40_5[1] = { + {23, 6}, +}; +static arc arcs_40_6[1] = { + {24, 7}, +}; +static arc arcs_40_7[1] = { + {0, 7}, +}; +static state states_40[8] = { {1, arcs_40_0}, {1, arcs_40_1}, {1, arcs_40_2}, + {1, arcs_40_3}, + {3, arcs_40_4}, + {1, arcs_40_5}, + {1, arcs_40_6}, + {1, arcs_40_7}, }; static arc arcs_41_0[1] = { - {99, 1}, + {96, 1}, }; -static arc arcs_41_1[2] = { - {26, 2}, - {0, 1}, +static arc arcs_41_1[1] = { + {22, 2}, }; -static arc arcs_41_2[2] = { - {27, 3}, - {0, 2}, +static arc arcs_41_2[1] = { + {23, 3}, }; static arc arcs_41_3[1] = { - {26, 4}, + {24, 4}, }; -static arc arcs_41_4[1] = { +static arc arcs_41_4[2] = { + {95, 5}, {0, 4}, }; -static state states_41[5] = { +static arc arcs_41_5[1] = { + {23, 6}, +}; +static arc arcs_41_6[1] = { + {24, 7}, +}; +static arc arcs_41_7[1] = { + {0, 7}, +}; +static state states_41[8] = { {1, arcs_41_0}, - {2, arcs_41_1}, - {2, arcs_41_2}, + {1, arcs_41_1}, + {1, arcs_41_2}, {1, arcs_41_3}, - {1, arcs_41_4}, + {2, arcs_41_4}, + {1, arcs_41_5}, + {1, arcs_41_6}, + {1, arcs_41_7}, }; -static arc arcs_42_0[2] = { - {3, 1}, - {2, 2}, +static arc arcs_42_0[1] = { + {97, 1}, }; static arc arcs_42_1[1] = { - {0, 1}, + {64, 2}, }; static arc arcs_42_2[1] = { - {100, 3}, + {98, 3}, }; static arc arcs_42_3[1] = { - {6, 4}, + {9, 4}, }; -static arc arcs_42_4[2] = { - {6, 4}, - {101, 1}, +static arc arcs_42_4[1] = { + {23, 5}, +}; +static arc arcs_42_5[1] = { + {24, 6}, +}; +static arc arcs_42_6[2] = { + {95, 7}, + {0, 6}, +}; +static arc arcs_42_7[1] = { + {23, 8}, }; -static state states_42[5] = { - {2, arcs_42_0}, +static arc arcs_42_8[1] = { + {24, 9}, +}; +static arc arcs_42_9[1] = { + {0, 9}, +}; +static state states_42[10] = { + {1, arcs_42_0}, {1, arcs_42_1}, {1, arcs_42_2}, {1, arcs_42_3}, - {2, arcs_42_4}, + {1, arcs_42_4}, + {1, arcs_42_5}, + {2, arcs_42_6}, + {1, arcs_42_7}, + {1, arcs_42_8}, + {1, arcs_42_9}, }; static arc arcs_43_0[1] = { - {103, 1}, + {99, 1}, }; -static arc arcs_43_1[2] = { - {27, 2}, - {0, 1}, +static arc arcs_43_1[1] = { + {23, 2}, }; static arc arcs_43_2[1] = { - {103, 3}, + {24, 3}, }; static arc arcs_43_3[2] = { - {27, 4}, - {0, 3}, + {100, 4}, + {101, 5}, }; -static arc arcs_43_4[2] = { - {103, 3}, - {0, 4}, +static arc arcs_43_4[1] = { + {23, 6}, +}; +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 state states_43[5] = { +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}, +}; +static state states_43[13] = { {1, arcs_43_0}, - {2, arcs_43_1}, + {1, arcs_43_1}, {1, arcs_43_2}, {2, arcs_43_3}, - {2, arcs_43_4}, + {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[2] = { - {104, 1}, - {105, 1}, +static arc arcs_44_0[1] = { + {102, 1}, }; static arc arcs_44_1[1] = { - {0, 1}, + {22, 2}, +}; +static arc arcs_44_2[2] = { + {103, 3}, + {23, 4}, +}; +static arc arcs_44_3[1] = { + {23, 4}, +}; +static arc arcs_44_4[1] = { + {24, 5}, }; -static state states_44[2] = { - {2, arcs_44_0}, +static arc arcs_44_5[1] = { + {0, 5}, +}; +static state states_44[6] = { + {1, arcs_44_0}, {1, arcs_44_1}, + {2, arcs_44_2}, + {1, arcs_44_3}, + {1, arcs_44_4}, + {1, arcs_44_5}, }; static arc arcs_45_0[1] = { - {106, 1}, + {83, 1}, }; -static arc arcs_45_1[2] = { - {23, 2}, - {21, 3}, +static arc arcs_45_1[1] = { + {104, 2}, }; static arc arcs_45_2[1] = { - {21, 3}, -}; -static arc arcs_45_3[1] = { - {103, 4}, -}; -static arc arcs_45_4[1] = { - {0, 4}, + {0, 2}, }; -static state states_45[5] = { +static state states_45[3] = { {1, arcs_45_0}, - {2, arcs_45_1}, + {1, arcs_45_1}, {1, arcs_45_2}, - {1, arcs_45_3}, - {1, arcs_45_4}, }; -static arc arcs_46_0[2] = { - {104, 1}, - {107, 2}, +static arc arcs_46_0[1] = { + {105, 1}, }; static arc arcs_46_1[2] = { - {87, 3}, + {22, 2}, {0, 1}, }; -static arc arcs_46_2[1] = { +static arc arcs_46_2[2] = { + {28, 3}, {0, 2}, }; static arc arcs_46_3[1] = { - {104, 4}, + {22, 4}, }; static arc arcs_46_4[1] = { - {89, 5}, -}; -static arc arcs_46_5[1] = { - {26, 2}, + {0, 4}, }; -static state states_46[6] = { - {2, arcs_46_0}, +static state states_46[5] = { + {1, arcs_46_0}, {2, arcs_46_1}, - {1, arcs_46_2}, + {2, arcs_46_2}, {1, arcs_46_3}, {1, arcs_46_4}, - {1, arcs_46_5}, }; -static arc arcs_47_0[1] = { - {108, 1}, +static arc arcs_47_0[2] = { + {3, 1}, + {2, 2}, }; -static arc arcs_47_1[2] = { - {109, 0}, +static arc arcs_47_1[1] = { {0, 1}, }; -static state states_47[2] = { - {1, arcs_47_0}, - {2, arcs_47_1}, +static arc arcs_47_2[1] = { + {106, 3}, +}; +static arc arcs_47_3[1] = { + {6, 4}, +}; +static arc arcs_47_4[2] = { + {6, 4}, + {107, 1}, +}; +static state states_47[5] = { + {2, arcs_47_0}, + {1, arcs_47_1}, + {1, arcs_47_2}, + {1, arcs_47_3}, + {2, arcs_47_4}, }; static arc arcs_48_0[1] = { - {110, 1}, + {109, 1}, }; static arc arcs_48_1[2] = { - {111, 0}, + {28, 2}, {0, 1}, }; -static state states_48[2] = { +static arc arcs_48_2[1] = { + {109, 3}, +}; +static arc arcs_48_3[2] = { + {28, 4}, + {0, 3}, +}; +static arc arcs_48_4[2] = { + {109, 3}, + {0, 4}, +}; +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_0[2] = { - {112, 1}, - {113, 2}, + {110, 1}, + {111, 1}, }; static arc arcs_49_1[1] = { - {110, 2}, -}; -static arc arcs_49_2[1] = { - {0, 2}, + {0, 1}, }; -static state states_49[3] = { +static state states_49[2] = { {2, arcs_49_0}, {1, arcs_49_1}, - {1, arcs_49_2}, }; static arc arcs_50_0[1] = { - {98, 1}, + {112, 1}, }; static arc arcs_50_1[2] = { - {114, 0}, - {0, 1}, + {33, 2}, + {23, 3}, +}; +static arc arcs_50_2[1] = { + {23, 3}, +}; +static arc arcs_50_3[1] = { + {109, 4}, +}; +static arc arcs_50_4[1] = { + {0, 4}, }; -static state states_50[2] = { +static state states_50[5] = { {1, arcs_50_0}, {2, arcs_50_1}, + {1, arcs_50_2}, + {1, arcs_50_3}, + {1, arcs_50_4}, }; -static arc arcs_51_0[9] = { - {115, 1}, - {116, 1}, - {117, 1}, - {118, 1}, - {119, 1}, - {120, 1}, - {92, 1}, - {112, 2}, - {121, 3}, +static arc arcs_51_0[2] = { + {110, 1}, + {113, 2}, }; -static arc arcs_51_1[1] = { +static arc arcs_51_1[2] = { + {93, 3}, {0, 1}, }; static arc arcs_51_2[1] = { - {92, 1}, + {0, 2}, }; -static arc arcs_51_3[2] = { - {112, 1}, - {0, 3}, +static arc arcs_51_3[1] = { + {110, 4}, +}; +static arc arcs_51_4[1] = { + {95, 5}, }; -static state states_51[4] = { - {9, arcs_51_0}, - {1, arcs_51_1}, +static arc arcs_51_5[1] = { + {22, 2}, +}; +static state states_51[6] = { + {2, arcs_51_0}, + {2, arcs_51_1}, {1, arcs_51_2}, - {2, arcs_51_3}, + {1, arcs_51_3}, + {1, arcs_51_4}, + {1, arcs_51_5}, }; static arc arcs_52_0[1] = { - {122, 1}, + {114, 1}, }; static arc arcs_52_1[2] = { - {123, 0}, + {115, 0}, {0, 1}, }; static state states_52[2] = { @@ -1126,856 +1188,947 @@ {2, arcs_52_1}, }; static arc arcs_53_0[1] = { - {124, 1}, + {116, 1}, }; static arc arcs_53_1[2] = { - {125, 0}, + {117, 0}, {0, 1}, }; static state states_53[2] = { {1, arcs_53_0}, {2, arcs_53_1}, }; -static arc arcs_54_0[1] = { - {126, 1}, +static arc arcs_54_0[2] = { + {118, 1}, + {119, 2}, }; -static arc arcs_54_1[2] = { - {127, 0}, - {0, 1}, +static arc arcs_54_1[1] = { + {116, 2}, }; -static state states_54[2] = { - {1, arcs_54_0}, - {2, arcs_54_1}, +static arc arcs_54_2[1] = { + {0, 2}, +}; +static state states_54[3] = { + {2, arcs_54_0}, + {1, arcs_54_1}, + {1, arcs_54_2}, }; static arc arcs_55_0[1] = { - {128, 1}, + {104, 1}, }; -static arc arcs_55_1[3] = { - {129, 0}, - {56, 0}, +static arc arcs_55_1[2] = { + {120, 0}, {0, 1}, }; static state states_55[2] = { {1, arcs_55_0}, - {3, arcs_55_1}, + {2, arcs_55_1}, }; -static arc arcs_56_0[1] = { - {130, 1}, +static arc arcs_56_0[9] = { + {121, 1}, + {122, 1}, + {123, 1}, + {124, 1}, + {125, 1}, + {126, 1}, + {98, 1}, + {118, 2}, + {127, 3}, }; -static arc arcs_56_1[3] = { - {131, 0}, - {132, 0}, +static arc arcs_56_1[1] = { {0, 1}, }; -static state states_56[2] = { - {1, arcs_56_0}, - {3, arcs_56_1}, +static arc arcs_56_2[1] = { + {98, 1}, +}; +static arc arcs_56_3[2] = { + {118, 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 arc arcs_57_0[1] = { - {133, 1}, + {128, 1}, }; -static arc arcs_57_1[5] = { - {28, 0}, - {134, 0}, - {135, 0}, - {136, 0}, +static arc arcs_57_1[2] = { + {129, 0}, {0, 1}, }; static state states_57[2] = { {1, arcs_57_0}, - {5, arcs_57_1}, + {2, arcs_57_1}, +}; +static arc arcs_58_0[1] = { + {130, 1}, +}; +static arc arcs_58_1[2] = { + {131, 0}, + {0, 1}, +}; +static state states_58[2] = { + {1, arcs_58_0}, + {2, arcs_58_1}, }; -static arc arcs_58_0[4] = { - {131, 1}, +static arc arcs_59_0[1] = { {132, 1}, +}; +static arc arcs_59_1[2] = { + {133, 0}, + {0, 1}, +}; +static state states_59[2] = { + {1, arcs_59_0}, + {2, arcs_59_1}, +}; +static arc arcs_60_0[1] = { + {134, 1}, +}; +static arc arcs_60_1[3] = { + {135, 0}, + {62, 0}, + {0, 1}, +}; +static state states_60[2] = { + {1, arcs_60_0}, + {3, arcs_60_1}, +}; +static arc arcs_61_0[1] = { + {136, 1}, +}; +static arc arcs_61_1[3] = { + {137, 0}, + {138, 0}, + {0, 1}, +}; +static state states_61[2] = { + {1, arcs_61_0}, + {3, 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, 2}, + {138, 1}, + {143, 1}, + {144, 2}, }; -static arc arcs_58_1[1] = { - {133, 2}, +static arc arcs_63_1[1] = { + {139, 2}, }; -static arc arcs_58_2[1] = { +static arc arcs_63_2[1] = { {0, 2}, }; -static state states_58[3] = { - {4, arcs_58_0}, - {1, arcs_58_1}, - {1, arcs_58_2}, +static state states_63[3] = { + {4, arcs_63_0}, + {1, arcs_63_1}, + {1, arcs_63_2}, }; -static arc arcs_59_0[1] = { - {139, 1}, +static arc arcs_64_0[1] = { + {145, 1}, }; -static arc arcs_59_1[3] = { - {140, 1}, - {29, 2}, +static arc arcs_64_1[3] = { + {146, 1}, + {31, 2}, {0, 1}, }; -static arc arcs_59_2[1] = { - {133, 3}, +static arc arcs_64_2[1] = { + {139, 3}, }; -static arc arcs_59_3[1] = { +static arc arcs_64_3[1] = { {0, 3}, }; -static state states_59[4] = { - {1, arcs_59_0}, - {3, arcs_59_1}, - {1, arcs_59_2}, - {1, arcs_59_3}, +static state states_64[4] = { + {1, arcs_64_0}, + {3, arcs_64_1}, + {1, arcs_64_2}, + {1, arcs_64_3}, }; -static arc arcs_60_0[7] = { +static arc arcs_65_0[7] = { {13, 1}, - {142, 2}, - {145, 3}, + {148, 2}, + {151, 3}, {19, 4}, - {148, 4}, - {149, 5}, - {74, 6}, + {154, 4}, + {155, 5}, + {80, 6}, }; -static arc arcs_60_1[3] = { - {42, 7}, - {141, 7}, +static arc arcs_65_1[3] = { + {48, 7}, + {147, 7}, {15, 4}, }; -static arc arcs_60_2[2] = { - {143, 8}, - {144, 4}, -}; -static arc arcs_60_3[2] = { - {146, 9}, - {147, 4}, +static arc arcs_65_2[2] = { + {149, 8}, + {150, 4}, +}; +static arc arcs_65_3[2] = { + {152, 9}, + {153, 4}, }; -static arc arcs_60_4[1] = { +static arc arcs_65_4[1] = { {0, 4}, }; -static arc arcs_60_5[2] = { - {149, 5}, +static arc arcs_65_5[2] = { + {155, 5}, {0, 5}, }; -static arc arcs_60_6[1] = { - {74, 10}, +static arc arcs_65_6[1] = { + {80, 10}, }; -static arc arcs_60_7[1] = { +static arc arcs_65_7[1] = { {15, 4}, }; -static arc arcs_60_8[1] = { - {144, 4}, +static arc arcs_65_8[1] = { + {150, 4}, }; -static arc arcs_60_9[1] = { - {147, 4}, +static arc arcs_65_9[1] = { + {153, 4}, }; -static arc arcs_60_10[1] = { - {74, 4}, +static arc arcs_65_10[1] = { + {80, 4}, }; -static state states_60[11] = { - {7, arcs_60_0}, - {3, arcs_60_1}, - {2, arcs_60_2}, - {2, arcs_60_3}, - {1, arcs_60_4}, - {2, arcs_60_5}, - {1, arcs_60_6}, - {1, arcs_60_7}, - {1, arcs_60_8}, - {1, arcs_60_9}, - {1, arcs_60_10}, -}; -static arc arcs_61_0[1] = { - {26, 1}, -}; -static arc arcs_61_1[3] = { - {150, 2}, - {27, 3}, +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 arc arcs_66_0[1] = { + {22, 1}, +}; +static arc arcs_66_1[3] = { + {156, 2}, + {28, 3}, {0, 1}, }; -static arc arcs_61_2[1] = { +static arc arcs_66_2[1] = { {0, 2}, }; -static arc arcs_61_3[2] = { - {26, 4}, +static arc arcs_66_3[2] = { + {22, 4}, {0, 3}, }; -static arc arcs_61_4[2] = { - {27, 3}, +static arc arcs_66_4[2] = { + {28, 3}, {0, 4}, }; -static state states_61[5] = { - {1, arcs_61_0}, - {3, arcs_61_1}, - {1, arcs_61_2}, - {2, arcs_61_3}, - {2, arcs_61_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_62_0[1] = { - {26, 1}, +static arc arcs_67_0[1] = { + {22, 1}, }; -static arc arcs_62_1[3] = { - {151, 2}, - {27, 3}, +static arc arcs_67_1[3] = { + {157, 2}, + {28, 3}, {0, 1}, }; -static arc arcs_62_2[1] = { +static arc arcs_67_2[1] = { {0, 2}, }; -static arc arcs_62_3[2] = { - {26, 4}, +static arc arcs_67_3[2] = { + {22, 4}, {0, 3}, }; -static arc arcs_62_4[2] = { - {27, 3}, +static arc arcs_67_4[2] = { + {28, 3}, {0, 4}, }; -static state states_62[5] = { - {1, arcs_62_0}, - {3, arcs_62_1}, - {1, arcs_62_2}, - {2, arcs_62_3}, - {2, arcs_62_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 arc arcs_63_0[1] = { - {106, 1}, +static arc arcs_68_0[1] = { + {112, 1}, }; -static arc arcs_63_1[2] = { - {23, 2}, - {21, 3}, +static arc arcs_68_1[2] = { + {33, 2}, + {23, 3}, }; -static arc arcs_63_2[1] = { - {21, 3}, +static arc arcs_68_2[1] = { + {23, 3}, }; -static arc arcs_63_3[1] = { - {26, 4}, +static arc arcs_68_3[1] = { + {22, 4}, }; -static arc arcs_63_4[1] = { +static arc arcs_68_4[1] = { {0, 4}, }; -static state states_63[5] = { - {1, arcs_63_0}, - {2, arcs_63_1}, - {1, arcs_63_2}, - {1, arcs_63_3}, - {1, arcs_63_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 arc arcs_64_0[3] = { +static arc arcs_69_0[3] = { {13, 1}, - {142, 2}, - {74, 3}, + {148, 2}, + {80, 3}, }; -static arc arcs_64_1[2] = { +static arc arcs_69_1[2] = { {14, 4}, {15, 5}, }; -static arc arcs_64_2[1] = { - {152, 6}, +static arc arcs_69_2[1] = { + {158, 6}, }; -static arc arcs_64_3[1] = { +static arc arcs_69_3[1] = { {19, 5}, }; -static arc arcs_64_4[1] = { +static arc arcs_69_4[1] = { {15, 5}, }; -static arc arcs_64_5[1] = { +static arc arcs_69_5[1] = { {0, 5}, }; -static arc arcs_64_6[1] = { - {144, 5}, +static arc arcs_69_6[1] = { + {150, 5}, }; -static state states_64[7] = { - {3, arcs_64_0}, - {2, arcs_64_1}, - {1, arcs_64_2}, - {1, arcs_64_3}, - {1, arcs_64_4}, - {1, arcs_64_5}, - {1, arcs_64_6}, +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 arc arcs_65_0[1] = { - {153, 1}, +static arc arcs_70_0[1] = { + {159, 1}, }; -static arc arcs_65_1[2] = { - {27, 2}, +static arc arcs_70_1[2] = { + {28, 2}, {0, 1}, }; -static arc arcs_65_2[2] = { - {153, 1}, +static arc arcs_70_2[2] = { + {159, 1}, {0, 2}, }; -static state states_65[3] = { - {1, arcs_65_0}, - {2, arcs_65_1}, - {2, arcs_65_2}, +static state states_70[3] = { + {1, arcs_70_0}, + {2, arcs_70_1}, + {2, arcs_70_2}, }; -static arc arcs_66_0[2] = { - {26, 1}, - {21, 2}, +static arc arcs_71_0[2] = { + {22, 1}, + {23, 2}, }; -static arc arcs_66_1[2] = { - {21, 2}, +static arc arcs_71_1[2] = { + {23, 2}, {0, 1}, }; -static arc arcs_66_2[3] = { - {26, 3}, - {154, 4}, +static arc arcs_71_2[3] = { + {22, 3}, + {160, 4}, {0, 2}, }; -static arc arcs_66_3[2] = { - {154, 4}, +static arc arcs_71_3[2] = { + {160, 4}, {0, 3}, }; -static arc arcs_66_4[1] = { +static arc arcs_71_4[1] = { {0, 4}, }; -static state states_66[5] = { - {2, arcs_66_0}, - {2, arcs_66_1}, - {3, arcs_66_2}, - {2, arcs_66_3}, - {1, arcs_66_4}, +static state states_71[5] = { + {2, arcs_71_0}, + {2, arcs_71_1}, + {3, arcs_71_2}, + {2, arcs_71_3}, + {1, arcs_71_4}, }; -static arc arcs_67_0[1] = { - {21, 1}, +static arc arcs_72_0[1] = { + {23, 1}, }; -static arc arcs_67_1[2] = { - {26, 2}, +static arc arcs_72_1[2] = { + {22, 2}, {0, 1}, }; -static arc arcs_67_2[1] = { +static arc arcs_72_2[1] = { {0, 2}, }; -static state states_67[3] = { - {1, arcs_67_0}, - {2, arcs_67_1}, - {1, arcs_67_2}, +static state states_72[3] = { + {1, arcs_72_0}, + {2, arcs_72_1}, + {1, arcs_72_2}, }; -static arc arcs_68_0[1] = { - {98, 1}, +static arc arcs_73_0[1] = { + {104, 1}, }; -static arc arcs_68_1[2] = { - {27, 2}, +static arc arcs_73_1[2] = { + {28, 2}, {0, 1}, }; -static arc arcs_68_2[2] = { - {98, 1}, +static arc arcs_73_2[2] = { + {104, 1}, {0, 2}, }; -static state states_68[3] = { - {1, arcs_68_0}, - {2, arcs_68_1}, - {2, arcs_68_2}, +static state states_73[3] = { + {1, arcs_73_0}, + {2, arcs_73_1}, + {2, arcs_73_2}, }; -static arc arcs_69_0[1] = { - {26, 1}, +static arc arcs_74_0[1] = { + {22, 1}, }; -static arc arcs_69_1[2] = { - {27, 2}, +static arc arcs_74_1[2] = { + {28, 2}, {0, 1}, }; -static arc arcs_69_2[2] = { - {26, 1}, +static arc arcs_74_2[2] = { + {22, 1}, {0, 2}, }; -static state states_69[3] = { - {1, arcs_69_0}, - {2, arcs_69_1}, - {2, arcs_69_2}, +static state states_74[3] = { + {1, arcs_74_0}, + {2, arcs_74_1}, + {2, arcs_74_2}, }; -static arc arcs_70_0[1] = { - {26, 1}, +static arc arcs_75_0[1] = { + {22, 1}, }; -static arc arcs_70_1[3] = { - {21, 2}, - {27, 3}, +static arc arcs_75_1[3] = { + {23, 2}, + {28, 3}, {0, 1}, }; -static arc arcs_70_2[1] = { - {26, 4}, +static arc arcs_75_2[1] = { + {22, 4}, }; -static arc arcs_70_3[2] = { - {26, 5}, +static arc arcs_75_3[2] = { + {22, 5}, {0, 3}, }; -static arc arcs_70_4[2] = { - {27, 6}, +static arc arcs_75_4[2] = { + {28, 6}, {0, 4}, }; -static arc arcs_70_5[2] = { - {27, 3}, +static arc arcs_75_5[2] = { + {28, 3}, {0, 5}, }; -static arc arcs_70_6[2] = { - {26, 7}, +static arc arcs_75_6[2] = { + {22, 7}, {0, 6}, }; -static arc arcs_70_7[1] = { - {21, 2}, +static arc arcs_75_7[1] = { + {23, 2}, }; -static state states_70[8] = { - {1, arcs_70_0}, - {3, arcs_70_1}, - {1, arcs_70_2}, - {2, arcs_70_3}, - {2, arcs_70_4}, - {2, arcs_70_5}, - {2, arcs_70_6}, - {1, arcs_70_7}, +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 arc arcs_71_0[1] = { - {155, 1}, +static arc arcs_76_0[1] = { + {161, 1}, }; -static arc arcs_71_1[1] = { +static arc arcs_76_1[1] = { {19, 2}, }; -static arc arcs_71_2[2] = { +static arc arcs_76_2[2] = { {13, 3}, - {21, 4}, + {23, 4}, }; -static arc arcs_71_3[2] = { +static arc arcs_76_3[2] = { {9, 5}, {15, 6}, }; -static arc arcs_71_4[1] = { - {22, 7}, +static arc arcs_76_4[1] = { + {24, 7}, }; -static arc arcs_71_5[1] = { +static arc arcs_76_5[1] = { {15, 6}, }; -static arc arcs_71_6[1] = { - {21, 4}, +static arc arcs_76_6[1] = { + {23, 4}, }; -static arc arcs_71_7[1] = { +static arc arcs_76_7[1] = { {0, 7}, }; -static state states_71[8] = { - {1, arcs_71_0}, - {1, arcs_71_1}, - {2, arcs_71_2}, - {2, arcs_71_3}, - {1, arcs_71_4}, - {1, arcs_71_5}, - {1, arcs_71_6}, - {1, arcs_71_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 arc arcs_72_0[3] = { - {156, 1}, - {28, 2}, - {29, 3}, +static arc arcs_77_0[3] = { + {162, 1}, + {29, 2}, + {31, 3}, }; -static arc arcs_72_1[2] = { - {27, 4}, +static arc arcs_77_1[2] = { + {28, 4}, {0, 1}, }; -static arc arcs_72_2[1] = { - {26, 5}, +static arc arcs_77_2[1] = { + {22, 5}, }; -static arc arcs_72_3[1] = { - {26, 6}, +static arc arcs_77_3[1] = { + {22, 6}, }; -static arc arcs_72_4[4] = { - {156, 1}, - {28, 2}, - {29, 3}, +static arc arcs_77_4[4] = { + {162, 1}, + {29, 2}, + {31, 3}, {0, 4}, }; -static arc arcs_72_5[2] = { - {27, 7}, +static arc arcs_77_5[2] = { + {28, 7}, {0, 5}, }; -static arc arcs_72_6[1] = { +static arc arcs_77_6[1] = { {0, 6}, }; -static arc arcs_72_7[1] = { - {29, 3}, +static arc arcs_77_7[1] = { + {31, 3}, }; -static state states_72[8] = { - {3, arcs_72_0}, - {2, arcs_72_1}, - {1, arcs_72_2}, - {1, arcs_72_3}, - {4, arcs_72_4}, - {2, arcs_72_5}, - {1, arcs_72_6}, - {1, arcs_72_7}, +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 arc arcs_73_0[1] = { - {26, 1}, +static arc arcs_78_0[1] = { + {22, 1}, }; -static arc arcs_73_1[3] = { - {151, 2}, - {25, 3}, +static arc arcs_78_1[3] = { + {157, 2}, + {27, 3}, {0, 1}, }; -static arc arcs_73_2[1] = { +static arc arcs_78_2[1] = { {0, 2}, }; -static arc arcs_73_3[1] = { - {26, 2}, +static arc arcs_78_3[1] = { + {22, 2}, }; -static state states_73[4] = { - {1, arcs_73_0}, - {3, arcs_73_1}, - {1, arcs_73_2}, - {1, arcs_73_3}, +static state states_78[4] = { + {1, arcs_78_0}, + {3, arcs_78_1}, + {1, arcs_78_2}, + {1, arcs_78_3}, }; -static arc arcs_74_0[2] = { - {150, 1}, - {158, 1}, +static arc arcs_79_0[2] = { + {156, 1}, + {164, 1}, }; -static arc arcs_74_1[1] = { +static arc arcs_79_1[1] = { {0, 1}, }; -static state states_74[2] = { - {2, arcs_74_0}, - {1, arcs_74_1}, +static state states_79[2] = { + {2, arcs_79_0}, + {1, arcs_79_1}, }; -static arc arcs_75_0[1] = { - {91, 1}, +static arc arcs_80_0[1] = { + {97, 1}, }; -static arc arcs_75_1[1] = { - {58, 2}, +static arc arcs_80_1[1] = { + {64, 2}, }; -static arc arcs_75_2[1] = { - {92, 3}, +static arc arcs_80_2[1] = { + {98, 3}, }; -static arc arcs_75_3[1] = { - {102, 4}, +static arc arcs_80_3[1] = { + {108, 4}, }; -static arc arcs_75_4[2] = { - {157, 5}, +static arc arcs_80_4[2] = { + {163, 5}, {0, 4}, }; -static arc arcs_75_5[1] = { +static arc arcs_80_5[1] = { {0, 5}, }; -static state states_75[6] = { - {1, arcs_75_0}, - {1, arcs_75_1}, - {1, arcs_75_2}, - {1, arcs_75_3}, - {2, arcs_75_4}, - {1, arcs_75_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 arc arcs_76_0[1] = { - {87, 1}, +static arc arcs_81_0[1] = { + {93, 1}, }; -static arc arcs_76_1[1] = { - {103, 2}, +static arc arcs_81_1[1] = { + {109, 2}, }; -static arc arcs_76_2[2] = { - {157, 3}, +static arc arcs_81_2[2] = { + {163, 3}, {0, 2}, }; -static arc arcs_76_3[1] = { +static arc arcs_81_3[1] = { {0, 3}, }; -static state states_76[4] = { - {1, arcs_76_0}, - {1, arcs_76_1}, - {2, arcs_76_2}, - {1, arcs_76_3}, +static state states_81[4] = { + {1, arcs_81_0}, + {1, arcs_81_1}, + {2, arcs_81_2}, + {1, arcs_81_3}, }; -static arc arcs_77_0[2] = { - {151, 1}, - {160, 1}, +static arc arcs_82_0[2] = { + {157, 1}, + {166, 1}, }; -static arc arcs_77_1[1] = { +static arc arcs_82_1[1] = { {0, 1}, }; -static state states_77[2] = { - {2, arcs_77_0}, - {1, arcs_77_1}, +static state states_82[2] = { + {2, arcs_82_0}, + {1, arcs_82_1}, }; -static arc arcs_78_0[1] = { - {91, 1}, +static arc arcs_83_0[1] = { + {97, 1}, }; -static arc arcs_78_1[1] = { - {58, 2}, +static arc arcs_83_1[1] = { + {64, 2}, }; -static arc arcs_78_2[1] = { - {92, 3}, +static arc arcs_83_2[1] = { + {98, 3}, }; -static arc arcs_78_3[1] = { - {104, 4}, +static arc arcs_83_3[1] = { + {110, 4}, }; -static arc arcs_78_4[2] = { - {159, 5}, +static arc arcs_83_4[2] = { + {165, 5}, {0, 4}, }; -static arc arcs_78_5[1] = { +static arc arcs_83_5[1] = { {0, 5}, }; -static state states_78[6] = { - {1, arcs_78_0}, - {1, arcs_78_1}, - {1, arcs_78_2}, - {1, arcs_78_3}, - {2, arcs_78_4}, - {1, arcs_78_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 arc arcs_79_0[1] = { - {87, 1}, +static arc arcs_84_0[1] = { + {93, 1}, }; -static arc arcs_79_1[1] = { - {103, 2}, +static arc arcs_84_1[1] = { + {109, 2}, }; -static arc arcs_79_2[2] = { - {159, 3}, +static arc arcs_84_2[2] = { + {165, 3}, {0, 2}, }; -static arc arcs_79_3[1] = { +static arc arcs_84_3[1] = { {0, 3}, }; -static state states_79[4] = { - {1, arcs_79_0}, - {1, arcs_79_1}, - {2, arcs_79_2}, - {1, arcs_79_3}, +static state states_84[4] = { + {1, arcs_84_0}, + {1, arcs_84_1}, + {2, arcs_84_2}, + {1, arcs_84_3}, }; -static arc arcs_80_0[1] = { - {26, 1}, +static arc arcs_85_0[1] = { + {22, 1}, }; -static arc arcs_80_1[2] = { - {27, 0}, +static arc arcs_85_1[2] = { + {28, 0}, {0, 1}, }; -static state states_80[2] = { - {1, arcs_80_0}, - {2, arcs_80_1}, +static state states_85[2] = { + {1, arcs_85_0}, + {2, arcs_85_1}, }; -static arc arcs_81_0[1] = { +static arc arcs_86_0[1] = { {19, 1}, }; -static arc arcs_81_1[1] = { +static arc arcs_86_1[1] = { {0, 1}, }; -static state states_81[2] = { - {1, arcs_81_0}, - {1, arcs_81_1}, +static state states_86[2] = { + {1, arcs_86_0}, + {1, arcs_86_1}, }; -static arc arcs_82_0[1] = { - {163, 1}, +static arc arcs_87_0[1] = { + {169, 1}, }; -static arc arcs_82_1[2] = { +static arc arcs_87_1[2] = { {9, 2}, {0, 1}, }; -static arc arcs_82_2[1] = { +static arc arcs_87_2[1] = { {0, 2}, }; -static state states_82[3] = { - {1, arcs_82_0}, - {2, arcs_82_1}, - {1, arcs_82_2}, +static state states_87[3] = { + {1, arcs_87_0}, + {2, arcs_87_1}, + {1, arcs_87_2}, }; -static dfa dfas[83] = { +static dfa dfas[88] = { {256, "single_input", 0, 3, states_0, - "\004\050\014\000\000\000\200\012\236\206\201\054\001\004\001\000\030\102\062\010\010"}, + "\004\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"}, {257, "file_input", 0, 2, states_1, - "\204\050\014\000\000\000\200\012\236\206\201\054\001\004\001\000\030\102\062\010\010"}, + "\204\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"}, {258, "eval_input", 0, 3, states_2, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, + "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\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\010\000\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"}, - {261, "funcdef", 0, 7, states_5, - "\000\010\004\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\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"}, {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"}, - {263, "varargslist", 0, 12, states_7, - "\000\040\010\060\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {264, "fpdef", 0, 4, states_8, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {265, "fplist", 0, 3, states_9, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {266, "stmt", 0, 2, states_10, - "\000\050\014\000\000\000\200\012\236\206\201\054\001\004\001\000\030\102\062\010\010"}, - {267, "simple_stmt", 0, 4, states_11, - "\000\040\010\000\000\000\200\012\236\206\001\000\000\004\001\000\030\102\062\000\010"}, - {268, "small_stmt", 0, 2, states_12, - "\000\040\010\000\000\000\200\012\236\206\001\000\000\004\001\000\030\102\062\000\010"}, - {269, "expr_stmt", 0, 6, states_13, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {270, "augassign", 0, 2, states_14, - "\000\000\000\000\000\370\177\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {271, "print_stmt", 0, 9, states_15, - "\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {272, "del_stmt", 0, 3, states_16, - "\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {273, "pass_stmt", 0, 2, states_17, - "\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {274, "flow_stmt", 0, 2, states_18, - "\000\000\000\000\000\000\000\000\036\000\000\000\000\000\000\000\000\000\000\000\010"}, - {275, "break_stmt", 0, 2, states_19, - "\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000"}, - {276, "continue_stmt", 0, 2, states_20, - "\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, - {277, "return_stmt", 0, 3, states_21, - "\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "yield_stmt", 0, 2, states_22, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\010"}, - {279, "raise_stmt", 0, 7, states_23, - "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, - {280, "import_stmt", 0, 2, states_24, - "\000\000\000\000\000\000\000\000\200\002\000\000\000\000\000\000\000\000\000\000\000"}, - {281, "import_name", 0, 3, states_25, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "import_from", 0, 8, states_26, - "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000"}, - {283, "import_as_name", 0, 4, states_27, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {284, "dotted_as_name", 0, 4, states_28, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {285, "import_as_names", 0, 3, states_29, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {286, "dotted_as_names", 0, 2, states_30, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {287, "dotted_name", 0, 2, states_31, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {288, "global_stmt", 0, 3, states_32, - "\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000"}, - {289, "assert_stmt", 0, 5, states_33, - "\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000"}, - {290, "compound_stmt", 0, 2, states_34, - "\000\010\004\000\000\000\000\000\000\000\200\054\001\000\000\000\000\000\000\010\000"}, - {291, "if_stmt", 0, 8, states_35, - "\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000"}, - {292, "while_stmt", 0, 8, states_36, - "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, - {293, "for_stmt", 0, 10, states_37, - "\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"}, - {294, "try_stmt", 0, 13, states_38, - "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"}, - {295, "with_stmt", 0, 6, states_39, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {296, "with_var", 0, 3, states_40, - "\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000"}, - {297, "except_clause", 0, 5, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000"}, - {298, "suite", 0, 5, states_42, - "\004\040\010\000\000\000\200\012\236\206\001\000\000\004\001\000\030\102\062\000\010"}, - {299, "testlist_safe", 0, 5, states_43, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {300, "old_test", 0, 2, states_44, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {301, "old_lambdef", 0, 5, states_45, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000"}, - {302, "test", 0, 6, states_46, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {303, "or_test", 0, 2, states_47, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\001\000\030\102\062\000\000"}, - {304, "and_test", 0, 2, states_48, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\001\000\030\102\062\000\000"}, - {305, "not_test", 0, 3, states_49, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\001\000\030\102\062\000\000"}, - {306, "comparison", 0, 2, states_50, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\030\102\062\000\000"}, - {307, "comp_op", 0, 4, states_51, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\371\003\000\000\000\000\000"}, - {308, "expr", 0, 2, states_52, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\030\102\062\000\000"}, - {309, "xor_expr", 0, 2, states_53, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\030\102\062\000\000"}, - {310, "and_expr", 0, 2, states_54, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\030\102\062\000\000"}, - {311, "shift_expr", 0, 2, states_55, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\030\102\062\000\000"}, - {312, "arith_expr", 0, 2, states_56, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\030\102\062\000\000"}, - {313, "term", 0, 2, states_57, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\030\102\062\000\000"}, - {314, "factor", 0, 3, states_58, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\030\102\062\000\000"}, - {315, "power", 0, 4, states_59, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\000\100\062\000\000"}, - {316, "atom", 0, 11, states_60, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\000\100\062\000\000"}, - {317, "listmaker", 0, 5, states_61, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {318, "testlist_gexp", 0, 5, states_62, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {319, "lambdef", 0, 5, states_63, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000"}, - {320, "trailer", 0, 7, states_64, - "\000\040\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\100\000\000\000"}, - {321, "subscriptlist", 0, 3, states_65, - "\000\040\050\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {322, "subscript", 0, 5, states_66, - "\000\040\050\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {323, "sliceop", 0, 3, states_67, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {324, "exprlist", 0, 3, states_68, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\000\000\000\030\102\062\000\000"}, - {325, "testlist", 0, 3, states_69, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {326, "dictsetmaker", 0, 8, states_70, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {327, "classdef", 0, 8, states_71, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\010\000"}, - {328, "arglist", 0, 8, states_72, - "\000\040\010\060\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {329, "argument", 0, 4, states_73, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {330, "list_iter", 0, 2, states_74, - "\000\000\000\000\000\000\000\000\000\000\200\010\000\000\000\000\000\000\000\000\000"}, - {331, "list_for", 0, 6, states_75, - "\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"}, - {332, "list_if", 0, 4, states_76, - "\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000"}, - {333, "gen_iter", 0, 2, states_77, - "\000\000\000\000\000\000\000\000\000\000\200\010\000\000\000\000\000\000\000\000\000"}, - {334, "gen_for", 0, 6, states_78, - "\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"}, - {335, "gen_if", 0, 4, states_79, - "\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000"}, - {336, "testlist1", 0, 2, states_80, - "\000\040\010\000\000\000\000\000\000\004\000\000\000\004\001\000\030\102\062\000\000"}, - {337, "encoding_decl", 0, 2, states_81, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {338, "yield_expr", 0, 3, states_82, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\010"}, + "\000\040\000\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"}, + {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"}, + {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"}, + {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"}, + {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"}, + {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"}, + {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"}, + {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"}, + {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"}, + {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"}, + {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"}, + {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"}, + {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"}, }; -static label labels[164] = { +static label labels[170] = { {0, "EMPTY"}, {256, 0}, {4, 0}, - {267, 0}, - {290, 0}, + {272, 0}, + {295, 0}, {257, 0}, - {266, 0}, + {271, 0}, {0, 0}, {258, 0}, - {325, 0}, + {330, 0}, {259, 0}, {50, 0}, - {287, 0}, + {292, 0}, {7, 0}, - {328, 0}, + {333, 0}, {8, 0}, {260, 0}, {261, 0}, {1, "def"}, {1, 0}, {262, 0}, + {51, 0}, + {307, 0}, {11, 0}, - {298, 0}, + {303, 0}, {263, 0}, - {264, 0}, + {265, 0}, {22, 0}, - {302, 0}, {12, 0}, {16, 0}, + {264, 0}, {36, 0}, - {265, 0}, - {268, 0}, - {13, 0}, + {266, 0}, + {267, 0}, {269, 0}, - {271, 0}, - {272, 0}, + {268, 0}, + {270, 0}, {273, 0}, + {13, 0}, {274, 0}, - {280, 0}, - {288, 0}, - {289, 0}, - {270, 0}, - {338, 0}, + {276, 0}, + {277, 0}, + {278, 0}, + {279, 0}, + {285, 0}, + {293, 0}, + {294, 0}, + {275, 0}, + {343, 0}, {37, 0}, {38, 0}, {39, 0}, @@ -1991,35 +2144,35 @@ {1, "print"}, {35, 0}, {1, "del"}, - {324, 0}, + {329, 0}, {1, "pass"}, - {275, 0}, - {276, 0}, - {277, 0}, - {279, 0}, - {278, 0}, + {280, 0}, + {281, 0}, + {282, 0}, + {284, 0}, + {283, 0}, {1, "break"}, {1, "continue"}, {1, "return"}, {1, "raise"}, - {281, 0}, - {282, 0}, - {1, "import"}, {286, 0}, + {287, 0}, + {1, "import"}, + {291, 0}, {1, "from"}, {23, 0}, - {285, 0}, - {283, 0}, + {290, 0}, + {288, 0}, {1, "as"}, - {284, 0}, + {289, 0}, {1, "global"}, {1, "assert"}, - {291, 0}, - {292, 0}, - {293, 0}, - {294, 0}, - {295, 0}, - {327, 0}, + {296, 0}, + {297, 0}, + {298, 0}, + {299, 0}, + {300, 0}, + {332, 0}, {1, "if"}, {1, "elif"}, {1, "else"}, @@ -2027,27 +2180,27 @@ {1, "for"}, {1, "in"}, {1, "try"}, - {297, 0}, + {302, 0}, {1, "finally"}, {1, "with"}, - {296, 0}, - {308, 0}, + {301, 0}, + {313, 0}, {1, "except"}, {5, 0}, {6, 0}, - {299, 0}, - {300, 0}, - {303, 0}, - {301, 0}, - {1, "lambda"}, - {319, 0}, {304, 0}, - {1, "or"}, {305, 0}, + {308, 0}, + {306, 0}, + {1, "lambda"}, + {324, 0}, + {309, 0}, + {1, "or"}, + {310, 0}, {1, "and"}, {1, "not"}, - {306, 0}, - {307, 0}, + {311, 0}, + {312, 0}, {20, 0}, {21, 0}, {28, 0}, @@ -2055,52 +2208,52 @@ {30, 0}, {29, 0}, {1, "is"}, - {309, 0}, + {314, 0}, {18, 0}, - {310, 0}, + {315, 0}, {33, 0}, - {311, 0}, + {316, 0}, {19, 0}, - {312, 0}, + {317, 0}, {34, 0}, - {313, 0}, + {318, 0}, {14, 0}, {15, 0}, - {314, 0}, + {319, 0}, {17, 0}, {24, 0}, {48, 0}, {32, 0}, - {315, 0}, - {316, 0}, {320, 0}, - {318, 0}, + {321, 0}, + {325, 0}, + {323, 0}, {9, 0}, - {317, 0}, + {322, 0}, {10, 0}, {26, 0}, - {326, 0}, + {331, 0}, {27, 0}, {2, 0}, {3, 0}, - {331, 0}, - {334, 0}, - {321, 0}, - {322, 0}, - {323, 0}, + {336, 0}, + {339, 0}, + {326, 0}, + {327, 0}, + {328, 0}, {1, "class"}, - {329, 0}, - {330, 0}, - {332, 0}, - {333, 0}, + {334, 0}, {335, 0}, - {336, 0}, {337, 0}, + {338, 0}, + {340, 0}, + {341, 0}, + {342, 0}, {1, "yield"}, }; grammar _PyParser_Grammar = { - 83, + 88, dfas, - {164, labels}, + {170, 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 Thu Jan 11 00:21:28 2007 @@ -70,9 +70,10 @@ 3010 (removed UNARY_CONVERT) 3020 (added BUILD_SET) 3030 (added keyword-only parameters) + 3040 (added signature annotations) . */ -#define MAGIC (3030 | ((long)'\r'<<16) | ((long)'\n'<<24)) +#define MAGIC (3040 | ((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 Thu Jan 11 00:21:28 2007 @@ -182,8 +182,8 @@ } else { char buf[256]; /* Plenty to format any double */ - PyFloat_AsReprString(buf, (PyFloatObject *)v); - n = strlen(buf); + n = _PyFloat_Repr(PyFloat_AS_DOUBLE(v), + buf, sizeof(buf)); w_byte(TYPE_FLOAT, p); w_byte((int)n, p); w_string(buf, (int)n, p); @@ -209,28 +209,14 @@ } else { char buf[256]; /* Plenty to format any double */ - PyFloatObject *temp; w_byte(TYPE_COMPLEX, p); - temp = (PyFloatObject*)PyFloat_FromDouble( - PyComplex_RealAsDouble(v)); - if (!temp) { - p->error = 1; - return; - } - PyFloat_AsReprString(buf, temp); - Py_DECREF(temp); + n = _PyFloat_Repr(PyComplex_RealAsDouble(v), + buf, sizeof(buf)); n = strlen(buf); w_byte((int)n, p); w_string(buf, (int)n, p); - temp = (PyFloatObject*)PyFloat_FromDouble( - PyComplex_ImagAsDouble(v)); - if (!temp) { - p->error = 1; - return; - } - PyFloat_AsReprString(buf, temp); - Py_DECREF(temp); - n = strlen(buf); + n = _PyFloat_Repr(PyComplex_ImagAsDouble(v), + buf, sizeof(buf)); w_byte((int)n, p); w_string(buf, (int)n, p); } Modified: python/branches/p3yk-noslice/Python/symtable.c ============================================================================== --- python/branches/p3yk-noslice/Python/symtable.c (original) +++ python/branches/p3yk-noslice/Python/symtable.c Thu Jan 11 00:21:28 2007 @@ -172,9 +172,12 @@ static int symtable_visit_comprehension(struct symtable *st, comprehension_ty); static int symtable_visit_keyword(struct symtable *st, keyword_ty); static int symtable_visit_slice(struct symtable *st, slice_ty); -static int symtable_visit_params(struct symtable *st, asdl_seq *args, int top); -static int symtable_visit_params_nested(struct symtable *st, asdl_seq *args); +static int symtable_visit_params(struct symtable *st, asdl_seq *args, int top, + int annotations); +static int symtable_visit_params_nested(struct symtable *st, asdl_seq *args, + int annotations); static int symtable_implicit_arg(struct symtable *st, int pos); +static int symtable_visit_annotations(struct symtable *st, stmt_ty s); static identifier top = NULL, lambda = NULL, genexpr = NULL; @@ -935,6 +938,8 @@ if (s->v.FunctionDef.args->kw_defaults) VISIT_KWONLYDEFAULTS(st, s->v.FunctionDef.args->kw_defaults); + if (!symtable_visit_annotations(st, s)) + return 0; if (s->v.FunctionDef.decorators) VISIT_SEQ(st, expr, s->v.FunctionDef.decorators); if (!symtable_enter_block(st, s->v.FunctionDef.name, @@ -1219,22 +1224,29 @@ } static int -symtable_visit_params(struct symtable *st, asdl_seq *args, int toplevel) +symtable_visit_params(struct symtable *st, asdl_seq *args, int toplevel, + int annotations) { int i; + + if (!args) + return -1; /* go through all the toplevel arguments first */ for (i = 0; i < asdl_seq_LEN(args); i++) { - expr_ty arg = (expr_ty)asdl_seq_GET(args, i); - if (arg->kind == Name_kind) { - assert(arg->v.Name.ctx == Param || - (arg->v.Name.ctx == Store && !toplevel)); - if (!symtable_add_def(st, arg->v.Name.id, DEF_PARAM)) - return 0; + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + if (arg->kind == SimpleArg_kind) { + if (!annotations) { + if (!symtable_add_def(st, + arg->v.SimpleArg.arg, + DEF_PARAM)) + return 0; + } + else if (arg->v.SimpleArg.annotation) + VISIT(st, expr, arg->v.SimpleArg.annotation); } - else if (arg->kind == Tuple_kind) { - assert(arg->v.Tuple.ctx == Store); - if (toplevel) { + else if (arg->kind == NestedArgs_kind) { + if (toplevel && !annotations) { if (!symtable_implicit_arg(st, i)) return 0; } @@ -1249,7 +1261,7 @@ } if (!toplevel) { - if (!symtable_visit_params_nested(st, args)) + if (!symtable_visit_params_nested(st, args, annotations)) return 0; } @@ -1257,16 +1269,37 @@ } static int -symtable_visit_params_nested(struct symtable *st, asdl_seq *args) +symtable_visit_params_nested(struct symtable *st, asdl_seq *args, + int annotations) { int i; for (i = 0; i < asdl_seq_LEN(args); i++) { - expr_ty arg = (expr_ty)asdl_seq_GET(args, i); - if (arg->kind == Tuple_kind && - !symtable_visit_params(st, arg->v.Tuple.elts, 0)) + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + if (arg->kind == NestedArgs_kind && + !symtable_visit_params(st, arg->v.NestedArgs.args, 0, + annotations)) return 0; } + + return 1; +} + + +static int +symtable_visit_annotations(struct symtable *st, stmt_ty s) +{ + arguments_ty a = s->v.FunctionDef.args; + if (a->args && !symtable_visit_params(st, a->args, 1, 1)) + return 0; + if (a->varargannotation) + VISIT(st, expr, a->varargannotation); + if (a->kwargannotation) + VISIT(st, expr, a->kwargannotation); + if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs, 1, 1)) + return 0; + if (s->v.FunctionDef.returns) + VISIT(st, expr, s->v.FunctionDef.returns); return 1; } @@ -1276,9 +1309,9 @@ /* skip default arguments inside function block XXX should ast be different? */ - if (a->args && !symtable_visit_params(st, a->args, 1)) + if (a->args && !symtable_visit_params(st, a->args, 1, 0)) return 0; - if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs, 1)) + if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs, 1, 0)) return 0; if (a->vararg) { if (!symtable_add_def(st, a->vararg, DEF_PARAM)) @@ -1290,7 +1323,7 @@ return 0; st->st_cur->ste_varkeywords = 1; } - if (a->args && !symtable_visit_params_nested(st, a->args)) + if (a->args && !symtable_visit_params_nested(st, a->args, 0)) return 0; return 1; } Modified: python/branches/p3yk-noslice/Python/sysmodule.c ============================================================================== --- python/branches/p3yk-noslice/Python/sysmodule.c (original) +++ python/branches/p3yk-noslice/Python/sysmodule.c Thu Jan 11 00:21:28 2007 @@ -264,6 +264,32 @@ #endif + +static PyObject * +sys_intern(PyObject *self, PyObject *args) +{ + PyObject *s; + if (!PyArg_ParseTuple(args, "S:intern", &s)) + return NULL; + if (!PyString_CheckExact(s)) { + PyErr_SetString(PyExc_TypeError, + "can't intern subclass of string"); + return NULL; + } + Py_INCREF(s); + PyString_InternInPlace(&s); + return s; +} + +PyDoc_STRVAR(intern_doc, +"intern(string) -> string\n\ +\n\ +``Intern'' the given string. This enters the string in the (global)\n\ +table of interned strings whose purpose is to speed up dictionary lookups.\n\ +Return the string itself or the previously interned string object with the\n\ +same value."); + + /* * Cached interned string objects used for calling the profile and * trace functions. Initialized by trace_init(). @@ -772,6 +798,7 @@ {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, getwindowsversion_doc}, #endif /* MS_WINDOWS */ + {"intern", sys_intern, METH_VARARGS, intern_doc}, #ifdef USE_MALLOPT {"mdebug", sys_mdebug, METH_VARARGS}, #endif Modified: python/branches/p3yk-noslice/README ============================================================================== --- python/branches/p3yk-noslice/README (original) +++ python/branches/p3yk-noslice/README Thu Jan 11 00:21:28 2007 @@ -1,7 +1,8 @@ This is Python 3000 -- unversioned (branched off 2.5 in various beta stages) ================================================================= -Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 +Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/branches/p3yk-noslice/Tools/compiler/ast.txt ============================================================================== --- python/branches/p3yk-noslice/Tools/compiler/ast.txt (original) +++ python/branches/p3yk-noslice/Tools/compiler/ast.txt Thu Jan 11 00:21:28 2007 @@ -12,8 +12,11 @@ Module: doc*, node Stmt: nodes! Decorators: nodes! -Function: decorators&, name*, argnames*, defaults!, kwonlyargs*, flags*, doc*, code -Lambda: argnames*, defaults!, kwonlyargs*, flags*, code +Function: decorators&, name*, arguments!, defaults!, kwonlyargs!, returns&, flags*, doc*, code +Lambda: arguments!, defaults!, kwonlyargs!, flags*, code +SimpleArg: name*, annotation& +NestedArgs: args! +Kwarg: arg, expr Class: name*, bases!, doc*, code Pass: Break: @@ -93,9 +96,10 @@ self.varargs = 1 if flags & CO_VARKEYWORDS: self.kwargs = 1 + self.returns = None init(GenExpr): - self.argnames = ['.0'] + self.arguments = [SimpleArg('.0', None)] self.varargs = self.kwargs = None self.kwonlyargs = () Modified: python/branches/p3yk-noslice/Tools/compiler/astgen.py ============================================================================== --- python/branches/p3yk-noslice/Tools/compiler/astgen.py (original) +++ python/branches/p3yk-noslice/Tools/compiler/astgen.py Thu Jan 11 00:21:28 2007 @@ -266,7 +266,10 @@ pass # implemented by subclasses class EmptyNode(Node): - pass + def getChildNodes(self): + return () + def getChildren(self): + return () class Expression(Node): # Expression is an artificial node class to support "eval" Modified: python/branches/p3yk-noslice/Tools/pybench/Strings.py ============================================================================== --- python/branches/p3yk-noslice/Tools/pybench/Strings.py (original) +++ python/branches/p3yk-noslice/Tools/pybench/Strings.py Thu Jan 11 00:21:28 2007 @@ -1,5 +1,6 @@ from pybench import Test from string import join +import sys class ConcatStrings(Test): @@ -174,7 +175,7 @@ def test(self): # Make sure the strings *are* interned - s = intern(join(map(str,range(10)))) + s = sys.intern(join(map(str,range(10)))) t = s for i in xrange(self.rounds): @@ -240,7 +241,7 @@ def calibrate(self): - s = intern(join(map(str,range(10)))) + s = sys.intern(join(map(str,range(10)))) t = s for i in xrange(self.rounds): Modified: python/branches/p3yk-noslice/Tools/scripts/fixdiv.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/fixdiv.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/fixdiv.py Thu Jan 11 00:21:28 2007 @@ -198,7 +198,7 @@ list = warnings.get(filename) if list is None: warnings[filename] = list = [] - list.append((int(lineno), intern(what))) + list.append((int(lineno), sys.intern(what))) f.close() return warnings Modified: python/branches/p3yk-noslice/setup.py ============================================================================== --- python/branches/p3yk-noslice/setup.py (original) +++ python/branches/p3yk-noslice/setup.py Thu Jan 11 00:21:28 2007 @@ -606,7 +606,7 @@ # a release. Most open source OSes come with one or more # versions of BerkeleyDB already installed. - max_db_ver = (4, 4) + max_db_ver = (4, 5) min_db_ver = (3, 3) db_setup_debug = False # verbose debug prints from this script? @@ -623,7 +623,7 @@ '/sw/include/db3', ] # 4.x minor number specific paths - for x in (0,1,2,3,4): + for x in (0,1,2,3,4,5): db_inc_paths.append('/usr/include/db4%d' % x) db_inc_paths.append('/usr/include/db4.%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x) @@ -631,7 +631,7 @@ db_inc_paths.append('/pkg/db-4.%d/include' % x) db_inc_paths.append('/opt/db-4.%d/include' % x) # 3.x minor number specific paths - for x in (2,3): + for x in (3,): db_inc_paths.append('/usr/include/db3%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x) db_inc_paths.append('/usr/local/include/db3%d' % x) From python-checkins at python.org Thu Jan 11 00:43:42 2007 From: python-checkins at python.org (thomas.wouters) Date: Thu, 11 Jan 2007 00:43:42 +0100 (CET) Subject: [Python-checkins] r53364 - in python/branches/p3yk-noslice: Demo/cgi/wiki.py Demo/comparisons/regextest.py Demo/comparisons/systemtest.py Demo/parser/test_parser.py Demo/parser/unparse.py Demo/pdist/FSProxy.py Demo/pdist/cmdfw.py Demo/pdist/cmptree.py Demo/pdist/cvslock.py Demo/pdist/rrcs.py Demo/pysvr/pysvr.py Demo/rpc/nfsclient.py Demo/rpc/rpc.py Demo/scripts/eqfix.py Demo/scripts/ftpstats.py Demo/scripts/mboxconvert.py Demo/scripts/newslist.py Demo/scripts/pp.py Demo/scripts/update.py Demo/sockets/gopher.py Demo/sockets/telnet.py Demo/threads/find.py Demo/threads/telnet.py Demo/tkinter/guido/AttrDialog.py Demo/tkinter/guido/ManPage.py Demo/tkinter/guido/mbox.py Demo/tkinter/guido/tkman.py Demo/tkinter/guido/wish.py Doc/Makefile.deps Doc/howto/urllib2.rst Doc/lib/email-unpack.py Doc/lib/lib.tex Doc/lib/libcsv.tex Doc/lib/libgetopt.tex Doc/lib/libsets.tex Doc/lib/libshutil.tex Doc/lib/libsocket.tex Doc/lib/libstdtypes.tex Doc/lib/libsubprocess.tex Doc/lib/libxdrlib.tex Doc/lib/libxmlrpclib.tex Doc/lib/sqlite3/complete_statement.py Doc/tools/findcsyms Doc/tools/listmodules Doc/tools/mkhowto Doc/tools/mksourcepkg Doc/tools/prechm.py Doc/tools/sgmlconv/docfixer.py Doc/tools/sgmlconv/esis2sgml.py Doc/tools/sgmlconv/esistools.py Doc/tools/sgmlconv/latex2esis.py Doc/tut/tut.tex Grammar/Grammar Include/Python-ast.h Lib/CGIHTTPServer.py Lib/ConfigParser.py Lib/SimpleXMLRPCServer.py Lib/_strptime.py Lib/asynchat.py Lib/asyncore.py Lib/base64.py Lib/bsddb/dbtables.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_compare.py Lib/bsddb/test/test_pickle.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_thread.py Lib/cgi.py Lib/codecs.py Lib/codeop.py Lib/compileall.py Lib/compiler/pycodegen.py Lib/compiler/transformer.py Lib/contextlib.py Lib/csv.py Lib/ctypes/macholib/dyld.py Lib/ctypes/test/__init__.py Lib/ctypes/test/test_bitfields.py Lib/ctypes/test/test_structures.py Lib/ctypes/util.py Lib/dis.py Lib/distutils/bcppcompiler.py Lib/distutils/command/register.py Lib/distutils/command/sdist.py Lib/distutils/command/upload.py Lib/distutils/core.py Lib/distutils/cygwinccompiler.py Lib/distutils/dir_util.py Lib/distutils/dist.py Lib/distutils/emxccompiler.py Lib/distutils/fancy_getopt.py Lib/distutils/file_util.py Lib/distutils/msvccompiler.py Lib/distutils/spawn.py Lib/distutils/sysconfig.py Lib/distutils/unixccompiler.py Lib/distutils/util.py Lib/doctest.py Lib/encodings/uu_codec.py Lib/filecmp.py Lib/ftplib.py Lib/hotshot/stones.py Lib/htmllib.py Lib/httplib.py Lib/idlelib/ClassBrowser.py Lib/idlelib/EditorWindow.py Lib/idlelib/GrepDialog.py Lib/idlelib/IOBinding.py Lib/idlelib/PyShell.py Lib/idlelib/ScriptBinding.py Lib/idlelib/SearchEngine.py Lib/idlelib/run.py Lib/imaplib.py Lib/lib-tk/Tkinter.py Lib/linecache.py Lib/logging/config.py Lib/mailbox.py Lib/mhlib.py Lib/mimetypes.py Lib/modulefinder.py Lib/msilib/__init__.py Lib/nntplib.py Lib/optparse.py Lib/os.py Lib/pdb.py Lib/pickle.py Lib/pkgutil.py Lib/plat-irix5/torgb.py Lib/plat-irix6/torgb.py Lib/plat-mac/EasyDialogs.py Lib/plat-mac/MiniAEFrame.py Lib/plat-mac/aetools.py Lib/plat-mac/applesingle.py Lib/plat-mac/argvemulator.py Lib/plat-mac/buildtools.py Lib/plat-mac/bundlebuilder.py Lib/plat-mac/gensuitemodule.py Lib/plat-mac/macresource.py Lib/plat-mac/pimp.py Lib/plat-mac/terminalcommand.py Lib/platform.py Lib/poplib.py Lib/pstats.py Lib/pty.py Lib/py_compile.py Lib/pydoc.py Lib/quopri.py Lib/re.py Lib/rexec.py Lib/sets.py Lib/sgmllib.py Lib/shutil.py Lib/site.py Lib/smtpd.py Lib/smtplib.py Lib/sqlite3/test/dbapi.py Lib/sqlite3/test/hooks.py Lib/sqlite3/test/userfunctions.py Lib/subprocess.py Lib/tabnanny.py Lib/tarfile.py Lib/telnetlib.py Lib/tempfile.py Lib/test/pickletester.py Lib/test/regrtest.py Lib/test/sortperf.py Lib/test/string_tests.py Lib/test/test_bool.py Lib/test/test_cfgparser.py Lib/test/test_cgi.py Lib/test/test_class.py Lib/test/test_codecs.py Lib/test/test_compiler.py Lib/test/test_contextlib.py Lib/test/test_cookielib.py Lib/test/test_dbm.py Lib/test/test_decimal.py Lib/test/test_defaultdict.py Lib/test/test_descr.py Lib/test/test_dict.py Lib/test/test_dl.py Lib/test/test_eof.py Lib/test/test_exceptions.py Lib/test/test_extcall.py Lib/test/test_file.py Lib/test/test_format.py Lib/test/test_frozen.py Lib/test/test_future.py Lib/test/test_generators.py Lib/test/test_grammar.py Lib/test/test_import.py Lib/test/test_linuxaudiodev.py Lib/test/test_nis.py Lib/test/test_opcodes.py Lib/test/test_optparse.py Lib/test/test_os.py Lib/test/test_ossaudiodev.py Lib/test/test_parser.py Lib/test/test_pep277.py Lib/test/test_pyexpat.py Lib/test/test_re.py Lib/test/test_runpy.py Lib/test/test_sax.py Lib/test/test_set.py Lib/test/test_sets.py Lib/test/test_socket.py Lib/test/test_socket_ssl.py Lib/test/test_socketserver.py Lib/test/test_strftime.py Lib/test/test_string.py Lib/test/test_strptime.py Lib/test/test_subprocess.py Lib/test/test_sunaudiodev.py Lib/test/test_support.py Lib/test/test_syntax.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/test_tcl.py Lib/test/test_trace.py Lib/test/test_traceback.py Lib/test/test_urllib2net.py Lib/test/test_userdict.py Lib/test/test_uu.py Lib/test/test_winreg.py Lib/timeit.py Lib/toaiff.py Lib/token.py Lib/trace.py Lib/unittest.py Lib/urllib.py Lib/urllib2.py Lib/uu.py Lib/warnings.py Lib/webbrowser.py Lib/xdrlib.py Lib/xml/sax/__init__.py Lib/xml/sax/expatreader.py Lib/xmllib.py Lib/xmlrpclib.py Lib/zipfile.py Mac/BuildScript/build-installer.py Mac/Demo/applescript/makedisk.py Mac/Demo/imgbrowse/imgbrowse.py Mac/Demo/mlte/mlted.py Mac/Demo/resources/copyres.py Mac/Demo/textedit/ped.py Mac/scripts/BuildApplet.py Mac/scripts/buildpkg.py Misc/BeOS-setup.py Misc/NEWS Modules/parsermodule.c Parser/Python.asdl Python/Python-ast.c Python/ast.c Python/compile.c Python/graminit.c Python/symtable.c Tools/audiopy/audiopy Tools/bgen/bgen/scantools.py Tools/compiler/compile.py Tools/compiler/regrtest.py Tools/faqwiz/faqw.py Tools/faqwiz/faqwiz.py Tools/freeze/checkextensions_win32.py Tools/freeze/freeze.py Tools/i18n/msgfmt.py Tools/i18n/pygettext.py Tools/pybench/CommandLine.py Tools/pybench/pybench.py Tools/pynche/Main.py Tools/scripts/byext.py Tools/scripts/byteyears.py Tools/scripts/checkappend.py Tools/scripts/classfix.py Tools/scripts/cleanfuture.py Tools/scripts/cvsfiles.py Tools/scripts/dutree.py Tools/scripts/finddiv.py Tools/scripts/findlinksto.py Tools/scripts/findnocoding.py Tools/scripts/fixcid.py Tools/scripts/fixdiv.py Tools/scripts/fixheader.py Tools/scripts/fixnotice.py Tools/scripts/fixps.py Tools/scripts/ftpmirror.py Tools/scripts/linktree.py Tools/scripts/logmerge.py Tools/scripts/md5sum.py Tools/scripts/methfix.py Tools/scripts/ndiff.py Tools/scripts/pathfix.py Tools/scripts/pindent.py Tools/scripts/pysource.py Tools/scripts/redemo.py Tools/scripts/reindent.py Tools/scripts/rgrep.py Tools/scripts/texi2html.py Tools/scripts/treesync.py Tools/scripts/untabify.py Tools/unicode/comparecodecs.py Tools/unicode/gencodec.py Tools/unicode/listcodecs.py Tools/versioncheck/pyversioncheck.py Tools/webchecker/wcgui.py Tools/webchecker/webchecker.py Tools/webchecker/websucker.py setup.py Message-ID: <20070110234342.617FF1E400A@bag.python.org> Author: thomas.wouters Date: Thu Jan 11 00:43:10 2007 New Revision: 53364 Removed: python/branches/p3yk-noslice/Lib/sets.py python/branches/p3yk-noslice/Lib/test/test_sets.py Modified: python/branches/p3yk-noslice/ (props changed) python/branches/p3yk-noslice/Demo/cgi/wiki.py python/branches/p3yk-noslice/Demo/comparisons/regextest.py python/branches/p3yk-noslice/Demo/comparisons/systemtest.py python/branches/p3yk-noslice/Demo/parser/test_parser.py python/branches/p3yk-noslice/Demo/parser/unparse.py python/branches/p3yk-noslice/Demo/pdist/FSProxy.py python/branches/p3yk-noslice/Demo/pdist/cmdfw.py python/branches/p3yk-noslice/Demo/pdist/cmptree.py python/branches/p3yk-noslice/Demo/pdist/cvslock.py python/branches/p3yk-noslice/Demo/pdist/rrcs.py python/branches/p3yk-noslice/Demo/pysvr/pysvr.py python/branches/p3yk-noslice/Demo/rpc/nfsclient.py python/branches/p3yk-noslice/Demo/rpc/rpc.py python/branches/p3yk-noslice/Demo/scripts/eqfix.py python/branches/p3yk-noslice/Demo/scripts/ftpstats.py python/branches/p3yk-noslice/Demo/scripts/mboxconvert.py python/branches/p3yk-noslice/Demo/scripts/newslist.py python/branches/p3yk-noslice/Demo/scripts/pp.py python/branches/p3yk-noslice/Demo/scripts/update.py python/branches/p3yk-noslice/Demo/sockets/gopher.py python/branches/p3yk-noslice/Demo/sockets/telnet.py python/branches/p3yk-noslice/Demo/threads/find.py python/branches/p3yk-noslice/Demo/threads/telnet.py python/branches/p3yk-noslice/Demo/tkinter/guido/AttrDialog.py python/branches/p3yk-noslice/Demo/tkinter/guido/ManPage.py python/branches/p3yk-noslice/Demo/tkinter/guido/mbox.py python/branches/p3yk-noslice/Demo/tkinter/guido/tkman.py python/branches/p3yk-noslice/Demo/tkinter/guido/wish.py python/branches/p3yk-noslice/Doc/Makefile.deps python/branches/p3yk-noslice/Doc/howto/urllib2.rst python/branches/p3yk-noslice/Doc/lib/email-unpack.py python/branches/p3yk-noslice/Doc/lib/lib.tex python/branches/p3yk-noslice/Doc/lib/libcsv.tex python/branches/p3yk-noslice/Doc/lib/libgetopt.tex python/branches/p3yk-noslice/Doc/lib/libsets.tex python/branches/p3yk-noslice/Doc/lib/libshutil.tex python/branches/p3yk-noslice/Doc/lib/libsocket.tex python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex python/branches/p3yk-noslice/Doc/lib/libsubprocess.tex python/branches/p3yk-noslice/Doc/lib/libxdrlib.tex python/branches/p3yk-noslice/Doc/lib/libxmlrpclib.tex python/branches/p3yk-noslice/Doc/lib/sqlite3/complete_statement.py python/branches/p3yk-noslice/Doc/tools/findcsyms python/branches/p3yk-noslice/Doc/tools/listmodules python/branches/p3yk-noslice/Doc/tools/mkhowto python/branches/p3yk-noslice/Doc/tools/mksourcepkg python/branches/p3yk-noslice/Doc/tools/prechm.py python/branches/p3yk-noslice/Doc/tools/sgmlconv/docfixer.py python/branches/p3yk-noslice/Doc/tools/sgmlconv/esis2sgml.py python/branches/p3yk-noslice/Doc/tools/sgmlconv/esistools.py python/branches/p3yk-noslice/Doc/tools/sgmlconv/latex2esis.py python/branches/p3yk-noslice/Doc/tut/tut.tex python/branches/p3yk-noslice/Grammar/Grammar python/branches/p3yk-noslice/Include/Python-ast.h python/branches/p3yk-noslice/Lib/CGIHTTPServer.py python/branches/p3yk-noslice/Lib/ConfigParser.py python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py python/branches/p3yk-noslice/Lib/_strptime.py python/branches/p3yk-noslice/Lib/asynchat.py python/branches/p3yk-noslice/Lib/asyncore.py python/branches/p3yk-noslice/Lib/base64.py python/branches/p3yk-noslice/Lib/bsddb/dbtables.py python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py python/branches/p3yk-noslice/Lib/bsddb/test/test_compare.py python/branches/p3yk-noslice/Lib/bsddb/test/test_pickle.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/cgi.py python/branches/p3yk-noslice/Lib/codecs.py python/branches/p3yk-noslice/Lib/codeop.py python/branches/p3yk-noslice/Lib/compileall.py python/branches/p3yk-noslice/Lib/compiler/pycodegen.py python/branches/p3yk-noslice/Lib/compiler/transformer.py python/branches/p3yk-noslice/Lib/contextlib.py python/branches/p3yk-noslice/Lib/csv.py python/branches/p3yk-noslice/Lib/ctypes/macholib/dyld.py python/branches/p3yk-noslice/Lib/ctypes/test/__init__.py python/branches/p3yk-noslice/Lib/ctypes/test/test_bitfields.py python/branches/p3yk-noslice/Lib/ctypes/test/test_structures.py python/branches/p3yk-noslice/Lib/ctypes/util.py python/branches/p3yk-noslice/Lib/dis.py python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py python/branches/p3yk-noslice/Lib/distutils/command/register.py python/branches/p3yk-noslice/Lib/distutils/command/sdist.py python/branches/p3yk-noslice/Lib/distutils/command/upload.py python/branches/p3yk-noslice/Lib/distutils/core.py python/branches/p3yk-noslice/Lib/distutils/cygwinccompiler.py python/branches/p3yk-noslice/Lib/distutils/dir_util.py python/branches/p3yk-noslice/Lib/distutils/dist.py python/branches/p3yk-noslice/Lib/distutils/emxccompiler.py python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py python/branches/p3yk-noslice/Lib/distutils/file_util.py python/branches/p3yk-noslice/Lib/distutils/msvccompiler.py python/branches/p3yk-noslice/Lib/distutils/spawn.py python/branches/p3yk-noslice/Lib/distutils/sysconfig.py python/branches/p3yk-noslice/Lib/distutils/unixccompiler.py python/branches/p3yk-noslice/Lib/distutils/util.py python/branches/p3yk-noslice/Lib/doctest.py python/branches/p3yk-noslice/Lib/encodings/uu_codec.py python/branches/p3yk-noslice/Lib/filecmp.py python/branches/p3yk-noslice/Lib/ftplib.py python/branches/p3yk-noslice/Lib/hotshot/stones.py python/branches/p3yk-noslice/Lib/htmllib.py python/branches/p3yk-noslice/Lib/httplib.py python/branches/p3yk-noslice/Lib/idlelib/ClassBrowser.py python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py python/branches/p3yk-noslice/Lib/idlelib/PyShell.py python/branches/p3yk-noslice/Lib/idlelib/ScriptBinding.py python/branches/p3yk-noslice/Lib/idlelib/SearchEngine.py python/branches/p3yk-noslice/Lib/idlelib/run.py python/branches/p3yk-noslice/Lib/imaplib.py python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py python/branches/p3yk-noslice/Lib/linecache.py python/branches/p3yk-noslice/Lib/logging/config.py python/branches/p3yk-noslice/Lib/mailbox.py python/branches/p3yk-noslice/Lib/mhlib.py python/branches/p3yk-noslice/Lib/mimetypes.py python/branches/p3yk-noslice/Lib/modulefinder.py python/branches/p3yk-noslice/Lib/msilib/__init__.py python/branches/p3yk-noslice/Lib/nntplib.py python/branches/p3yk-noslice/Lib/optparse.py python/branches/p3yk-noslice/Lib/os.py python/branches/p3yk-noslice/Lib/pdb.py python/branches/p3yk-noslice/Lib/pickle.py python/branches/p3yk-noslice/Lib/pkgutil.py python/branches/p3yk-noslice/Lib/plat-irix5/torgb.py python/branches/p3yk-noslice/Lib/plat-irix6/torgb.py python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py python/branches/p3yk-noslice/Lib/plat-mac/MiniAEFrame.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/buildtools.py python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.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/terminalcommand.py python/branches/p3yk-noslice/Lib/platform.py python/branches/p3yk-noslice/Lib/poplib.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/pydoc.py python/branches/p3yk-noslice/Lib/quopri.py python/branches/p3yk-noslice/Lib/re.py python/branches/p3yk-noslice/Lib/rexec.py python/branches/p3yk-noslice/Lib/sgmllib.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/sqlite3/test/dbapi.py python/branches/p3yk-noslice/Lib/sqlite3/test/hooks.py python/branches/p3yk-noslice/Lib/sqlite3/test/userfunctions.py python/branches/p3yk-noslice/Lib/subprocess.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/tempfile.py python/branches/p3yk-noslice/Lib/test/pickletester.py python/branches/p3yk-noslice/Lib/test/regrtest.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_bool.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_class.py python/branches/p3yk-noslice/Lib/test/test_codecs.py python/branches/p3yk-noslice/Lib/test/test_compiler.py python/branches/p3yk-noslice/Lib/test/test_contextlib.py python/branches/p3yk-noslice/Lib/test/test_cookielib.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_descr.py python/branches/p3yk-noslice/Lib/test/test_dict.py python/branches/p3yk-noslice/Lib/test/test_dl.py python/branches/p3yk-noslice/Lib/test/test_eof.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_file.py python/branches/p3yk-noslice/Lib/test/test_format.py python/branches/p3yk-noslice/Lib/test/test_frozen.py python/branches/p3yk-noslice/Lib/test/test_future.py python/branches/p3yk-noslice/Lib/test/test_generators.py python/branches/p3yk-noslice/Lib/test/test_grammar.py python/branches/p3yk-noslice/Lib/test/test_import.py python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py python/branches/p3yk-noslice/Lib/test/test_nis.py python/branches/p3yk-noslice/Lib/test/test_opcodes.py python/branches/p3yk-noslice/Lib/test/test_optparse.py python/branches/p3yk-noslice/Lib/test/test_os.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_pep277.py python/branches/p3yk-noslice/Lib/test/test_pyexpat.py python/branches/p3yk-noslice/Lib/test/test_re.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_set.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_strftime.py python/branches/p3yk-noslice/Lib/test/test_string.py python/branches/p3yk-noslice/Lib/test/test_strptime.py python/branches/p3yk-noslice/Lib/test/test_subprocess.py python/branches/p3yk-noslice/Lib/test/test_sunaudiodev.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_sys.py python/branches/p3yk-noslice/Lib/test/test_tarfile.py python/branches/p3yk-noslice/Lib/test/test_tcl.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_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_winreg.py python/branches/p3yk-noslice/Lib/timeit.py python/branches/p3yk-noslice/Lib/toaiff.py python/branches/p3yk-noslice/Lib/token.py python/branches/p3yk-noslice/Lib/trace.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/uu.py python/branches/p3yk-noslice/Lib/warnings.py python/branches/p3yk-noslice/Lib/webbrowser.py python/branches/p3yk-noslice/Lib/xdrlib.py python/branches/p3yk-noslice/Lib/xml/sax/__init__.py python/branches/p3yk-noslice/Lib/xml/sax/expatreader.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/Mac/BuildScript/build-installer.py python/branches/p3yk-noslice/Mac/Demo/applescript/makedisk.py python/branches/p3yk-noslice/Mac/Demo/imgbrowse/imgbrowse.py python/branches/p3yk-noslice/Mac/Demo/mlte/mlted.py python/branches/p3yk-noslice/Mac/Demo/resources/copyres.py python/branches/p3yk-noslice/Mac/Demo/textedit/ped.py python/branches/p3yk-noslice/Mac/scripts/BuildApplet.py python/branches/p3yk-noslice/Mac/scripts/buildpkg.py python/branches/p3yk-noslice/Misc/BeOS-setup.py python/branches/p3yk-noslice/Misc/NEWS python/branches/p3yk-noslice/Modules/parsermodule.c python/branches/p3yk-noslice/Parser/Python.asdl python/branches/p3yk-noslice/Python/Python-ast.c python/branches/p3yk-noslice/Python/ast.c python/branches/p3yk-noslice/Python/compile.c python/branches/p3yk-noslice/Python/graminit.c python/branches/p3yk-noslice/Python/symtable.c python/branches/p3yk-noslice/Tools/audiopy/audiopy python/branches/p3yk-noslice/Tools/bgen/bgen/scantools.py python/branches/p3yk-noslice/Tools/compiler/compile.py python/branches/p3yk-noslice/Tools/compiler/regrtest.py python/branches/p3yk-noslice/Tools/faqwiz/faqw.py python/branches/p3yk-noslice/Tools/faqwiz/faqwiz.py python/branches/p3yk-noslice/Tools/freeze/checkextensions_win32.py python/branches/p3yk-noslice/Tools/freeze/freeze.py python/branches/p3yk-noslice/Tools/i18n/msgfmt.py python/branches/p3yk-noslice/Tools/i18n/pygettext.py python/branches/p3yk-noslice/Tools/pybench/CommandLine.py python/branches/p3yk-noslice/Tools/pybench/pybench.py python/branches/p3yk-noslice/Tools/pynche/Main.py python/branches/p3yk-noslice/Tools/scripts/byext.py python/branches/p3yk-noslice/Tools/scripts/byteyears.py python/branches/p3yk-noslice/Tools/scripts/checkappend.py python/branches/p3yk-noslice/Tools/scripts/classfix.py python/branches/p3yk-noslice/Tools/scripts/cleanfuture.py python/branches/p3yk-noslice/Tools/scripts/cvsfiles.py python/branches/p3yk-noslice/Tools/scripts/dutree.py python/branches/p3yk-noslice/Tools/scripts/finddiv.py python/branches/p3yk-noslice/Tools/scripts/findlinksto.py python/branches/p3yk-noslice/Tools/scripts/findnocoding.py python/branches/p3yk-noslice/Tools/scripts/fixcid.py python/branches/p3yk-noslice/Tools/scripts/fixdiv.py python/branches/p3yk-noslice/Tools/scripts/fixheader.py python/branches/p3yk-noslice/Tools/scripts/fixnotice.py python/branches/p3yk-noslice/Tools/scripts/fixps.py python/branches/p3yk-noslice/Tools/scripts/ftpmirror.py python/branches/p3yk-noslice/Tools/scripts/linktree.py python/branches/p3yk-noslice/Tools/scripts/logmerge.py python/branches/p3yk-noslice/Tools/scripts/md5sum.py python/branches/p3yk-noslice/Tools/scripts/methfix.py python/branches/p3yk-noslice/Tools/scripts/ndiff.py python/branches/p3yk-noslice/Tools/scripts/pathfix.py python/branches/p3yk-noslice/Tools/scripts/pindent.py python/branches/p3yk-noslice/Tools/scripts/pysource.py python/branches/p3yk-noslice/Tools/scripts/redemo.py python/branches/p3yk-noslice/Tools/scripts/reindent.py python/branches/p3yk-noslice/Tools/scripts/rgrep.py python/branches/p3yk-noslice/Tools/scripts/texi2html.py python/branches/p3yk-noslice/Tools/scripts/treesync.py python/branches/p3yk-noslice/Tools/scripts/untabify.py python/branches/p3yk-noslice/Tools/unicode/comparecodecs.py python/branches/p3yk-noslice/Tools/unicode/gencodec.py python/branches/p3yk-noslice/Tools/unicode/listcodecs.py python/branches/p3yk-noslice/Tools/versioncheck/pyversioncheck.py python/branches/p3yk-noslice/Tools/webchecker/wcgui.py python/branches/p3yk-noslice/Tools/webchecker/webchecker.py python/branches/p3yk-noslice/Tools/webchecker/websucker.py python/branches/p3yk-noslice/setup.py Log: ... and another merge with the p3yk branch for good measure. Merged revisions 53334-53363 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/p3yk ........ r53335 | guido.van.rossum | 2007-01-10 02:28:32 +0100 (Wed, 10 Jan 2007) | 2 lines Excise the sets module. SF #1500611 by Collin Winter. ........ r53336 | guido.van.rossum | 2007-01-10 02:29:06 +0100 (Wed, 10 Jan 2007) | 2 lines News about removal of the sets module. ........ r53342 | guido.van.rossum | 2007-01-10 17:19:56 +0100 (Wed, 10 Jan 2007) | 5 lines SF patch 1631942 by Collin Winter: (a) "except E, V" -> "except E as V" (b) V is now limited to a simple name (local variable) (c) V is now deleted at the end of the except block ........ r53349 | guido.van.rossum | 2007-01-10 19:51:35 +0100 (Wed, 10 Jan 2007) | 3 lines Some more changes related to the new except syntax and semantics, by Collin Winter. ........ Modified: python/branches/p3yk-noslice/Demo/cgi/wiki.py ============================================================================== --- python/branches/p3yk-noslice/Demo/cgi/wiki.py (original) +++ python/branches/p3yk-noslice/Demo/cgi/wiki.py Thu Jan 11 00:43:10 2007 @@ -119,5 +119,5 @@ f.write('\n') f.close() return "" - except IOError, err: + except IOError as err: return "IOError: %s" % str(err) Modified: python/branches/p3yk-noslice/Demo/comparisons/regextest.py ============================================================================== --- python/branches/p3yk-noslice/Demo/comparisons/regextest.py (original) +++ python/branches/p3yk-noslice/Demo/comparisons/regextest.py Thu Jan 11 00:43:10 2007 @@ -28,7 +28,7 @@ for file in sys.argv[1:]: try: fp = open(file, 'r') - except IOError, msg: + except IOError as msg: print "%s: %s" % (file, msg) continue lineno = 0 Modified: python/branches/p3yk-noslice/Demo/comparisons/systemtest.py ============================================================================== --- python/branches/p3yk-noslice/Demo/comparisons/systemtest.py (original) +++ python/branches/p3yk-noslice/Demo/comparisons/systemtest.py Thu Jan 11 00:43:10 2007 @@ -41,7 +41,7 @@ def reportboguslinks(prefix): try: names = os.listdir('.') - except os.error, msg: + except os.error as msg: print "%s%s: can't list: %s" % (prefix, '.', msg) return names.sort() @@ -62,7 +62,7 @@ elif S_ISDIR(mode): try: os.chdir(name) - except os.error, msg: + except os.error as msg: print "%s%s: can't chdir: %s" % \ (prefix, name, msg) continue Modified: python/branches/p3yk-noslice/Demo/parser/test_parser.py ============================================================================== --- python/branches/p3yk-noslice/Demo/parser/test_parser.py (original) +++ python/branches/p3yk-noslice/Demo/parser/test_parser.py Thu Jan 11 00:43:10 2007 @@ -17,7 +17,7 @@ # against a large source file like Tkinter.py. ast = None new = parser.tuple2ast(tup) - except parser.ParserError, err: + except parser.ParserError as err: print print 'parser module raised exception on input file', fileName + ':' traceback.print_exc() Modified: python/branches/p3yk-noslice/Demo/parser/unparse.py ============================================================================== --- python/branches/p3yk-noslice/Demo/parser/unparse.py (original) +++ python/branches/p3yk-noslice/Demo/parser/unparse.py Thu Jan 11 00:43:10 2007 @@ -492,7 +492,7 @@ print 'Testing %s' % fullname try: roundtrip(fullname, output) - except Exception, e: + except Exception as e: print ' Failed to compile, exception is %s' % repr(e) elif os.path.isdir(fullname): testdir(fullname) Modified: python/branches/p3yk-noslice/Demo/pdist/FSProxy.py ============================================================================== --- python/branches/p3yk-noslice/Demo/pdist/FSProxy.py (original) +++ python/branches/p3yk-noslice/Demo/pdist/FSProxy.py Thu Jan 11 00:43:10 2007 @@ -87,7 +87,7 @@ fs = macfs.FSSpec(name) c, t = fs.GetCreatorType() if t != 'TEXT': return 0 - except macfs.error, msg: + except macfs.error as msg: print "***", name, msg return 0 else: Modified: python/branches/p3yk-noslice/Demo/pdist/cmdfw.py ============================================================================== --- python/branches/p3yk-noslice/Demo/pdist/cmdfw.py (original) +++ python/branches/p3yk-noslice/Demo/pdist/cmdfw.py Thu Jan 11 00:43:10 2007 @@ -42,7 +42,7 @@ if args is None: args = sys.argv[1:] try: opts, args = getopt.getopt(args, self.GlobalFlags) - except getopt.error, msg: + except getopt.error as msg: return self.usage(msg) self.options(opts) if not args: @@ -62,7 +62,7 @@ flags = '' try: opts, args = getopt.getopt(args[1:], flags) - except getopt.error, msg: + except getopt.error as msg: return self.usage( "subcommand %s: " % cmd + str(msg)) self.ready() Modified: python/branches/p3yk-noslice/Demo/pdist/cmptree.py ============================================================================== --- python/branches/p3yk-noslice/Demo/pdist/cmptree.py (original) +++ python/branches/p3yk-noslice/Demo/pdist/cmptree.py Thu Jan 11 00:43:10 2007 @@ -135,7 +135,7 @@ def sendfile(local, remote, name): try: remote.create(name) - except (IOError, os.error), msg: + except (IOError, os.error) as msg: print "cannot create:", msg return @@ -171,7 +171,7 @@ def recvfile_real(local, remote, name): try: local.create(name) - except (IOError, os.error), msg: + except (IOError, os.error) as msg: print "cannot create:", msg return Modified: python/branches/p3yk-noslice/Demo/pdist/cvslock.py ============================================================================== --- python/branches/p3yk-noslice/Demo/pdist/cvslock.py (original) +++ python/branches/p3yk-noslice/Demo/pdist/cvslock.py Thu Jan 11 00:43:10 2007 @@ -129,7 +129,7 @@ self.lockdir = self.cvslck os.mkdir(self.cvslck, 0777) return - except os.error, msg: + except os.error as msg: self.lockdir = None if msg[0] == EEXIST: try: @@ -234,7 +234,7 @@ for r in repositories: try: locks.append(WriteLock(r, 0)) - except Locked, instance: + except Locked as instance: del locks break else: Modified: python/branches/p3yk-noslice/Demo/pdist/rrcs.py ============================================================================== --- python/branches/p3yk-noslice/Demo/pdist/rrcs.py (original) +++ python/branches/p3yk-noslice/Demo/pdist/rrcs.py Thu Jan 11 00:43:10 2007 @@ -22,7 +22,7 @@ raise getopt.error, "unknown command" coptset, func = commands[cmd] copts, files = getopt.getopt(rest, coptset) - except getopt.error, msg: + except getopt.error as msg: print msg print "usage: rrcs [options] command [options] [file] ..." print "where command can be:" @@ -41,7 +41,7 @@ for fn in files: try: func(x, copts, fn) - except (IOError, os.error), msg: + except (IOError, os.error) as msg: print "%s: %s" % (fn, msg) def checkin(x, copts, fn): Modified: python/branches/p3yk-noslice/Demo/pysvr/pysvr.py ============================================================================== --- python/branches/p3yk-noslice/Demo/pysvr/pysvr.py (original) +++ python/branches/p3yk-noslice/Demo/pysvr/pysvr.py Thu Jan 11 00:43:10 2007 @@ -21,14 +21,14 @@ opts, args = getopt.getopt(sys.argv[1:], "") if len(args) > 1: raise getopt.error, "Too many arguments." - except getopt.error, msg: + except getopt.error as msg: usage(msg) for o, a in opts: pass if args: try: port = string.atoi(args[0]) - except ValueError, msg: + except ValueError as msg: usage(msg) else: port = PORT @@ -83,7 +83,7 @@ source = source + line try: code = compile_command(source) - except SyntaxError, err: + except SyntaxError as err: source = "" traceback.print_exception(SyntaxError, err, None, file=stdout) continue @@ -92,7 +92,7 @@ source = "" try: run_command(code, stdin, stdout, globals) - except SystemExit, how: + except SystemExit as how: if how: try: how = str(how) @@ -109,7 +109,7 @@ sys.stdin = stdin try: exec(code, globals) - except SystemExit, how: + except SystemExit as how: raise SystemExit, how, sys.exc_info()[2] except: type, value, tb = sys.exc_info() Modified: python/branches/p3yk-noslice/Demo/rpc/nfsclient.py ============================================================================== --- python/branches/p3yk-noslice/Demo/rpc/nfsclient.py (original) +++ python/branches/p3yk-noslice/Demo/rpc/nfsclient.py Thu Jan 11 00:43:10 2007 @@ -194,8 +194,7 @@ fh = sf[1] if fh: ncl = NFSClient(host) - as = ncl.Getattr(fh) - print as + print ncl.Getattr(fh) list = ncl.Listdir(fh) for item in list: print item mcl.Umnt(filesys) Modified: python/branches/p3yk-noslice/Demo/rpc/rpc.py ============================================================================== --- python/branches/p3yk-noslice/Demo/rpc/rpc.py (original) +++ python/branches/p3yk-noslice/Demo/rpc/rpc.py Thu Jan 11 00:43:10 2007 @@ -330,7 +330,8 @@ try: sock.bind((host, i)) return last_resv_port_tried - except socket.error, (errno, msg): + except socket.error as e: + (errno, msg) = e if errno != 114: raise socket.error, (errno, msg) raise RuntimeError, 'can\'t assign reserved port' @@ -765,7 +766,7 @@ call = recvrecord(sock) except EOFError: break - except socket.error, msg: + except socket.error as msg: print 'socket error:', msg break reply = self.handle(call) @@ -866,7 +867,7 @@ s = S('', 0x20000000, 1, 0) try: s.unregister() - except RuntimeError, msg: + except RuntimeError as msg: print 'RuntimeError:', msg, '(ignored)' s.register() print 'Service started...' Modified: python/branches/p3yk-noslice/Demo/scripts/eqfix.py ============================================================================== --- python/branches/p3yk-noslice/Demo/scripts/eqfix.py (original) +++ python/branches/p3yk-noslice/Demo/scripts/eqfix.py Thu Jan 11 00:43:10 2007 @@ -62,7 +62,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() @@ -83,7 +83,7 @@ ## dbg('fix(%r)\n' % (dirname,)) try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 head, tail = os.path.split(filename) @@ -120,7 +120,7 @@ if g is None: try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 @@ -144,17 +144,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes Modified: python/branches/p3yk-noslice/Demo/scripts/ftpstats.py ============================================================================== --- python/branches/p3yk-noslice/Demo/scripts/ftpstats.py (original) +++ python/branches/p3yk-noslice/Demo/scripts/ftpstats.py Thu Jan 11 00:43:10 2007 @@ -25,7 +25,7 @@ search = None try: opts, args = getopt.getopt(sys.argv[1:], 'm:s:') - except getopt.error, msg: + except getopt.error as msg: print msg print 'usage: ftpstats [-m maxitems] [file]' sys.exit(2) @@ -41,7 +41,7 @@ else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ':', msg sys.exit(1) bydate = {} Modified: python/branches/p3yk-noslice/Demo/scripts/mboxconvert.py ============================================================================== --- python/branches/p3yk-noslice/Demo/scripts/mboxconvert.py (original) +++ python/branches/p3yk-noslice/Demo/scripts/mboxconvert.py Thu Jan 11 00:43:10 2007 @@ -16,7 +16,7 @@ dofile = mmdf try: opts, args = getopt.getopt(sys.argv[1:], 'f') - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write('%s\n' % msg) sys.exit(2) for o, a in opts: @@ -33,7 +33,7 @@ elif os.path.isfile(arg): try: f = open(arg) - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: %s\n' % (arg, msg)) sts = 1 continue @@ -56,7 +56,7 @@ fn = os.path.join(dir, msg) try: f = open(fn) - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: %s\n' % (fn, msg)) sts = 1 continue Modified: python/branches/p3yk-noslice/Demo/scripts/newslist.py ============================================================================== --- python/branches/p3yk-noslice/Demo/scripts/newslist.py (original) +++ python/branches/p3yk-noslice/Demo/scripts/newslist.py Thu Jan 11 00:43:10 2007 @@ -330,7 +330,7 @@ else: s = NNTP(newshost) connected = 1 - except (nntplib.error_temp, nntplib.error_perm), x: + except (nntplib.error_temp, nntplib.error_perm) as x: print 'Error connecting to host:', x print 'I\'ll try to use just the local list.' connected = 0 Modified: python/branches/p3yk-noslice/Demo/scripts/pp.py ============================================================================== --- python/branches/p3yk-noslice/Demo/scripts/pp.py (original) +++ python/branches/p3yk-noslice/Demo/scripts/pp.py Thu Jan 11 00:43:10 2007 @@ -35,7 +35,7 @@ try: optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np') -except getopt.error, msg: +except getopt.error as msg: sys.stderr.write(sys.argv[0] + ': ' + msg + '\n') sys.exit(2) Modified: python/branches/p3yk-noslice/Demo/scripts/update.py ============================================================================== --- python/branches/p3yk-noslice/Demo/scripts/update.py (original) +++ python/branches/p3yk-noslice/Demo/scripts/update.py Thu Jan 11 00:43:10 2007 @@ -19,7 +19,7 @@ self.changed = 0 try: self.lines = open(filename, 'r').readlines() - except IOError, msg: + except IOError as msg: print '*** Can\'t open "%s":' % filename, msg self.lines = None return @@ -32,7 +32,7 @@ try: os.rename(self.filename, self.filename + '~') fp = open(self.filename, 'w') - except (os.error, IOError), msg: + except (os.error, IOError) as msg: print '*** Can\'t rewrite "%s":' % self.filename, msg return print 'writing', self.filename @@ -67,7 +67,7 @@ if sys.argv[1:]: try: fp = open(sys.argv[1], 'r') - except IOError, msg: + except IOError as msg: print 'Can\'t open "%s":' % sys.argv[1], msg sys.exit(1) else: Modified: python/branches/p3yk-noslice/Demo/sockets/gopher.py ============================================================================== --- python/branches/p3yk-noslice/Demo/sockets/gopher.py (original) +++ python/branches/p3yk-noslice/Demo/sockets/gopher.py Thu Jan 11 00:43:10 2007 @@ -142,7 +142,7 @@ raise RuntimeError, 'too many args' try: browse_menu(selector, host, port) - except socket.error, msg: + except socket.error as msg: print 'Socket error:', msg sys.exit(1) except KeyboardInterrupt: @@ -202,7 +202,7 @@ p = os.popen('${PAGER-more}', 'w') x = SaveLines(p) get_alt_textfile(selector, host, port, x.writeln) - except IOError, msg: + except IOError as msg: print 'IOError:', msg if x: x.close() @@ -213,7 +213,7 @@ try: get_alt_textfile(selector, host, port, x.writeln) print 'Done.' - except IOError, msg: + except IOError as msg: print 'IOError:', msg x.close() @@ -311,7 +311,7 @@ cmd = savefile[1:].strip() try: p = os.popen(cmd, 'w') - except IOError, msg: + except IOError as msg: print repr(cmd), ':', msg return None print 'Piping through', repr(cmd), '...' @@ -320,7 +320,7 @@ savefile = os.path.expanduser(savefile) try: f = open(savefile, 'w') - except IOError, msg: + except IOError as msg: print repr(savefile), ':', msg return None print 'Saving to', repr(savefile), '...' Modified: python/branches/p3yk-noslice/Demo/sockets/telnet.py ============================================================================== --- python/branches/p3yk-noslice/Demo/sockets/telnet.py (original) +++ python/branches/p3yk-noslice/Demo/sockets/telnet.py Thu Jan 11 00:43:10 2007 @@ -52,7 +52,7 @@ # try: s.connect((host, port)) - except error, msg: + except error as msg: sys.stderr.write('connect failed: ' + repr(msg) + '\n') sys.exit(1) # Modified: python/branches/p3yk-noslice/Demo/threads/find.py ============================================================================== --- python/branches/p3yk-noslice/Demo/threads/find.py (original) +++ python/branches/p3yk-noslice/Demo/threads/find.py Thu Jan 11 00:43:10 2007 @@ -131,7 +131,7 @@ def find(dir, pred, wq): try: names = os.listdir(dir) - except os.error, msg: + except os.error as msg: print repr(dir), ':', msg return for name in names: @@ -139,7 +139,7 @@ fullname = os.path.join(dir, name) try: stat = os.lstat(fullname) - except os.error, msg: + except os.error as msg: print repr(fullname), ':', msg continue if pred(dir, name, fullname, stat): Modified: python/branches/p3yk-noslice/Demo/threads/telnet.py ============================================================================== --- python/branches/p3yk-noslice/Demo/threads/telnet.py (original) +++ python/branches/p3yk-noslice/Demo/threads/telnet.py Thu Jan 11 00:43:10 2007 @@ -56,7 +56,7 @@ # try: s.connect((host, port)) - except error, msg: + except error as msg: sys.stderr.write('connect failed: %r\n' % (msg,)) sys.exit(1) # Modified: python/branches/p3yk-noslice/Demo/tkinter/guido/AttrDialog.py ============================================================================== --- python/branches/p3yk-noslice/Demo/tkinter/guido/AttrDialog.py (original) +++ python/branches/p3yk-noslice/Demo/tkinter/guido/AttrDialog.py Thu Jan 11 00:43:10 2007 @@ -156,7 +156,7 @@ self.current = self.var.get() try: self.dialog.widget.pack(**{self.option: self.current}) - except TclError, msg: + except TclError as msg: print msg self.refresh() @@ -212,7 +212,7 @@ 'pack', 'info', self.widget)) - except TclError, msg: + except TclError as msg: print msg return dict = {} @@ -239,7 +239,7 @@ '-'+self.option, self.dialog.master.tk.merge( self.current)) - except TclError, msg: + except TclError as msg: print msg self.refresh() @@ -285,7 +285,7 @@ self.current = self.var.get() try: self.dialog.widget[self.option] = self.current - except TclError, msg: + except TclError as msg: print msg self.refresh() @@ -374,7 +374,7 @@ self.master.send(self.app, self.widget, 'config')) - except TclError, msg: + except TclError as msg: print msg return dict = {} @@ -398,7 +398,7 @@ 'config', '-'+self.option, self.current) - except TclError, msg: + except TclError as msg: print msg self.refresh() @@ -445,7 +445,7 @@ if widget == '.': continue try: RemotePackDialog(list, list.app, widget) - except TclError, msg: + except TclError as msg: print msg test() Modified: python/branches/p3yk-noslice/Demo/tkinter/guido/ManPage.py ============================================================================== --- python/branches/p3yk-noslice/Demo/tkinter/guido/ManPage.py (original) +++ python/branches/p3yk-noslice/Demo/tkinter/guido/ManPage.py Thu Jan 11 00:43:10 2007 @@ -95,7 +95,7 @@ self._parseline('') try: self.tk.deletefilehandler(self.fp) - except TclError, msg: + except TclError as msg: pass self.fp.close() self.fp = None Modified: python/branches/p3yk-noslice/Demo/tkinter/guido/mbox.py ============================================================================== --- python/branches/p3yk-noslice/Demo/tkinter/guido/mbox.py (original) +++ python/branches/p3yk-noslice/Demo/tkinter/guido/mbox.py Thu Jan 11 00:43:10 2007 @@ -27,7 +27,7 @@ seq = 'all' try: opts, args = getopt.getopt(sys.argv[1:], '') - except getopt.error, msg: + except getopt.error as msg: print msg sys.exit(2) for arg in args: Modified: python/branches/p3yk-noslice/Demo/tkinter/guido/tkman.py ============================================================================== --- python/branches/p3yk-noslice/Demo/tkinter/guido/tkman.py (original) +++ python/branches/p3yk-noslice/Demo/tkinter/guido/tkman.py Thu Jan 11 00:43:10 2007 @@ -216,7 +216,7 @@ prog = re.compile(search, map) else: prog = re.compile(search) - except re.error, msg: + except re.error as msg: self.frame.bell() print 'Regex error:', msg return Modified: python/branches/p3yk-noslice/Demo/tkinter/guido/wish.py ============================================================================== --- python/branches/p3yk-noslice/Demo/tkinter/guido/wish.py (original) +++ python/branches/p3yk-noslice/Demo/tkinter/guido/wish.py Thu Jan 11 00:43:10 2007 @@ -23,7 +23,7 @@ tk.record(line) try: result = tk.call('eval', cmd) - except _tkinter.TclError, msg: + except _tkinter.TclError as msg: print 'TclError:', msg else: if result: print result Modified: python/branches/p3yk-noslice/Doc/Makefile.deps ============================================================================== --- python/branches/p3yk-noslice/Doc/Makefile.deps (original) +++ python/branches/p3yk-noslice/Doc/Makefile.deps Thu Jan 11 00:43:10 2007 @@ -109,7 +109,6 @@ lib/libplatform.tex \ lib/libfpectl.tex \ lib/libgc.tex \ - lib/libsets.tex \ lib/libweakref.tex \ lib/libinspect.tex \ lib/libpydoc.tex \ Modified: python/branches/p3yk-noslice/Doc/howto/urllib2.rst ============================================================================== --- python/branches/p3yk-noslice/Doc/howto/urllib2.rst (original) +++ python/branches/p3yk-noslice/Doc/howto/urllib2.rst Thu Jan 11 00:43:10 2007 @@ -214,7 +214,7 @@ >>> req = urllib2.Request('http://www.pretend_server.org') >>> try: urllib2.urlopen(req) - >>> except URLError, e: + >>> except URLError as e: >>> print e.reason >>> (4, 'getaddrinfo failed') @@ -326,7 +326,7 @@ >>> req = urllib2.Request('http://www.python.org/fish.html') >>> try: >>> urllib2.urlopen(req) - >>> except URLError, e: + >>> except URLError as e: >>> print e.code >>> print e.read() >>> @@ -354,10 +354,10 @@ req = Request(someurl) try: response = urlopen(req) - except HTTPError, e: + except HTTPError as e: print 'The server couldn\'t fulfill the request.' print 'Error code: ', e.code - except URLError, e: + except URLError as e: print 'We failed to reach a server.' print 'Reason: ', e.reason else: @@ -378,7 +378,7 @@ req = Request(someurl) try: response = urlopen(req) - except URLError, e: + except URLError as e: if hasattr(e, 'reason'): print 'We failed to reach a server.' print 'Reason: ', e.reason Modified: python/branches/p3yk-noslice/Doc/lib/email-unpack.py ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/email-unpack.py (original) +++ python/branches/p3yk-noslice/Doc/lib/email-unpack.py Thu Jan 11 00:43:10 2007 @@ -35,7 +35,7 @@ try: os.mkdir(opts.directory) - except OSError, e: + except OSError as e: # Ignore directory exists error if e.errno != errno.EEXIST: raise Modified: python/branches/p3yk-noslice/Doc/lib/lib.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/lib.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/lib.tex Thu Jan 11 00:43:10 2007 @@ -104,7 +104,6 @@ \input{libheapq} \input{libbisect} \input{libarray} -\input{libsets} \input{libsched} \input{libmutex} \input{libqueue} Modified: python/branches/p3yk-noslice/Doc/lib/libcsv.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libcsv.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libcsv.tex Thu Jan 11 00:43:10 2007 @@ -426,7 +426,7 @@ try: for row in reader: print row -except csv.Error, e: +except csv.Error as e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) \end{verbatim} Modified: python/branches/p3yk-noslice/Doc/lib/libgetopt.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libgetopt.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libgetopt.tex Thu Jan 11 00:43:10 2007 @@ -126,7 +126,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() Modified: python/branches/p3yk-noslice/Doc/lib/libsets.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libsets.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libsets.tex Thu Jan 11 00:43:10 2007 @@ -1,264 +0,0 @@ -\section{\module{sets} --- - Unordered collections of unique elements} - -\declaremodule{standard}{sets} -\modulesynopsis{Implementation of sets of unique elements.} -\moduleauthor{Greg V. Wilson}{gvwilson at nevex.com} -\moduleauthor{Alex Martelli}{aleax at aleax.it} -\moduleauthor{Guido van Rossum}{guido at python.org} -\sectionauthor{Raymond D. Hettinger}{python at rcn.com} - -\versionadded{2.3} - -The \module{sets} module provides classes for constructing and manipulating -unordered collections of unique elements. Common uses include membership -testing, removing duplicates from a sequence, and computing standard math -operations on sets such as intersection, union, difference, and symmetric -difference. - -Like other collections, sets support \code{\var{x} in \var{set}}, -\code{len(\var{set})}, and \code{for \var{x} in \var{set}}. Being an -unordered collection, sets do not record element position or order of -insertion. Accordingly, sets do not support indexing, slicing, or -other sequence-like behavior. - -Most set applications use the \class{Set} class which provides every set -method except for \method{__hash__()}. For advanced applications requiring -a hash method, the \class{ImmutableSet} class adds a \method{__hash__()} -method but omits methods which alter the contents of the set. Both -\class{Set} and \class{ImmutableSet} derive from \class{BaseSet}, an -abstract class useful for determining whether something is a set: -\code{isinstance(\var{obj}, BaseSet)}. - -The set classes are implemented using dictionaries. Accordingly, the -requirements for set elements are the same as those for dictionary keys; -namely, that the element defines both \method{__eq__} and \method{__hash__}. -As a result, sets -cannot contain mutable elements such as lists or dictionaries. -However, they can contain immutable collections such as tuples or -instances of \class{ImmutableSet}. For convenience in implementing -sets of sets, inner sets are automatically converted to immutable -form, for example, \code{Set([Set(['dog'])])} is transformed to -\code{Set([ImmutableSet(['dog'])])}. - -\begin{classdesc}{Set}{\optional{iterable}} -Constructs a new empty \class{Set} object. If the optional \var{iterable} -parameter is supplied, updates the set with elements obtained from iteration. -All of the elements in \var{iterable} should be immutable or be transformable -to an immutable using the protocol described in -section~\ref{immutable-transforms}. -\end{classdesc} - -\begin{classdesc}{ImmutableSet}{\optional{iterable}} -Constructs a new empty \class{ImmutableSet} object. If the optional -\var{iterable} parameter is supplied, updates the set with elements obtained -from iteration. All of the elements in \var{iterable} should be immutable or -be transformable to an immutable using the protocol described in -section~\ref{immutable-transforms}. - -Because \class{ImmutableSet} objects provide a \method{__hash__()} method, -they can be used as set elements or as dictionary keys. \class{ImmutableSet} -objects do not have methods for adding or removing elements, so all of the -elements must be known when the constructor is called. -\end{classdesc} - - -\subsection{Set Objects \label{set-objects}} - -Instances of \class{Set} and \class{ImmutableSet} both provide -the following operations: - -\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result} - \lineiii{len(\var{s})}{}{cardinality of set \var{s}} - - \hline - \lineiii{\var{x} in \var{s}}{} - {test \var{x} for membership in \var{s}} - \lineiii{\var{x} not in \var{s}}{} - {test \var{x} for non-membership in \var{s}} - \lineiii{\var{s}.issubset(\var{t})}{\code{\var{s} <= \var{t}}} - {test whether every element in \var{s} is in \var{t}} - \lineiii{\var{s}.issuperset(\var{t})}{\code{\var{s} >= \var{t}}} - {test whether every element in \var{t} is in \var{s}} - - \hline - \lineiii{\var{s}.union(\var{t})}{\var{s} \textbar{} \var{t}} - {new set with elements from both \var{s} and \var{t}} - \lineiii{\var{s}.intersection(\var{t})}{\var{s} \&\ \var{t}} - {new set with elements common to \var{s} and \var{t}} - \lineiii{\var{s}.difference(\var{t})}{\var{s} - \var{t}} - {new set with elements in \var{s} but not in \var{t}} - \lineiii{\var{s}.symmetric_difference(\var{t})}{\var{s} \^\ \var{t}} - {new set with elements in either \var{s} or \var{t} but not both} - \lineiii{\var{s}.copy()}{} - {new set with a shallow copy of \var{s}} -\end{tableiii} - -Note, the non-operator versions of \method{union()}, -\method{intersection()}, \method{difference()}, and -\method{symmetric_difference()} will accept any iterable as an argument. -In contrast, their operator based counterparts require their arguments to -be sets. This precludes error-prone constructions like -\code{Set('abc') \&\ 'cbs'} in favor of the more readable -\code{Set('abc').intersection('cbs')}. -\versionchanged[Formerly all arguments were required to be sets]{2.3.1} - -In addition, both \class{Set} and \class{ImmutableSet} -support set to set comparisons. Two sets are equal if and only if -every element of each set is contained in the other (each is a subset -of the other). -A set is less than another set if and only if the first set is a proper -subset of the second set (is a subset, but is not equal). -A set is greater than another set if and only if the first set is a proper -superset of the second set (is a superset, but is not equal). - -The subset and equality comparisons do not generalize to a complete -ordering function. For example, any two disjoint sets are not equal and -are not subsets of each other, so \emph{all} of the following return -\code{False}: \code{\var{a}<\var{b}}, \code{\var{a}==\var{b}}, or -\code{\var{a}>\var{b}}. -Accordingly, sets do not implement the \method{__cmp__} method. - -Since sets only define partial ordering (subset relationships), the output -of the \method{list.sort()} method is undefined for lists of sets. - -The following table lists operations available in \class{ImmutableSet} -but not found in \class{Set}: - -\begin{tableii}{c|l}{code}{Operation}{Result} - \lineii{hash(\var{s})}{returns a hash value for \var{s}} -\end{tableii} - -The following table lists operations available in \class{Set} -but not found in \class{ImmutableSet}: - -\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result} - \lineiii{\var{s}.update(\var{t})} - {\var{s} \textbar= \var{t}} - {return set \var{s} with elements added from \var{t}} - \lineiii{\var{s}.intersection_update(\var{t})} - {\var{s} \&= \var{t}} - {return set \var{s} keeping only elements also found in \var{t}} - \lineiii{\var{s}.difference_update(\var{t})} - {\var{s} -= \var{t}} - {return set \var{s} after removing elements found in \var{t}} - \lineiii{\var{s}.symmetric_difference_update(\var{t})} - {\var{s} \textasciicircum= \var{t}} - {return set \var{s} with elements from \var{s} or \var{t} - but not both} - - \hline - \lineiii{\var{s}.add(\var{x})}{} - {add element \var{x} to set \var{s}} - \lineiii{\var{s}.remove(\var{x})}{} - {remove \var{x} from set \var{s}; raises \exception{KeyError} - if not present} - \lineiii{\var{s}.discard(\var{x})}{} - {removes \var{x} from set \var{s} if present} - \lineiii{\var{s}.pop()}{} - {remove and return an arbitrary element from \var{s}; raises - \exception{KeyError} if empty} - \lineiii{\var{s}.clear()}{} - {remove all elements from set \var{s}} -\end{tableiii} - -Note, the non-operator versions of \method{update()}, -\method{intersection_update()}, \method{difference_update()}, and -\method{symmetric_difference_update()} will accept any iterable as -an argument. -\versionchanged[Formerly all arguments were required to be sets]{2.3.1} - -Also note, the module also includes a \method{union_update()} method -which is an alias for \method{update()}. The method is included for -backwards compatibility. Programmers should prefer the -\method{update()} method because it is supported by the builtin -\class{set()} and \class{frozenset()} types. - -\subsection{Example \label{set-example}} - -\begin{verbatim} ->>> from sets import Set ->>> engineers = Set(['John', 'Jane', 'Jack', 'Janice']) ->>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice']) ->>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack']) ->>> employees = engineers | programmers | managers # union ->>> engineering_management = engineers & managers # intersection ->>> fulltime_management = managers - engineers - programmers # difference ->>> engineers.add('Marvin') # add element ->>> print engineers -Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack']) ->>> employees.issuperset(engineers) # superset test -False ->>> employees.union_update(engineers) # update from another set ->>> employees.issuperset(engineers) -True ->>> for group in [engineers, programmers, managers, employees]: -... group.discard('Susan') # unconditionally remove element -... print group -... -Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack']) -Set(['Janice', 'Jack', 'Sam']) -Set(['Jane', 'Zack', 'Jack']) -Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack']) -\end{verbatim} - - -\subsection{Protocol for automatic conversion to immutable - \label{immutable-transforms}} - -Sets can only contain immutable elements. For convenience, mutable -\class{Set} objects are automatically copied to an \class{ImmutableSet} -before being added as a set element. - -The mechanism is to always add a hashable element, or if it is not -hashable, the element is checked to see if it has an -\method{__as_immutable__()} method which returns an immutable equivalent. - -Since \class{Set} objects have a \method{__as_immutable__()} method -returning an instance of \class{ImmutableSet}, it is possible to -construct sets of sets. - -A similar mechanism is needed by the \method{__contains__()} and -\method{remove()} methods which need to hash an element to check -for membership in a set. Those methods check an element for hashability -and, if not, check for a \method{__as_temporarily_immutable__()} method -which returns the element wrapped by a class that provides temporary -methods for \method{__hash__()}, \method{__eq__()}, and \method{__ne__()}. - -The alternate mechanism spares the need to build a separate copy of -the original mutable object. - -\class{Set} objects implement the \method{__as_temporarily_immutable__()} -method which returns the \class{Set} object wrapped by a new class -\class{_TemporarilyImmutableSet}. - -The two mechanisms for adding hashability are normally invisible to the -user; however, a conflict can arise in a multi-threaded environment -where one thread is updating a set while another has temporarily wrapped it -in \class{_TemporarilyImmutableSet}. In other words, sets of mutable sets -are not thread-safe. - - -\subsection{Comparison to the built-in \class{set} types - \label{comparison-to-builtin-set}} - -The built-in \class{set} and \class{frozenset} types were designed based -on lessons learned from the \module{sets} module. The key differences are: - -\begin{itemize} -\item \class{Set} and \class{ImmutableSet} were renamed to \class{set} and - \class{frozenset}. -\item There is no equivalent to \class{BaseSet}. Instead, use - \code{isinstance(x, (set, frozenset))}. -\item The hash algorithm for the built-ins performs significantly better - (fewer collisions) for most datasets. -\item The built-in versions have more space efficient pickles. -\item The built-in versions do not have a \method{union_update()} method. - Instead, use the \method{update()} method which is equivalent. -\item The built-in versions do not have a \method{_repr(sorted=True)} method. - Instead, use the built-in \function{repr()} and \function{sorted()} - functions: \code{repr(sorted(s))}. -\item The built-in version does not have a protocol for automatic conversion - to immutable. Many found this feature to be confusing and no one - in the community reported having found real uses for it. -\end{itemize} Modified: python/branches/p3yk-noslice/Doc/lib/libshutil.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libshutil.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libshutil.tex Thu Jan 11 00:43:10 2007 @@ -144,6 +144,6 @@ copytree(srcname, dstname, symlinks) else: copy2(srcname, dstname) - except (IOError, os.error), why: + except (IOError, os.error) as why: print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why)) \end{verbatim} Modified: python/branches/p3yk-noslice/Doc/lib/libsocket.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libsocket.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libsocket.tex Thu Jan 11 00:43:10 2007 @@ -813,13 +813,13 @@ af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) - except socket.error, msg: + except socket.error as msg: s = None continue try: s.bind(sa) s.listen(1) - except socket.error, msg: + except socket.error as msg: s.close() s = None continue @@ -848,12 +848,12 @@ af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) - except socket.error, msg: + except socket.error as msg: s = None continue try: s.connect(sa) - except socket.error, msg: + except socket.error as msg: s.close() s = None continue Modified: python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex Thu Jan 11 00:43:10 2007 @@ -1334,16 +1334,6 @@ \method{intersection_update()}, \method{difference_update()}, and \method{symmetric_difference_update()} methods will accept any iterable as an argument. - -The design of the set types was based on lessons learned from the -\module{sets} module. - -\begin{seealso} - \seelink{comparison-to-builtin-set.html} - {Comparison to the built-in set types} - {Differences between the \module{sets} module and the - built-in set types.} -\end{seealso} \section{Mapping Types --- \class{dict} \label{typesmapping}} Modified: python/branches/p3yk-noslice/Doc/lib/libsubprocess.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libsubprocess.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libsubprocess.tex Thu Jan 11 00:43:10 2007 @@ -284,7 +284,7 @@ print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode -except OSError, e: +except OSError as e: print >>sys.stderr, "Execution failed:", e \end{verbatim} Modified: python/branches/p3yk-noslice/Doc/lib/libxdrlib.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libxdrlib.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libxdrlib.tex Thu Jan 11 00:43:10 2007 @@ -246,6 +246,6 @@ p = xdrlib.Packer() try: p.pack_double(8.01) -except xdrlib.ConversionError, instance: +except xdrlib.ConversionError as instance: print 'packing the double failed:', instance.msg \end{verbatim} Modified: python/branches/p3yk-noslice/Doc/lib/libxmlrpclib.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/libxmlrpclib.tex (original) +++ python/branches/p3yk-noslice/Doc/lib/libxmlrpclib.tex Thu Jan 11 00:43:10 2007 @@ -358,7 +358,7 @@ try: print server.examples.getStateName(41) -except Error, v: +except Error as v: print "ERROR", v \end{verbatim} Modified: python/branches/p3yk-noslice/Doc/lib/sqlite3/complete_statement.py ============================================================================== --- python/branches/p3yk-noslice/Doc/lib/sqlite3/complete_statement.py (original) +++ python/branches/p3yk-noslice/Doc/lib/sqlite3/complete_statement.py Thu Jan 11 00:43:10 2007 @@ -23,7 +23,7 @@ if buffer.lstrip().upper().startswith("SELECT"): print cur.fetchall() - except sqlite3.Error, e: + except sqlite3.Error as e: print "An error occurred:", e.args[0] buffer = "" Modified: python/branches/p3yk-noslice/Doc/tools/findcsyms ============================================================================== --- python/branches/p3yk-noslice/Doc/tools/findcsyms (original) +++ python/branches/p3yk-noslice/Doc/tools/findcsyms Thu Jan 11 00:43:10 2007 @@ -127,7 +127,7 @@ print_list(undocumented, "Undocumented symbols") else: print_list(L) - except IOError, e: + except IOError as e: if e.errno != errno.EPIPE: raise Modified: python/branches/p3yk-noslice/Doc/tools/listmodules ============================================================================== --- python/branches/p3yk-noslice/Doc/tools/listmodules (original) +++ python/branches/p3yk-noslice/Doc/tools/listmodules Thu Jan 11 00:43:10 2007 @@ -53,7 +53,7 @@ opts, args = getopt.getopt( args, "abchi:", ["annotate", "built-in", "categorize", "help", "ignore-from="]) - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print Modified: python/branches/p3yk-noslice/Doc/tools/mkhowto ============================================================================== --- python/branches/p3yk-noslice/Doc/tools/mkhowto (original) +++ python/branches/p3yk-noslice/Doc/tools/mkhowto Thu Jan 11 00:43:10 2007 @@ -599,7 +599,7 @@ options = Options() try: args = options.parse(sys.argv[1:]) - except getopt.error, msg: + except getopt.error as msg: error(options, msg) if not args: # attempt to locate single .tex file in current directory: Modified: python/branches/p3yk-noslice/Doc/tools/mksourcepkg ============================================================================== --- python/branches/p3yk-noslice/Doc/tools/mksourcepkg (original) +++ python/branches/p3yk-noslice/Doc/tools/mksourcepkg Thu Jan 11 00:43:10 2007 @@ -45,7 +45,7 @@ opts, args = getopt.getopt(sys.argv[1:], "Aabgtzq", ["all", "bzip2", "gzip", "tools", "zip", "quiet", "anonymous"]) - except getopt.error, e: + except getopt.error as e: usage(warning=str(e)) sys.exit(2) if len(args) not in (1, 2): Modified: python/branches/p3yk-noslice/Doc/tools/prechm.py ============================================================================== --- python/branches/p3yk-noslice/Doc/tools/prechm.py (original) +++ python/branches/p3yk-noslice/Doc/tools/prechm.py Thu Jan 11 00:43:10 2007 @@ -448,7 +448,7 @@ def openfile(file): try: p = open(file, "w") - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) return p @@ -466,7 +466,7 @@ try: optlist, args = getopt.getopt(args, 'ckpv:') - except getopt.error, msg: + except getopt.error as msg: print msg usage() Modified: python/branches/p3yk-noslice/Doc/tools/sgmlconv/docfixer.py ============================================================================== --- python/branches/p3yk-noslice/Doc/tools/sgmlconv/docfixer.py (original) +++ python/branches/p3yk-noslice/Doc/tools/sgmlconv/docfixer.py Thu Jan 11 00:43:10 2007 @@ -1039,7 +1039,8 @@ # try: write_esis(fragment, ofp, knownempty) - except IOError, (err, msg): + except IOError as e: + (err, msg) = e # Ignore EPIPE; it just means that whoever we're writing to stopped # reading. The rest of the output would be ignored. All other errors # should still be reported, Modified: python/branches/p3yk-noslice/Doc/tools/sgmlconv/esis2sgml.py ============================================================================== --- python/branches/p3yk-noslice/Doc/tools/sgmlconv/esis2sgml.py (original) +++ python/branches/p3yk-noslice/Doc/tools/sgmlconv/esis2sgml.py Thu Jan 11 00:43:10 2007 @@ -255,7 +255,8 @@ if xml and xmldecl: opf.write('\n') convert(ifp, ofp, xml=xml, autoclose=autoclose, verbatims=verbatims) - except IOError, (err, msg): + except IOError as e: + (err, msg) = e if err != errno.EPIPE: raise Modified: python/branches/p3yk-noslice/Doc/tools/sgmlconv/esistools.py ============================================================================== --- python/branches/p3yk-noslice/Doc/tools/sgmlconv/esistools.py (original) +++ python/branches/p3yk-noslice/Doc/tools/sgmlconv/esistools.py Thu Jan 11 00:43:10 2007 @@ -139,7 +139,7 @@ def _get_token(self, fp): try: line = fp.readline() - except IOError, e: + except IOError as e: e = SAXException("I/O error reading input stream", e) self.getErrorHandler().fatalError(e) return Modified: python/branches/p3yk-noslice/Doc/tools/sgmlconv/latex2esis.py ============================================================================== --- python/branches/p3yk-noslice/Doc/tools/sgmlconv/latex2esis.py (original) +++ python/branches/p3yk-noslice/Doc/tools/sgmlconv/latex2esis.py Thu Jan 11 00:43:10 2007 @@ -397,7 +397,8 @@ c = Conversion(ifp, ofp, table) try: c.convert() - except IOError, (err, msg): + except IOError as e: + (err, msg) = e if err != errno.EPIPE: raise Modified: python/branches/p3yk-noslice/Doc/tut/tut.tex ============================================================================== --- python/branches/p3yk-noslice/Doc/tut/tut.tex (original) +++ python/branches/p3yk-noslice/Doc/tut/tut.tex Thu Jan 11 00:43:10 2007 @@ -3480,8 +3480,9 @@ f = open('myfile.txt') s = f.readline() i = int(s.strip()) -except IOError, (errno, strerror): - print "I/O error(%s): %s" % (errno, strerror) +except IOError as e: + (errno, strerror) = e + print "I/O error(%s): %s" % (e.errno, e.strerror) except ValueError: print "Could not convert data to an integer." except: @@ -3530,7 +3531,7 @@ \begin{verbatim} >>> try: ... raise Exception('spam', 'eggs') -... except Exception, inst: +... except Exception as inst: ... print type(inst) # the exception instance ... print inst.args # arguments stored in .args ... print inst # __str__ allows args to printed directly @@ -3559,7 +3560,7 @@ ... >>> try: ... this_fails() -... except ZeroDivisionError, detail: +... except ZeroDivisionError as detail: ... print 'Handling run-time error:', detail ... Handling run-time error: integer division or modulo by zero @@ -3619,7 +3620,7 @@ ... >>> try: ... raise MyError(2*2) -... except MyError, e: +... except MyError as e: ... print 'My exception occurred, value:', e.value ... My exception occurred, value: 4 Modified: python/branches/p3yk-noslice/Grammar/Grammar ============================================================================== --- python/branches/p3yk-noslice/Grammar/Grammar (original) +++ python/branches/p3yk-noslice/Grammar/Grammar Thu Jan 11 00:43:10 2007 @@ -79,7 +79,7 @@ with_stmt: 'with' test [ with_var ] ':' suite with_var: 'as' expr # NB compile.c makes sure that the default except clause is last -except_clause: 'except' [test [',' test]] +except_clause: 'except' [test ['as' NAME]] suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT # Backward compatibility cruft to support: 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 Thu Jan 11 00:43:10 2007 @@ -322,7 +322,7 @@ struct _excepthandler { expr_ty type; - expr_ty name; + identifier name; asdl_seq *body; int lineno; int col_offset; @@ -448,8 +448,8 @@ slice_ty Index(expr_ty value, PyArena *arena); comprehension_ty comprehension(expr_ty target, expr_ty iter, asdl_seq * ifs, PyArena *arena); -excepthandler_ty excepthandler(expr_ty type, expr_ty name, asdl_seq * body, int - lineno, int col_offset, PyArena *arena); +excepthandler_ty excepthandler(expr_ty type, identifier name, asdl_seq * body, + int lineno, int col_offset, PyArena *arena); arguments_ty arguments(asdl_seq * args, identifier vararg, expr_ty varargannotation, asdl_seq * kwonlyargs, identifier kwarg, expr_ty kwargannotation, asdl_seq * defaults, Modified: python/branches/p3yk-noslice/Lib/CGIHTTPServer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/CGIHTTPServer.py (original) +++ python/branches/p3yk-noslice/Lib/CGIHTTPServer.py Thu Jan 11 00:43:10 2007 @@ -320,7 +320,7 @@ sys.stdout = save_stdout sys.stderr = save_stderr os.chdir(save_cwd) - except SystemExit, sts: + except SystemExit as sts: self.log_error("CGI script exit status %s", str(sts)) else: self.log_message("CGI script exited OK") Modified: python/branches/p3yk-noslice/Lib/ConfigParser.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ConfigParser.py (original) +++ python/branches/p3yk-noslice/Lib/ConfigParser.py Thu Jan 11 00:43:10 2007 @@ -567,7 +567,7 @@ value = self._KEYCRE.sub(self._interpolation_replace, value) try: value = value % vars - except KeyError, e: + except KeyError as e: raise InterpolationMissingOptionError( option, section, rawval, e[0]) else: Modified: python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py (original) +++ python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py Thu Jan 11 00:43:10 2007 @@ -259,7 +259,7 @@ response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) - except Fault, fault: + except Fault as fault: response = xmlrpclib.dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except: @@ -359,7 +359,7 @@ # XXX A marshalling error in any response will fail the entire # multicall. If someone cares they should fix this. results.append([self._dispatch(method_name, params)]) - except Fault, fault: + except Fault as fault: results.append( {'faultCode' : fault.faultCode, 'faultString' : fault.faultString} Modified: python/branches/p3yk-noslice/Lib/_strptime.py ============================================================================== --- python/branches/p3yk-noslice/Lib/_strptime.py (original) +++ python/branches/p3yk-noslice/Lib/_strptime.py Thu Jan 11 00:43:10 2007 @@ -291,7 +291,7 @@ format_regex = time_re.compile(format) # KeyError raised when a bad format is found; can be specified as # \\, in which case it was a stray % but with a space after it - except KeyError, err: + except KeyError as err: bad_directive = err.args[0] if bad_directive == "\\": bad_directive = "%" Modified: python/branches/p3yk-noslice/Lib/asynchat.py ============================================================================== --- python/branches/p3yk-noslice/Lib/asynchat.py (original) +++ python/branches/p3yk-noslice/Lib/asynchat.py Thu Jan 11 00:43:10 2007 @@ -87,7 +87,7 @@ try: data = self.recv (self.ac_in_buffer_size) - except socket.error, why: + except socket.error as why: self.handle_error() return @@ -220,7 +220,7 @@ if num_sent: self.ac_out_buffer = self.ac_out_buffer[num_sent:] - except socket.error, why: + except socket.error as why: self.handle_error() return Modified: python/branches/p3yk-noslice/Lib/asyncore.py ============================================================================== --- python/branches/p3yk-noslice/Lib/asyncore.py (original) +++ python/branches/p3yk-noslice/Lib/asyncore.py Thu Jan 11 00:43:10 2007 @@ -119,7 +119,7 @@ else: try: r, w, e = select.select(r, w, e, timeout) - except select.error, err: + except select.error as err: if err[0] != EINTR: raise else: @@ -165,7 +165,7 @@ pollster.register(fd, flags) try: r = pollster.poll(timeout) - except select.error, err: + except select.error as err: if err[0] != EINTR: raise r = [] @@ -320,7 +320,7 @@ try: conn, addr = self.socket.accept() return conn, addr - except socket.error, why: + except socket.error as why: if why[0] == EWOULDBLOCK: pass else: @@ -330,7 +330,7 @@ try: result = self.socket.send(data) return result - except socket.error, why: + except socket.error as why: if why[0] == EWOULDBLOCK: return 0 else: @@ -347,7 +347,7 @@ return '' else: return data - except socket.error, why: + except socket.error as why: # winsock sometimes throws ENOTCONN if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]: self.handle_close() Modified: python/branches/p3yk-noslice/Lib/base64.py ============================================================================== --- python/branches/p3yk-noslice/Lib/base64.py (original) +++ python/branches/p3yk-noslice/Lib/base64.py Thu Jan 11 00:43:10 2007 @@ -71,7 +71,7 @@ s = _translate(s, {altchars[0]: '+', altchars[1]: '/'}) try: return binascii.a2b_base64(s) - except binascii.Error, msg: + except binascii.Error as msg: # Transform this exception for consistency raise TypeError(msg) @@ -328,7 +328,7 @@ import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'deut') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print """usage: %s [-d|-e|-u|-t] [file|-] Modified: python/branches/p3yk-noslice/Lib/bsddb/dbtables.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/dbtables.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/dbtables.py Thu Jan 11 00:43:10 2007 @@ -260,7 +260,7 @@ txn.commit() txn = None - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise TableDBError, dberror[1] @@ -338,7 +338,7 @@ txn = None self.__load_column_info(table) - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise TableDBError, dberror[1] @@ -407,7 +407,7 @@ txn.commit() txn = None - except DBError, dberror: + except DBError as dberror: # WIBNI we could just abort the txn and re-raise the exception? # But no, because TableDBError is not related to DBError via # inheritance, so it would be backwards incompatible. Do the next @@ -466,7 +466,7 @@ txn.abort() raise - except DBError, dberror: + except DBError as dberror: raise TableDBError, dberror[1] def Delete(self, table, conditions={}): @@ -502,11 +502,11 @@ pass txn.commit() txn = None - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise - except DBError, dberror: + except DBError as dberror: raise TableDBError, dberror[1] @@ -526,7 +526,7 @@ if columns is None: columns = self.__tablecolumns[table] matching_rowids = self.__Select(table, columns, conditions) - except DBError, dberror: + except DBError as dberror: raise TableDBError, dberror[1] # return the matches as a list of dictionaries return matching_rowids.values() @@ -616,7 +616,7 @@ key, data = cur.next() - except DBError, dberror: + except DBError as dberror: if dberror[0] != DB_NOTFOUND: raise continue @@ -636,7 +636,7 @@ try: rowdata[column] = self.db.get( _data_key(table, column, rowid)) - except DBError, dberror: + except DBError as dberror: if dberror[0] != DB_NOTFOUND: raise rowdata[column] = None @@ -700,7 +700,7 @@ if table in self.__tablecolumns: del self.__tablecolumns[table] - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise TableDBError, dberror[1] Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -58,7 +58,7 @@ self.homeDir = homeDir try: shutil.rmtree(homeDir) - except OSError, e: + except OSError as e: # unix returns ENOENT, windows returns ESRCH if e.errno not in (errno.ENOENT, errno.ESRCH): raise os.mkdir(homeDir) @@ -162,7 +162,7 @@ # set_get_returns_none() to change it. try: d.delete('abcd') - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND if verbose: print val else: @@ -181,7 +181,7 @@ try: d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE) - except db.DBKeyExistError, val: + except db.DBKeyExistError as val: assert val[0] == db.DB_KEYEXIST if verbose: print val else: @@ -313,7 +313,7 @@ print rec try: rec = c.next() - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND if verbose: print val @@ -333,7 +333,7 @@ print rec try: rec = c.prev() - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND if verbose: print val @@ -357,7 +357,7 @@ try: n = c.set('bad key') - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND if verbose: print val else: @@ -371,7 +371,7 @@ try: n = c.get_both('0404', 'bad data') - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND if verbose: print val else: @@ -399,7 +399,7 @@ c.delete() try: rec = c.current() - except db.DBKeyEmptyError, val: + except db.DBKeyEmptyError as val: if get_raises_error: assert val[0] == db.DB_KEYEMPTY if verbose: print val @@ -445,7 +445,7 @@ method # a bug may cause a NULL pointer dereference... getattr(c, method)(*args) - except db.DBError, val: + except db.DBError as val: assert val[0] == 0 if verbose: print val else: @@ -730,7 +730,7 @@ txn.abort() try: txn.abort() - except db.DBError, e: + except db.DBError as e: pass else: raise RuntimeError, "DBTxn.abort() called after DB_TXN no longer valid w/o an exception" @@ -739,7 +739,7 @@ txn.commit() try: txn.commit() - except db.DBError, e: + except db.DBError as e: pass else: raise RuntimeError, "DBTxn.commit() called after DB_TXN no longer valid w/o an exception" Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_compare.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_compare.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_compare.py Thu Jan 11 00:43:10 2007 @@ -234,7 +234,7 @@ self.db.set_bt_compare (my_compare) assert False, "this set should fail" - except RuntimeError, msg: + except RuntimeError as msg: pass def test_suite (): Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_pickle.py ============================================================================== --- python/branches/p3yk-noslice/Lib/bsddb/test/test_pickle.py (original) +++ python/branches/p3yk-noslice/Lib/bsddb/test/test_pickle.py Thu Jan 11 00:43:10 2007 @@ -11,7 +11,7 @@ try: # For Pythons w/distutils pybsddb from bsddb3 import db -except ImportError, e: +except ImportError as e: # For Python 2.3 from bsddb import db @@ -47,7 +47,7 @@ assert self.db['spam'] == 'eggs' try: self.db.put('spam', 'ham', flags=db.DB_NOOVERWRITE) - except db.DBError, egg: + except db.DBError as egg: pickledEgg = pickle.dumps(egg) #print repr(pickledEgg) rottenEgg = pickle.loads(pickledEgg) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -29,7 +29,7 @@ def tearDown(self): try: os.remove(self.filename) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise def test01_basic(self): @@ -63,7 +63,7 @@ try: data = d[0] # This should raise a KeyError!?!?! - except db.DBInvalidArgError, val: + except db.DBInvalidArgError as val: assert val[0] == db.EINVAL if verbose: print val else: @@ -72,7 +72,7 @@ # test that has_key raises DB exceptions (fixed in pybsddb 4.3.2) try: d.has_key(0) - except db.DBError, val: + except db.DBError as val: pass else: self.fail("has_key did not raise a proper exception") @@ -86,7 +86,7 @@ try: data = d.get(100) - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: if get_returns_none: self.fail("unexpected exception") else: @@ -177,7 +177,7 @@ try: d.get(99) - except db.DBKeyEmptyError, val: + except db.DBKeyEmptyError as val: if get_returns_none: self.fail("unexpected DBKeyEmptyError exception") else: @@ -267,7 +267,7 @@ try: # this one will fail d.append('bad' * 20) - except db.DBInvalidArgError, val: + except db.DBInvalidArgError as val: assert val[0] == db.EINVAL if verbose: print val else: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -57,7 +57,7 @@ self.homeDir = homeDir try: os.mkdir(homeDir) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise self.env = db.DBEnv() self.setEnvOpts() @@ -247,7 +247,7 @@ # flush them try: dbutils.DeadlockWrap(d.sync, max_retries=12) - except db.DBIncompleteError, val: + except db.DBIncompleteError as val: if verbose: print "could not complete sync()..." @@ -360,7 +360,7 @@ print "%s: records %d - %d finished" % (name, start, x) txn.commit() finished = True - except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: + except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) txn.abort() @@ -398,7 +398,7 @@ finished = True if verbose: print "%s: deleted records %s" % (name, recs) - except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: + except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) txn.abort() @@ -428,7 +428,7 @@ c.close() txn.commit() finished = True - except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: + except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) c.close() Modified: python/branches/p3yk-noslice/Lib/cgi.py ============================================================================== --- python/branches/p3yk-noslice/Lib/cgi.py (original) +++ python/branches/p3yk-noslice/Lib/cgi.py Thu Jan 11 00:43:10 2007 @@ -982,7 +982,7 @@ print "

Current Working Directory:

" try: pwd = os.getcwd() - except os.error, msg: + except os.error as msg: print "os.error:", escape(str(msg)) else: print escape(pwd) Modified: python/branches/p3yk-noslice/Lib/codecs.py ============================================================================== --- python/branches/p3yk-noslice/Lib/codecs.py (original) +++ python/branches/p3yk-noslice/Lib/codecs.py Thu Jan 11 00:43:10 2007 @@ -13,7 +13,7 @@ try: from _codecs import * -except ImportError, why: +except ImportError as why: raise SystemError('Failed to load the builtin codecs: %s' % why) __all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE", @@ -422,7 +422,7 @@ data = self.bytebuffer + newdata try: newchars, decodedbytes = self.decode(data, self.errors) - except UnicodeDecodeError, exc: + except UnicodeDecodeError as exc: if firstline: newchars, decodedbytes = self.decode(data[:exc.start], self.errors) lines = newchars.splitlines(True) Modified: python/branches/p3yk-noslice/Lib/codeop.py ============================================================================== --- python/branches/p3yk-noslice/Lib/codeop.py (original) +++ python/branches/p3yk-noslice/Lib/codeop.py Thu Jan 11 00:43:10 2007 @@ -80,18 +80,18 @@ try: code = compiler(source, filename, symbol) - except SyntaxError, err: + except SyntaxError as err: pass try: code1 = compiler(source + "\n", filename, symbol) - except SyntaxError, err1: - pass + except SyntaxError as e: + err1 = e try: code2 = compiler(source + "\n\n", filename, symbol) - except SyntaxError, err2: - pass + except SyntaxError as e: + err2 = e if code: return code Modified: python/branches/p3yk-noslice/Lib/compileall.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compileall.py (original) +++ python/branches/p3yk-noslice/Lib/compileall.py Thu Jan 11 00:43:10 2007 @@ -65,12 +65,12 @@ ok = py_compile.compile(fullname, None, dfile, True) except KeyboardInterrupt: raise KeyboardInterrupt - except py_compile.PyCompileError,err: + except py_compile.PyCompileError as err: if quiet: print 'Compiling', fullname, '...' print err.msg success = 0 - except IOError, e: + except IOError as e: print "Sorry", e success = 0 else: @@ -109,7 +109,7 @@ import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:') - except getopt.error, msg: + except getopt.error as msg: print msg print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ "[-x regexp] [directory ...]" Modified: python/branches/p3yk-noslice/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/pycodegen.py Thu Jan 11 00:43:10 2007 @@ -227,7 +227,7 @@ assert getattr(self, 'NameFinder') assert getattr(self, 'FunctionGen') assert getattr(self, 'ClassGen') - except AssertionError, msg: + except AssertionError as msg: intro = "Bad class construction for %s" % self.__class__.__name__ raise AssertionError, intro @@ -825,11 +825,33 @@ self.emit('POP_TOP') self.emit('POP_TOP') if target: - self.visit(target) + cleanup_body = self.newBlock() + cleanup_final = self.newBlock() + target_name = target[1] + + self.storeName(target_name) + self.emit('POP_TOP') + self.emit('SETUP_FINALLY', cleanup_final) + self.nextBlock(cleanup_body) + self.setups.push((TRY_FINALLY, cleanup_body)) + self.visit(body) + self.emit('POP_BLOCK') + self.setups.pop() + self.emit('LOAD_CONST', None) + self.nextBlock(cleanup_final) + self.setups.push((END_FINALLY, cleanup_final)) + + + self.emit('LOAD_CONST', None) + self.storeName(target_name) + self._implicitNameOp('DELETE', target_name) + + self.emit('END_FINALLY') + self.setups.pop() else: self.emit('POP_TOP') - self.emit('POP_TOP') - self.visit(body) + self.emit('POP_TOP') + self.visit(body) self.emit('JUMP_FORWARD', end) if expr: self.nextBlock(next) Modified: python/branches/p3yk-noslice/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk-noslice/Lib/compiler/transformer.py (original) +++ python/branches/p3yk-noslice/Lib/compiler/transformer.py Thu Jan 11 00:43:10 2007 @@ -988,16 +988,16 @@ for i in range(3, len(nodelist), 3): node = nodelist[i] if node[0] == symbol.except_clause: - # except_clause: 'except' [expr [',' expr]] */ + # except_clause: 'except' [expr ['as' NAME]] */ if len(node) > 2: - expr1 = self.com_node(node[2]) + expr = self.com_node(node[2]) if len(node) > 4: - expr2 = self.com_assign(node[4], OP_ASSIGN) + expr_name = node[4] else: - expr2 = None + expr_name = None else: - expr1 = expr2 = None - clauses.append((expr1, expr2, self.com_node(nodelist[i+2]))) + expr = expr_name = None + clauses.append((expr, expr_name, self.com_node(nodelist[i+2]))) if node[0] == token.NAME: if node[1] == 'else': Modified: python/branches/p3yk-noslice/Lib/contextlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/contextlib.py (original) +++ python/branches/p3yk-noslice/Lib/contextlib.py Thu Jan 11 00:43:10 2007 @@ -28,7 +28,7 @@ try: self.gen.throw(type, value, traceback) raise RuntimeError("generator didn't stop after throw()") - except StopIteration, exc: + except StopIteration as exc: # Suppress the exception *unless* it's the same exception that # was passed to throw(). This prevents a StopIteration # raised inside the "with" statement from being suppressed Modified: python/branches/p3yk-noslice/Lib/csv.py ============================================================================== --- python/branches/p3yk-noslice/Lib/csv.py (original) +++ python/branches/p3yk-noslice/Lib/csv.py Thu Jan 11 00:43:10 2007 @@ -48,7 +48,7 @@ def _validate(self): try: _Dialect(self) - except TypeError, e: + except TypeError as e: # We do this for compatibility with py2.3 raise Error(str(e)) Modified: python/branches/p3yk-noslice/Lib/ctypes/macholib/dyld.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/macholib/dyld.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/macholib/dyld.py Thu Jan 11 00:43:10 2007 @@ -148,7 +148,7 @@ """ try: return dyld_find(fn, executable_path=executable_path, env=env) - except ValueError, e: + except ValueError as e: pass fmwk_index = fn.rfind('.framework') if fmwk_index == -1: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -57,12 +57,12 @@ for modname in find_package_modules(package, mask): try: mod = __import__(modname, globals(), locals(), ['*']) - except ResourceDenied, detail: + except ResourceDenied as detail: skipped.append(modname) if verbosity > 1: print >> sys.stderr, "Skipped %s: %s" % (modname, detail) continue - except Exception, detail: + except Exception as detail: print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail) continue for name in dir(mod): Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_bitfields.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_bitfields.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_bitfields.py Thu Jan 11 00:43:10 2007 @@ -191,7 +191,7 @@ def get_except(self, func, *args, **kw): try: func(*args, **kw) - except Exception, detail: + except Exception as detail: return detail.__class__, str(detail) def test_mixed_1(self): Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_structures.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/test/test_structures.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/test/test_structures.py Thu Jan 11 00:43:10 2007 @@ -313,7 +313,7 @@ def get_except(self, func, *args): try: func(*args) - except Exception, detail: + except Exception as detail: return detail.__class__, str(detail) @@ -388,7 +388,7 @@ try: Recursive._fields_ = [("next", Recursive)] - except AttributeError, details: + except AttributeError as details: self.failUnless("Structure or union cannot contain itself" in str(details)) else: @@ -405,7 +405,7 @@ try: Second._fields_ = [("first", First)] - except AttributeError, details: + except AttributeError as details: self.failUnless("_fields_ is final" in str(details)) else: Modified: python/branches/p3yk-noslice/Lib/ctypes/util.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ctypes/util.py (original) +++ python/branches/p3yk-noslice/Lib/ctypes/util.py Thu Jan 11 00:43:10 2007 @@ -60,12 +60,12 @@ finally: try: os.unlink(outfile) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise try: os.unlink(ccout) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise res = re.search(expr, trace) Modified: python/branches/p3yk-noslice/Lib/dis.py ============================================================================== --- python/branches/p3yk-noslice/Lib/dis.py (original) +++ python/branches/p3yk-noslice/Lib/dis.py Thu Jan 11 00:43:10 2007 @@ -33,7 +33,7 @@ print "Disassembly of %s:" % name try: dis(x1) - except TypeError, msg: + except TypeError as msg: print "Sorry:", msg print elif hasattr(x, 'co_code'): Modified: python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py Thu Jan 11 00:43:10 2007 @@ -115,7 +115,7 @@ # This needs to be compiled to a .res file -- do it now. try: self.spawn (["brcc32", "-fo", obj, src]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg continue # the 'for' loop @@ -139,7 +139,7 @@ self.spawn ([self.cc] + compile_opts + pp_opts + [input_opt, output_opt] + extra_postargs + [src]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg return objects @@ -164,7 +164,7 @@ pass # XXX what goes here? try: self.spawn ([self.lib] + lib_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LibError, msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -298,7 +298,7 @@ self.mkpath (os.path.dirname (output_filename)) try: self.spawn ([self.linker] + ld_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LinkError, msg else: @@ -391,7 +391,7 @@ self.mkpath(os.path.dirname(output_file)) try: self.spawn(pp_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: print msg raise CompileError, msg Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -284,11 +284,11 @@ data = '' try: result = opener.open(req) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if self.show_response: data = e.fp.read() result = e.code, e.msg - except urllib2.URLError, e: + except urllib2.URLError as e: result = 500, str(e) else: if self.show_response: Modified: python/branches/p3yk-noslice/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/command/sdist.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/command/sdist.py Thu Jan 11 00:43:10 2007 @@ -333,7 +333,7 @@ try: self.filelist.process_template_line(line) - except DistutilsTemplateError, msg: + except DistutilsTemplateError as msg: self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg)) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -184,7 +184,7 @@ http.putheader('Authorization', auth) http.endheaders() http.send(body) - except socket.error, e: + except socket.error as e: self.announce(str(e), log.ERROR) return Modified: python/branches/p3yk-noslice/Lib/distutils/core.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/core.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/core.py Thu Jan 11 00:43:10 2007 @@ -110,7 +110,7 @@ # (ie. everything except distclass) to initialize it try: _setup_distribution = dist = klass(attrs) - except DistutilsSetupError, msg: + except DistutilsSetupError as msg: if 'name' not in attrs: raise SystemExit, "error in %s setup command: %s" % \ (attrs['name'], msg) @@ -135,7 +135,7 @@ # fault, so turn them into SystemExit to suppress tracebacks. try: ok = dist.parse_command_line() - except DistutilsArgError, msg: + except DistutilsArgError as msg: raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg if DEBUG: @@ -151,7 +151,7 @@ dist.run_commands() except KeyboardInterrupt: raise SystemExit, "interrupted" - except (IOError, os.error), exc: + except (IOError, os.error) as exc: error = grok_environment_error(exc) if DEBUG: @@ -161,7 +161,7 @@ raise SystemExit, error except (DistutilsError, - CCompilerError), msg: + CCompilerError) as msg: if DEBUG: raise else: Modified: python/branches/p3yk-noslice/Lib/distutils/cygwinccompiler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/cygwinccompiler.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/cygwinccompiler.py Thu Jan 11 00:43:10 2007 @@ -142,13 +142,13 @@ # gcc needs '.res' and '.rc' compiled to object files !!! try: self.spawn(["windres", "-i", src, "-o", obj]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg else: # for other files use the C-compiler try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def link (self, @@ -379,7 +379,7 @@ s = f.read() f.close() - except IOError, exc: + except IOError as exc: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing return (CONFIG_H_UNCERTAIN, Modified: python/branches/p3yk-noslice/Lib/distutils/dir_util.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/dir_util.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/dir_util.py Thu Jan 11 00:43:10 2007 @@ -75,7 +75,7 @@ try: os.mkdir(head) created_dirs.append(head) - except OSError, exc: + except OSError as exc: raise DistutilsFileError, \ "could not create '%s': %s" % (head, exc[-1]) @@ -142,7 +142,8 @@ "cannot copy tree '%s': not a directory" % src try: names = os.listdir(src) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e if dry_run: names = [] else: @@ -209,7 +210,7 @@ abspath = os.path.abspath(cmd[1]) if abspath in _path_created: del _path_created[abspath] - except (IOError, OSError), exc: + except (IOError, OSError) as exc: log.warn(grok_environment_error( exc, "error removing %s: " % directory)) Modified: python/branches/p3yk-noslice/Lib/distutils/dist.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/dist.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/dist.py Thu Jan 11 00:43:10 2007 @@ -398,7 +398,7 @@ setattr(self, opt, strtobool(val)) else: setattr(self, opt, val) - except ValueError, msg: + except ValueError as msg: raise DistutilsOptionError, msg # parse_config_files () @@ -515,7 +515,7 @@ # it takes. try: cmd_class = self.get_command_class(command) - except DistutilsModuleError, msg: + except DistutilsModuleError as msg: raise DistutilsArgError, msg # Require that the command class be derived from Command -- want @@ -917,7 +917,7 @@ raise DistutilsOptionError, \ ("error in %s: command '%s' has no such option '%s'" % (source, command_name, option)) - except ValueError, msg: + except ValueError as msg: raise DistutilsOptionError, msg def reinitialize_command (self, command, reinit_subcommands=0): Modified: python/branches/p3yk-noslice/Lib/distutils/emxccompiler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/emxccompiler.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/emxccompiler.py Thu Jan 11 00:43:10 2007 @@ -79,13 +79,13 @@ # gcc requires '.rc' compiled to binary ('.res') files !!! try: self.spawn(["rc", "-r", src]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg else: # for other files use the C-compiler try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def link (self, @@ -275,7 +275,7 @@ s = f.read() f.close() - except IOError, exc: + except IOError as exc: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing return (CONFIG_H_UNCERTAIN, Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -256,7 +256,7 @@ short_opts = string.join(self.short_opts) try: opts, args = getopt.getopt(args, short_opts, self.long_opts) - except getopt.error, msg: + except getopt.error as msg: raise DistutilsArgError, msg for opt, val in opts: Modified: python/branches/p3yk-noslice/Lib/distutils/file_util.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/file_util.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/file_util.py Thu Jan 11 00:43:10 2007 @@ -32,27 +32,31 @@ try: try: fsrc = open(src, 'rb') - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not open '%s': %s" % (src, errstr) if os.path.exists(dst): try: os.unlink(dst) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not delete '%s': %s" % (dst, errstr) try: fdst = open(dst, 'wb') - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not create '%s': %s" % (dst, errstr) while 1: try: buf = fsrc.read(buffer_size) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not read from '%s': %s" % (src, errstr) @@ -61,7 +65,8 @@ try: fdst.write(buf) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not write to '%s': %s" % (dst, errstr) @@ -146,7 +151,7 @@ import macostools try: macostools.copy(src, dst, 0, preserve_times) - except os.error, exc: + except os.error as exc: raise DistutilsFileError, \ "could not copy '%s' to '%s': %s" % (src, dst, exc[-1]) @@ -217,7 +222,8 @@ copy_it = 0 try: os.rename(src, dst) - except os.error, (num, msg): + except os.error as e: + (num, msg) = e if num == errno.EXDEV: copy_it = 1 else: @@ -228,7 +234,8 @@ copy_file(src, dst) try: os.unlink(src) - except os.error, (num, msg): + except os.error as e: + (num, msg) = e try: os.unlink(dst) except os.error: Modified: python/branches/p3yk-noslice/Lib/distutils/msvccompiler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/msvccompiler.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/msvccompiler.py Thu Jan 11 00:43:10 2007 @@ -129,7 +129,7 @@ self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") - except KeyError, exc: # + except KeyError as exc: # raise DistutilsPlatformError, \ ("""Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. @@ -371,7 +371,7 @@ try: self.spawn ([self.rc] + pp_opts + [output_opt] + [input_opt]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg continue elif ext in self._mc_extensions: @@ -400,7 +400,7 @@ self.spawn ([self.rc] + ["/fo" + obj] + [rc_file]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg continue else: @@ -414,7 +414,7 @@ self.spawn ([self.cc] + compile_opts + pp_opts + [input_opt, output_opt] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg return objects @@ -440,7 +440,7 @@ pass # XXX what goes here? try: self.spawn ([self.lib] + lib_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LibError, msg else: @@ -519,7 +519,7 @@ self.mkpath (os.path.dirname (output_filename)) try: self.spawn ([self.linker] + ld_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LinkError, msg else: Modified: python/branches/p3yk-noslice/Lib/distutils/spawn.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/spawn.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/spawn.py Thu Jan 11 00:43:10 2007 @@ -78,7 +78,7 @@ # spawn for NT requires a full path to the .exe try: rc = os.spawnv(os.P_WAIT, executable, cmd) - except OSError, exc: + except OSError as exc: # this seems to happen when the command isn't found raise DistutilsExecError, \ "command '%s' failed: %s" % (cmd[0], exc[-1]) @@ -103,7 +103,7 @@ # spawnv for OS/2 EMX requires a full path to the .exe try: rc = os.spawnv(os.P_WAIT, executable, cmd) - except OSError, exc: + except OSError as exc: # this seems to happen when the command isn't found raise DistutilsExecError, \ "command '%s' failed: %s" % (cmd[0], exc[-1]) @@ -131,7 +131,7 @@ #print "cmd[0] =", cmd[0] #print "cmd =", cmd exec_fn(cmd[0], cmd) - except OSError, e: + except OSError as e: sys.stderr.write("unable to execute %s: %s\n" % (cmd[0], e.strerror)) os._exit(1) @@ -146,7 +146,7 @@ while 1: try: (pid, status) = os.waitpid(pid, 0) - except OSError, exc: + except OSError as exc: import errno if exc.errno == errno.EINTR: continue Modified: python/branches/p3yk-noslice/Lib/distutils/sysconfig.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/sysconfig.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/sysconfig.py Thu Jan 11 00:43:10 2007 @@ -344,7 +344,7 @@ try: filename = get_makefile_filename() parse_makefile(filename, g) - except IOError, msg: + except IOError as msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror @@ -355,7 +355,7 @@ try: filename = get_config_h_filename() parse_config_h(open(filename), g) - except IOError, msg: + except IOError as msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror Modified: python/branches/p3yk-noslice/Lib/distutils/unixccompiler.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/unixccompiler.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/unixccompiler.py Thu Jan 11 00:43:10 2007 @@ -162,7 +162,7 @@ self.mkpath(os.path.dirname(output_file)) try: self.spawn(pp_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): @@ -172,7 +172,7 @@ try: self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def create_static_lib(self, objects, output_libname, @@ -196,7 +196,7 @@ if self.ranlib: try: self.spawn(self.ranlib + [output_filename]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LibError, msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -250,7 +250,7 @@ linker = _darwin_compiler_fixup(linker, ld_args) self.spawn(linker + ld_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LinkError, msg else: log.debug("skipping %s (up-to-date)", output_filename) Modified: python/branches/p3yk-noslice/Lib/distutils/util.py ============================================================================== --- python/branches/p3yk-noslice/Lib/distutils/util.py (original) +++ python/branches/p3yk-noslice/Lib/distutils/util.py Thu Jan 11 00:43:10 2007 @@ -229,7 +229,7 @@ try: return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s) - except KeyError, var: + except KeyError as var: raise ValueError, "invalid variable '$%s'" % var # subst_vars () Modified: python/branches/p3yk-noslice/Lib/doctest.py ============================================================================== --- python/branches/p3yk-noslice/Lib/doctest.py (original) +++ python/branches/p3yk-noslice/Lib/doctest.py Thu Jan 11 00:43:10 2007 @@ -1604,8 +1604,8 @@ ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) - ... except UnexpectedException, failure: - ... pass + ... except UnexpectedException as f: + ... failure = f >>> failure.test is test True @@ -1632,8 +1632,8 @@ >>> try: ... runner.run(test) - ... except DocTestFailure, failure: - ... pass + ... except DocTestFailure as f: + ... failure = f DocTestFailure objects provide access to the test: @@ -2141,8 +2141,8 @@ >>> case = DocTestCase(test) >>> try: ... case.debug() - ... except UnexpectedException, failure: - ... pass + ... except UnexpectedException as f: + ... failure = f The UnexpectedException contains the test, the example, and the original exception: @@ -2170,8 +2170,8 @@ >>> try: ... case.debug() - ... except DocTestFailure, failure: - ... pass + ... except DocTestFailure as f: + ... failure = f DocTestFailure objects provide access to the test: Modified: python/branches/p3yk-noslice/Lib/encodings/uu_codec.py ============================================================================== --- python/branches/p3yk-noslice/Lib/encodings/uu_codec.py (original) +++ python/branches/p3yk-noslice/Lib/encodings/uu_codec.py Thu Jan 11 00:43:10 2007 @@ -81,7 +81,7 @@ break try: data = a2b_uu(s) - except binascii.Error, v: + except binascii.Error as v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = a2b_uu(s[:nbytes]) Modified: python/branches/p3yk-noslice/Lib/filecmp.py ============================================================================== --- python/branches/p3yk-noslice/Lib/filecmp.py (original) +++ python/branches/p3yk-noslice/Lib/filecmp.py Thu Jan 11 00:43:10 2007 @@ -148,12 +148,12 @@ ok = 1 try: a_stat = os.stat(a_path) - except os.error, why: + except os.error as why: # print 'Can\'t stat', a_path, ':', why[1] ok = 0 try: b_stat = os.stat(b_path) - except os.error, why: + except os.error as why: # print 'Can\'t stat', b_path, ':', why[1] ok = 0 Modified: python/branches/p3yk-noslice/Lib/ftplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/ftplib.py (original) +++ python/branches/p3yk-noslice/Lib/ftplib.py Thu Jan 11 00:43:10 2007 @@ -119,7 +119,7 @@ try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None @@ -277,7 +277,7 @@ try: sock = socket.socket(af, socktype, proto) sock.bind(sa) - except socket.error, msg: + except socket.error as msg: if sock: sock.close() sock = None @@ -496,7 +496,7 @@ if dirname == '..': try: return self.voidcmd('CDUP') - except error_perm, msg: + except error_perm as msg: if msg.args[0][:3] != '500': raise elif dirname == '': Modified: python/branches/p3yk-noslice/Lib/hotshot/stones.py ============================================================================== --- python/branches/p3yk-noslice/Lib/hotshot/stones.py (original) +++ python/branches/p3yk-noslice/Lib/hotshot/stones.py Thu Jan 11 00:43:10 2007 @@ -19,7 +19,7 @@ stats.sort_stats('time', 'calls') try: stats.print_stats(20) - except IOError, e: + except IOError as e: if e.errno != errno.EPIPE: raise Modified: python/branches/p3yk-noslice/Lib/htmllib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/htmllib.py (original) +++ python/branches/p3yk-noslice/Lib/htmllib.py Thu Jan 11 00:43:10 2007 @@ -463,7 +463,7 @@ else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) Modified: python/branches/p3yk-noslice/Lib/httplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/httplib.py (original) +++ python/branches/p3yk-noslice/Lib/httplib.py Thu Jan 11 00:43:10 2007 @@ -667,7 +667,7 @@ if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: @@ -713,7 +713,7 @@ data=str.read(blocksize) else: self.sock.sendall(str) - except socket.error, v: + except socket.error as v: if v[0] == 32: # Broken pipe self.close() raise @@ -868,7 +868,7 @@ try: self._send_request(method, url, body, headers) - except socket.error, v: + except socket.error as v: # trap 'Broken pipe' if we're allowed to automatically reconnect if v[0] != 32 or not self.auto_open: raise @@ -890,7 +890,7 @@ thelen=None try: thelen=str(len(body)) - except TypeError, te: + except TypeError as te: # If this is a file-like object, try to # fstat its file descriptor import os @@ -1019,7 +1019,7 @@ while True: try: buf = self._ssl.read(self._bufsize) - except socket.sslerror, err: + except socket.sslerror as err: if (err[0] == socket.SSL_ERROR_WANT_READ or err[0] == socket.SSL_ERROR_WANT_WRITE): continue @@ -1027,7 +1027,7 @@ or err[0] == socket.SSL_ERROR_EOF): break raise - except socket.error, err: + except socket.error as err: if err[0] == errno.EINTR: continue if err[0] == errno.EBADF: @@ -1215,7 +1215,7 @@ """ try: response = self._conn.getresponse() - except BadStatusLine, e: + except BadStatusLine as e: ### hmm. if getresponse() ever closes the socket on a bad request, ### then we are going to have problems with self.sock Modified: python/branches/p3yk-noslice/Lib/idlelib/ClassBrowser.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/ClassBrowser.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/ClassBrowser.py Thu Jan 11 00:43:10 2007 @@ -94,7 +94,7 @@ return [] try: dict = pyclbr.readmodule_ex(name, [dir] + sys.path) - except ImportError, msg: + except ImportError as msg: return [] items = [] self.classes = {} Modified: python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py Thu Jan 11 00:43:10 2007 @@ -505,7 +505,7 @@ # XXX Ought to insert current file's directory in front of path try: (f, file, (suffix, mode, type)) = _find_module(name) - except (NameError, ImportError), msg: + except (NameError, ImportError) as msg: tkMessageBox.showerror("Import error", str(msg), parent=self.text) return if type != imp.PY_SOURCE: Modified: python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py Thu Jan 11 00:43:10 2007 @@ -82,7 +82,7 @@ for fn in list: try: f = open(fn) - except IOError, msg: + except IOError as msg: print msg continue lineno = 0 @@ -110,7 +110,7 @@ def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) - except os.error, msg: + except os.error as msg: print msg return [] list = [] Modified: python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py Thu Jan 11 00:43:10 2007 @@ -246,7 +246,7 @@ f = open(filename,'rb') chars = f.read() f.close() - except IOError, msg: + except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False @@ -289,7 +289,7 @@ # Next look for coding specification try: enc = coding_spec(chars) - except LookupError, name: + except LookupError as name: tkMessageBox.showerror( title="Error loading the file", message="The encoding '%s' is not known to this Python "\ @@ -380,7 +380,7 @@ f.flush() f.close() return True - except IOError, msg: + except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False @@ -400,7 +400,7 @@ try: enc = coding_spec(chars) failed = None - except LookupError, msg: + except LookupError as msg: failed = msg enc = None if enc: Modified: python/branches/p3yk-noslice/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/PyShell.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/PyShell.py Thu Jan 11 00:43:10 2007 @@ -380,7 +380,7 @@ try: self.rpcclt = MyRPCClient(addr) break - except socket.error, err: + except socket.error as err: pass else: self.display_port_binding_error() @@ -389,7 +389,7 @@ self.rpcclt.listening_sock.settimeout(10) try: self.rpcclt.accept() - except socket.timeout, err: + except socket.timeout as err: self.display_no_subprocess_error() return None self.rpcclt.register("stdin", self.tkconsole) @@ -423,7 +423,7 @@ self.spawn_subprocess() try: self.rpcclt.accept() - except socket.timeout, err: + except socket.timeout as err: self.display_no_subprocess_error() return None self.transfer_path() @@ -1324,7 +1324,7 @@ startup = False try: opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:") - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) Modified: python/branches/p3yk-noslice/Lib/idlelib/ScriptBinding.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/ScriptBinding.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/ScriptBinding.py Thu Jan 11 00:43:10 2007 @@ -66,13 +66,13 @@ f = open(filename, 'r') try: tabnanny.process_tokens(tokenize.generate_tokens(f.readline)) - except tokenize.TokenError, msg: + except tokenize.TokenError as msg: msgtxt, (lineno, start) = msg self.editwin.gotoline(lineno) self.errorbox("Tabnanny Tokenizing Error", "Token Error: %s" % msgtxt) return False - except tabnanny.NannyNag, nag: + except tabnanny.NannyNag as nag: # The error messages from tabnanny are too confusing... self.editwin.gotoline(nag.get_lineno()) self.errorbox("Tab/space error", indent_message) @@ -97,7 +97,7 @@ try: # If successful, return the compiled code return compile(source, filename, "exec") - except (SyntaxError, OverflowError), err: + except (SyntaxError, OverflowError) as err: try: msg, (errorfilename, lineno, offset, line) = err if not errorfilename: Modified: python/branches/p3yk-noslice/Lib/idlelib/SearchEngine.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/SearchEngine.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/SearchEngine.py Thu Jan 11 00:43:10 2007 @@ -66,7 +66,7 @@ flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) - except re.error, what: + except re.error as what: try: msg, col = what except: Modified: python/branches/p3yk-noslice/Lib/idlelib/run.py ============================================================================== --- python/branches/p3yk-noslice/Lib/idlelib/run.py (original) +++ python/branches/p3yk-noslice/Lib/idlelib/run.py Thu Jan 11 00:43:10 2007 @@ -114,7 +114,7 @@ try: server = MyRPCServer(address, MyHandler) break - except socket.error, err: + except socket.error as err: print>>sys.__stderr__,"IDLE Subprocess: socket error: "\ + err[1] + ", retrying...." else: Modified: python/branches/p3yk-noslice/Lib/imaplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/imaplib.py (original) +++ python/branches/p3yk-noslice/Lib/imaplib.py Thu Jan 11 00:43:10 2007 @@ -845,7 +845,7 @@ try: self.send('%s%s' % (data, CRLF)) - except (socket.error, OSError), val: + except (socket.error, OSError) as val: raise self.abort('socket error: %s' % val) if literal is None: @@ -870,7 +870,7 @@ try: self.send(literal) self.send(CRLF) - except (socket.error, OSError), val: + except (socket.error, OSError) as val: raise self.abort('socket error: %s' % val) if not literator: @@ -883,9 +883,9 @@ self._check_bye() try: typ, data = self._get_tagged_response(tag) - except self.abort, val: + except self.abort as val: raise self.abort('command: %s => %s' % (name, val)) - except self.error, val: + except self.error as val: raise self.error('command: %s => %s' % (name, val)) self._check_bye() if typ == 'BAD': @@ -984,7 +984,7 @@ try: self._get_response() - except self.abort, val: + except self.abort as val: if __debug__: if self.debug >= 1: self.print_log() @@ -1402,7 +1402,7 @@ try: optlist, args = getopt.getopt(sys.argv[1:], 'd:s:') - except getopt.error, val: + except getopt.error as val: optlist, args = (), () stream_command = None Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -85,7 +85,7 @@ for c in _flatten(cnfs): try: cnf.update(c) - except (AttributeError, TypeError), msg: + except (AttributeError, TypeError) as msg: print "_cnfmerge: fallback due to:", msg for k, v in c.items(): cnf[k] = v @@ -1401,7 +1401,7 @@ if self.subst: args = self.subst(*args) return self.func(*args) - except SystemExit, msg: + except SystemExit as msg: raise SystemExit, msg except: self.widget._report_exception() Modified: python/branches/p3yk-noslice/Lib/linecache.py ============================================================================== --- python/branches/p3yk-noslice/Lib/linecache.py (original) +++ python/branches/p3yk-noslice/Lib/linecache.py Thu Jan 11 00:43:10 2007 @@ -78,7 +78,7 @@ fullname = filename try: stat = os.stat(fullname) - except os.error, msg: + except os.error as msg: basename = os.path.split(filename)[1] # Try for a __loader__, if available @@ -128,7 +128,7 @@ fp = open(fullname, 'rU') lines = fp.readlines() fp.close() - except IOError, msg: + except IOError as msg: ## print '*** Cannot open', fullname, ':', msg return [] size, mtime = stat.st_size, stat.st_mtime Modified: python/branches/p3yk-noslice/Lib/logging/config.py ============================================================================== --- python/branches/p3yk-noslice/Lib/logging/config.py (original) +++ python/branches/p3yk-noslice/Lib/logging/config.py Thu Jan 11 00:43:10 2007 @@ -288,7 +288,7 @@ except: traceback.print_exc() os.remove(file) - except socket.error, e: + except socket.error as e: if type(e.args) != types.TupleType: raise else: Modified: python/branches/p3yk-noslice/Lib/mailbox.py ============================================================================== --- python/branches/p3yk-noslice/Lib/mailbox.py (original) +++ python/branches/p3yk-noslice/Lib/mailbox.py Thu Jan 11 00:43:10 2007 @@ -258,7 +258,7 @@ os.remove(tmp_file.name) else: os.rename(tmp_file.name, dest) - except OSError, e: + except OSError as e: os.remove(tmp_file.name) if e.errno == errno.EEXIST: raise ExternalClashError('Name clash with existing message: %s' @@ -280,7 +280,7 @@ self.remove(key) except KeyError: pass - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise @@ -437,12 +437,12 @@ path = os.path.join(self._path, 'tmp', uniq) try: os.stat(path) - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: Maildir._count += 1 try: return _create_carefully(path) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise else: @@ -495,7 +495,7 @@ Mailbox.__init__(self, path, factory, create) try: f = open(self._path, 'rb+') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: if create: f = open(self._path, 'wb+') @@ -605,7 +605,7 @@ self._file.close() try: os.rename(new_file.name, self._path) - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(self._path) @@ -837,7 +837,7 @@ path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -859,7 +859,7 @@ path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -885,7 +885,7 @@ f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -912,7 +912,7 @@ f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -932,7 +932,7 @@ """Return a file-like representation or raise a KeyError.""" try: f = open(os.path.join(self._path, str(key)), 'rb') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -1843,7 +1843,7 @@ if fcntl: try: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) - except IOError, e: + except IOError as e: if e.errno in (errno.EAGAIN, errno.EACCES): raise ExternalClashError('lockf: lock unavailable: %s' % f.name) @@ -1853,7 +1853,7 @@ try: pre_lock = _create_temporary(f.name + '.lock') pre_lock.close() - except IOError, e: + except IOError as e: if e.errno == errno.EACCES: return # Without write access, just skip dotlocking. else: @@ -1866,7 +1866,7 @@ else: os.rename(pre_lock.name, f.name + '.lock') dotlock_done = True - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(pre_lock.name) Modified: python/branches/p3yk-noslice/Lib/mhlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/mhlib.py (original) +++ python/branches/p3yk-noslice/Lib/mhlib.py Thu Jan 11 00:43:10 2007 @@ -370,7 +370,7 @@ count = len(all) try: anchor = self._parseindex(head, all) - except Error, msg: + except Error as msg: seqs = self.getsequences() if not head in seqs: if not msg: @@ -407,7 +407,7 @@ # Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence try: n = self._parseindex(seq, all) - except Error, msg: + except Error as msg: seqs = self.getsequences() if not seq in seqs: if not msg: @@ -471,7 +471,7 @@ pass try: os.rename(path, commapath) - except os.error, msg: + except os.error as msg: errors.append(msg) else: deleted.append(n) @@ -499,7 +499,7 @@ try: shutil.copy2(path, topath) os.unlink(path) - except (IOError, os.error), msg: + except (IOError, os.error) as msg: errors.append(msg) try: os.unlink(topath) @@ -989,7 +989,7 @@ 'all'): try: do('f.parsesequence(%r)' % (seq,)) - except Error, msg: + except Error as msg: print "Error:", msg stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read() list = map(int, stuff.split()) Modified: python/branches/p3yk-noslice/Lib/mimetypes.py ============================================================================== --- python/branches/p3yk-noslice/Lib/mimetypes.py (original) +++ python/branches/p3yk-noslice/Lib/mimetypes.py Thu Jan 11 00:43:10 2007 @@ -510,7 +510,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'hle', ['help', 'lenient', 'extension']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) strict = 1 Modified: python/branches/p3yk-noslice/Lib/modulefinder.py ============================================================================== --- python/branches/p3yk-noslice/Lib/modulefinder.py (original) +++ python/branches/p3yk-noslice/Lib/modulefinder.py Thu Jan 11 00:43:10 2007 @@ -317,7 +317,7 @@ return try: self.import_hook(name, caller, level=level) - except ImportError, msg: + except ImportError as msg: self.msg(2, "ImportError:", str(msg)) self._add_badmodule(name, caller) else: @@ -328,7 +328,7 @@ continue try: self.import_hook(name, caller, [sub], level=level) - except ImportError, msg: + except ImportError as msg: self.msg(2, "ImportError:", str(msg)) fullname = name + "." + sub self._add_badmodule(fullname, caller) @@ -602,7 +602,7 @@ import getopt try: opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") - except getopt.error, msg: + except getopt.error as msg: print msg return Modified: python/branches/p3yk-noslice/Lib/msilib/__init__.py ============================================================================== --- python/branches/p3yk-noslice/Lib/msilib/__init__.py (original) +++ python/branches/p3yk-noslice/Lib/msilib/__init__.py Thu Jan 11 00:43:10 2007 @@ -2,7 +2,7 @@ # Copyright (C) 2005 Martin v. L?wis # Licensed to PSF under a Contributor Agreement. from _msi import * -import sets, os, string, re +import os, string, re Win64=0 @@ -111,7 +111,7 @@ raise TypeError, "Unsupported type %s" % field.__class__.__name__ try: v.Modify(MSIMODIFY_INSERT, r) - except Exception, e: + except Exception as e: raise MSIError("Could not insert "+repr(values)+" into "+table) r.ClearData() @@ -184,7 +184,7 @@ def __init__(self, name): self.name = name self.files = [] - self.filenames = sets.Set() + self.filenames = set() self.index = 0 def gen_id(self, file): @@ -215,7 +215,7 @@ os.unlink(filename) db.Commit() -_directories = sets.Set() +_directories = set() class Directory: def __init__(self, db, cab, basedir, physical, _logical, default, componentflags=None): """Create a new directory in the Directory table. There is a current component @@ -239,8 +239,8 @@ self.physical = physical self.logical = logical self.component = None - self.short_names = sets.Set() - self.ids = sets.Set() + self.short_names = set() + self.ids = set() self.keyfiles = {} self.componentflags = componentflags if basedir: Modified: python/branches/p3yk-noslice/Lib/nntplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/nntplib.py (original) +++ python/branches/p3yk-noslice/Lib/nntplib.py Thu Jan 11 00:43:10 2007 @@ -127,7 +127,7 @@ except NNTPPermanentError: # error 500, probably 'not implemented' pass - except NNTPTemporaryError, e: + except NNTPTemporaryError as e: if user and e.response[:3] == '480': # Need authorization before 'mode reader' readermode_afterauth = 1 Modified: python/branches/p3yk-noslice/Lib/optparse.py ============================================================================== --- python/branches/p3yk-noslice/Lib/optparse.py (original) +++ python/branches/p3yk-noslice/Lib/optparse.py Thu Jan 11 00:43:10 2007 @@ -1376,7 +1376,7 @@ try: stop = self._process_args(largs, rargs, values) - except (BadOptionError, OptionValueError), err: + except (BadOptionError, OptionValueError) as err: self.error(str(err)) args = largs + rargs Modified: python/branches/p3yk-noslice/Lib/os.py ============================================================================== --- python/branches/p3yk-noslice/Lib/os.py (original) +++ python/branches/p3yk-noslice/Lib/os.py Thu Jan 11 00:43:10 2007 @@ -163,7 +163,7 @@ if head and tail and not path.exists(head): try: makedirs(head, mode) - except OSError, e: + except OSError as e: # be happy if someone already created the path if e.errno != EEXIST: raise @@ -284,7 +284,7 @@ # Note that listdir and error are globals in this module due # to earlier import-*. names = listdir(top) - except error, err: + except error as err: if onerror is not None: onerror(err) return @@ -390,7 +390,7 @@ fullname = path.join(dir, file) try: func(fullname, *argrest) - except error, e: + except error as e: tb = sys.exc_info()[2] if (e.errno != ENOENT and e.errno != ENOTDIR and saved_exc is None): Modified: python/branches/p3yk-noslice/Lib/pdb.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pdb.py (original) +++ python/branches/p3yk-noslice/Lib/pdb.py Thu Jan 11 00:43:10 2007 @@ -330,7 +330,7 @@ arg = arg[colon+1:].lstrip() try: lineno = int(arg) - except ValueError, msg: + except ValueError as msg: print >>self.stdout, '*** Bad lineno:', arg return else: @@ -618,7 +618,7 @@ self.curframe.f_lineno = arg self.stack[self.curindex] = self.stack[self.curindex][0], arg self.print_stack_entry(self.stack[self.curindex]) - except ValueError, e: + except ValueError as e: print >>self.stdout, '*** Jump failed:', e do_j = do_jump Modified: python/branches/p3yk-noslice/Lib/pickle.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pickle.py (original) +++ python/branches/p3yk-noslice/Lib/pickle.py Thu Jan 11 00:43:10 2007 @@ -816,7 +816,7 @@ while 1: key = read(1) dispatch[key](self) - except _Stop, stopinst: + except _Stop as stopinst: return stopinst.value # Return largest index k such that self.stack[k] is self.mark. @@ -1018,7 +1018,7 @@ if not instantiated: try: value = klass(*args) - except TypeError, err: + except TypeError as err: raise TypeError, "in constructor for %s: %s" % ( klass.__name__, str(err)), sys.exc_info()[2] self.append(value) Modified: python/branches/p3yk-noslice/Lib/pkgutil.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pkgutil.py (original) +++ python/branches/p3yk-noslice/Lib/pkgutil.py Thu Jan 11 00:43:10 2007 @@ -532,7 +532,7 @@ if os.path.isfile(pkgfile): try: f = open(pkgfile) - except IOError, msg: + except IOError as msg: sys.stderr.write("Can't open %s: %s\n" % (pkgfile, msg)) else: Modified: python/branches/p3yk-noslice/Lib/plat-irix5/torgb.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix5/torgb.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix5/torgb.py Thu Jan 11 00:43:10 2007 @@ -80,7 +80,7 @@ fname = filename try: ftype = imghdr.what(fname) - except IOError, msg: + except IOError as msg: if type(msg) == type(()) and len(msg) == 2 and \ type(msg[0]) == type(0) and type(msg[1]) == type(''): msg = msg[1] Modified: python/branches/p3yk-noslice/Lib/plat-irix6/torgb.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-irix6/torgb.py (original) +++ python/branches/p3yk-noslice/Lib/plat-irix6/torgb.py Thu Jan 11 00:43:10 2007 @@ -80,7 +80,7 @@ fname = filename try: ftype = imghdr.what(fname) - except IOError, msg: + except IOError as msg: if type(msg) == type(()) and len(msg) == 2 and \ type(msg[0]) == type(0) and type(msg[1]) == type(''): msg = msg[1] Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -651,7 +651,7 @@ try: rr = Nav.NavChooseFile(args) good = 1 - except Nav.error, arg: + except Nav.error as arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None @@ -704,7 +704,7 @@ try: rr = Nav.NavPutFile(args) good = 1 - except Nav.error, arg: + except Nav.error as arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None @@ -764,7 +764,7 @@ try: rr = Nav.NavChooseFolder(args) good = 1 - except Nav.error, arg: + except Nav.error as arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -70,7 +70,7 @@ msg = "High Level Event: %r %r" % (code(message), code(h | (v<<16))) try: AE.AEProcessAppleEvent(event) - except AE.Error, err: + except AE.Error as err: print 'AE error: ', err print 'in', msg traceback.print_exc() Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -57,7 +57,7 @@ def missed(ae): try: desc = ae.AEGetAttributeDesc('miss', 'keyw') - except AE.Error, msg: + except AE.Error as msg: return None return desc.data @@ -86,7 +86,7 @@ for key in aekeywords: try: desc = ae.AEGetAttributeDesc(key, '****') - except (AE.Error, MacOS.Error), msg: + except (AE.Error, MacOS.Error) as msg: if msg[0] != -1701 and msg[0] != -1704: raise continue Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -48,7 +48,7 @@ header = fileobj.read(AS_HEADER_LENGTH) try: magic, version, ig, nentry = struct.unpack(AS_HEADER_FORMAT, header) - except ValueError, arg: + except ValueError as arg: raise Error, "Unpack header error: %s" % (arg,) if verbose: print 'Magic: 0x%8.8x' % (magic,) @@ -65,7 +65,7 @@ for hdr in headers: try: restype, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) - except ValueError, arg: + except ValueError as arg: raise Error, "Unpack entry error: %s" % (arg,) if verbose: print "Fork %d, offset %d, length %d" % (restype, offset, length) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -52,7 +52,7 @@ if what == kHighLevelEvent: try: AE.AEProcessAppleEvent(event) - except AE.Error, err: + except AE.Error as err: msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16))) print 'AE error: ', err print 'in', msg @@ -77,7 +77,7 @@ fsref = alias.FSResolveAlias(None)[0] pathname = fsref.as_pathname() sys.argv.append(pathname) - except Exception, e: + except Exception as e: print "argvemulator.py warning: can't unpack an open document event" import traceback traceback.print_exc() Modified: python/branches/p3yk-noslice/Lib/plat-mac/buildtools.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/buildtools.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/buildtools.py Thu Jan 11 00:43:10 2007 @@ -78,7 +78,7 @@ fp.close() try: code = compile(text + '\n', filename, "exec") - except SyntaxError, arg: + except SyntaxError as arg: raise BuildError, "Syntax error in script %s: %s" % (filename, arg) except EOFError: raise BuildError, "End-of-file in script %s" % (filename,) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -764,7 +764,7 @@ directory. Don't moan if any path element already exists.""" try: os.makedirs(dir) - except OSError, why: + except OSError as why: if why.errno != errno.EEXIST: raise Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -114,7 +114,7 @@ try: processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) - except MacOS.Error, arg: + except MacOS.Error as arg: print "Error getting terminology:", arg print "Retry, manually parsing resources" processfile_fromresource(filename, edit_modnames=edit_modnames, @@ -190,7 +190,7 @@ print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname) try: aedescobj, launched = OSATerminology.GetAppTerminology(fullname) - except MacOS.Error, arg: + except MacOS.Error as arg: if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound if verbose: print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually" @@ -244,7 +244,7 @@ talker = aetools.TalkTo(cr) try: talker._start() - except (MacOS.Error, aetools.Error), arg: + except (MacOS.Error, aetools.Error) as arg: if verbose: print >>verbose, 'Warning: start() failed, continuing anyway:', arg reply = talker.send("ascr", "gdte") Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -76,14 +76,14 @@ AppleSingle file""" try: refno = Res.FSpOpenResFile(pathname, 1) - except Res.Error, arg: + except Res.Error as arg: if arg[0] in (-37, -39): # No resource fork. We may be on OSX, and this may be either # a data-fork based resource file or a AppleSingle file # from the CVS repository. try: refno = Res.FSOpenResourceFile(pathname, u'', 1) - except Res.Error, arg: + except Res.Error as arg: if arg[0] != -199: # -199 is "bad resource map" raise @@ -103,14 +103,14 @@ try: refno = Res.FSpOpenResFile(pathname, 1) Res.CloseResFile(refno) - except Res.Error, arg: + except Res.Error as arg: if arg[0] in (-37, -39): # No resource fork. We may be on OSX, and this may be either # a data-fork based resource file or a AppleSingle file # from the CVS repository. try: refno = Res.FSOpenResourceFile(pathname, u'', 1) - except Res.Error, arg: + except Res.Error as arg: if arg[0] != -199: # -199 is "bad resource map" raise Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -76,7 +76,7 @@ url = DEFAULT_PIMPDATABASE_FMT % (PIMP_VERSION, status, pyvers, osname, rel, machine) try: urllib2.urlopen(url) - except urllib2.HTTPError, arg: + except urllib2.HTTPError as arg: pass else: break @@ -589,13 +589,13 @@ installTest = self._dict['Install-test'].strip() + '\n' try: exec(installTest, namespace) - except ImportError, arg: + except ImportError as arg: return "no", str(arg) - except _scriptExc_NotInstalled, arg: + except _scriptExc_NotInstalled as arg: return "no", str(arg) - except _scriptExc_OldInstalled, arg: + except _scriptExc_OldInstalled as arg: return "old", str(arg) - except _scriptExc_BadInstalled, arg: + except _scriptExc_BadInstalled as arg: return "bad", str(arg) except: sys.stderr.write("-------------------------------------\n") Modified: python/branches/p3yk-noslice/Lib/plat-mac/terminalcommand.py ============================================================================== --- python/branches/p3yk-noslice/Lib/plat-mac/terminalcommand.py (original) +++ python/branches/p3yk-noslice/Lib/plat-mac/terminalcommand.py Thu Jan 11 00:43:10 2007 @@ -35,7 +35,7 @@ try: theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout) - except AE.Error, why: + except AE.Error as why: if why[0] != -600: # Terminal.app not yet running raise os.system(START_TERMINAL) Modified: python/branches/p3yk-noslice/Lib/platform.py ============================================================================== --- python/branches/p3yk-noslice/Lib/platform.py (original) +++ python/branches/p3yk-noslice/Lib/platform.py Thu Jan 11 00:43:10 2007 @@ -404,10 +404,10 @@ raise os.error,'command failed' # XXX How can I supress shell errors from being written # to stderr ? - except os.error,why: + except os.error as why: #print 'Command %s failed: %s' % (cmd,why) continue - except IOError,why: + except IOError as why: #print 'Command %s failed: %s' % (cmd,why) continue else: Modified: python/branches/p3yk-noslice/Lib/poplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/poplib.py (original) +++ python/branches/p3yk-noslice/Lib/poplib.py Thu Jan 11 00:43:10 2007 @@ -86,7 +86,7 @@ try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None @@ -262,7 +262,7 @@ """Signoff: commit changes on server, unlock mailbox, close connection.""" try: resp = self._shortcmd('QUIT') - except error_proto, val: + except error_proto as val: resp = val self.file.close() self.sock.close() @@ -347,7 +347,7 @@ try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None @@ -399,7 +399,7 @@ """Signoff: commit changes on server, unlock mailbox, close connection.""" try: resp = self._shortcmd('QUIT') - except error_proto, val: + except error_proto as val: resp = val self.sock.close() del self.sslobj, self.sock Modified: python/branches/p3yk-noslice/Lib/pstats.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pstats.py (original) +++ python/branches/p3yk-noslice/Lib/pstats.py Thu Jan 11 00:43:10 2007 @@ -618,7 +618,7 @@ if line: try: self.stats = Stats(line) - except IOError, args: + except IOError as args: print >> self.stream, args[1] return self.prompt = line + "% " Modified: python/branches/p3yk-noslice/Lib/pty.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pty.py (original) +++ python/branches/p3yk-noslice/Lib/pty.py Thu Jan 11 00:43:10 2007 @@ -56,7 +56,7 @@ else: try: tty_name, master_fd = sgi._getpty(os.O_RDWR, 0666, 0) - except IOError, msg: + except IOError as msg: raise os.error, msg return master_fd, tty_name for x in 'pqrstuvwxyzPQRST': Modified: python/branches/p3yk-noslice/Lib/py_compile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/py_compile.py (original) +++ python/branches/p3yk-noslice/Lib/py_compile.py Thu Jan 11 00:43:10 2007 @@ -123,7 +123,7 @@ codestring = codestring + '\n' try: codeobject = __builtin__.compile(codestring, dfile or file,'exec') - except Exception,err: + except Exception as err: py_exc = PyCompileError(err.__class__,err.args,dfile or file) if doraise: raise py_exc @@ -157,7 +157,7 @@ for filename in args: try: compile(filename, doraise=True) - except PyCompileError,err: + except PyCompileError as err: sys.stderr.write(err.msg) if __name__ == "__main__": Modified: python/branches/p3yk-noslice/Lib/pydoc.py ============================================================================== --- python/branches/p3yk-noslice/Lib/pydoc.py (original) +++ python/branches/p3yk-noslice/Lib/pydoc.py Thu Jan 11 00:43:10 2007 @@ -1479,7 +1479,7 @@ object = type(object) desc += ' object' pager(title % desc + '\n\n' + text.document(object, name)) - except (ImportError, ErrorDuringImport), value: + except (ImportError, ErrorDuringImport) as value: print value def writedoc(thing, forceload=0): @@ -1491,7 +1491,7 @@ file.write(page) file.close() print 'wrote', name + '.html' - except (ImportError, ErrorDuringImport), value: + except (ImportError, ErrorDuringImport) as value: print value def writedocs(dir, pkgpath='', done=None): @@ -1920,7 +1920,7 @@ if path and path != '.': try: obj = locate(path, forceload=1) - except ErrorDuringImport, value: + except ErrorDuringImport as value: self.send_document(path, html.escape(str(value))) return if obj: @@ -2223,7 +2223,7 @@ writedoc(arg) else: help.help(arg) - except ErrorDuringImport, value: + except ErrorDuringImport as value: print value except (getopt.error, BadUsage): Modified: python/branches/p3yk-noslice/Lib/quopri.py ============================================================================== --- python/branches/p3yk-noslice/Lib/quopri.py (original) +++ python/branches/p3yk-noslice/Lib/quopri.py Thu Jan 11 00:43:10 2007 @@ -194,7 +194,7 @@ import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'td') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print "usage: quopri [-t | -d] [file] ..." @@ -218,7 +218,7 @@ else: try: fp = open(file) - except IOError, msg: + except IOError as msg: sys.stderr.write("%s: can't open (%s)\n" % (file, msg)) sts = 1 continue Modified: python/branches/p3yk-noslice/Lib/re.py ============================================================================== --- python/branches/p3yk-noslice/Lib/re.py (original) +++ python/branches/p3yk-noslice/Lib/re.py Thu Jan 11 00:43:10 2007 @@ -229,7 +229,7 @@ raise TypeError, "first argument must be string or compiled pattern" try: p = sre_compile.compile(pattern, flags) - except error, v: + except error as v: raise error, v # invalid expression if len(_cache) >= _MAXCACHE: _cache.clear() @@ -244,7 +244,7 @@ repl, pattern = key try: p = sre_parse.parse_template(repl, pattern) - except error, v: + except error as v: raise error, v # invalid expression if len(_cache_repl) >= _MAXCACHE: _cache_repl.clear() Modified: python/branches/p3yk-noslice/Lib/rexec.py ============================================================================== --- python/branches/p3yk-noslice/Lib/rexec.py (original) +++ python/branches/p3yk-noslice/Lib/rexec.py Thu Jan 11 00:43:10 2007 @@ -551,7 +551,7 @@ if args and args[0] != '-': try: fp = open(args[0]) - except IOError, msg: + except IOError as msg: print "%s: can't open file %r" % (sys.argv[0], args[0]) return 1 if fp.isatty(): @@ -566,7 +566,7 @@ r.s_apply(code.InteractiveConsole.runcode, (self, co)) try: RestrictedConsole(r.modules['__main__'].__dict__).interact() - except SystemExit, n: + except SystemExit as n: return n else: text = fp.read() @@ -574,7 +574,7 @@ c = compile(text, fp.name, 'exec') try: r.s_exec(c) - except SystemExit, n: + except SystemExit as n: return n except: traceback.print_exc() Deleted: /python/branches/p3yk-noslice/Lib/sets.py ============================================================================== --- /python/branches/p3yk-noslice/Lib/sets.py Thu Jan 11 00:43:10 2007 +++ (empty file) @@ -1,577 +0,0 @@ -"""Classes to represent arbitrary sets (including sets of sets). - -This module implements sets using dictionaries whose values are -ignored. The usual operations (union, intersection, deletion, etc.) -are provided as both methods and operators. - -Important: sets are not sequences! While they support 'x in s', -'len(s)', and 'for x in s', none of those operations are unique for -sequences; for example, mappings support all three as well. The -characteristic operation for sequences is subscripting with small -integers: s[i], for i in range(len(s)). Sets don't support -subscripting at all. Also, sequences allow multiple occurrences and -their elements have a definite order; sets on the other hand don't -record multiple occurrences and don't remember the order of element -insertion (which is why they don't support s[i]). - -The following classes are provided: - -BaseSet -- All the operations common to both mutable and immutable - sets. This is an abstract class, not meant to be directly - instantiated. - -Set -- Mutable sets, subclass of BaseSet; not hashable. - -ImmutableSet -- Immutable sets, subclass of BaseSet; hashable. - An iterable argument is mandatory to create an ImmutableSet. - -_TemporarilyImmutableSet -- A wrapper around a Set, hashable, - giving the same hash value as the immutable set equivalent - would have. Do not use this class directly. - -Only hashable objects can be added to a Set. In particular, you cannot -really add a Set as an element to another Set; if you try, what is -actually added is an ImmutableSet built from it (it compares equal to -the one you tried adding). - -When you ask if `x in y' where x is a Set and y is a Set or -ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and -what's tested is actually `z in y'. - -""" - -# Code history: -# -# - Greg V. Wilson wrote the first version, using a different approach -# to the mutable/immutable problem, and inheriting from dict. -# -# - Alex Martelli modified Greg's version to implement the current -# Set/ImmutableSet approach, and make the data an attribute. -# -# - Guido van Rossum rewrote much of the code, made some API changes, -# and cleaned up the docstrings. -# -# - Raymond Hettinger added a number of speedups and other -# improvements. - -from __future__ import generators -try: - from itertools import ifilter, ifilterfalse -except ImportError: - # Code to make the module run under Py2.2 - def ifilter(predicate, iterable): - if predicate is None: - def predicate(x): - return x - for x in iterable: - if predicate(x): - yield x - def ifilterfalse(predicate, iterable): - if predicate is None: - def predicate(x): - return x - for x in iterable: - if not predicate(x): - yield x - try: - True, False - except NameError: - True, False = (0==0, 0!=0) - -__all__ = ['BaseSet', 'Set', 'ImmutableSet'] - -class BaseSet(object): - """Common base class for mutable and immutable sets.""" - - __slots__ = ['_data'] - - # Constructor - - def __init__(self): - """This is an abstract class.""" - # Don't call this from a concrete subclass! - if self.__class__ is BaseSet: - raise TypeError, ("BaseSet is an abstract class. " - "Use Set or ImmutableSet.") - - # Standard protocols: __len__, __repr__, __str__, __iter__ - - def __len__(self): - """Return the number of elements of a set.""" - return len(self._data) - - def __repr__(self): - """Return string representation of a set. - - This looks like 'Set([])'. - """ - return self._repr() - - # __str__ is the same as __repr__ - __str__ = __repr__ - - def _repr(self, sorted=False): - elements = self._data.keys() - if sorted: - elements.sort() - return '%s(%r)' % (self.__class__.__name__, elements) - - def __iter__(self): - """Return an iterator over the elements or a set. - - This is the keys iterator for the underlying dict. - """ - return self._data.iterkeys() - - # Three-way comparison is not supported. However, because __eq__ is - # tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and - # then cmp(x, y) returns 0 (Python doesn't actually call __cmp__ in this - # case). - - def __cmp__(self, other): - raise TypeError, "can't compare sets using cmp()" - - # Equality comparisons using the underlying dicts. Mixed-type comparisons - # are allowed here, where Set == z for non-Set z always returns False, - # and Set != z always True. This allows expressions like "x in y" to - # give the expected result when y is a sequence of mixed types, not - # raising a pointless TypeError just because y contains a Set, or x is - # a Set and y contain's a non-set ("in" invokes only __eq__). - # Subtle: it would be nicer if __eq__ and __ne__ could return - # NotImplemented instead of True or False. Then the other comparand - # would get a chance to determine the result, and if the other comparand - # also returned NotImplemented then it would fall back to object address - # comparison (which would always return False for __eq__ and always - # True for __ne__). However, that doesn't work, because this type - # *also* implements __cmp__: if, e.g., __eq__ returns NotImplemented, - # Python tries __cmp__ next, and the __cmp__ here then raises TypeError. - - def __eq__(self, other): - if isinstance(other, BaseSet): - return self._data == other._data - else: - return False - - def __ne__(self, other): - if isinstance(other, BaseSet): - return self._data != other._data - else: - return True - - # Copying operations - - def copy(self): - """Return a shallow copy of a set.""" - result = self.__class__() - result._data.update(self._data) - return result - - __copy__ = copy # For the copy module - - def __deepcopy__(self, memo): - """Return a deep copy of a set; used by copy module.""" - # This pre-creates the result and inserts it in the memo - # early, in case the deep copy recurses into another reference - # to this same set. A set can't be an element of itself, but - # it can certainly contain an object that has a reference to - # itself. - from copy import deepcopy - result = self.__class__() - memo[id(self)] = result - data = result._data - value = True - for elt in self: - data[deepcopy(elt, memo)] = value - return result - - # Standard set operations: union, intersection, both differences. - # Each has an operator version (e.g. __or__, invoked with |) and a - # method version (e.g. union). - # Subtle: Each pair requires distinct code so that the outcome is - # correct when the type of other isn't suitable. For example, if - # we did "union = __or__" instead, then Set().union(3) would return - # NotImplemented instead of raising TypeError (albeit that *why* it - # raises TypeError as-is is also a bit subtle). - - def __or__(self, other): - """Return the union of two sets as a new set. - - (I.e. all elements that are in either set.) - """ - if not isinstance(other, BaseSet): - return NotImplemented - return self.union(other) - - def union(self, other): - """Return the union of two sets as a new set. - - (I.e. all elements that are in either set.) - """ - result = self.__class__(self) - result._update(other) - return result - - def __and__(self, other): - """Return the intersection of two sets as a new set. - - (I.e. all elements that are in both sets.) - """ - if not isinstance(other, BaseSet): - return NotImplemented - return self.intersection(other) - - def intersection(self, other): - """Return the intersection of two sets as a new set. - - (I.e. all elements that are in both sets.) - """ - if not isinstance(other, BaseSet): - other = Set(other) - if len(self) <= len(other): - little, big = self, other - else: - little, big = other, self - common = ifilter(big._data.__contains__, little) - return self.__class__(common) - - def __xor__(self, other): - """Return the symmetric difference of two sets as a new set. - - (I.e. all elements that are in exactly one of the sets.) - """ - if not isinstance(other, BaseSet): - return NotImplemented - return self.symmetric_difference(other) - - def symmetric_difference(self, other): - """Return the symmetric difference of two sets as a new set. - - (I.e. all elements that are in exactly one of the sets.) - """ - result = self.__class__() - data = result._data - value = True - selfdata = self._data - try: - otherdata = other._data - except AttributeError: - otherdata = Set(other)._data - for elt in ifilterfalse(otherdata.__contains__, selfdata): - data[elt] = value - for elt in ifilterfalse(selfdata.__contains__, otherdata): - data[elt] = value - return result - - def __sub__(self, other): - """Return the difference of two sets as a new Set. - - (I.e. all elements that are in this set and not in the other.) - """ - if not isinstance(other, BaseSet): - return NotImplemented - return self.difference(other) - - def difference(self, other): - """Return the difference of two sets as a new Set. - - (I.e. all elements that are in this set and not in the other.) - """ - result = self.__class__() - data = result._data - try: - otherdata = other._data - except AttributeError: - otherdata = Set(other)._data - value = True - for elt in ifilterfalse(otherdata.__contains__, self): - data[elt] = value - return result - - # Membership test - - def __contains__(self, element): - """Report whether an element is a member of a set. - - (Called in response to the expression `element in self'.) - """ - try: - return element in self._data - except TypeError: - transform = getattr(element, "__as_temporarily_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - return transform() in self._data - - # Subset and superset test - - def issubset(self, other): - """Report whether another set contains this set.""" - self._binary_sanity_check(other) - if len(self) > len(other): # Fast check for obvious cases - return False - for elt in ifilterfalse(other._data.__contains__, self): - return False - return True - - def issuperset(self, other): - """Report whether this set contains another set.""" - self._binary_sanity_check(other) - if len(self) < len(other): # Fast check for obvious cases - return False - for elt in ifilterfalse(self._data.__contains__, other): - return False - return True - - # Inequality comparisons using the is-subset relation. - __le__ = issubset - __ge__ = issuperset - - def __lt__(self, other): - self._binary_sanity_check(other) - return len(self) < len(other) and self.issubset(other) - - def __gt__(self, other): - self._binary_sanity_check(other) - return len(self) > len(other) and self.issuperset(other) - - # Assorted helpers - - def _binary_sanity_check(self, other): - # Check that the other argument to a binary operation is also - # a set, raising a TypeError otherwise. - if not isinstance(other, BaseSet): - raise TypeError, "Binary operation only permitted between sets" - - def _compute_hash(self): - # Calculate hash code for a set by xor'ing the hash codes of - # the elements. This ensures that the hash code does not depend - # on the order in which elements are added to the set. This is - # not called __hash__ because a BaseSet should not be hashable; - # only an ImmutableSet is hashable. - result = 0 - for elt in self: - result ^= hash(elt) - return result - - def _update(self, iterable): - # The main loop for update() and the subclass __init__() methods. - data = self._data - - # Use the fast update() method when a dictionary is available. - if isinstance(iterable, BaseSet): - data.update(iterable._data) - return - - value = True - - if type(iterable) in (list, tuple, xrange): - # Optimized: we know that __iter__() and next() can't - # raise TypeError, so we can move 'try:' out of the loop. - it = iter(iterable) - while True: - try: - for element in it: - data[element] = value - return - except TypeError: - transform = getattr(element, "__as_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - data[transform()] = value - else: - # Safe: only catch TypeError where intended - for element in iterable: - try: - data[element] = value - except TypeError: - transform = getattr(element, "__as_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - data[transform()] = value - - -class ImmutableSet(BaseSet): - """Immutable set class.""" - - __slots__ = ['_hashcode'] - - # BaseSet + hashing - - def __init__(self, iterable=None): - """Construct an immutable set from an optional iterable.""" - self._hashcode = None - self._data = {} - if iterable is not None: - self._update(iterable) - - def __hash__(self): - if self._hashcode is None: - self._hashcode = self._compute_hash() - return self._hashcode - - def __getstate__(self): - return self._data, self._hashcode - - def __setstate__(self, state): - self._data, self._hashcode = state - -class Set(BaseSet): - """ Mutable set class.""" - - __slots__ = [] - - # BaseSet + operations requiring mutability; no hashing - - def __init__(self, iterable=None): - """Construct a set from an optional iterable.""" - self._data = {} - if iterable is not None: - self._update(iterable) - - def __getstate__(self): - # getstate's results are ignored if it is not - return self._data, - - def __setstate__(self, data): - self._data, = data - - def __hash__(self): - """A Set cannot be hashed.""" - # We inherit object.__hash__, so we must deny this explicitly - raise TypeError, "Can't hash a Set, only an ImmutableSet." - - # In-place union, intersection, differences. - # Subtle: The xyz_update() functions deliberately return None, - # as do all mutating operations on built-in container types. - # The __xyz__ spellings have to return self, though. - - def __ior__(self, other): - """Update a set with the union of itself and another.""" - self._binary_sanity_check(other) - self._data.update(other._data) - return self - - def union_update(self, other): - """Update a set with the union of itself and another.""" - self._update(other) - - def __iand__(self, other): - """Update a set with the intersection of itself and another.""" - self._binary_sanity_check(other) - self._data = (self & other)._data - return self - - def intersection_update(self, other): - """Update a set with the intersection of itself and another.""" - if isinstance(other, BaseSet): - self &= other - else: - self._data = (self.intersection(other))._data - - def __ixor__(self, other): - """Update a set with the symmetric difference of itself and another.""" - self._binary_sanity_check(other) - self.symmetric_difference_update(other) - return self - - def symmetric_difference_update(self, other): - """Update a set with the symmetric difference of itself and another.""" - data = self._data - value = True - if not isinstance(other, BaseSet): - other = Set(other) - if self is other: - self.clear() - for elt in other: - if elt in data: - del data[elt] - else: - data[elt] = value - - def __isub__(self, other): - """Remove all elements of another set from this set.""" - self._binary_sanity_check(other) - self.difference_update(other) - return self - - def difference_update(self, other): - """Remove all elements of another set from this set.""" - data = self._data - if not isinstance(other, BaseSet): - other = Set(other) - if self is other: - self.clear() - for elt in ifilter(data.__contains__, other): - del data[elt] - - # Python dict-like mass mutations: update, clear - - def update(self, iterable): - """Add all values from an iterable (such as a list or file).""" - self._update(iterable) - - def clear(self): - """Remove all elements from this set.""" - self._data.clear() - - # Single-element mutations: add, remove, discard - - def add(self, element): - """Add an element to a set. - - This has no effect if the element is already present. - """ - try: - self._data[element] = True - except TypeError: - transform = getattr(element, "__as_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - self._data[transform()] = True - - def remove(self, element): - """Remove an element from a set; it must be a member. - - If the element is not a member, raise a KeyError. - """ - try: - del self._data[element] - except TypeError: - transform = getattr(element, "__as_temporarily_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - del self._data[transform()] - - def discard(self, element): - """Remove an element from a set if it is a member. - - If the element is not a member, do nothing. - """ - try: - self.remove(element) - except KeyError: - pass - - def pop(self): - """Remove and return an arbitrary set element.""" - return self._data.popitem()[0] - - def __as_immutable__(self): - # Return a copy of self as an immutable set - return ImmutableSet(self) - - def __as_temporarily_immutable__(self): - # Return self wrapped in a temporarily immutable set - return _TemporarilyImmutableSet(self) - - -class _TemporarilyImmutableSet(BaseSet): - # Wrap a mutable set as if it was temporarily immutable. - # This only supplies hashing and equality comparisons. - - def __init__(self, set): - self._set = set - self._data = set._data # Needed by ImmutableSet.__eq__() - - def __hash__(self): - return self._set._compute_hash() Modified: python/branches/p3yk-noslice/Lib/sgmllib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sgmllib.py (original) +++ python/branches/p3yk-noslice/Lib/sgmllib.py Thu Jan 11 00:43:10 2007 @@ -530,7 +530,7 @@ else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) Modified: python/branches/p3yk-noslice/Lib/shutil.py ============================================================================== --- python/branches/p3yk-noslice/Lib/shutil.py (original) +++ python/branches/p3yk-noslice/Lib/shutil.py Thu Jan 11 00:43:10 2007 @@ -121,18 +121,18 @@ else: copy2(srcname, dstname) # XXX What about devices, sockets etc.? - except (IOError, os.error), why: + except (IOError, os.error) as why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files - except Error, err: + except Error as err: errors.extend(err.args[0]) try: copystat(src, dst) except WindowsError: # can't copy file access times on Windows pass - except OSError, why: + except OSError as why: errors.extend((src, dst, str(why))) if errors: raise Error, errors @@ -157,7 +157,7 @@ names = [] try: names = os.listdir(path) - except os.error, err: + except os.error as err: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) @@ -170,7 +170,7 @@ else: try: os.remove(fullname) - except os.error, err: + except os.error as err: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) Modified: python/branches/p3yk-noslice/Lib/site.py ============================================================================== --- python/branches/p3yk-noslice/Lib/site.py (original) +++ python/branches/p3yk-noslice/Lib/site.py Thu Jan 11 00:43:10 2007 @@ -391,7 +391,7 @@ import sitecustomize except ImportError: pass - except Exception, err: + except Exception as err: if os.environ.get("PYTHONVERBOSE"): raise sys.stderr.write( Modified: python/branches/p3yk-noslice/Lib/smtpd.py ============================================================================== --- python/branches/p3yk-noslice/Lib/smtpd.py (original) +++ python/branches/p3yk-noslice/Lib/smtpd.py Thu Jan 11 00:43:10 2007 @@ -357,10 +357,10 @@ refused = s.sendmail(mailfrom, rcpttos, data) finally: s.quit() - except smtplib.SMTPRecipientsRefused, e: + except smtplib.SMTPRecipientsRefused as e: print >> DEBUGSTREAM, 'got SMTPRecipientsRefused' refused = e.recipients - except (socket.error, smtplib.SMTPException), e: + except (socket.error, smtplib.SMTPException) as e: print >> DEBUGSTREAM, 'got', e.__class__ # All recipients were refused. If the exception had an associated # error code, use it. Otherwise,fake it with a non-triggering @@ -464,7 +464,7 @@ opts, args = getopt.getopt( sys.argv[1:], 'nVhc:d', ['class=', 'nosetuid', 'version', 'help', 'debug']) - except getopt.error, e: + except getopt.error as e: usage(1, e) options = Options() @@ -528,7 +528,7 @@ nobody = pwd.getpwnam('nobody')[2] try: os.setuid(nobody) - except OSError, e: + except OSError as e: if e.errno != errno.EPERM: raise print >> sys.stderr, \ 'Cannot setuid "nobody"; try running with -n option.' Modified: python/branches/p3yk-noslice/Lib/smtplib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/smtplib.py (original) +++ python/branches/p3yk-noslice/Lib/smtplib.py Thu Jan 11 00:43:10 2007 @@ -306,7 +306,7 @@ af, socktype, proto, canonname, sa = res try: self._get_socket(af,socktype,proto,sa) - except socket.error, msg: + except socket.error as msg: if self.debuglevel > 0: print>>stderr, 'connect fail:', msg if self.sock: self.sock.close() Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -326,7 +326,7 @@ self.fail("should have raised a TypeError") except TypeError: return - except Exception, e: + except Exception as e: print "raised", e.__class__ self.fail("raised wrong exception.") Modified: python/branches/p3yk-noslice/Lib/sqlite3/test/hooks.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sqlite3/test/hooks.py (original) +++ python/branches/p3yk-noslice/Lib/sqlite3/test/hooks.py Thu Jan 11 00:43:10 2007 @@ -36,7 +36,7 @@ try: con.create_collation("X", 42) self.fail("should have raised a TypeError") - except TypeError, e: + except TypeError as e: self.failUnlessEqual(e.args[0], "parameter must be callable") def CheckCreateCollationNotAscii(self): @@ -44,7 +44,7 @@ try: con.create_collation("coll?", cmp) self.fail("should have raised a ProgrammingError") - except sqlite.ProgrammingError, e: + except sqlite.ProgrammingError as e: pass def CheckCollationIsUsed(self): @@ -73,7 +73,7 @@ try: result = con.execute(sql).fetchall() self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0].lower(), "no such collation sequence: mycoll") def CheckCollationRegisterTwice(self): @@ -101,7 +101,7 @@ try: con.execute("select 'a' as x union select 'b' as x order by x collate mycoll") self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: if not e.args[0].startswith("no such collation sequence"): self.fail("wrong OperationalError raised") Modified: python/branches/p3yk-noslice/Lib/sqlite3/test/userfunctions.py ============================================================================== --- python/branches/p3yk-noslice/Lib/sqlite3/test/userfunctions.py (original) +++ python/branches/p3yk-noslice/Lib/sqlite3/test/userfunctions.py Thu Jan 11 00:43:10 2007 @@ -205,7 +205,7 @@ cur.execute("select raiseexception()") cur.fetchone() self.fail("should have raised OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], 'user-defined function raised exception') def CheckParamString(self): @@ -279,7 +279,7 @@ try: cur.execute("select nostep(t) from test") self.fail("should have raised an AttributeError") - except AttributeError, e: + except AttributeError as e: self.failUnlessEqual(e.args[0], "'AggrNoStep' object has no attribute 'step'") def CheckAggrNoFinalize(self): @@ -288,7 +288,7 @@ cur.execute("select nofinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrExceptionInInit(self): @@ -297,7 +297,7 @@ cur.execute("select excInit(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's '__init__' method raised error") def CheckAggrExceptionInStep(self): @@ -306,7 +306,7 @@ cur.execute("select excStep(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'step' method raised error") def CheckAggrExceptionInFinalize(self): @@ -315,7 +315,7 @@ cur.execute("select excFinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrCheckParamStr(self): @@ -384,7 +384,7 @@ def CheckTableAccess(self): try: self.con.execute("select * from t2") - except sqlite.DatabaseError, e: + except sqlite.DatabaseError as e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return @@ -393,7 +393,7 @@ def CheckColumnAccess(self): try: self.con.execute("select c2 from t1") - except sqlite.DatabaseError, e: + except sqlite.DatabaseError as e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return Modified: python/branches/p3yk-noslice/Lib/subprocess.py ============================================================================== --- python/branches/p3yk-noslice/Lib/subprocess.py (original) +++ python/branches/p3yk-noslice/Lib/subprocess.py Thu Jan 11 00:43:10 2007 @@ -792,7 +792,7 @@ env, cwd, startupinfo) - except pywintypes.error, e: + except pywintypes.error as e: # Translate pywintypes.error to WindowsError, which is # a subclass of OSError. FIXME: We should really # translate errno using _sys_errlist (or simliar), but @@ -1190,7 +1190,7 @@ print "Trying a weird file..." try: print Popen(["/this/path/does/not/exist"]).communicate() - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: print "The file didn't exist. I thought so..." print "Child traceback:" Modified: python/branches/p3yk-noslice/Lib/tabnanny.py ============================================================================== --- python/branches/p3yk-noslice/Lib/tabnanny.py (original) +++ python/branches/p3yk-noslice/Lib/tabnanny.py Thu Jan 11 00:43:10 2007 @@ -43,7 +43,7 @@ global verbose, filename_only try: opts, args = getopt.getopt(sys.argv[1:], "qv") - except getopt.error, msg: + except getopt.error as msg: errprint(msg) return for o, a in opts: @@ -95,7 +95,7 @@ try: f = open(file) - except IOError, msg: + except IOError as msg: errprint("%r: I/O Error: %s" % (file, msg)) return @@ -105,15 +105,15 @@ try: process_tokens(tokenize.generate_tokens(f.readline)) - except tokenize.TokenError, msg: + except tokenize.TokenError as msg: errprint("%r: Token Error: %s" % (file, msg)) return - except IndentationError, msg: + except IndentationError as msg: errprint("%r: Indentation Error: %s" % (file, msg)) return - except NannyNag, nag: + except NannyNag as nag: badline = nag.get_lineno() line = nag.get_line() if verbose: Modified: python/branches/p3yk-noslice/Lib/tarfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/tarfile.py (original) +++ python/branches/p3yk-noslice/Lib/tarfile.py Thu Jan 11 00:43:10 2007 @@ -1540,7 +1540,7 @@ self.chown(tarinfo, path) self.utime(tarinfo, path) self.chmod(tarinfo, path) - except ExtractError, e: + except ExtractError as e: if self.errorlevel > 1: raise else: @@ -1565,7 +1565,7 @@ try: self._extract_member(tarinfo, os.path.join(path, tarinfo.name)) - except EnvironmentError, e: + except EnvironmentError as e: if self.errorlevel > 0: raise else: @@ -1573,7 +1573,7 @@ self._dbg(1, "tarfile: %s" % e.strerror) else: self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) - except ExtractError, e: + except ExtractError as e: if self.errorlevel > 1: raise else: @@ -1681,7 +1681,7 @@ """ try: os.mkdir(targetpath) - except EnvironmentError, e: + except EnvironmentError as e: if e.errno != errno.EEXIST: raise @@ -1745,11 +1745,11 @@ try: self._extract_member(self.getmember(linkpath), targetpath) - except (EnvironmentError, KeyError), e: + except (EnvironmentError, KeyError) as e: linkpath = os.path.normpath(linkpath) try: shutil.copy2(linkpath, targetpath) - except EnvironmentError, e: + except EnvironmentError as e: raise IOError("link could not be created") def chown(self, tarinfo, targetpath): @@ -1777,7 +1777,7 @@ else: if sys.platform != "os2emx": os.chown(targetpath, u, g) - except EnvironmentError, e: + except EnvironmentError as e: raise ExtractError("could not change owner") def chmod(self, tarinfo, targetpath): @@ -1786,7 +1786,7 @@ if hasattr(os, 'chmod'): try: os.chmod(targetpath, tarinfo.mode) - except EnvironmentError, e: + except EnvironmentError as e: raise ExtractError("could not change mode") def utime(self, tarinfo, targetpath): @@ -1800,7 +1800,7 @@ return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) - except EnvironmentError, e: + except EnvironmentError as e: raise ExtractError("could not change modification time") #-------------------------------------------------------------------------- @@ -1833,7 +1833,7 @@ tarinfo = self.proc_member(tarinfo) - except HeaderError, e: + except HeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE Modified: python/branches/p3yk-noslice/Lib/telnetlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/telnetlib.py (original) +++ python/branches/p3yk-noslice/Lib/telnetlib.py Thu Jan 11 00:43:10 2007 @@ -227,7 +227,7 @@ try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None Modified: python/branches/p3yk-noslice/Lib/tempfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/tempfile.py (original) +++ python/branches/p3yk-noslice/Lib/tempfile.py Thu Jan 11 00:43:10 2007 @@ -201,7 +201,7 @@ _os.unlink(filename) del fp, fd return dir - except (OSError, IOError), e: + except (OSError, IOError) as e: if e[0] != _errno.EEXIST: break # no point trying more names in this directory pass @@ -236,7 +236,7 @@ fd = _os.open(file, flags, 0600) _set_cloexec(fd) return (fd, _os.path.abspath(file)) - except OSError, e: + except OSError as e: if e.errno == _errno.EEXIST: continue # try again raise @@ -327,7 +327,7 @@ try: _os.mkdir(file, 0700) return file - except OSError, e: + except OSError as e: if e.errno == _errno.EEXIST: continue # try again raise Modified: python/branches/p3yk-noslice/Lib/test/pickletester.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/pickletester.py (original) +++ python/branches/p3yk-noslice/Lib/test/pickletester.py Thu Jan 11 00:43:10 2007 @@ -585,7 +585,7 @@ badpickle = pickle.PROTO + chr(oob) + build_none try: self.loads(badpickle) - except ValueError, detail: + except ValueError as detail: self.failUnless(str(detail).startswith( "unsupported pickle protocol")) else: Modified: python/branches/p3yk-noslice/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/regrtest.py (original) +++ python/branches/p3yk-noslice/Lib/test/regrtest.py Thu Jan 11 00:43:10 2007 @@ -211,7 +211,7 @@ 'coverdir=', 'nocoverdir', 'runleaks', 'huntrleaks=', 'verbose2', 'memlimit=', ]) - except getopt.error, msg: + except getopt.error as msg: usage(2, msg) # Defaults @@ -556,19 +556,19 @@ dash_R(the_module, test, indirect_test, huntrleaks) finally: sys.stdout = save_stdout - except test_support.ResourceDenied, msg: + except test_support.ResourceDenied as msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() return -2 - except (ImportError, test_support.TestSkipped), msg: + except (ImportError, test_support.TestSkipped) as msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() return -1 except KeyboardInterrupt: raise - except test_support.TestFailed, msg: + except test_support.TestFailed as msg: print "test", test, "failed --", msg sys.stdout.flush() return 0 @@ -640,7 +640,7 @@ print "%r left behind %s %r" % (testname, kind, name) try: nuker(name) - except Exception, msg: + except Exception as msg: print >> sys.stderr, ("%r left behind %s %r and it couldn't be " "removed: %s" % (testname, kind, name, msg)) Modified: python/branches/p3yk-noslice/Lib/test/sortperf.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/sortperf.py (original) +++ python/branches/p3yk-noslice/Lib/test/sortperf.py Thu Jan 11 00:43:10 2007 @@ -37,7 +37,7 @@ os.unlink(fn) except os.error: pass - except IOError, msg: + except IOError as msg: print "can't write", fn, ":", msg else: result = marshal.load(fp) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -967,7 +967,7 @@ def f(): yield 4 + "" self.fixtype(' ').join(f()) - except TypeError, e: + except TypeError as e: if '+' not in str(e): self.fail('join() ate exception message') else: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -373,13 +373,11 @@ return badval try: bool(A()) - except (Exception), e_bool: - pass - try: - len(A()) - except (Exception), e_len: - pass - self.assertEqual(str(e_bool), str(e_len)) + except (Exception) as e_bool: + try: + len(A()) + except (Exception) as e_len: + self.assertEqual(str(e_bool), str(e_len)) def test_main(): test_support.run_unittest(BoolTest) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -181,7 +181,7 @@ def get_error(self, exc, section, option): try: self.cf.get(section, option) - except exc, e: + except exc as e: return e else: self.fail("expected exception type %s.%s" Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -50,7 +50,7 @@ raise ValueError, "unknown method: %s" % method try: return cgi.parse(fp, env, strict_parsing=1) - except StandardError, err: + except StandardError as err: return ComparableException(err) # A list of test cases. Each test case is a a two-tuple that contains Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -372,7 +372,7 @@ a = property(booh) try: A().a # Raised AttributeError: A instance has no attribute 'a' -except AttributeError, x: +except AttributeError as x: if str(x) != "booh": print "attribute error for A().a got masked:", str(x) @@ -384,7 +384,7 @@ __init__ = property(booh) try: I() # In debug mode, printed XXX undetected error and raises AttributeError -except AttributeError, x: +except AttributeError as x: pass else: print "attribute error for I.__init__ got masked" Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -595,7 +595,7 @@ if sys.maxunicode > 0xffff: try: "\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal") - except UnicodeDecodeError, ex: + except UnicodeDecodeError as ex: self.assertEquals("unicode_internal", ex.encoding) self.assertEquals("\x00\x00\x00\x00\x00\x11\x11\x00", ex.object) self.assertEquals(4, ex.start) @@ -782,7 +782,7 @@ prepped = unicode(prepped, "utf-8") try: self.assertEquals(nameprep(orig), prepped) - except Exception,e: + except Exception as e: raise test_support.TestFailed("Test 3.%d: %s" % (pos+1, str(e))) class IDNACodecTest(unittest.TestCase): Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -44,7 +44,7 @@ else: try: compiler.compile(buf, basename, "exec") - except Exception, e: + except Exception as e: args = list(e.args) args[0] += "[in file %s]" % basename e.args = tuple(args) Modified: python/branches/p3yk-noslice/Lib/test/test_contextlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_contextlib.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_contextlib.py Thu Jan 11 00:43:10 2007 @@ -76,7 +76,7 @@ state.append(1) try: yield 42 - except ZeroDivisionError, e: + except ZeroDivisionError as e: state.append(e.args[0]) self.assertEqual(state, [1, 42, 999]) with woohoo() as x: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -257,7 +257,7 @@ try: c.load(filename="for this test to work, a file with this " "filename should not exist") - except IOError, exc: + except IOError as exc: # exactly IOError, not LoadError self.assertEqual(exc.__class__, IOError) else: @@ -1723,7 +1723,6 @@ def test_main(verbose=None): - from test import test_sets test_support.run_unittest( DateTimeTests, HeaderTests, 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 Thu Jan 11 00:43:10 2007 @@ -16,7 +16,8 @@ for suffix in ['', '.pag', '.dir', '.db']: try: os.unlink(filename + suffix) - except OSError, (errno, strerror): + except OSError as e: + (errno, strerror) = e # if we can't delete the file because of permissions, # nothing will work, so skip the test if errno == 1: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -146,7 +146,7 @@ print 'Error in test cases:' print line continue - except DecimalException, exception: + except DecimalException as exception: #Exception raised where there shoudn't have been one. self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line) @@ -238,7 +238,7 @@ funct(self.context.create_decimal(v)) except error: pass - except Signals, e: + except Signals as e: self.fail("Raised %s in %s when %s disabled" % \ (e, s, error)) else: @@ -258,7 +258,7 @@ funct(*vals) except error: pass - except Signals, e: + except Signals as e: self.fail("Raised %s in %s when %s disabled" % \ (e, s, error)) else: @@ -268,7 +268,7 @@ result = str(funct(*vals)) if fname == 'same_quantum': result = str(int(eval(result))) # 'True', 'False' -> '1', '0' - except Signals, error: + except Signals as error: self.fail("Raised %s in %s" % (error, s)) except: #Catch any error long enough to state the test case. print "ERROR:", s Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -43,7 +43,7 @@ self.assertEqual(d2.default_factory, None) try: d2[15] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (15,)) else: self.fail("d2[15] didn't raise KeyError") Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -945,7 +945,7 @@ def raises(exc, expected, callable, *args): try: callable(*args) - except exc, msg: + except exc as msg: if not str(msg).startswith(expected): raise TestFailed, "Message %r, expected %r" % (str(msg), expected) @@ -1806,7 +1806,7 @@ no = NoWeak() try: weakref.ref(no) - except TypeError, msg: + except TypeError as msg: verify(str(msg).find("weak reference") >= 0) else: verify(0, "weakref.ref(no) should be illegal") @@ -1859,7 +1859,7 @@ for attr in "__doc__", "fget", "fset", "fdel": try: setattr(raw, attr, 42) - except TypeError, msg: + except TypeError as msg: if str(msg).find('readonly') < 0: raise TestFailed("when setting readonly attr %r on a " "property, got unexpected TypeError " @@ -2409,7 +2409,7 @@ for code in code1, code2, code3: try: sandbox.r_exec(code) - except IOError, msg: + except IOError as msg: if str(msg).find("restricted") >= 0: outcome = "OK" else: @@ -3516,7 +3516,7 @@ try: D.__bases__ = () - except TypeError, msg: + except TypeError as msg: if str(msg) == "a new-style class can't have only classic bases": raise TestFailed, "wrong error message for .__bases__ = ()" else: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -414,7 +414,7 @@ e = E() try: e[42] - except RuntimeError, err: + except RuntimeError as err: self.assertEqual(err.args, (42,)) else: self.fail_("e[42] didn't raise RuntimeError") @@ -425,7 +425,7 @@ f = F() try: f[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("f[42] didn't raise KeyError") @@ -434,7 +434,7 @@ g = G() try: g[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("g[42] didn't raise KeyError") @@ -444,7 +444,7 @@ d = {} try: d[(1,)] - except KeyError, e: + except KeyError as e: self.assertEqual(e.args, ((1,),)) else: self.fail("missing KeyError") Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -18,7 +18,7 @@ if verbose: print 'trying to open:', s, l = dl.open(s) - except dl.error, err: + except dl.error as err: if verbose: print 'failed', repr(str(err)) pass Modified: python/branches/p3yk-noslice/Lib/test/test_eof.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_eof.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_eof.py Thu Jan 11 00:43:10 2007 @@ -11,7 +11,7 @@ try: eval("""'this is a test\ """) - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(str(msg), expect) else: raise test_support.TestFailed @@ -20,7 +20,7 @@ expect = "EOF while scanning triple-quoted string (, line 1)" try: eval("""'''this is a test""") - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(str(msg), expect) else: raise test_support.TestFailed Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -21,17 +21,17 @@ try: import exceptions reload(exceptions) - except ImportError, e: + except ImportError as e: self.fail("reloading exceptions: %s" % e) def raise_catch(self, exc, excname): try: raise exc, "spam" - except exc, err: + except exc as err: buf1 = str(err) try: raise exc("spam") - except exc, err: + except exc as err: buf2 = str(err) self.assertEquals(buf1, buf2) self.assertEquals(exc.__name__, excname) @@ -115,7 +115,7 @@ self.raise_catch(Exception, "Exception") try: x = 1/0 - except Exception, e: pass + except Exception as e: pass def testSyntaxErrorMessage(self): # make sure the right exception message is raised for each of @@ -124,7 +124,7 @@ def ckmsg(src, msg): try: compile(src, '', 'exec') - except SyntaxError, e: + except SyntaxError as e: if e.msg != msg: self.fail("expected %s, got %s" % (msg, e.msg)) else: @@ -163,7 +163,7 @@ import _testcapi try: _testcapi.raise_exception(BadException, 1) - except TypeError, err: + except TypeError as err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEquals(co.co_name, "test_capi1") @@ -175,7 +175,7 @@ import _testcapi try: _testcapi.raise_exception(BadException, 0) - except RuntimeError, err: + except RuntimeError as err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEquals(co.co_name, "__init__") @@ -285,7 +285,7 @@ for exc, args, expected in exceptionList: try: raise exc(*args) - except BaseException, e: + except BaseException as e: if type(e) is not exc: raise # Verify module name @@ -344,6 +344,16 @@ self.failUnless(str(Exception('a'))) self.failUnless(unicode(Exception(u'a'))) + def testExceptionCleanup(self): + # Make sure "except V as N" exceptions are cleaned up properly + + try: + raise Exception() + except Exception as e: + self.failUnless(e) + del e + self.failIf('e' in locals()) + def test_main(): run_unittest(ExceptionTests) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -35,21 +35,21 @@ try: g() -except TypeError, err: +except TypeError as err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" try: g(*()) -except TypeError, err: +except TypeError as err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" try: g(*(), **{}) -except TypeError, err: +except TypeError as err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" @@ -61,7 +61,7 @@ class Nothing: pass try: g(*Nothing()) -except TypeError, attr: +except TypeError as attr: pass else: print "should raise TypeError" @@ -71,7 +71,7 @@ return 5 try: g(*Nothing()) -except TypeError, attr: +except TypeError as attr: pass else: print "should raise TypeError" @@ -93,7 +93,7 @@ return self try: g(*Nothing()) -except TypeError, attr: +except TypeError as attr: pass else: print "should raise TypeError" @@ -132,77 +132,77 @@ try: g(1, 2, 3, **{'x':4, 'y':5}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: keyword parameter redefined" try: g(1, 2, 3, a=4, b=5, *(6, 7), **{'a':8, 'b':9}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: keyword parameter redefined" try: f(**{1:2}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: keywords must be strings" try: h(**{'e': 2}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: unexpected keyword argument: e" try: h(*h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: * argument must be a tuple" try: dir(*h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: * argument must be a tuple" try: None(*h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: * argument must be a tuple" try: h(**h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: ** argument must be a dictionary" try: dir(**h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: ** argument must be a dictionary" try: None(**h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: ** argument must be a dictionary" try: dir(b=1,**{'b':1}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: dir() got multiple values for keyword argument 'b'" @@ -226,13 +226,13 @@ print Foo.method(x, *(1, 2)) try: print Foo.method(*(1, 2, 3)) -except TypeError, err: +except TypeError as err: pass else: print 'expected a TypeError for unbound method call' try: print Foo.method(1, *(2, 3)) -except TypeError, err: +except TypeError as err: pass else: print 'expected a TypeError for unbound method call' @@ -276,4 +276,4 @@ for k in kwargs: kwdict[k] = k + k print func.func_name, args, sortdict(kwdict), '->', try: func(*args, **kwdict) - except TypeError, err: print err + except TypeError as err: print err Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -159,7 +159,7 @@ bad_mode = "qwerty" try: f = open(TESTFN, bad_mode) - except ValueError, msg: + except ValueError as msg: if msg[0] != 0: s = str(msg) if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: @@ -183,7 +183,7 @@ d = int(f.read()) f.close() f.close() - except IOError, msg: + except IOError as msg: self.fail('error setting buffer size %d: %s' % (s, str(msg))) self.assertEquals(d, s) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -199,7 +199,7 @@ def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) - except exception, exc: + except exception as exc: if str(exc) == excmsg: if verbose: print "yes" Modified: python/branches/p3yk-noslice/Lib/test/test_frozen.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_frozen.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_frozen.py Thu Jan 11 00:43:10 2007 @@ -12,17 +12,17 @@ try: import __hello__ -except ImportError, x: +except ImportError as x: raise TestFailed, "import __hello__ failed:" + str(x) try: import __phello__ -except ImportError, x: +except ImportError as x: raise TestFailed, "import __phello__ failed:" + str(x) try: import __phello__.spam -except ImportError, x: +except ImportError as x: raise TestFailed, "import __phello__.spam failed:" + str(x) if sys.platform != "mac": # On the Mac this import does succeed. Modified: python/branches/p3yk-noslice/Lib/test/test_future.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_future.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_future.py Thu Jan 11 00:43:10 2007 @@ -29,7 +29,7 @@ def test_badfuture3(self): try: from test import badsyntax_future3 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future3", '3')) else: self.fail("expected exception didn't occur") @@ -37,7 +37,7 @@ def test_badfuture4(self): try: from test import badsyntax_future4 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future4", '3')) else: self.fail("expected exception didn't occur") @@ -45,7 +45,7 @@ def test_badfuture5(self): try: from test import badsyntax_future5 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future5", '4')) else: self.fail("expected exception didn't occur") @@ -53,7 +53,7 @@ def test_badfuture6(self): try: from test import badsyntax_future6 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future6", '3')) else: self.fail("expected exception didn't occur") @@ -61,7 +61,7 @@ def test_badfuture7(self): try: from test import badsyntax_future7 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future7", '3')) else: self.fail("expected exception didn't occur") @@ -69,7 +69,7 @@ def test_badfuture8(self): try: from test import badsyntax_future8 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future8", '3')) else: self.fail("expected exception didn't occur") @@ -77,7 +77,7 @@ def test_badfuture9(self): try: from test import badsyntax_future9 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future9", '3')) else: self.fail("expected exception didn't occur") Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -1554,7 +1554,7 @@ ... while True: ... try: ... print (yield) -... except ValueError,v: +... except ValueError as v: ... print "caught ValueError (%s)" % (v), >>> import sys >>> g = f() Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -554,7 +554,7 @@ assert 1, lambda x:x+1 try: assert 0, "msg" - except AssertionError, e: + except AssertionError as e: self.assertEquals(e.args[0], "msg") else: if __debug__: @@ -612,7 +612,7 @@ def testTry(self): ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] ### | 'try' ':' suite 'finally' ':' suite - ### except_clause: 'except' [expr [',' expr]] + ### except_clause: 'except' [expr ['as' expr]] try: 1/0 except ZeroDivisionError: @@ -621,14 +621,14 @@ pass try: 1/0 except EOFError: pass - except TypeError, msg: pass - except RuntimeError, msg: pass + except TypeError as msg: pass + except RuntimeError as msg: pass except: pass else: pass try: 1/0 except (EOFError, TypeError, ZeroDivisionError): pass try: 1/0 - except (EOFError, TypeError, ZeroDivisionError), msg: pass + except (EOFError, TypeError, ZeroDivisionError) as msg: pass try: pass finally: pass Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -55,7 +55,7 @@ try: try: mod = __import__(TESTFN) - except ImportError, err: + except ImportError as err: self.fail("import from %s failed: %s" % (ext, err)) self.assertEquals(mod.a, a, @@ -68,7 +68,7 @@ try: try: reload(mod) - except ImportError, err: + except ImportError as err: self.fail("import from .pyc/.pyo failed: %s" % err) finally: try: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -27,7 +27,7 @@ try: a = linuxaudiodev.open('w') - except linuxaudiodev.error, msg: + except linuxaudiodev.error as msg: if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise TestSkipped, msg raise TestFailed, msg @@ -62,27 +62,27 @@ nchannels = 1 try: a.setparameters(-1, size, nchannels, fmt) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, -2, nchannels, fmt) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, size, 3, fmt) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, size, nchannels, 177) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, 16, nchannels, fmt) - except ValueError, msg: + except ValueError as msg: print msg def test(): Modified: python/branches/p3yk-noslice/Lib/test/test_nis.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_nis.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_nis.py Thu Jan 11 00:43:10 2007 @@ -6,7 +6,7 @@ def test_maps(self): try: maps = nis.maps() - except nis.error, msg: + except nis.error as msg: # NIS is probably not active, so this test isn't useful if verbose: self.fail("(failing because of verbose mode) %s" % msg) Modified: python/branches/p3yk-noslice/Lib/test/test_opcodes.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_opcodes.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_opcodes.py Thu Jan 11 00:43:10 2007 @@ -47,12 +47,12 @@ b = BClass() try: raise AClass, b - except BClass, v: + except BClass as v: if v != b: self.fail("v!=b") else: self.fail("no exception") try: raise b - except AClass, v: + except AClass as v: if v != b: self.fail("v!=b AClass") else: self.fail("no exception") @@ -63,7 +63,7 @@ ##else: self.fail("no exception") try: raise DClass, a - except DClass, v: + except DClass as v: self.assert_(isinstance(v, DClass)) else: self.fail("no exception") Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -114,7 +114,7 @@ try: func(*args, **kwargs) - except expected_exception, err: + except expected_exception as err: actual_message = str(err) if isinstance(expected_message, retype): self.assert_(expected_message.search(actual_message), @@ -152,7 +152,7 @@ """ try: self.parser.parse_args(cmdline_args) - except InterceptedError, err: + except InterceptedError as err: self.assertEqual(err.error_message, expected_output) else: self.assertFalse("expected parse failure") @@ -175,7 +175,7 @@ output = sys.stdout.getvalue() sys.stdout = save_stdout - except InterceptedError, err: + except InterceptedError as err: self.assert_( type(output) is types.StringType, "expected output to be an ordinary string, not %r" @@ -460,7 +460,7 @@ return int(value) else: return int(value[:-1]) * _time_units[value[-1]] - except ValueError, IndexError: + except ValueError as IndexError: raise OptionValueError( 'option %s: invalid duration: %r' % (opt, value)) Modified: python/branches/p3yk-noslice/Lib/test/test_os.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_os.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_os.py Thu Jan 11 00:43:10 2007 @@ -179,7 +179,7 @@ import statvfs try: result = os.statvfs(self.fname) - except OSError, e: + except OSError as e: # On AtheOS, glibc always returns ENOSYS import errno if e.errno == errno.ENOSYS: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -48,7 +48,7 @@ def play_sound_file(data, rate, ssize, nchannels): try: dsp = ossaudiodev.open('w') - except IOError, msg: + except IOError as msg: if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise TestSkipped, msg raise TestFailed, msg @@ -142,7 +142,7 @@ try: result = dsp.setparameters(fmt, channels, rate, True) raise AssertionError("setparameters: expected OSSAudioError") - except ossaudiodev.OSSAudioError, err: + except ossaudiodev.OSSAudioError as err: print "setparameters: got OSSAudioError as expected" def test(): Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -15,7 +15,7 @@ t = st1.totuple() try: st2 = parser.sequence2st(t) - except parser.ParserError, why: + except parser.ParserError as why: self.fail("could not roundtrip %r: %s" % (s, why)) self.assertEquals(t, st2.totuple(), Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -50,7 +50,7 @@ fn(filename) raise test_support.TestFailed("Expected to fail calling '%s(%r)'" % (fn.__name__, filename)) - except expected_exception, details: + except expected_exception as details: if check_fn_in_exception and details.filename != filename: raise test_support.TestFailed("Function '%s(%r) failed with " "bad filename in the exception: %r" Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -177,7 +177,7 @@ print "Legal values tested o.k." try: expat.ParserCreate(namespace_separator=42) -except TypeError, e: +except TypeError as e: print "Caught expected TypeError:" print e else: @@ -185,7 +185,7 @@ try: expat.ParserCreate(namespace_separator='too long') -except ValueError, e: +except ValueError as e: print "Caught expected ValueError:" print e else: @@ -321,7 +321,7 @@ try: parser.Parse("", 1) -except RuntimeError, e: +except RuntimeError as e: if e.args[0] != "a": print "Expected RuntimeError for element 'a'; found %r" % e.args[0] else: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -633,7 +633,7 @@ else: try: result = obj.search(s) - except re.error, msg: + except re.error as msg: print '=== Unexpected exception', t, repr(msg) if outcome == SYNTAX_ERROR: # This should have been a syntax error; forget it. Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -117,7 +117,7 @@ entry = parts[0] try: del sys.modules[entry] - except KeyError, ex: + except KeyError as ex: if verbose: print ex # Persist with cleaning up if verbose: print " Removed sys.modules entries" del sys.path[0] @@ -126,18 +126,18 @@ for name in files: try: os.remove(os.path.join(root, name)) - except OSError, ex: + except OSError as ex: if verbose: print ex # Persist with cleaning up for name in dirs: fullname = os.path.join(root, name) try: os.rmdir(fullname) - except OSError, ex: + except OSError as ex: if verbose: print ex # Persist with cleaning up try: os.rmdir(top) if verbose: print " Removed package tree" - except OSError, ex: + except OSError as ex: if verbose: print ex # Persist with cleaning up def _check_module(self, depth): Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -479,7 +479,7 @@ source.setSystemId(name) try: parser.parse(source) - except SAXException, e: + except SAXException as e: return e.getSystemId() == name def test_expat_incomplete(): Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -332,7 +332,7 @@ for v1 in ['Q', (1,)]: try: self.s.remove(v1) - except KeyError, e: + except KeyError as e: v2 = e.args[0] self.assertEqual(v1, v2) else: @@ -1451,7 +1451,6 @@ #============================================================================== def test_main(verbose=None): - from test import test_sets test_classes = ( TestSet, TestSetSubclass, Deleted: /python/branches/p3yk-noslice/Lib/test/test_sets.py ============================================================================== --- /python/branches/p3yk-noslice/Lib/test/test_sets.py Thu Jan 11 00:43:10 2007 +++ (empty file) @@ -1,853 +0,0 @@ -#!/usr/bin/env python - -import unittest, operator, copy, pickle, random -from sets import Set, ImmutableSet -from test import test_support - -empty_set = Set() - -#============================================================================== - -class TestBasicOps(unittest.TestCase): - - def test_repr(self): - if self.repr is not None: - self.assertEqual(repr(self.set), self.repr) - - def test_length(self): - self.assertEqual(len(self.set), self.length) - - def test_self_equality(self): - self.assertEqual(self.set, self.set) - - def test_equivalent_equality(self): - self.assertEqual(self.set, self.dup) - - def test_copy(self): - self.assertEqual(self.set.copy(), self.dup) - - def test_self_union(self): - result = self.set | self.set - self.assertEqual(result, self.dup) - - def test_empty_union(self): - result = self.set | empty_set - self.assertEqual(result, self.dup) - - def test_union_empty(self): - result = empty_set | self.set - self.assertEqual(result, self.dup) - - def test_self_intersection(self): - result = self.set & self.set - self.assertEqual(result, self.dup) - - def test_empty_intersection(self): - result = self.set & empty_set - self.assertEqual(result, empty_set) - - def test_intersection_empty(self): - result = empty_set & self.set - self.assertEqual(result, empty_set) - - def test_self_symmetric_difference(self): - result = self.set ^ self.set - self.assertEqual(result, empty_set) - - def checkempty_symmetric_difference(self): - result = self.set ^ empty_set - self.assertEqual(result, self.set) - - def test_self_difference(self): - result = self.set - self.set - self.assertEqual(result, empty_set) - - def test_empty_difference(self): - result = self.set - empty_set - self.assertEqual(result, self.dup) - - def test_empty_difference_rev(self): - result = empty_set - self.set - self.assertEqual(result, empty_set) - - def test_iteration(self): - for v in self.set: - self.assert_(v in self.values) - - def test_pickling(self): - p = pickle.dumps(self.set) - copy = pickle.loads(p) - self.assertEqual(self.set, copy, - "%s != %s" % (self.set, copy)) - -#------------------------------------------------------------------------------ - -class TestBasicOpsEmpty(TestBasicOps): - def setUp(self): - self.case = "empty set" - self.values = [] - self.set = Set(self.values) - self.dup = Set(self.values) - self.length = 0 - self.repr = "Set([])" - -#------------------------------------------------------------------------------ - -class TestBasicOpsSingleton(TestBasicOps): - def setUp(self): - self.case = "unit set (number)" - self.values = [3] - self.set = Set(self.values) - self.dup = Set(self.values) - self.length = 1 - self.repr = "Set([3])" - - def test_in(self): - self.failUnless(3 in self.set) - - def test_not_in(self): - self.failUnless(2 not in self.set) - -#------------------------------------------------------------------------------ - -class TestBasicOpsTuple(TestBasicOps): - def setUp(self): - self.case = "unit set (tuple)" - self.values = [(0, "zero")] - self.set = Set(self.values) - self.dup = Set(self.values) - self.length = 1 - self.repr = "Set([(0, 'zero')])" - - def test_in(self): - self.failUnless((0, "zero") in self.set) - - def test_not_in(self): - self.failUnless(9 not in self.set) - -#------------------------------------------------------------------------------ - -class TestBasicOpsTriple(TestBasicOps): - def setUp(self): - self.case = "triple set" - self.values = [0, "zero", operator.add] - self.set = Set(self.values) - self.dup = Set(self.values) - self.length = 3 - self.repr = None - -#============================================================================== - -def baditer(): - raise TypeError - yield True - -def gooditer(): - yield True - -class TestExceptionPropagation(unittest.TestCase): - """SF 628246: Set constructor should not trap iterator TypeErrors""" - - def test_instanceWithException(self): - self.assertRaises(TypeError, Set, baditer()) - - def test_instancesWithoutException(self): - # All of these iterables should load without exception. - Set([1,2,3]) - Set((1,2,3)) - Set({'one':1, 'two':2, 'three':3}) - Set(xrange(3)) - Set('abc') - Set(gooditer()) - -#============================================================================== - -class TestSetOfSets(unittest.TestCase): - def test_constructor(self): - inner = Set([1]) - outer = Set([inner]) - element = outer.pop() - self.assertEqual(type(element), ImmutableSet) - outer.add(inner) # Rebuild set of sets with .add method - outer.remove(inner) - self.assertEqual(outer, Set()) # Verify that remove worked - outer.discard(inner) # Absence of KeyError indicates working fine - -#============================================================================== - -class TestBinaryOps(unittest.TestCase): - def setUp(self): - self.set = Set((2, 4, 6)) - - def test_eq(self): # SF bug 643115 - self.assertEqual(self.set, Set({2:1,4:3,6:5})) - - def test_union_subset(self): - result = self.set | Set([2]) - self.assertEqual(result, Set((2, 4, 6))) - - def test_union_superset(self): - result = self.set | Set([2, 4, 6, 8]) - self.assertEqual(result, Set([2, 4, 6, 8])) - - def test_union_overlap(self): - result = self.set | Set([3, 4, 5]) - self.assertEqual(result, Set([2, 3, 4, 5, 6])) - - def test_union_non_overlap(self): - result = self.set | Set([8]) - self.assertEqual(result, Set([2, 4, 6, 8])) - - def test_intersection_subset(self): - result = self.set & Set((2, 4)) - self.assertEqual(result, Set((2, 4))) - - def test_intersection_superset(self): - result = self.set & Set([2, 4, 6, 8]) - self.assertEqual(result, Set([2, 4, 6])) - - def test_intersection_overlap(self): - result = self.set & Set([3, 4, 5]) - self.assertEqual(result, Set([4])) - - def test_intersection_non_overlap(self): - result = self.set & Set([8]) - self.assertEqual(result, empty_set) - - def test_sym_difference_subset(self): - result = self.set ^ Set((2, 4)) - self.assertEqual(result, Set([6])) - - def test_sym_difference_superset(self): - result = self.set ^ Set((2, 4, 6, 8)) - self.assertEqual(result, Set([8])) - - def test_sym_difference_overlap(self): - result = self.set ^ Set((3, 4, 5)) - self.assertEqual(result, Set([2, 3, 5, 6])) - - def test_sym_difference_non_overlap(self): - result = self.set ^ Set([8]) - self.assertEqual(result, Set([2, 4, 6, 8])) - - def test_cmp(self): - a, b = Set('a'), Set('b') - self.assertRaises(TypeError, cmp, a, b) - - # In py3k, this works! - self.assertRaises(TypeError, cmp, a, a) - - self.assertRaises(TypeError, cmp, a, 12) - self.assertRaises(TypeError, cmp, "abc", a) - - def test_inplace_on_self(self): - t = self.set.copy() - t |= t - self.assertEqual(t, self.set) - t &= t - self.assertEqual(t, self.set) - t -= t - self.assertEqual(len(t), 0) - t = self.set.copy() - t ^= t - self.assertEqual(len(t), 0) - - -#============================================================================== - -class TestUpdateOps(unittest.TestCase): - def setUp(self): - self.set = Set((2, 4, 6)) - - def test_union_subset(self): - self.set |= Set([2]) - self.assertEqual(self.set, Set((2, 4, 6))) - - def test_union_superset(self): - self.set |= Set([2, 4, 6, 8]) - self.assertEqual(self.set, Set([2, 4, 6, 8])) - - def test_union_overlap(self): - self.set |= Set([3, 4, 5]) - self.assertEqual(self.set, Set([2, 3, 4, 5, 6])) - - def test_union_non_overlap(self): - self.set |= Set([8]) - self.assertEqual(self.set, Set([2, 4, 6, 8])) - - def test_union_method_call(self): - self.set.union_update(Set([3, 4, 5])) - self.assertEqual(self.set, Set([2, 3, 4, 5, 6])) - - def test_intersection_subset(self): - self.set &= Set((2, 4)) - self.assertEqual(self.set, Set((2, 4))) - - def test_intersection_superset(self): - self.set &= Set([2, 4, 6, 8]) - self.assertEqual(self.set, Set([2, 4, 6])) - - def test_intersection_overlap(self): - self.set &= Set([3, 4, 5]) - self.assertEqual(self.set, Set([4])) - - def test_intersection_non_overlap(self): - self.set &= Set([8]) - self.assertEqual(self.set, empty_set) - - def test_intersection_method_call(self): - self.set.intersection_update(Set([3, 4, 5])) - self.assertEqual(self.set, Set([4])) - - def test_sym_difference_subset(self): - self.set ^= Set((2, 4)) - self.assertEqual(self.set, Set([6])) - - def test_sym_difference_superset(self): - self.set ^= Set((2, 4, 6, 8)) - self.assertEqual(self.set, Set([8])) - - def test_sym_difference_overlap(self): - self.set ^= Set((3, 4, 5)) - self.assertEqual(self.set, Set([2, 3, 5, 6])) - - def test_sym_difference_non_overlap(self): - self.set ^= Set([8]) - self.assertEqual(self.set, Set([2, 4, 6, 8])) - - def test_sym_difference_method_call(self): - self.set.symmetric_difference_update(Set([3, 4, 5])) - self.assertEqual(self.set, Set([2, 3, 5, 6])) - - def test_difference_subset(self): - self.set -= Set((2, 4)) - self.assertEqual(self.set, Set([6])) - - def test_difference_superset(self): - self.set -= Set((2, 4, 6, 8)) - self.assertEqual(self.set, Set([])) - - def test_difference_overlap(self): - self.set -= Set((3, 4, 5)) - self.assertEqual(self.set, Set([2, 6])) - - def test_difference_non_overlap(self): - self.set -= Set([8]) - self.assertEqual(self.set, Set([2, 4, 6])) - - def test_difference_method_call(self): - self.set.difference_update(Set([3, 4, 5])) - self.assertEqual(self.set, Set([2, 6])) - -#============================================================================== - -class TestMutate(unittest.TestCase): - def setUp(self): - self.values = ["a", "b", "c"] - self.set = Set(self.values) - - def test_add_present(self): - self.set.add("c") - self.assertEqual(self.set, Set("abc")) - - def test_add_absent(self): - self.set.add("d") - self.assertEqual(self.set, Set("abcd")) - - def test_add_until_full(self): - tmp = Set() - expected_len = 0 - for v in self.values: - tmp.add(v) - expected_len += 1 - self.assertEqual(len(tmp), expected_len) - self.assertEqual(tmp, self.set) - - def test_remove_present(self): - self.set.remove("b") - self.assertEqual(self.set, Set("ac")) - - def test_remove_absent(self): - try: - self.set.remove("d") - self.fail("Removing missing element should have raised LookupError") - except LookupError: - pass - - def test_remove_until_empty(self): - expected_len = len(self.set) - for v in self.values: - self.set.remove(v) - expected_len -= 1 - self.assertEqual(len(self.set), expected_len) - - def test_discard_present(self): - self.set.discard("c") - self.assertEqual(self.set, Set("ab")) - - def test_discard_absent(self): - self.set.discard("d") - self.assertEqual(self.set, Set("abc")) - - def test_clear(self): - self.set.clear() - self.assertEqual(len(self.set), 0) - - def test_pop(self): - popped = {} - while self.set: - popped[self.set.pop()] = None - self.assertEqual(len(popped), len(self.values)) - for v in self.values: - self.failUnless(v in popped) - - def test_update_empty_tuple(self): - self.set.union_update(()) - self.assertEqual(self.set, Set(self.values)) - - def test_update_unit_tuple_overlap(self): - self.set.union_update(("a",)) - self.assertEqual(self.set, Set(self.values)) - - def test_update_unit_tuple_non_overlap(self): - self.set.union_update(("a", "z")) - self.assertEqual(self.set, Set(self.values + ["z"])) - -#============================================================================== - -class TestSubsets(unittest.TestCase): - - case2method = {"<=": "issubset", - ">=": "issuperset", - } - - reverse = {"==": "==", - "!=": "!=", - "<": ">", - ">": "<", - "<=": ">=", - ">=": "<=", - } - - def test_issubset(self): - x = self.left - y = self.right - for case in "!=", "==", "<", "<=", ">", ">=": - expected = case in self.cases - # Test the binary infix spelling. - result = eval("x" + case + "y", locals()) - self.assertEqual(result, expected) - # Test the "friendly" method-name spelling, if one exists. - if case in TestSubsets.case2method: - method = getattr(x, TestSubsets.case2method[case]) - result = method(y) - self.assertEqual(result, expected) - - # Now do the same for the operands reversed. - rcase = TestSubsets.reverse[case] - result = eval("y" + rcase + "x", locals()) - self.assertEqual(result, expected) - if rcase in TestSubsets.case2method: - method = getattr(y, TestSubsets.case2method[rcase]) - result = method(x) - self.assertEqual(result, expected) -#------------------------------------------------------------------------------ - -class TestSubsetEqualEmpty(TestSubsets): - left = Set() - right = Set() - name = "both empty" - cases = "==", "<=", ">=" - -#------------------------------------------------------------------------------ - -class TestSubsetEqualNonEmpty(TestSubsets): - left = Set([1, 2]) - right = Set([1, 2]) - name = "equal pair" - cases = "==", "<=", ">=" - -#------------------------------------------------------------------------------ - -class TestSubsetEmptyNonEmpty(TestSubsets): - left = Set() - right = Set([1, 2]) - name = "one empty, one non-empty" - cases = "!=", "<", "<=" - -#------------------------------------------------------------------------------ - -class TestSubsetPartial(TestSubsets): - left = Set([1]) - right = Set([1, 2]) - name = "one a non-empty proper subset of other" - cases = "!=", "<", "<=" - -#------------------------------------------------------------------------------ - -class TestSubsetNonOverlap(TestSubsets): - left = Set([1]) - right = Set([2]) - name = "neither empty, neither contains" - cases = "!=" - -#============================================================================== - -class TestOnlySetsInBinaryOps(unittest.TestCase): - - def test_eq_ne(self): - # Unlike the others, this is testing that == and != *are* allowed. - self.assertEqual(self.other == self.set, False) - self.assertEqual(self.set == self.other, False) - self.assertEqual(self.other != self.set, True) - self.assertEqual(self.set != self.other, True) - - def test_ge_gt_le_lt(self): - self.assertRaises(TypeError, lambda: self.set < self.other) - self.assertRaises(TypeError, lambda: self.set <= self.other) - self.assertRaises(TypeError, lambda: self.set > self.other) - self.assertRaises(TypeError, lambda: self.set >= self.other) - - self.assertRaises(TypeError, lambda: self.other < self.set) - self.assertRaises(TypeError, lambda: self.other <= self.set) - self.assertRaises(TypeError, lambda: self.other > self.set) - self.assertRaises(TypeError, lambda: self.other >= self.set) - - def test_union_update_operator(self): - try: - self.set |= self.other - except TypeError: - pass - else: - self.fail("expected TypeError") - - def test_union_update(self): - if self.otherIsIterable: - self.set.union_update(self.other) - else: - self.assertRaises(TypeError, self.set.union_update, self.other) - - def test_union(self): - self.assertRaises(TypeError, lambda: self.set | self.other) - self.assertRaises(TypeError, lambda: self.other | self.set) - if self.otherIsIterable: - self.set.union(self.other) - else: - self.assertRaises(TypeError, self.set.union, self.other) - - def test_intersection_update_operator(self): - try: - self.set &= self.other - except TypeError: - pass - else: - self.fail("expected TypeError") - - def test_intersection_update(self): - if self.otherIsIterable: - self.set.intersection_update(self.other) - else: - self.assertRaises(TypeError, - self.set.intersection_update, - self.other) - - def test_intersection(self): - self.assertRaises(TypeError, lambda: self.set & self.other) - self.assertRaises(TypeError, lambda: self.other & self.set) - if self.otherIsIterable: - self.set.intersection(self.other) - else: - self.assertRaises(TypeError, self.set.intersection, self.other) - - def test_sym_difference_update_operator(self): - try: - self.set ^= self.other - except TypeError: - pass - else: - self.fail("expected TypeError") - - def test_sym_difference_update(self): - if self.otherIsIterable: - self.set.symmetric_difference_update(self.other) - else: - self.assertRaises(TypeError, - self.set.symmetric_difference_update, - self.other) - - def test_sym_difference(self): - self.assertRaises(TypeError, lambda: self.set ^ self.other) - self.assertRaises(TypeError, lambda: self.other ^ self.set) - if self.otherIsIterable: - self.set.symmetric_difference(self.other) - else: - self.assertRaises(TypeError, self.set.symmetric_difference, self.other) - - def test_difference_update_operator(self): - try: - self.set -= self.other - except TypeError: - pass - else: - self.fail("expected TypeError") - - def test_difference_update(self): - if self.otherIsIterable: - self.set.difference_update(self.other) - else: - self.assertRaises(TypeError, - self.set.difference_update, - self.other) - - def test_difference(self): - self.assertRaises(TypeError, lambda: self.set - self.other) - self.assertRaises(TypeError, lambda: self.other - self.set) - if self.otherIsIterable: - self.set.difference(self.other) - else: - self.assertRaises(TypeError, self.set.difference, self.other) - -#------------------------------------------------------------------------------ - -class TestOnlySetsNumeric(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = 19 - self.otherIsIterable = False - -#------------------------------------------------------------------------------ - -class TestOnlySetsDict(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = {1:2, 3:4} - self.otherIsIterable = True - -#------------------------------------------------------------------------------ - -class TestOnlySetsOperator(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = operator.add - self.otherIsIterable = False - -#------------------------------------------------------------------------------ - -class TestOnlySetsTuple(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = (2, 4, 6) - self.otherIsIterable = True - -#------------------------------------------------------------------------------ - -class TestOnlySetsString(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = 'abc' - self.otherIsIterable = True - -#------------------------------------------------------------------------------ - -class TestOnlySetsGenerator(TestOnlySetsInBinaryOps): - def setUp(self): - def gen(): - for i in xrange(0, 10, 2): - yield i - self.set = Set((1, 2, 3)) - self.other = gen() - self.otherIsIterable = True - -#------------------------------------------------------------------------------ - -class TestOnlySetsofSets(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = [Set('ab'), ImmutableSet('cd')] - self.otherIsIterable = True - -#============================================================================== - -class TestCopying(unittest.TestCase): - - def test_copy(self): - dup = self.set.copy() - dup_list = sorted(dup, key=repr) - set_list = sorted(self.set, key=repr) - self.assertEqual(len(dup_list), len(set_list)) - for i in range(len(dup_list)): - self.failUnless(dup_list[i] is set_list[i]) - - def test_deep_copy(self): - dup = copy.deepcopy(self.set) - ##print type(dup), repr(dup) - dup_list = sorted(dup, key=repr) - set_list = sorted(self.set, key=repr) - self.assertEqual(len(dup_list), len(set_list)) - for i in range(len(dup_list)): - self.assertEqual(dup_list[i], set_list[i]) - -#------------------------------------------------------------------------------ - -class TestCopyingEmpty(TestCopying): - def setUp(self): - self.set = Set() - -#------------------------------------------------------------------------------ - -class TestCopyingSingleton(TestCopying): - def setUp(self): - self.set = Set(["hello"]) - -#------------------------------------------------------------------------------ - -class TestCopyingTriple(TestCopying): - def setUp(self): - self.set = Set(["zero", 0, None]) - -#------------------------------------------------------------------------------ - -class TestCopyingTuple(TestCopying): - def setUp(self): - self.set = Set([(1, 2)]) - -#------------------------------------------------------------------------------ - -class TestCopyingNested(TestCopying): - def setUp(self): - self.set = Set([((1, 2), (3, 4))]) - -#============================================================================== - -class TestIdentities(unittest.TestCase): - def setUp(self): - self.a = Set([random.randrange(100) for i in xrange(50)]) - self.b = Set([random.randrange(100) for i in xrange(50)]) - - def test_binopsVsSubsets(self): - a, b = self.a, self.b - self.assert_(a - b <= a) - self.assert_(b - a <= b) - self.assert_(a & b <= a) - self.assert_(a & b <= b) - self.assert_(a | b >= a) - self.assert_(a | b >= b) - self.assert_(a ^ b <= a | b) - - def test_commutativity(self): - a, b = self.a, self.b - self.assertEqual(a&b, b&a) - self.assertEqual(a|b, b|a) - self.assertEqual(a^b, b^a) - if a != b: - self.assertNotEqual(a-b, b-a) - - def test_reflexsive_relations(self): - a, zero = self.a, Set() - self.assertEqual(a ^ a, zero) - self.assertEqual(a - a, zero) - self.assertEqual(a | a, a) - self.assertEqual(a & a, a) - self.assert_(a <= a) - self.assert_(a >= a) - self.assert_(a == a) - - def test_summations(self): - # check that sums of parts equal the whole - a, b = self.a, self.b - self.assertEqual((a-b)|(a&b)|(b-a), a|b) - self.assertEqual((a&b)|(a^b), a|b) - self.assertEqual(a|(b-a), a|b) - self.assertEqual((a-b)|b, a|b) - self.assertEqual((a-b)|(a&b), a) - self.assertEqual((b-a)|(a&b), b) - self.assertEqual((a-b)|(b-a), a^b) - - def test_exclusion(self): - # check that inverse operations do not overlap - a, b, zero = self.a, self.b, Set() - self.assertEqual((a-b)&b, zero) - self.assertEqual((b-a)&a, zero) - self.assertEqual((a&b)&(a^b), zero) - - def test_cardinality_relations(self): - a, b = self.a, self.b - self.assertEqual(len(a), len(a-b) + len(a&b)) - self.assertEqual(len(b), len(b-a) + len(a&b)) - self.assertEqual(len(a^b), len(a-b) + len(b-a)) - self.assertEqual(len(a|b), len(a-b) + len(a&b) + len(b-a)) - self.assertEqual(len(a^b) + len(a&b), len(a|b)) - -#============================================================================== - -libreftest = """ -Example from the Library Reference: Doc/lib/libsets.tex - ->>> from sets import Set as Base # override _repr to get sorted output ->>> class Set(Base): -... def _repr(self): -... return Base._repr(self, sorted=True) ->>> engineers = Set(['John', 'Jane', 'Jack', 'Janice']) ->>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice']) ->>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack']) ->>> employees = engineers | programmers | managers # union ->>> engineering_management = engineers & managers # intersection ->>> fulltime_management = managers - engineers - programmers # difference ->>> engineers.add('Marvin') ->>> print engineers -Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin']) ->>> employees.issuperset(engineers) # superset test -False ->>> employees.union_update(engineers) # update from another set ->>> employees.issuperset(engineers) -True ->>> for group in [engineers, programmers, managers, employees]: -... group.discard('Susan') # unconditionally remove element -... print group -... -Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin']) -Set(['Jack', 'Janice', 'Sam']) -Set(['Jack', 'Jane', 'Zack']) -Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin', 'Sam', 'Zack']) -""" - -#============================================================================== - -__test__ = {'libreftest' : libreftest} - -def test_main(verbose=None): - import doctest - from test import test_sets - test_support.run_unittest( - TestSetOfSets, - TestExceptionPropagation, - TestBasicOpsEmpty, - TestBasicOpsSingleton, - TestBasicOpsTuple, - TestBasicOpsTriple, - TestBinaryOps, - TestUpdateOps, - TestMutate, - TestSubsetEqualEmpty, - TestSubsetEqualNonEmpty, - TestSubsetEmptyNonEmpty, - TestSubsetPartial, - TestSubsetNonOverlap, - TestOnlySetsNumeric, - TestOnlySetsDict, - TestOnlySetsOperator, - TestOnlySetsTuple, - TestOnlySetsString, - TestOnlySetsGenerator, - TestOnlySetsofSets, - TestCopyingEmpty, - TestCopyingSingleton, - TestCopyingTriple, - TestCopyingTuple, - TestCopyingNested, - TestIdentities, - doctest.DocTestSuite(test_sets), - ) - -if __name__ == "__main__": - test_main(verbose=True) 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 Thu Jan 11 00:43:10 2007 @@ -129,7 +129,7 @@ raise TypeError, "test_func must be a callable function" try: test_func() - except Exception, strerror: + except Exception as strerror: self.queue.put(strerror) self.clientTearDown() Modified: python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py Thu Jan 11 00:43:10 2007 @@ -58,7 +58,7 @@ except socket.timeout: error_msg('timed out') return - except socket.error, exc: # In case connection is refused. + except socket.error as exc: # In case connection is refused. if exc.args[0] == errno.ECONNREFUSED: error_msg('was refused') return Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -155,7 +155,8 @@ self.server_address = host, port TCPServer.server_bind(self) break - except socket.error, (err, msg): + except socket.error as e: + (err, msg) = e if err != errno.EADDRINUSE: raise print >>sys.__stderr__, \ Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -119,7 +119,7 @@ for e in expectations: try: result = time.strftime(e[0], now) - except ValueError, error: + except ValueError as error: print "Standard '%s' format gave error:" % e[0], error continue if re.match(escapestr(e[1], ampm), result): continue @@ -132,7 +132,7 @@ for e in nonstandard_expectations: try: result = time.strftime(e[0], now) - except ValueError, result: + except ValueError as result: if verbose: print "Error for nonstandard '%s' format (%s): %s" % \ (e[0], e[2], str(result)) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -55,7 +55,7 @@ def f(): yield 4 + "" self.fixtype(' ').join(f()) - except TypeError, e: + except TypeError as e: if '+' not in str(e): self.fail('join() ate exception message') else: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -206,7 +206,7 @@ _strptime.strptime("2005", bad_format) except ValueError: continue - except Exception, err: + except Exception as err: self.fail("'%s' raised %s, not ValueError" % (bad_format, err.__class__.__name__)) else: Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -67,7 +67,7 @@ try: subprocess.check_call([sys.executable, "-c", "import sys; sys.exit(47)"]) - except subprocess.CalledProcessError, e: + except subprocess.CalledProcessError as e: self.assertEqual(e.returncode, 47) else: self.fail("Expected CalledProcessError") @@ -475,7 +475,7 @@ try: p = subprocess.Popen([sys.executable, "-c", ""], cwd="/this/path/does/not/exist") - except OSError, e: + except OSError as e: # The attribute child_traceback should contain "os.chdir" # somewhere. self.assertNotEqual(e.child_traceback.find("os.chdir"), -1) Modified: python/branches/p3yk-noslice/Lib/test/test_sunaudiodev.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_sunaudiodev.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_sunaudiodev.py Thu Jan 11 00:43:10 2007 @@ -16,7 +16,7 @@ fp.close() try: a = sunaudiodev.open('w') - except sunaudiodev.error, msg: + except sunaudiodev.error as msg: raise TestFailed, msg else: a.write(data) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -102,7 +102,8 @@ try: sock.bind((host, port)) return port - except socket.error, (err, msg): + except socket.error as e: + (err, msg) = e if err != errno.EADDRINUSE: raise print >>sys.__stderr__, \ Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -387,7 +387,7 @@ """ try: compile(code, filename, mode) - except SyntaxError, err: + except SyntaxError as err: if subclass and not isinstance(err, subclass): self.fail("SyntaxError is not a %s" % subclass.__name__) mo = re.search(errtext, str(err)) Modified: python/branches/p3yk-noslice/Lib/test/test_sys.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_sys.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_sys.py Thu Jan 11 00:43:10 2007 @@ -54,7 +54,7 @@ self.assertRaises(TypeError, eh) try: raise ValueError(42) - except ValueError, exc: + except ValueError as exc: eh(*sys.exc_info()) sys.stderr = savestderr @@ -84,7 +84,7 @@ def clear(): try: raise ValueError, 42 - except ValueError, exc: + except ValueError as exc: clear_check(exc) # Raise an exception and check that it can be cleared @@ -94,7 +94,7 @@ # unaffected by calling exc_clear in a nested frame. try: raise ValueError, 13 - except ValueError, exc: + except ValueError as exc: typ1, value1, traceback1 = sys.exc_info() clear() typ2, value2, traceback2 = sys.exc_info() @@ -104,16 +104,13 @@ self.assert_(value1 is value2) self.assert_(traceback1 is traceback2) - # Check that an exception can be cleared outside of an except block - clear_check(exc) - def test_exit(self): self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument try: sys.exit(0) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, 0) except: self.fail("wrong exception") @@ -124,7 +121,7 @@ # entry will be unpacked try: sys.exit(42) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, 42) except: self.fail("wrong exception") @@ -134,7 +131,7 @@ # call with integer argument try: sys.exit((42,)) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, 42) except: self.fail("wrong exception") @@ -144,7 +141,7 @@ # call with string argument try: sys.exit("exit") - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, "exit") except: self.fail("wrong exception") @@ -154,7 +151,7 @@ # call with tuple argument with two entries try: sys.exit((17, 23)) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, (17, 23)) except: self.fail("wrong exception") Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -545,7 +545,7 @@ try: # Extract 1-LNKTYPE which is a hardlink to 0-REGTYPE self.tar.extract("1-LNKTYPE", dirname()) - except EnvironmentError, e: + except EnvironmentError as e: import errno if e.errno == errno.ENOENT: self.fail("hardlink not extracted properly") Modified: python/branches/p3yk-noslice/Lib/test/test_tcl.py ============================================================================== --- python/branches/p3yk-noslice/Lib/test/test_tcl.py (original) +++ python/branches/p3yk-noslice/Lib/test/test_tcl.py Thu Jan 11 00:43:10 2007 @@ -107,7 +107,7 @@ filename = "doesnotexists" try: os.remove(filename) - except Exception,e: + except Exception as e: pass self.assertRaises(TclError,tcl.evalfile,filename) Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -97,7 +97,7 @@ def test_raise(): try: raises() - except Exception, exc: + except Exception as exc: x = 1 test_raise.events = [(0, 'call'), @@ -127,7 +127,7 @@ def settrace_and_raise(tracefunc): try: _settrace_and_raise(tracefunc) - except RuntimeError, exc: + except RuntimeError as exc: pass settrace_and_raise.events = [(2, 'exception'), @@ -432,7 +432,7 @@ try: output.append(2) output.append(3) - except ValueError, e: + except ValueError as e: output.append('after' in str(e)) no_jump_too_far_forwards.jump = (3, 6) @@ -442,7 +442,7 @@ try: output.append(2) output.append(3) - except ValueError, e: + except ValueError as e: output.append('before' in str(e)) no_jump_too_far_backwards.jump = (3, -1) @@ -472,7 +472,7 @@ def no_jump_to_except_3(output): try: output.append(2) - except ValueError, e: + except ValueError as e: output.append('except' in str(e)) no_jump_to_except_3.jump = (2, 3) @@ -481,7 +481,7 @@ def no_jump_to_except_4(output): try: output.append(2) - except (ValueError, RuntimeError), e: + except (ValueError, RuntimeError) as e: output.append('except' in str(e)) no_jump_to_except_4.jump = (2, 3) @@ -492,7 +492,7 @@ output.append(2) for i in 1, 2: output.append(4) - except ValueError, e: + except ValueError as e: output.append('into' in str(e)) no_jump_forwards_into_block.jump = (2, 4) @@ -503,7 +503,7 @@ for i in 1, 2: output.append(3) output.append(4) - except ValueError, e: + except ValueError as e: output.append('into' in str(e)) no_jump_backwards_into_block.jump = (4, 3) @@ -516,7 +516,7 @@ x = 1 finally: output.append(6) - except ValueError, e: + except ValueError as e: output.append('finally' in str(e)) no_jump_into_finally_block.jump = (4, 6) @@ -529,7 +529,7 @@ finally: output.append(5) output.append(6) - except ValueError, e: + except ValueError as e: output.append('finally' in str(e)) no_jump_out_of_finally_block.jump = (5, 1) @@ -539,7 +539,7 @@ def no_jump_to_non_integers(output): try: output.append(2) - except ValueError, e: + except ValueError as e: output.append('integer' in str(e)) no_jump_to_non_integers.jump = (2, "Spam") @@ -551,7 +551,7 @@ try: previous_frame = sys._getframe().f_back previous_frame.f_lineno = previous_frame.f_lineno - except ValueError, e: + except ValueError as e: # This is the exception we wanted; make sure the error message # talks about trace functions. if 'trace' not in str(e): Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -12,7 +12,7 @@ def get_exception_format(self, func, exc): try: func() - except exc, value: + except exc as value: return traceback.format_exception_only(exc, value) else: raise ValueError, "call did not raise exception" Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -236,7 +236,7 @@ debug(url) try: f = urllib2.urlopen(url, req) - except (IOError, socket.error, OSError), err: + except (IOError, socket.error, OSError) as err: debug(err) if expected_err: msg = ("Didn't get expected error(s) %s for %s %s, got %s" % Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -168,7 +168,7 @@ e = E() try: e[42] - except RuntimeError, err: + except RuntimeError as err: self.assertEqual(err.args, (42,)) else: self.fail_("e[42] didn't raise RuntimeError") @@ -180,7 +180,7 @@ f = F() try: f[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("f[42] didn't raise KeyError") @@ -189,7 +189,7 @@ g = G() try: g[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("g[42] didn't raise KeyError") Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -50,7 +50,7 @@ try: uu.decode(inp, out) self.fail("No exception thrown") - except uu.Error, e: + except uu.Error as e: self.assertEqual(str(e), "Truncated input file") def test_missingbegin(self): @@ -59,7 +59,7 @@ try: uu.decode(inp, out) self.fail("No exception thrown") - except uu.Error, e: + except uu.Error as e: self.assertEqual(str(e), "No valid begin line found in input file") class UUStdIOTest(unittest.TestCase): Modified: python/branches/p3yk-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 Thu Jan 11 00:43:10 2007 @@ -142,7 +142,7 @@ if remote_name is not None: try: remote_key = ConnectRegistry(remote_name, HKEY_CURRENT_USER) - except EnvironmentError, exc: + except EnvironmentError as exc: print "Could not connect to the remote machine -", exc.strerror remote_key = None if remote_key is not None: Modified: python/branches/p3yk-noslice/Lib/timeit.py ============================================================================== --- python/branches/p3yk-noslice/Lib/timeit.py (original) +++ python/branches/p3yk-noslice/Lib/timeit.py Thu Jan 11 00:43:10 2007 @@ -209,7 +209,7 @@ opts, args = getopt.getopt(args, "n:s:r:tcvh", ["number=", "setup=", "repeat=", "time", "clock", "verbose", "help"]) - except getopt.error, err: + except getopt.error as err: print err print "use -h/--help for command line help" return 2 Modified: python/branches/p3yk-noslice/Lib/toaiff.py ============================================================================== --- python/branches/p3yk-noslice/Lib/toaiff.py (original) +++ python/branches/p3yk-noslice/Lib/toaiff.py Thu Jan 11 00:43:10 2007 @@ -87,7 +87,7 @@ ftype = sndhdr.whathdr(fname) if ftype: ftype = ftype[0] # All we're interested in - except IOError, msg: + except IOError as msg: if type(msg) == type(()) and len(msg) == 2 and \ type(msg[0]) == type(0) and type(msg[1]) == type(''): msg = msg[1] Modified: python/branches/p3yk-noslice/Lib/token.py ============================================================================== --- python/branches/p3yk-noslice/Lib/token.py (original) +++ python/branches/p3yk-noslice/Lib/token.py Thu Jan 11 00:43:10 2007 @@ -93,7 +93,7 @@ outFileName = args[1] try: fp = open(inFileName) - except IOError, err: + except IOError as err: sys.stdout.write("I/O error: %s\n" % str(err)) sys.exit(1) lines = fp.read().split("\n") @@ -113,7 +113,7 @@ # load the output skeleton from the target: try: fp = open(outFileName) - except IOError, err: + except IOError as err: sys.stderr.write("I/O error: %s\n" % str(err)) sys.exit(2) format = fp.read().split("\n") @@ -130,7 +130,7 @@ format[start:end] = lines try: fp = open(outFileName, 'w') - except IOError, err: + except IOError as err: sys.stderr.write("I/O error: %s\n" % str(err)) sys.exit(4) fp.write("\n".join(format)) Modified: python/branches/p3yk-noslice/Lib/trace.py ============================================================================== --- python/branches/p3yk-noslice/Lib/trace.py (original) +++ python/branches/p3yk-noslice/Lib/trace.py Thu Jan 11 00:43:10 2007 @@ -220,7 +220,7 @@ counts, calledfuncs, callers = \ pickle.load(open(self.infile, 'rb')) self.update(self.__class__(counts, calledfuncs, callers)) - except (IOError, EOFError, ValueError), err: + except (IOError, EOFError, ValueError) as err: print >> sys.stderr, ("Skipping counts file %r: %s" % (self.infile, err)) @@ -328,7 +328,7 @@ try: pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1) - except IOError, err: + except IOError as err: print >> sys.stderr, "Can't save counts files because %s" % err def write_results_file(self, path, lines, lnotab, lines_hit): @@ -336,7 +336,7 @@ try: outfile = open(path, "w") - except IOError, err: + except IOError as err: print >> sys.stderr, ("trace: Could not open %r for writing: %s" "- skipping" % (path, err)) return 0, 0 @@ -422,7 +422,7 @@ """Return dict where keys are line numbers in the line number table.""" try: prog = open(filename, "rU").read() - except IOError, err: + except IOError as err: print >> sys.stderr, ("Not printing coverage data for %r: %s" % (filename, err)) return {} @@ -658,7 +658,7 @@ "coverdir=", "listfuncs", "trackcalls"]) - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0]) @@ -778,7 +778,7 @@ outfile=counts_file) try: t.run('execfile(%r)' % (progname,)) - except IOError, err: + except IOError as err: _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err)) except SystemExit: pass Modified: python/branches/p3yk-noslice/Lib/unittest.py ============================================================================== --- python/branches/p3yk-noslice/Lib/unittest.py (original) +++ python/branches/p3yk-noslice/Lib/unittest.py Thu Jan 11 00:43:10 2007 @@ -783,7 +783,7 @@ else: self.testNames = (self.defaultTest,) self.createTests() - except getopt.error, msg: + except getopt.error as msg: self.usageExit(msg) def createTests(self): Modified: python/branches/p3yk-noslice/Lib/urllib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/urllib.py (original) +++ python/branches/p3yk-noslice/Lib/urllib.py Thu Jan 11 00:43:10 2007 @@ -190,7 +190,7 @@ return getattr(self, name)(url) else: return getattr(self, name)(url, data) - except socket.error, msg: + except socket.error as msg: raise IOError, ('socket error', msg), sys.exc_info()[2] def open_unknown(self, fullurl, data=None): @@ -217,7 +217,7 @@ hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs - except IOError, msg: + except IOError as msg: pass fp = self.open(url, data) headers = fp.info() @@ -461,7 +461,7 @@ localname = url2pathname(file) try: stats = os.stat(localname) - except OSError, e: + except OSError as e: raise IOError(e.errno, e.strerror, e.filename) size = stats.st_size modified = email.Utils.formatdate(stats.st_mtime, usegmt=True) @@ -544,7 +544,7 @@ headers += "Content-Length: %d\n" % retrlen headers = mimetools.Message(StringIO(headers)) return addinfourl(fp, headers, "ftp:" + url) - except ftperrors(), msg: + except ftperrors() as msg: raise IOError, ('ftp error', msg), sys.exc_info()[2] def open_data(self, url, data=None): @@ -861,7 +861,7 @@ try: cmd = 'RETR ' + file conn = self.ftp.ntransfercmd(cmd) - except ftplib.error_perm, reason: + except ftplib.error_perm as reason: if str(reason)[:3] != '550': raise IOError, ('ftp error', reason), sys.exc_info()[2] if not conn: @@ -1503,7 +1503,7 @@ import getopt, sys try: opts, args = getopt.getopt(sys.argv[1:], "th") - except getopt.error, msg: + except getopt.error as msg: print msg print "Use -h for help" return Modified: python/branches/p3yk-noslice/Lib/urllib2.py ============================================================================== --- python/branches/p3yk-noslice/Lib/urllib2.py (original) +++ python/branches/p3yk-noslice/Lib/urllib2.py Thu Jan 11 00:43:10 2007 @@ -1072,7 +1072,7 @@ try: h.request(req.get_method(), req.get_selector(), req.data, headers) r = h.getresponse() - except socket.error, err: # XXX what error? + except socket.error as err: # XXX what error? raise URLError(err) # Pick apart the HTTPResponse object to get the addinfourl @@ -1254,7 +1254,7 @@ try: host = socket.gethostbyname(host) - except socket.error, msg: + except socket.error as msg: raise URLError(msg) path, attrs = splitattr(req.get_selector()) dirs = path.split('/') @@ -1280,7 +1280,7 @@ sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) - except ftplib.all_errors, msg: + except ftplib.all_errors as msg: raise IOError, ('ftp error', msg), sys.exc_info()[2] def connect_ftp(self, user, passwd, host, port, dirs): Modified: python/branches/p3yk-noslice/Lib/uu.py ============================================================================== --- python/branches/p3yk-noslice/Lib/uu.py (original) +++ python/branches/p3yk-noslice/Lib/uu.py Thu Jan 11 00:43:10 2007 @@ -132,7 +132,7 @@ while s and s.strip() != 'end': try: data = binascii.a2b_uu(s) - except binascii.Error, v: + except binascii.Error as v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3 data = binascii.a2b_uu(s[:nbytes]) Modified: python/branches/p3yk-noslice/Lib/warnings.py ============================================================================== --- python/branches/p3yk-noslice/Lib/warnings.py (original) +++ python/branches/p3yk-noslice/Lib/warnings.py Thu Jan 11 00:43:10 2007 @@ -192,7 +192,7 @@ for arg in args: try: _setoption(arg) - except _OptionError, msg: + except _OptionError as msg: print >>sys.stderr, "Invalid -W option ignored:", msg # Helper for _processoptions() Modified: python/branches/p3yk-noslice/Lib/webbrowser.py ============================================================================== --- python/branches/p3yk-noslice/Lib/webbrowser.py (original) +++ python/branches/p3yk-noslice/Lib/webbrowser.py Thu Jan 11 00:43:10 2007 @@ -625,7 +625,7 @@ -t: open new tab""" % sys.argv[0] try: opts, args = getopt.getopt(sys.argv[1:], 'ntd') - except getopt.error, msg: + except getopt.error as msg: print >>sys.stderr, msg print >>sys.stderr, usage sys.exit(1) Modified: python/branches/p3yk-noslice/Lib/xdrlib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xdrlib.py (original) +++ python/branches/p3yk-noslice/Lib/xdrlib.py Thu Jan 11 00:43:10 2007 @@ -68,12 +68,12 @@ def pack_float(self, x): try: self.__buf.write(struct.pack('>f', x)) - except struct.error, msg: + except struct.error as msg: raise ConversionError, msg def pack_double(self, x): try: self.__buf.write(struct.pack('>d', x)) - except struct.error, msg: + except struct.error as msg: raise ConversionError, msg def pack_fstring(self, n, s): Modified: python/branches/p3yk-noslice/Lib/xml/sax/__init__.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xml/sax/__init__.py (original) +++ python/branches/p3yk-noslice/Lib/xml/sax/__init__.py Thu Jan 11 00:43:10 2007 @@ -79,7 +79,7 @@ for parser_name in parser_list + default_parser_list: try: return _create_parser(parser_name) - except ImportError,e: + except ImportError as e: import sys if parser_name in sys.modules: # The parser module was found, but importing it Modified: python/branches/p3yk-noslice/Lib/xml/sax/expatreader.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xml/sax/expatreader.py (original) +++ python/branches/p3yk-noslice/Lib/xml/sax/expatreader.py Thu Jan 11 00:43:10 2007 @@ -205,7 +205,7 @@ # document. When feeding chunks, they are not normally final - # except when invoked from close. self._parser.Parse(data, isFinal) - except expat.error, e: + except expat.error as e: exc = SAXParseException(expat.ErrorString(e.code), e, self) # FIXME: when to invoke error()? self._err_handler.fatalError(exc) Modified: python/branches/p3yk-noslice/Lib/xmllib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xmllib.py (original) +++ python/branches/p3yk-noslice/Lib/xmllib.py Thu Jan 11 00:43:10 2007 @@ -896,7 +896,7 @@ else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) @@ -914,7 +914,7 @@ for c in data: x.feed(c) x.close() - except Error, msg: + except Error as msg: t1 = time() print msg if do_time: Modified: python/branches/p3yk-noslice/Lib/xmlrpclib.py ============================================================================== --- python/branches/p3yk-noslice/Lib/xmlrpclib.py (original) +++ python/branches/p3yk-noslice/Lib/xmlrpclib.py Thu Jan 11 00:43:10 2007 @@ -1454,7 +1454,7 @@ try: print server.currentTime.getCurrentTime() - except Error, v: + except Error as v: print "ERROR", v multi = MultiCall(server) @@ -1463,5 +1463,5 @@ try: for response in multi(): print response - except Error, v: + except Error as v: print "ERROR", v Modified: python/branches/p3yk-noslice/Lib/zipfile.py ============================================================================== --- python/branches/p3yk-noslice/Lib/zipfile.py (original) +++ python/branches/p3yk-noslice/Lib/zipfile.py Thu Jan 11 00:43:10 2007 @@ -812,7 +812,7 @@ print "Compiling", file_py try: py_compile.compile(file_py, file_pyc, None, True) - except py_compile.PyCompileError,err: + except py_compile.PyCompileError as err: print err.msg fname = file_pyc else: Modified: python/branches/p3yk-noslice/Mac/BuildScript/build-installer.py ============================================================================== --- python/branches/p3yk-noslice/Mac/BuildScript/build-installer.py (original) +++ python/branches/p3yk-noslice/Mac/BuildScript/build-installer.py Thu Jan 11 00:43:10 2007 @@ -335,7 +335,7 @@ try: options, args = getopt.getopt(args, '?hb', [ 'build-dir=', 'third-party=', 'sdk-path=' , 'src-dir=']) - except getopt.error, msg: + except getopt.error as msg: print msg sys.exit(1) Modified: python/branches/p3yk-noslice/Mac/Demo/applescript/makedisk.py ============================================================================== --- python/branches/p3yk-noslice/Mac/Demo/applescript/makedisk.py (original) +++ python/branches/p3yk-noslice/Mac/Demo/applescript/makedisk.py Thu Jan 11 00:43:10 2007 @@ -7,7 +7,7 @@ filespec = macfs.FSSpec('my disk image.img') try: objref = talker.create('my disk image', saving_as=filespec, leave_image_mounted=1) -except Disk_Copy.Error, arg: +except Disk_Copy.Error as arg: print "ERROR: my disk image:", arg else: print 'objref=', objref Modified: python/branches/p3yk-noslice/Mac/Demo/imgbrowse/imgbrowse.py ============================================================================== --- python/branches/p3yk-noslice/Mac/Demo/imgbrowse/imgbrowse.py (original) +++ python/branches/p3yk-noslice/Mac/Demo/imgbrowse/imgbrowse.py Thu Jan 11 00:43:10 2007 @@ -52,7 +52,7 @@ bar = EasyDialogs.ProgressBar('Reading and converting...') try: rdr = img.reader(imgformat.macrgb16, pathname) - except img.error, arg: + except img.error as arg: EasyDialogs.Message(repr(arg)) return w, h = rdr.width, rdr.height Modified: python/branches/p3yk-noslice/Mac/Demo/mlte/mlted.py ============================================================================== --- python/branches/p3yk-noslice/Mac/Demo/mlte/mlted.py (original) +++ python/branches/p3yk-noslice/Mac/Demo/mlte/mlted.py Thu Jan 11 00:43:10 2007 @@ -275,7 +275,7 @@ fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line data = fp.read() fp.close() - except IOError, arg: + except IOError as arg: EasyDialogs.Message("IOERROR: %r" % (arg,)) return else: Modified: python/branches/p3yk-noslice/Mac/Demo/resources/copyres.py ============================================================================== --- python/branches/p3yk-noslice/Mac/Demo/resources/copyres.py (original) +++ python/branches/p3yk-noslice/Mac/Demo/resources/copyres.py Thu Jan 11 00:43:10 2007 @@ -39,7 +39,7 @@ UseResFile(output) try: res2 = Get1Resource(type, id) - except (RuntimeError, Res.Error), msg: + except (RuntimeError, Res.Error) as msg: res2 = None if res2: print "Duplicate type+id, not copied" Modified: python/branches/p3yk-noslice/Mac/Demo/textedit/ped.py ============================================================================== --- python/branches/p3yk-noslice/Mac/Demo/textedit/ped.py (original) +++ python/branches/p3yk-noslice/Mac/Demo/textedit/ped.py Thu Jan 11 00:43:10 2007 @@ -273,7 +273,7 @@ fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line data = fp.read() fp.close() - except IOError, arg: + except IOError as arg: EasyDialogs.Message("IOERROR: %r" % (arg,)) return else: Modified: python/branches/p3yk-noslice/Mac/scripts/BuildApplet.py ============================================================================== --- python/branches/p3yk-noslice/Mac/scripts/BuildApplet.py (original) +++ python/branches/p3yk-noslice/Mac/scripts/BuildApplet.py Thu Jan 11 00:43:10 2007 @@ -31,7 +31,7 @@ def main(): try: buildapplet() - except buildtools.BuildError, detail: + except buildtools.BuildError as detail: EasyDialogs.Message(detail) Modified: python/branches/p3yk-noslice/Mac/scripts/buildpkg.py ============================================================================== --- python/branches/p3yk-noslice/Mac/scripts/buildpkg.py (original) +++ python/branches/p3yk-noslice/Mac/scripts/buildpkg.py Thu Jan 11 00:43:10 2007 @@ -451,7 +451,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], shortOpts, longOpts) - except getopt.GetoptError, details: + except getopt.GetoptError as details: print details printUsage() return Modified: python/branches/p3yk-noslice/Misc/BeOS-setup.py ============================================================================== --- python/branches/p3yk-noslice/Misc/BeOS-setup.py (original) +++ python/branches/p3yk-noslice/Misc/BeOS-setup.py Thu Jan 11 00:43:10 2007 @@ -127,7 +127,7 @@ try: build_ext.build_extension(self, ext) - except (CCompilerError, DistutilsError), why: + except (CCompilerError, DistutilsError) as why: self.announce('WARNING: building of extension "%s" failed: %s' % (ext.name, sys.exc_info()[1])) Modified: python/branches/p3yk-noslice/Misc/NEWS ============================================================================== --- python/branches/p3yk-noslice/Misc/NEWS (original) +++ python/branches/p3yk-noslice/Misc/NEWS Thu Jan 11 00:43:10 2007 @@ -105,6 +105,8 @@ Library ------- +- Removed all traces of the sets module. + Build ----- Modified: python/branches/p3yk-noslice/Modules/parsermodule.c ============================================================================== --- python/branches/p3yk-noslice/Modules/parsermodule.c (original) +++ python/branches/p3yk-noslice/Modules/parsermodule.c Thu Jan 11 00:43:10 2007 @@ -2110,8 +2110,8 @@ if (res && (nch > 1)) res = validate_test(CHILD(tree, 1)); if (res && (nch == 4)) - res = (validate_comma(CHILD(tree, 2)) - && validate_test(CHILD(tree, 3))); + res = (validate_name(CHILD(tree, 2), "as") + && validate_ntype(CHILD(tree, 3), NAME)); return (res); } Modified: python/branches/p3yk-noslice/Parser/Python.asdl ============================================================================== --- python/branches/p3yk-noslice/Parser/Python.asdl (original) +++ python/branches/p3yk-noslice/Parser/Python.asdl Thu Jan 11 00:43:10 2007 @@ -97,7 +97,7 @@ -- TODO(jhylton): Figure out if there is a better way to handle -- lineno and col_offset fields, particularly when -- ast is exposed to Python. - excepthandler = (expr? type, expr? name, stmt* body, int lineno, + excepthandler = (expr? type, identifier? name, stmt* body, int lineno, int col_offset) arguments = (arg* args, identifier? vararg, expr? varargannotation, Modified: python/branches/p3yk-noslice/Python/Python-ast.c ============================================================================== --- python/branches/p3yk-noslice/Python/Python-ast.c (original) +++ python/branches/p3yk-noslice/Python/Python-ast.c Thu Jan 11 00:43:10 2007 @@ -1836,7 +1836,7 @@ } excepthandler_ty -excepthandler(expr_ty type, expr_ty name, asdl_seq * body, int lineno, int +excepthandler(expr_ty type, identifier name, asdl_seq * body, int lineno, int col_offset, PyArena *arena) { excepthandler_ty p; @@ -2928,7 +2928,7 @@ if (PyObject_SetAttrString(result, "type", value) == -1) goto failed; Py_DECREF(value); - value = ast2obj_expr(o->name); + value = ast2obj_identifier(o->name); if (!value) goto failed; if (PyObject_SetAttrString(result, "name", value) == -1) goto failed; @@ -3126,7 +3126,7 @@ if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) return; - if (PyModule_AddStringConstant(m, "__version__", "53170") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53363") < 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-noslice/Python/ast.c ============================================================================== --- python/branches/p3yk-noslice/Python/ast.c (original) +++ python/branches/p3yk-noslice/Python/ast.c Thu Jan 11 00:43:10 2007 @@ -2899,11 +2899,9 @@ else if (NCH(exc) == 4) { asdl_seq *suite_seq; expr_ty expression; - expr_ty e = ast_for_expr(c, CHILD(exc, 3)); + identifier e = NEW_IDENTIFIER(CHILD(exc, 3)); if (!e) return NULL; - if (!set_context(e, Store, CHILD(exc, 3))) - return NULL; expression = ast_for_expr(c, CHILD(exc, 1)); if (!expression) return NULL; Modified: python/branches/p3yk-noslice/Python/compile.c ============================================================================== --- python/branches/p3yk-noslice/Python/compile.c (original) +++ python/branches/p3yk-noslice/Python/compile.c Thu Jan 11 00:43:10 2007 @@ -1928,13 +1928,59 @@ } ADDOP(c, POP_TOP); if (handler->name) { - VISIT(c, expr, handler->name); + basicblock *cleanup_end, *cleanup_body; + + cleanup_end = compiler_new_block(c); + cleanup_body = compiler_new_block(c); + if(!(cleanup_end || cleanup_body)) + return 0; + + compiler_nameop(c, handler->name, Store); + ADDOP(c, POP_TOP); + + /* + try: + # body + except type as name: + try: + # body + finally: + name = None + del name + */ + + /* second try: */ + ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); + compiler_use_next_block(c, cleanup_body); + if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) + return 0; + + /* second # body */ + VISIT_SEQ(c, stmt, handler->body); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); + + /* finally: */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_use_next_block(c, cleanup_end); + if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) + return 0; + + /* name = None */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_nameop(c, handler->name, Store); + + /* del name */ + compiler_nameop(c, handler->name, Del); + + ADDOP(c, END_FINALLY); + compiler_pop_fblock(c, FINALLY_END, cleanup_end); } else { - ADDOP(c, POP_TOP); + ADDOP(c, POP_TOP); + ADDOP(c, POP_TOP); + VISIT_SEQ(c, stmt, handler->body); } - ADDOP(c, POP_TOP); - VISIT_SEQ(c, stmt, handler->body); ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, except); if (handler->type) Modified: python/branches/p3yk-noslice/Python/graminit.c ============================================================================== --- python/branches/p3yk-noslice/Python/graminit.c (original) +++ python/branches/p3yk-noslice/Python/graminit.c Thu Jan 11 00:43:10 2007 @@ -1049,11 +1049,11 @@ {0, 1}, }; static arc arcs_46_2[2] = { - {28, 3}, + {83, 3}, {0, 2}, }; static arc arcs_46_3[1] = { - {22, 4}, + {19, 4}, }; static arc arcs_46_4[1] = { {0, 4}, Modified: python/branches/p3yk-noslice/Python/symtable.c ============================================================================== --- python/branches/p3yk-noslice/Python/symtable.c (original) +++ python/branches/p3yk-noslice/Python/symtable.c Thu Jan 11 00:43:10 2007 @@ -1335,7 +1335,8 @@ if (eh->type) VISIT(st, expr, eh->type); if (eh->name) - VISIT(st, expr, eh->name); + if (!symtable_add_def(st, eh->name, DEF_LOCAL)) + return 0; VISIT_SEQ(st, stmt, eh->body); return 1; } Modified: python/branches/p3yk-noslice/Tools/audiopy/audiopy ============================================================================== --- python/branches/p3yk-noslice/Tools/audiopy/audiopy (original) +++ python/branches/p3yk-noslice/Tools/audiopy/audiopy Thu Jan 11 00:43:10 2007 @@ -309,7 +309,7 @@ info.o_gain = self.__scalevar.get() try: self.__devctl.setinfo(info) - except sunaudiodev.error, msg: + except sunaudiodev.error as msg: # TBD: what to do? it's probably temporary. pass @@ -496,7 +496,8 @@ # now set the values try: device.setinfo(info) - except sunaudiodev.error, (code, msg): + except sunaudiodev.error as e: + (code, msg) = e if code <> errno.EINVAL: raise device.close() Modified: python/branches/p3yk-noslice/Tools/bgen/bgen/scantools.py ============================================================================== --- python/branches/p3yk-noslice/Tools/bgen/bgen/scantools.py (original) +++ python/branches/p3yk-noslice/Tools/bgen/bgen/scantools.py Thu Jan 11 00:43:10 2007 @@ -293,7 +293,7 @@ def openrepairfile(self, filename = "REPAIR"): try: return open(filename, "rU") - except IOError, msg: + except IOError as msg: print repr(filename), ":", msg print "Cannot open repair file -- assume no repair needed" return None @@ -419,7 +419,7 @@ def openoutput(self, filename): try: file = open(filename, 'w') - except IOError, arg: + except IOError as arg: raise IOError, (filename, arg) self.setfiletype(filename) return file @@ -460,7 +460,7 @@ # If not on the path, or absolute, try default open() try: return open(filename, 'rU') - except IOError, arg: + except IOError as arg: raise IOError, (arg, filename) def getline(self): Modified: python/branches/p3yk-noslice/Tools/compiler/compile.py ============================================================================== --- python/branches/p3yk-noslice/Tools/compiler/compile.py (original) +++ python/branches/p3yk-noslice/Tools/compiler/compile.py Thu Jan 11 00:43:10 2007 @@ -40,7 +40,7 @@ else: compileFile(filename, DISPLAY) - except SyntaxError, err: + except SyntaxError as err: print err if err.lineno is not None: print err.lineno Modified: python/branches/p3yk-noslice/Tools/compiler/regrtest.py ============================================================================== --- python/branches/p3yk-noslice/Tools/compiler/regrtest.py (original) +++ python/branches/p3yk-noslice/Tools/compiler/regrtest.py Thu Jan 11 00:43:10 2007 @@ -42,7 +42,7 @@ print file, try: compileFile(source) - except SyntaxError, err: + except SyntaxError as err: print err continue # make sure the .pyc file is not over-written Modified: python/branches/p3yk-noslice/Tools/faqwiz/faqw.py ============================================================================== --- python/branches/p3yk-noslice/Tools/faqwiz/faqw.py (original) +++ python/branches/p3yk-noslice/Tools/faqwiz/faqw.py Thu Jan 11 00:43:10 2007 @@ -24,7 +24,7 @@ os.chdir(FAQDIR) sys.path.insert(0, SRCDIR) import faqwiz -except SystemExit, n: +except SystemExit as n: sys.exit(n) except: t, v, tb = sys.exc_info() Modified: python/branches/p3yk-noslice/Tools/faqwiz/faqwiz.py ============================================================================== --- python/branches/p3yk-noslice/Tools/faqwiz/faqwiz.py (original) +++ python/branches/p3yk-noslice/Tools/faqwiz/faqwiz.py Thu Jan 11 00:43:10 2007 @@ -348,7 +348,7 @@ raise InvalidFile(file) try: fp = open(file) - except IOError, msg: + except IOError as msg: raise NoSuchFile(file, msg) try: return self.entryclass(fp, file, sec_num) @@ -387,11 +387,11 @@ else: try: meth() - except InvalidFile, exc: + except InvalidFile as exc: self.error("Invalid entry file name %s" % exc.file) - except NoSuchFile, exc: + except NoSuchFile as exc: self.error("No entry with file name %s" % exc.file) - except NoSuchSection, exc: + except NoSuchSection as exc: self.error("No section number %s" % exc.section) self.epilogue() @@ -796,7 +796,7 @@ pass try: f = open(file, 'w') - except IOError, why: + except IOError as why: self.error(CANTWRITE, file=file, why=why) return date = time.ctime(now) Modified: python/branches/p3yk-noslice/Tools/freeze/checkextensions_win32.py ============================================================================== --- python/branches/p3yk-noslice/Tools/freeze/checkextensions_win32.py (original) +++ python/branches/p3yk-noslice/Tools/freeze/checkextensions_win32.py Thu Jan 11 00:43:10 2007 @@ -131,7 +131,7 @@ dsp_path, dsp_name = os.path.split(dsp) try: lines = open(dsp, "r").readlines() - except IOError, msg: + except IOError as msg: sys.stderr.write("%s: %s\n" % (dsp, msg)) return None for line in lines: Modified: python/branches/p3yk-noslice/Tools/freeze/freeze.py ============================================================================== --- python/branches/p3yk-noslice/Tools/freeze/freeze.py (original) +++ python/branches/p3yk-noslice/Tools/freeze/freeze.py Thu Jan 11 00:43:10 2007 @@ -145,7 +145,7 @@ if sys.argv[pos] == '-i': try: options = open(sys.argv[pos+1]).read().split() - except IOError, why: + except IOError as why: usage("File name '%s' specified with the -i option " "can not be read - %s" % (sys.argv[pos+1], why) ) # Replace the '-i' and the filename with the read params. @@ -156,7 +156,7 @@ # Now parse the command line with the extras inserted. try: opts, args = getopt.getopt(sys.argv[1:], 'r:a:dEe:hmo:p:P:qs:wX:x:l:') - except getopt.error, msg: + except getopt.error as msg: usage('getopt error: ' + str(msg)) # proces option arguments @@ -311,7 +311,7 @@ try: os.mkdir(odir) print "Created output directory", odir - except os.error, msg: + except os.error as msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) base = '' if odir: @@ -333,7 +333,7 @@ try: custom_entry_point, python_entry_is_main = \ winmakemakefile.get_custom_entry_point(subsystem) - except ValueError, why: + except ValueError as why: usage(why) Modified: python/branches/p3yk-noslice/Tools/i18n/msgfmt.py ============================================================================== --- python/branches/p3yk-noslice/Tools/i18n/msgfmt.py (original) +++ python/branches/p3yk-noslice/Tools/i18n/msgfmt.py Thu Jan 11 00:43:10 2007 @@ -110,7 +110,7 @@ try: lines = open(infile).readlines() - except IOError, msg: + except IOError as msg: print >> sys.stderr, msg sys.exit(1) @@ -167,7 +167,7 @@ try: open(outfile,"wb").write(output) - except IOError,msg: + except IOError as msg: print >> sys.stderr, msg @@ -176,7 +176,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'hVo:', ['help', 'version', 'output-file=']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) outfile = None Modified: python/branches/p3yk-noslice/Tools/i18n/pygettext.py ============================================================================== --- python/branches/p3yk-noslice/Tools/i18n/pygettext.py (original) +++ python/branches/p3yk-noslice/Tools/i18n/pygettext.py Thu Jan 11 00:43:10 2007 @@ -512,7 +512,7 @@ 'style=', 'verbose', 'version', 'width=', 'exclude-file=', 'docstrings', 'no-docstrings', ]) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) # for holding option values @@ -635,7 +635,7 @@ eater.set_filename(filename) try: tokenize.tokenize(fp.readline, eater) - except tokenize.TokenError, e: + except tokenize.TokenError as e: print >> sys.stderr, '%s: %s, line %d, column %d' % ( e[0], filename, e[1][0], e[1][1]) finally: Modified: python/branches/p3yk-noslice/Tools/pybench/CommandLine.py ============================================================================== --- python/branches/p3yk-noslice/Tools/pybench/CommandLine.py (original) +++ python/branches/p3yk-noslice/Tools/pybench/CommandLine.py Thu Jan 11 00:43:10 2007 @@ -347,7 +347,7 @@ if rc is None: rc = 0 - except SystemExit,rc: + except SystemExit as rc: pass except KeyboardInterrupt: @@ -433,7 +433,7 @@ files = l self.optionlist = optlist self.files = files + self.files - except getopt.error,why: + except getopt.error as why: self.help(why) sys.exit(1) Modified: python/branches/p3yk-noslice/Tools/pybench/pybench.py ============================================================================== --- python/branches/p3yk-noslice/Tools/pybench/pybench.py (original) +++ python/branches/p3yk-noslice/Tools/pybench/pybench.py Thu Jan 11 00:43:10 2007 @@ -865,7 +865,7 @@ bench.name = compare_to f.close() compare_to = bench - except IOError, reason: + except IOError as reason: print '* Error opening/reading file %s: %s' % ( repr(compare_to), reason) @@ -885,7 +885,7 @@ else: bench.print_benchmark(hidenoise=hidenoise, limitnames=limitnames) - except IOError, reason: + except IOError as reason: print '* Error opening/reading file %s: %s' % ( repr(show_bench), reason) @@ -931,9 +931,9 @@ bench.name = reportfile pickle.dump(bench,f) f.close() - except IOError, reason: + except IOError as reason: print '* Error opening/writing reportfile' - except IOError, reason: + except IOError as reason: print '* Error opening/writing reportfile %s: %s' % ( reportfile, reason) Modified: python/branches/p3yk-noslice/Tools/pynche/Main.py ============================================================================== --- python/branches/p3yk-noslice/Tools/pynche/Main.py (original) +++ python/branches/p3yk-noslice/Tools/pynche/Main.py Thu Jan 11 00:43:10 2007 @@ -186,7 +186,7 @@ sys.argv[1:], 'hd:i:Xv', ['database=', 'initfile=', 'ignore', 'help', 'version']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) if len(args) == 0: Modified: python/branches/p3yk-noslice/Tools/scripts/byext.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/byext.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/byext.py Thu Jan 11 00:43:10 2007 @@ -24,7 +24,7 @@ self.addstats("", "dirs", 1) try: names = os.listdir(dir) - except os.error, err: + except os.error as err: sys.stderr.write("Can't list %s: %s\n" % (dir, err)) self.addstats("", "unlistable", 1) return @@ -53,7 +53,7 @@ self.addstats(ext, "files", 1) try: f = open(filename, "rb") - except IOError, err: + except IOError as err: sys.stderr.write("Can't open %s: %s\n" % (filename, err)) self.addstats(ext, "unopenable", 1) return Modified: python/branches/p3yk-noslice/Tools/scripts/byteyears.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/byteyears.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/byteyears.py Thu Jan 11 00:43:10 2007 @@ -43,7 +43,7 @@ for filename in sys.argv[1:]: try: st = statfunc(filename) - except os.error, msg: + except os.error as msg: sys.stderr.write("can't stat %r: %r\n" % (filename, msg)) status = 1 st = () Modified: python/branches/p3yk-noslice/Tools/scripts/checkappend.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/checkappend.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/checkappend.py Thu Jan 11 00:43:10 2007 @@ -50,7 +50,7 @@ global verbose try: opts, args = getopt.getopt(sys.argv[1:], "v") - except getopt.error, msg: + except getopt.error as msg: errprint(str(msg) + "\n\n" + __doc__) return for opt, optarg in opts: @@ -77,7 +77,7 @@ try: f = open(file) - except IOError, msg: + except IOError as msg: errprint("%r: I/O Error: %s" % (file, msg)) return @@ -104,7 +104,7 @@ def run(self): try: tokenize.tokenize(self.file.readline, self.tokeneater) - except tokenize.TokenError, msg: + except tokenize.TokenError as msg: errprint("%r: Token Error: %s" % (self.fname, msg)) self.nerrors = self.nerrors + 1 return self.nerrors == 0 Modified: python/branches/p3yk-noslice/Tools/scripts/classfix.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/classfix.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/classfix.py Thu Jan 11 00:43:10 2007 @@ -62,7 +62,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() @@ -83,7 +83,7 @@ ## dbg('fix(%r)\n' % (filename,)) try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 head, tail = os.path.split(filename) @@ -106,7 +106,7 @@ if g is None: try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 @@ -130,17 +130,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes Modified: python/branches/p3yk-noslice/Tools/scripts/cleanfuture.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/cleanfuture.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/cleanfuture.py Thu Jan 11 00:43:10 2007 @@ -59,7 +59,7 @@ global verbose, recurse, dryrun try: opts, args = getopt.getopt(sys.argv[1:], "drv") - except getopt.error, msg: + except getopt.error as msg: errprint(msg) return for o, a in opts: @@ -92,7 +92,7 @@ print "checking", file, "...", try: f = open(file) - except IOError, msg: + except IOError as msg: errprint("%r: I/O Error: %s" % (file, str(msg))) return Modified: python/branches/p3yk-noslice/Tools/scripts/cvsfiles.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/cvsfiles.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/cvsfiles.py Thu Jan 11 00:43:10 2007 @@ -20,7 +20,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "n:") - except getopt.error, msg: + except getopt.error as msg: print msg print __doc__, return 1 Modified: python/branches/p3yk-noslice/Tools/scripts/dutree.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/dutree.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/dutree.py Thu Jan 11 00:43:10 2007 @@ -18,7 +18,7 @@ total, d = store(size, comps, total, d) try: display(total, d) - except IOError, e: + except IOError as e: if e.errno != errno.EPIPE: raise Modified: python/branches/p3yk-noslice/Tools/scripts/finddiv.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/finddiv.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/finddiv.py Thu Jan 11 00:43:10 2007 @@ -23,7 +23,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "lh") - except getopt.error, msg: + except getopt.error as msg: usage(msg) return 2 if not args: @@ -52,7 +52,7 @@ return processdir(filename, listnames) try: fp = open(filename) - except IOError, msg: + except IOError as msg: sys.stderr.write("Can't open: %s\n" % msg) return 1 g = tokenize.generate_tokens(fp.readline) @@ -70,7 +70,7 @@ def processdir(dir, listnames): try: names = os.listdir(dir) - except os.error, msg: + except os.error as msg: sys.stderr.write("Can't list directory: %s\n" % dir) return 1 files = [] Modified: python/branches/p3yk-noslice/Tools/scripts/findlinksto.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/findlinksto.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/findlinksto.py Thu Jan 11 00:43:10 2007 @@ -14,7 +14,7 @@ opts, args = getopt.getopt(sys.argv[1:], '') if len(args) < 2: raise getopt.GetoptError('not enough arguments', None) - except getopt.GetoptError, msg: + except getopt.GetoptError as msg: sys.stdout = sys.stderr print msg print 'usage: findlinksto pattern directory ...' Modified: python/branches/p3yk-noslice/Tools/scripts/findnocoding.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/findnocoding.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/findnocoding.py Thu Jan 11 00:43:10 2007 @@ -78,7 +78,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'cd') -except getopt.error, msg: +except getopt.error as msg: print >>sys.stderr, msg print >>sys.stderr, usage sys.exit(1) Modified: python/branches/p3yk-noslice/Tools/scripts/fixcid.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/fixcid.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/fixcid.py Thu Jan 11 00:43:10 2007 @@ -62,7 +62,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'crs:') - except getopt.error, msg: + except getopt.error as msg: err('Options error: ' + str(msg) + '\n') usage() sys.exit(2) @@ -97,7 +97,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err(dirname + ': cannot list directory: ' + str(msg) + '\n') return 1 names.sort() @@ -124,7 +124,7 @@ # File replacement mode try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err(filename + ': cannot open: ' + str(msg) + '\n') return 1 head, tail = os.path.split(filename) @@ -148,7 +148,7 @@ if g is None: try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err(tempname+': cannot create: '+ str(msg)+'\n') @@ -175,17 +175,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err(tempname + ': warning: chmod failed (' + str(msg) + ')\n') # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err(filename + ': warning: backup failed (' + str(msg) + ')\n') # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err(filename + ': rename failed (' + str(msg) + ')\n') return 1 # Return succes @@ -276,7 +276,7 @@ def addsubst(substfile): try: fp = open(substfile, 'r') - except IOError, msg: + except IOError as msg: err(substfile + ': cannot read substfile: ' + str(msg) + '\n') sys.exit(1) lineno = 0 Modified: python/branches/p3yk-noslice/Tools/scripts/fixdiv.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/fixdiv.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/fixdiv.py Thu Jan 11 00:43:10 2007 @@ -140,7 +140,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hm") - except getopt.error, msg: + except getopt.error as msg: usage(msg) return 2 for o, a in opts: @@ -181,7 +181,7 @@ prog = re.compile(PATTERN) try: f = open(warningsfile) - except IOError, msg: + except IOError as msg: sys.stderr.write("can't open: %s\n" % msg) return warnings = {} @@ -207,7 +207,7 @@ assert list # if this fails, readwarnings() is broken try: fp = open(filename) - except IOError, msg: + except IOError as msg: sys.stderr.write("can't open: %s\n" % msg) return 1 print "Index:", filename Modified: python/branches/p3yk-noslice/Tools/scripts/fixheader.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/fixheader.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/fixheader.py Thu Jan 11 00:43:10 2007 @@ -12,7 +12,7 @@ def process(filename): try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: can\'t open: %s\n' % (filename, str(msg))) return data = f.read() @@ -22,7 +22,7 @@ return try: f = open(filename, 'w') - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: can\'t write: %s\n' % (filename, str(msg))) return sys.stderr.write('Processing %s ...\n' % filename) Modified: python/branches/p3yk-noslice/Tools/scripts/fixnotice.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/fixnotice.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/fixnotice.py Thu Jan 11 00:43:10 2007 @@ -62,7 +62,7 @@ opts, args = getopt.getopt(sys.argv[1:], 'hv', ['help', 'oldnotice=', 'newnotice=', 'dry-run', 'verbose']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) for opt, arg in opts: Modified: python/branches/p3yk-noslice/Tools/scripts/fixps.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/fixps.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/fixps.py Thu Jan 11 00:43:10 2007 @@ -11,7 +11,7 @@ for filename in sys.argv[1:]: try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: print filename, ': can\'t open :', msg continue line = f.readline() Modified: python/branches/p3yk-noslice/Tools/scripts/ftpmirror.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/ftpmirror.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/ftpmirror.py Thu Jan 11 00:43:10 2007 @@ -45,7 +45,7 @@ global verbose, interactive, mac, rmok, nologin try: opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v') - except getopt.error, msg: + except getopt.error as msg: usage(msg) login = '' passwd = '' @@ -108,13 +108,13 @@ if verbose: print 'Creating local directory', repr(localdir) try: makedir(localdir) - except os.error, msg: + except os.error as msg: print "Failed to establish local directory", repr(localdir) return infofilename = os.path.join(localdir, '.mirrorinfo') try: text = open(infofilename, 'r').read() - except IOError, msg: + except IOError as msg: text = '{}' try: info = eval(text) @@ -190,13 +190,13 @@ print "Creating symlink %r -> %r" % (filename, linkto) try: os.symlink(linkto, tempname) - except IOError, msg: + except IOError as msg: print "Can't create %r: %s" % (tempname, msg) continue else: try: fp = open(tempname, 'wb') - except IOError, msg: + except IOError as msg: print "Can't create %r: %s" % (tempname, msg) continue if verbose: @@ -209,7 +209,7 @@ try: f.retrbinary('RETR ' + filename, fp1.write, 8*1024) - except ftplib.error_perm, msg: + except ftplib.error_perm as msg: print msg t1 = time.time() bytes = fp.tell() @@ -222,7 +222,7 @@ pass # Ignore the error try: os.rename(tempname, fullname) - except os.error, msg: + except os.error as msg: print "Can't rename %r to %r: %s" % (tempname, fullname, msg) continue info[filename] = infostuff @@ -292,7 +292,7 @@ print 'Remote cwd', repr(subdir) try: f.cwd(subdir) - except ftplib.error_perm, msg: + except ftplib.error_perm as msg: print "Can't chdir to", repr(subdir), ":", repr(msg) else: if verbose: print 'Mirroring as', repr(localsubdir) @@ -322,13 +322,13 @@ return 0 try: os.rmdir(fullname) - except os.error, msg: + except os.error as msg: print "Can't remove local directory %r: %s" % (fullname, msg) return 0 else: try: os.unlink(fullname) - except os.error, msg: + except os.error as msg: print "Can't remove local file %r: %s" % (fullname, msg) return 0 return 1 Modified: python/branches/p3yk-noslice/Tools/scripts/linktree.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/linktree.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/linktree.py Thu Jan 11 00:43:10 2007 @@ -32,13 +32,13 @@ return 1 try: os.mkdir(newtree, 0777) - except os.error, msg: + except os.error as msg: print newtree + ': cannot mkdir:', msg return 1 linkname = os.path.join(newtree, link) try: os.symlink(os.path.join(os.pardir, oldtree), linkname) - except os.error, msg: + except os.error as msg: if not link_may_fail: print linkname + ': cannot symlink:', msg return 1 @@ -51,7 +51,7 @@ if debug: print 'linknames', (old, new, link) try: names = os.listdir(old) - except os.error, msg: + except os.error as msg: print old + ': warning: cannot listdir:', msg return for name in names: Modified: python/branches/p3yk-noslice/Tools/scripts/logmerge.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/logmerge.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/logmerge.py Thu Jan 11 00:43:10 2007 @@ -180,6 +180,6 @@ if __name__ == '__main__': try: main() - except IOError, e: + except IOError as e: if e.errno != errno.EPIPE: raise Modified: python/branches/p3yk-noslice/Tools/scripts/md5sum.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/md5sum.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/md5sum.py Thu Jan 11 00:43:10 2007 @@ -43,7 +43,7 @@ def printsum(filename, out=sys.stdout): try: fp = open(filename, rmode) - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg)) return 1 if fnfilter: @@ -60,7 +60,7 @@ if not data: break m.update(data) - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: I/O error: %s\n' % (filename, msg)) return 1 out.write('%s %s\n' % (m.hexdigest(), filename)) @@ -70,7 +70,7 @@ global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: Modified: python/branches/p3yk-noslice/Tools/scripts/methfix.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/methfix.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/methfix.py Thu Jan 11 00:43:10 2007 @@ -59,7 +59,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() @@ -80,7 +80,7 @@ ## dbg('fix(%r)\n' % (filename,)) try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 head, tail = os.path.split(filename) @@ -117,7 +117,7 @@ if g is None: try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 @@ -141,17 +141,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes Modified: python/branches/p3yk-noslice/Tools/scripts/ndiff.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/ndiff.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/ndiff.py Thu Jan 11 00:43:10 2007 @@ -61,7 +61,7 @@ def fopen(fname): try: return open(fname, 'U') - except IOError, detail: + except IOError as detail: return fail("couldn't open " + fname + ": " + str(detail)) # open two files & spray the diff to stdout; return false iff a problem @@ -85,7 +85,7 @@ import getopt try: opts, args = getopt.getopt(args, "qr:") - except getopt.error, detail: + except getopt.error as detail: return fail(str(detail)) noisy = 1 qseen = rseen = 0 Modified: python/branches/p3yk-noslice/Tools/scripts/pathfix.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/pathfix.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/pathfix.py Thu Jan 11 00:43:10 2007 @@ -37,7 +37,7 @@ sys.argv[0]) try: opts, args = getopt.getopt(sys.argv[1:], 'i:') - except getopt.error, msg: + except getopt.error as msg: err(msg + '\n') err(usage) sys.exit(2) @@ -68,7 +68,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() @@ -89,7 +89,7 @@ ## dbg('fix(%r)\n' % (filename,)) try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 line = f.readline() @@ -102,7 +102,7 @@ tempname = os.path.join(head, '@' + tail) try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 @@ -122,17 +122,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes Modified: python/branches/p3yk-noslice/Tools/scripts/pindent.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/pindent.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/pindent.py Thu Jan 11 00:43:10 2007 @@ -491,7 +491,7 @@ import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'cdrs:t:e') - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write('Error: %s\n' % msg) sys.stderr.write(usage) sys.exit(2) Modified: python/branches/p3yk-noslice/Tools/scripts/pysource.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/pysource.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/pysource.py Thu Jan 11 00:43:10 2007 @@ -33,7 +33,7 @@ def _open(fullpath): try: size = os.stat(fullpath).st_size - except OSError, err: # Permission denied - ignore the file + except OSError as err: # Permission denied - ignore the file print_debug("%s: permission denied: %s" % (fullpath, err)) return None @@ -43,7 +43,7 @@ try: return open(fullpath, 'rU') - except IOError, err: # Access denied, or a special file - ignore it + except IOError as err: # Access denied, or a special file - ignore it print_debug("%s: access denied: %s" % (fullpath, err)) return None @@ -81,7 +81,7 @@ try: compile(code, fullpath, "exec") - except Exception, err: + except Exception as err: print_debug("%s: cannot compile: %s" % (fullpath, err)) return False Modified: python/branches/p3yk-noslice/Tools/scripts/redemo.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/redemo.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/redemo.py Thu Jan 11 00:43:10 2007 @@ -104,7 +104,7 @@ self.getflags()) bg = self.promptdisplay['background'] self.statusdisplay.config(text="", background=bg) - except re.error, msg: + except re.error as msg: self.compiled = None self.statusdisplay.config( text="re.error: %s" % str(msg), Modified: python/branches/p3yk-noslice/Tools/scripts/reindent.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/reindent.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/reindent.py Thu Jan 11 00:43:10 2007 @@ -61,7 +61,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], "drvh", ["dryrun", "recurse", "verbose", "help"]) - except getopt.error, msg: + except getopt.error as msg: usage(msg) return for o, a in opts: @@ -99,7 +99,7 @@ print "checking", file, "...", try: f = open(file) - except IOError, msg: + except IOError as msg: errprint("%s: I/O Error: %s" % (file, str(msg))) return Modified: python/branches/p3yk-noslice/Tools/scripts/rgrep.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/rgrep.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/rgrep.py Thu Jan 11 00:43:10 2007 @@ -23,11 +23,11 @@ pattern, filename = args try: prog = re.compile(pattern, reflags) - except re.error, msg: + except re.error as msg: usage("error in regular expression: %s" % str(msg)) try: f = open(filename) - except IOError, msg: + except IOError as msg: usage("can't open %s: %s" % (repr(filename), str(msg)), 1) f.seek(0, 2) pos = f.tell() Modified: python/branches/p3yk-noslice/Tools/scripts/texi2html.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/texi2html.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/texi2html.py Thu Jan 11 00:43:10 2007 @@ -554,7 +554,7 @@ file = os.path.join(self.includedir, file) try: fp = open(file, 'r') - except IOError, msg: + except IOError as msg: print '*** Can\'t open include file', repr(file) return print '!'*self.debugging, '--> file', repr(file) @@ -1797,7 +1797,7 @@ print>>fp, '' self.dumpfiles(fp) fp.close() - except IOError, msg: + except IOError as msg: print projectfile, ':', msg sys.exit(1) @@ -1822,7 +1822,7 @@ print>>fp, '' print>>fp, '' fp.close() - except IOError, msg: + except IOError as msg: print contentfile, ':', msg sys.exit(1) @@ -1844,7 +1844,7 @@ print>>fp, '' print>>fp, '' fp.close() - except IOError, msg: + except IOError as msg: print indexfile , ':', msg sys.exit(1) @@ -2063,7 +2063,7 @@ try: fp = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ':', msg sys.exit(1) Modified: python/branches/p3yk-noslice/Tools/scripts/treesync.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/treesync.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/treesync.py Thu Jan 11 00:43:10 2007 @@ -78,7 +78,7 @@ print "creating slave directory", slave try: os.mkdir(slave) - except os.error, msg: + except os.error as msg: print "can't make slave directory", slave, ":", msg return else: Modified: python/branches/p3yk-noslice/Tools/scripts/untabify.py ============================================================================== --- python/branches/p3yk-noslice/Tools/scripts/untabify.py (original) +++ python/branches/p3yk-noslice/Tools/scripts/untabify.py Thu Jan 11 00:43:10 2007 @@ -12,7 +12,7 @@ opts, args = getopt.getopt(sys.argv[1:], "t:") if not args: raise getopt.error, "At least one file argument required" - except getopt.error, msg: + except getopt.error as msg: print msg print "usage:", sys.argv[0], "[-t tabwidth] file ..." return @@ -28,7 +28,7 @@ f = open(filename) text = f.read() f.close() - except IOError, msg: + except IOError as msg: print "%r: I/O error: %s" % (filename, msg) return newtext = text.expandtabs(tabsize) Modified: python/branches/p3yk-noslice/Tools/unicode/comparecodecs.py ============================================================================== --- python/branches/p3yk-noslice/Tools/unicode/comparecodecs.py (original) +++ python/branches/p3yk-noslice/Tools/unicode/comparecodecs.py Thu Jan 11 00:43:10 2007 @@ -18,11 +18,11 @@ u = unichr(i) try: c1 = u.encode(encoding1) - except UnicodeError, reason: + except UnicodeError as reason: c1 = '' try: c2 = u.encode(encoding2) - except UnicodeError, reason: + except UnicodeError as reason: c2 = '' if c1 != c2: print ' * encoding mismatch for 0x%04X: %-14r != %r' % \ Modified: python/branches/p3yk-noslice/Tools/unicode/gencodec.py ============================================================================== --- python/branches/p3yk-noslice/Tools/unicode/gencodec.py (original) +++ python/branches/p3yk-noslice/Tools/unicode/gencodec.py Thu Jan 11 00:43:10 2007 @@ -130,7 +130,7 @@ try: return '(' + ', '.join(['0x%0*X' % (precision, item) for item in t]) + ')' - except TypeError, why: + except TypeError as why: print '* failed to convert %r: %s' % (t, why) raise @@ -393,7 +393,7 @@ else: pymap(mappathname, map, dirprefix + codefile,name,comments) marshalmap(mappathname, map, dirprefix + marshalfile) - except ValueError, why: + except ValueError as why: print '* conversion failed: %s' % why raise @@ -414,7 +414,7 @@ print '* map is empty; skipping' else: pymap(mapname, map, dirprefix + codefile,name,comments) - except ValueError, why: + except ValueError as why: print '* conversion failed: %s' % why if __name__ == '__main__': Modified: python/branches/p3yk-noslice/Tools/unicode/listcodecs.py ============================================================================== --- python/branches/p3yk-noslice/Tools/unicode/listcodecs.py (original) +++ python/branches/p3yk-noslice/Tools/unicode/listcodecs.py Thu Jan 11 00:43:10 2007 @@ -22,7 +22,7 @@ except LookupError: # Codec not found continue - except Exception, reason: + except Exception as reason: # Probably an error from importing the codec; still it's # a valid code name if _debug: Modified: python/branches/p3yk-noslice/Tools/versioncheck/pyversioncheck.py ============================================================================== --- python/branches/p3yk-noslice/Tools/versioncheck/pyversioncheck.py (original) +++ python/branches/p3yk-noslice/Tools/versioncheck/pyversioncheck.py Thu Jan 11 00:43:10 2007 @@ -49,7 +49,7 @@ print ' Checking %s'%url try: fp = urllib.urlopen(url) - except IOError, arg: + except IOError as arg: if verbose >= VERBOSE_EACHFILE: print ' Cannot open:', arg return -1, None, None Modified: python/branches/p3yk-noslice/Tools/webchecker/wcgui.py ============================================================================== --- python/branches/p3yk-noslice/Tools/webchecker/wcgui.py (original) +++ python/branches/p3yk-noslice/Tools/webchecker/wcgui.py Thu Jan 11 00:43:10 2007 @@ -74,7 +74,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], 't:m:qva') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print __doc__%vars(webchecker) Modified: python/branches/p3yk-noslice/Tools/webchecker/webchecker.py ============================================================================== --- python/branches/p3yk-noslice/Tools/webchecker/webchecker.py (original) +++ python/branches/p3yk-noslice/Tools/webchecker/webchecker.py Thu Jan 11 00:43:10 2007 @@ -153,7 +153,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print __doc__%globals() @@ -335,7 +335,7 @@ rp.set_url(url) try: rp.read() - except (OSError, IOError), msg: + except (OSError, IOError) as msg: self.note(1, "I/O error parsing %s: %s", url, msg) def run(self): @@ -402,7 +402,7 @@ return try: page = self.getpage(url_pair) - except sgmllib.SGMLParseError, msg: + except sgmllib.SGMLParseError as msg: msg = self.sanitize(msg) self.note(0, "Error parsing %s: %s", self.format_url(url_pair), msg) @@ -541,7 +541,7 @@ url, fragment = url_pair try: return self.urlopener.open(url) - except (OSError, IOError), msg: + except (OSError, IOError) as msg: msg = self.sanitize(msg) self.note(0, "Error %s", msg) if self.verbose > 0: @@ -759,7 +759,7 @@ return self.open_file(url + "index.html") try: names = os.listdir(path) - except os.error, msg: + except os.error as msg: exc_type, exc_value, exc_tb = sys.exc_info() raise IOError, msg, exc_tb names.sort() Modified: python/branches/p3yk-noslice/Tools/webchecker/websucker.py ============================================================================== --- python/branches/p3yk-noslice/Tools/webchecker/websucker.py (original) +++ python/branches/p3yk-noslice/Tools/webchecker/websucker.py Thu Jan 11 00:43:10 2007 @@ -21,7 +21,7 @@ verbose = webchecker.VERBOSE try: opts, args = getopt.getopt(sys.argv[1:], "qv") - except getopt.error, msg: + except getopt.error as msg: print msg print "usage:", sys.argv[0], "[-qv] ... [rooturl] ..." return 2 @@ -83,7 +83,7 @@ f.write(text) f.close() self.message("saved %s", path) - except IOError, msg: + except IOError as msg: self.message("didn't save %s: %s", path, str(msg)) def savefilename(self, url): Modified: python/branches/p3yk-noslice/setup.py ============================================================================== --- python/branches/p3yk-noslice/setup.py (original) +++ python/branches/p3yk-noslice/setup.py Thu Jan 11 00:43:10 2007 @@ -186,7 +186,7 @@ try: build_ext.build_extension(self, ext) - except (CCompilerError, DistutilsError), why: + except (CCompilerError, DistutilsError) as why: self.announce('WARNING: building of extension "%s" failed: %s' % (ext.name, sys.exc_info()[1])) return @@ -208,7 +208,7 @@ self.get_ext_filename(self.get_ext_fullname(ext.name))) try: imp.load_dynamic(ext.name, ext_filename) - except ImportError, why: + except ImportError as why: self.announce('*** WARNING: renaming "%s" since importing it' ' failed: %s' % (ext.name, why), level=3) assert not self.inplace From python-checkins at python.org Thu Jan 11 00:44:42 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 11 Jan 2007 00:44:42 +0100 (CET) Subject: [Python-checkins] r53365 - sandbox/trunk/sio/bench_cat.py Message-ID: <20070110234442.EE78E1E400A@bag.python.org> Author: guido.van.rossum Date: Thu Jan 11 00:44:42 2007 New Revision: 53365 Modified: sandbox/trunk/sio/bench_cat.py Log: Turn some constants into names. Modified: sandbox/trunk/sio/bench_cat.py ============================================================================== --- sandbox/trunk/sio/bench_cat.py (original) +++ sandbox/trunk/sio/bench_cat.py Thu Jan 11 00:44:42 2007 @@ -1,11 +1,14 @@ import random import timeit +LISTSIZE = 1000000 +MULTIPLIER = 3 + for size in [10, 20, 50, 100, 200, 500, 1000]: print "------ size = %d ------" % size strings = [] byteses = [] - for i in range(100000): + for i in range(LISTSIZE): n = random.randrange(0, size) s = "x"*n b = bytes(s) @@ -14,16 +17,16 @@ timer = timeit.Timer("bbb = bytes()\nfor b in byteses: bbb += b", "from __main__ import strings, byteses") - print "bytes+= %.3f" % min(timer.repeat(3, 10)) + print "bytes+= %.3f" % min(timer.repeat(3, MULTIPLIER)) timer = timeit.Timer("bbb = bytes.join(byteses)", "from __main__ import strings, byteses") - print "bytes.join %.3f" % min(timer.repeat(3, 10)) + print "bytes.join %.3f" % min(timer.repeat(3, MULTIPLIER)) timer = timeit.Timer("sss = ''\nfor s in strings: sss += s", "from __main__ import strings, byteses") - print "str+= %.3f" % min(timer.repeat(3, 10)) + print "str+= %.3f" % min(timer.repeat(3, MULTIPLIER)) timer = timeit.Timer("sss = ''.join(strings)", "from __main__ import strings, byteses") - print "str.join %.3f" % min(timer.repeat(3, 10)) + print "str.join %.3f" % min(timer.repeat(3, MULTIPLIER)) From buildbot at python.org Thu Jan 11 02:27:32 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 11 Jan 2007 01:27:32 +0000 Subject: [Python-checkins] buildbot warnings in alpha Debian trunk Message-ID: <20070111012733.88BFC1E400A@bag.python.org> The Buildbot has detected a new failure of alpha Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Debian%2520trunk/builds/4 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: guido.van.rossum Build had warnings: warnings test Excerpt from the test logfile: sincerely, -The Buildbot From python-checkins at python.org Thu Jan 11 11:25:46 2007 From: python-checkins at python.org (matthias.klose) Date: Thu, 11 Jan 2007 11:25:46 +0100 (CET) Subject: [Python-checkins] r53369 - python/branches/release25-maint/Doc/lib/libsmtplib.tex Message-ID: <20070111102546.193E51E4018@bag.python.org> Author: matthias.klose Date: Thu Jan 11 11:25:45 2007 New Revision: 53369 Modified: python/branches/release25-maint/Doc/lib/libsmtplib.tex Log: - Make the documentation match the code and the docstring Modified: python/branches/release25-maint/Doc/lib/libsmtplib.tex ============================================================================== --- python/branches/release25-maint/Doc/lib/libsmtplib.tex (original) +++ python/branches/release25-maint/Doc/lib/libsmtplib.tex Thu Jan 11 11:25:45 2007 @@ -173,7 +173,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} From python-checkins at python.org Thu Jan 11 11:26:31 2007 From: python-checkins at python.org (matthias.klose) Date: Thu, 11 Jan 2007 11:26:31 +0100 (CET) Subject: [Python-checkins] r53370 - python/trunk/Doc/lib/libsmtplib.tex Message-ID: <20070111102631.CF6231E4012@bag.python.org> Author: matthias.klose Date: Thu Jan 11 11:26:31 2007 New Revision: 53370 Modified: python/trunk/Doc/lib/libsmtplib.tex Log: - Make the documentation match the code and the docstring Modified: python/trunk/Doc/lib/libsmtplib.tex ============================================================================== --- python/trunk/Doc/lib/libsmtplib.tex (original) +++ python/trunk/Doc/lib/libsmtplib.tex Thu Jan 11 11:26:31 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} From python-checkins at python.org Thu Jan 11 11:27:34 2007 From: python-checkins at python.org (matthias.klose) Date: Thu, 11 Jan 2007 11:27:34 +0100 (CET) Subject: [Python-checkins] r53371 - python/branches/release24-maint/Doc/lib/libsmtplib.tex Message-ID: <20070111102734.43E201E400A@bag.python.org> Author: matthias.klose Date: Thu Jan 11 11:27:33 2007 New Revision: 53371 Modified: python/branches/release24-maint/Doc/lib/libsmtplib.tex Log: - Make the documentation match the code and the docstring Modified: python/branches/release24-maint/Doc/lib/libsmtplib.tex ============================================================================== --- python/branches/release24-maint/Doc/lib/libsmtplib.tex (original) +++ python/branches/release24-maint/Doc/lib/libsmtplib.tex Thu Jan 11 11:27:33 2007 @@ -173,7 +173,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} From python-checkins at python.org Thu Jan 11 12:40:31 2007 From: python-checkins at python.org (matthias.klose) Date: Thu, 11 Jan 2007 12:40:31 +0100 (CET) Subject: [Python-checkins] r53373 - in python/branches/release24-maint: Lib/idlelib/EditorWindow.py Misc/NEWS Message-ID: <20070111114031.9C4501E400A@bag.python.org> Author: matthias.klose Date: Thu Jan 11 12:40:28 2007 New Revision: 53373 Modified: python/branches/release24-maint/Lib/idlelib/EditorWindow.py python/branches/release24-maint/Misc/NEWS Log: - idle: Honor the "Cancel" action in the save dialog (Debian bug #299092). Modified: python/branches/release24-maint/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/release24-maint/Lib/idlelib/EditorWindow.py (original) +++ python/branches/release24-maint/Lib/idlelib/EditorWindow.py Thu Jan 11 12:40:28 2007 @@ -703,7 +703,7 @@ def close(self): reply = self.maybesave() - if reply != "cancel": + if str(reply) != "cancel": self._close() return reply Modified: python/branches/release24-maint/Misc/NEWS ============================================================================== --- python/branches/release24-maint/Misc/NEWS (original) +++ python/branches/release24-maint/Misc/NEWS Thu Jan 11 12:40:28 2007 @@ -24,6 +24,8 @@ Library ------- +- idle: Honor the "Cancel" action in the save dialog (Debian bug #299092). + Tests ----- From python-checkins at python.org Thu Jan 11 12:42:44 2007 From: python-checkins at python.org (matthias.klose) Date: Thu, 11 Jan 2007 12:42:44 +0100 (CET) Subject: [Python-checkins] r53374 - in python/branches/release25-maint: Lib/idlelib/EditorWindow.py Misc/NEWS Message-ID: <20070111114244.747921E400A@bag.python.org> Author: matthias.klose Date: Thu Jan 11 12:42:43 2007 New Revision: 53374 Modified: python/branches/release25-maint/Lib/idlelib/EditorWindow.py python/branches/release25-maint/Misc/NEWS Log: - idle: Honor the "Cancel" action in the save dialog (Debian bug #299092). Modified: python/branches/release25-maint/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/release25-maint/Lib/idlelib/EditorWindow.py (original) +++ python/branches/release25-maint/Lib/idlelib/EditorWindow.py Thu Jan 11 12:42:43 2007 @@ -819,7 +819,7 @@ def close(self): reply = self.maybesave() - if reply != "cancel": + if str(reply) != "cancel": self._close() return reply Modified: python/branches/release25-maint/Misc/NEWS ============================================================================== --- python/branches/release25-maint/Misc/NEWS (original) +++ python/branches/release25-maint/Misc/NEWS Thu Jan 11 12:42:43 2007 @@ -248,6 +248,8 @@ - Patch #1552024: add decorator support to unparse.py demo script. +- idle: Honor the "Cancel" action in the save dialog (Debian bug #299092). + Tests ----- From python-checkins at python.org Thu Jan 11 12:44:05 2007 From: python-checkins at python.org (matthias.klose) Date: Thu, 11 Jan 2007 12:44:05 +0100 (CET) Subject: [Python-checkins] r53375 - in python/trunk: Lib/idlelib/EditorWindow.py Misc/NEWS Message-ID: <20070111114405.2B4E51E400A@bag.python.org> Author: matthias.klose Date: Thu Jan 11 12:44:04 2007 New Revision: 53375 Modified: python/trunk/Lib/idlelib/EditorWindow.py python/trunk/Misc/NEWS Log: - idle: Honor the "Cancel" action in the save dialog (Debian bug #299092). Modified: python/trunk/Lib/idlelib/EditorWindow.py ============================================================================== --- python/trunk/Lib/idlelib/EditorWindow.py (original) +++ python/trunk/Lib/idlelib/EditorWindow.py Thu Jan 11 12:44:04 2007 @@ -819,7 +819,7 @@ def close(self): reply = self.maybesave() - if reply != "cancel": + if str(reply) != "cancel": self._close() return reply Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu Jan 11 12:44:04 2007 @@ -286,6 +286,8 @@ - fixed a bug with bsddb.DB.stat: the flags and txn keyword arguments were transposed. +- idle: Honor the "Cancel" action in the save dialog (Debian bug #299092). + Extension Modules ----------------- From python-checkins at python.org Thu Jan 11 18:54:08 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 11 Jan 2007 18:54:08 +0100 (CET) Subject: [Python-checkins] r53379 - sandbox/trunk/2to3/Grammar.txt Message-ID: <20070111175408.271D81E400C@bag.python.org> Author: guido.van.rossum Date: Thu Jan 11 18:54:07 2007 New Revision: 53379 Modified: sandbox/trunk/2to3/Grammar.txt Log: Make the grammar accept 'as' in an except clause, so fix_except can be idempotent. Modified: sandbox/trunk/2to3/Grammar.txt ============================================================================== --- sandbox/trunk/2to3/Grammar.txt (original) +++ sandbox/trunk/2to3/Grammar.txt Thu Jan 11 18:54:07 2007 @@ -85,7 +85,7 @@ with_stmt: 'with' test [ with_var ] ':' suite with_var: 'as' expr # NB compile.c makes sure that the default except clause is last -except_clause: 'except' [test [',' test]] +except_clause: 'except' [test [(',' | 'as') test]] suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT # Backward compatibility cruft to support: From python-checkins at python.org Thu Jan 11 19:21:05 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 11 Jan 2007 19:21:05 +0100 (CET) Subject: [Python-checkins] r53380 - in python/branches/release25-maint: Lib/test/test_set.py Objects/setobject.c Message-ID: <20070111182105.ABBC61E4012@bag.python.org> Author: raymond.hettinger Date: Thu Jan 11 19:21:04 2007 New Revision: 53380 Modified: python/branches/release25-maint/Lib/test/test_set.py python/branches/release25-maint/Objects/setobject.c Log: SF #1486663 -- Allow keyword args in subclasses of set() and frozenset(). 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 Thu Jan 11 19:21:04 2007 @@ -468,6 +468,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 @@ -1450,6 +1460,7 @@ test_classes = ( TestSet, TestSetSubclass, + TestSetSubclassWithKeywordArgs, TestFrozenSet, TestFrozenSetSubclass, TestSetOfSets, Modified: python/branches/release25-maint/Objects/setobject.c ============================================================================== --- python/branches/release25-maint/Objects/setobject.c (original) +++ python/branches/release25-maint/Objects/setobject.c Thu Jan 11 19:21:04 2007 @@ -1004,7 +1004,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)) @@ -1048,7 +1048,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); From python-checkins at python.org Thu Jan 11 19:22:56 2007 From: python-checkins at python.org (raymond.hettinger) Date: Thu, 11 Jan 2007 19:22:56 +0100 (CET) Subject: [Python-checkins] r53381 - in python/trunk: Lib/test/test_set.py Objects/setobject.c Message-ID: <20070111182256.4FA5C1E400C@bag.python.org> Author: raymond.hettinger Date: Thu Jan 11 19:22:55 2007 New Revision: 53381 Modified: python/trunk/Lib/test/test_set.py python/trunk/Objects/setobject.c Log: SF #1486663 -- Allow keyword args in subclasses of set() and frozenset(). Modified: python/trunk/Lib/test/test_set.py ============================================================================== --- python/trunk/Lib/test/test_set.py (original) +++ python/trunk/Lib/test/test_set.py Thu Jan 11 19:22:55 2007 @@ -468,6 +468,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 @@ -1450,6 +1460,7 @@ test_classes = ( TestSet, TestSetSubclass, + TestSetSubclassWithKeywordArgs, TestFrozenSet, TestFrozenSetSubclass, TestSetOfSets, Modified: python/trunk/Objects/setobject.c ============================================================================== --- python/trunk/Objects/setobject.c (original) +++ python/trunk/Objects/setobject.c Thu Jan 11 19:22:55 2007 @@ -1004,7 +1004,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)) @@ -1048,7 +1048,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); From buildbot at python.org Thu Jan 11 19:29:31 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 11 Jan 2007 18:29:31 +0000 Subject: [Python-checkins] buildbot failure in x86 XP 2.5 Message-ID: <20070111182931.7BEBA1E4015@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/74 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch branches/release25-maint] HEAD Blamelist: raymond.hettinger BUILD FAILED: failed failed slave lost sincerely, -The Buildbot From buildbot at python.org Thu Jan 11 19:46:12 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 11 Jan 2007 18:46:12 +0000 Subject: [Python-checkins] buildbot warnings in x86 mvlgcc 2.5 Message-ID: <20070111184613.123DC1E4014@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/83 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_ssl make: *** [buildbottest] Error 1 sincerely, -The Buildbot From python-checkins at python.org Thu Jan 11 20:02:09 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 11 Jan 2007 20:02:09 +0100 (CET) Subject: [Python-checkins] r53382 - in sandbox/trunk/2to3: example.py fixes/basefix.py fixes/fix_except.py pgen2/parse.py refactor.py Message-ID: <20070111190209.C94C21E400B@bag.python.org> Author: guido.van.rossum Date: Thu Jan 11 20:02:08 2007 New Revision: 53382 Modified: sandbox/trunk/2to3/example.py sandbox/trunk/2to3/fixes/basefix.py sandbox/trunk/2to3/fixes/fix_except.py sandbox/trunk/2to3/pgen2/parse.py sandbox/trunk/2to3/refactor.py Log: Collin Winter's improvements to fix_except.py. I changed new_name() slightly, and got rid of a spurious 'o' in a docstring. Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Thu Jan 11 20:02:08 2007 @@ -162,7 +162,9 @@ def except_examples(): try: pass - except Exception, e: + except Exception, (f, e): + pass + except ImportError, e: pass # try: @@ -170,8 +172,6 @@ except (RuntimeError, ImportError), e: pass # - # These should not be touched - # try: pass except Exception, (a, b): @@ -192,6 +192,13 @@ except Exception, a().foo: pass # + # These should not be touched: + # + try: + pass + except: + pass + # try: pass except Exception: @@ -199,7 +206,8 @@ # try: pass - except (RuntimeError, ImportError): + except (Exception, SystemExit): pass + # This is the last line. Modified: sandbox/trunk/2to3/fixes/basefix.py ============================================================================== --- sandbox/trunk/2to3/fixes/basefix.py (original) +++ sandbox/trunk/2to3/fixes/basefix.py Thu Jan 11 20:02:08 2007 @@ -5,11 +5,14 @@ # Python imports import logging +import itertools # Local imports import patcomp import pygram +# For new_name() +numbers = itertools.count(1) class BaseFix(object): @@ -26,13 +29,14 @@ options = None # Options object passed to initializer filename = None # The filename (set by set_filename) logger = None # A logger (set by set_filename) + used_names = set() # A set of all used NAMEs # Shortcut for access to Python grammar symbols syms = pygram.python_symbols def __init__(self, options): """Initializer. Subclass may override. -o + The argument is an optparse.Values instance which can be used to inspect the command line options. """ @@ -80,3 +84,10 @@ def parenthesize(self, node): """Wrapper around pygram.parenthesize().""" return pygram.parenthesize(node) + + def new_name(self, template="xxx_todo_changeme"): + name = template + while name in self.used_names: + name = template + str(numbers.next()) + self.used_names.add(name) + return name Modified: sandbox/trunk/2to3/fixes/fix_except.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_except.py (original) +++ sandbox/trunk/2to3/fixes/fix_except.py Thu Jan 11 20:02:08 2007 @@ -2,6 +2,7 @@ # Python imports import token +import pprint # Local imports import pytree @@ -13,11 +14,27 @@ return node = node.children[0] return node.lineno + +def find_excepts(nodes): + for i in range(len(nodes)): + n = nodes[i] + if isinstance(n, pytree.Node): + if n.children[0].value == 'except': + yield (n, nodes[i+2]) + +as_leaf = pytree.Leaf(token.NAME, "as") +as_leaf.set_prefix(" ") + +ass_leaf = pytree.Leaf(token.EQUAL, "=") +ass_leaf.set_prefix(" ") class FixExcept(basefix.BaseFix): PATTERN = """ - except_clause< 'except' a=any ',' b=any > + try_stmt< 'try' ':' suite + cleanup=((except_clause ':' suite)+ ['else' ':' suite] + ['finally' ':' suite] + | 'finally' ':' suite) > """ def transform(self, node): @@ -25,27 +42,38 @@ results = self.match(node) assert results - a = results["a"].clone() - b = results["b"].clone() - - if b.type != token.NAME: - lineno = get_lineno(node) - self.logger.warning("At line %s, unable to transform: %s" % - (lineno, node)) - return node - - as_leaf = pytree.Leaf(token.NAME, "as") - as_leaf.set_prefix(" ") - - # Python 2 excepts could take the form except E,V: (no space) - # That doesn't work for the new version - if not b.get_prefix(): - b.set_prefix(" ") + 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 + lineno = get_lineno(N) + msg = "At line %d, exception unpacking is going away" + self.logger.warning(msg % lineno) + elif N.type != token.NAME: + # Generate a new N for the except clause + new_N = pytree.Leaf(token.NAME, self.new_name()) + new_N.set_prefix(" ") + target = N.clone() + target.set_prefix("") + N.replace(new_N) + + # Insert "old_N = new_N" as the first statement in + # the except body + 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 + suite_stmts = suite_stmts[:i] + [assign] + suite_stmts + e_suite.children = tuple(suite_stmts) - new = pytree.Node(syms.except_clause, - [pytree.Leaf(token.NAME, "except"), - pytree.Node(syms.test, [a]), - as_leaf, - pytree.Node(syms.test, [b])]) - new.set_prefix(node.get_prefix()) - return new + children = [c.clone() for c in node.children[:3]] + try_cleanup + return pytree.Node(node.type, children) Modified: sandbox/trunk/2to3/pgen2/parse.py ============================================================================== --- sandbox/trunk/2to3/pgen2/parse.py (original) +++ sandbox/trunk/2to3/pgen2/parse.py Thu Jan 11 20:02:08 2007 @@ -108,6 +108,7 @@ stackentry = (self.grammar.dfas[start], 0, newnode) self.stack = [stackentry] self.rootnode = None + self.used_names = set() # Aliased to self.rootnode.used_names in pop() def addtoken(self, type, value, context): """Add a token; return True iff this is the end of the program.""" @@ -160,6 +161,8 @@ def classify(self, type, value, context): """Turn a token into a label. (Internal)""" if type == token.NAME: + # Keep a listing of all used names + self.used_names.add(value) # Check for reserved words ilabel = self.grammar.keywords.get(value) if ilabel is not None: @@ -195,3 +198,4 @@ node[-1].append(newnode) else: self.rootnode = newnode + self.rootnode.used_names = self.used_names Modified: sandbox/trunk/2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/refactor.py (original) +++ sandbox/trunk/2to3/refactor.py Thu Jan 11 20:02:08 2007 @@ -195,6 +195,7 @@ """Refactors a parse tree.""" for fixer in self.fixers: fixer.set_filename(filename) + fixer.used_names = tree.used_names changes = 0 for node in tree.post_order(): for fixer in self.fixers: From brett at python.org Thu Jan 11 20:06:05 2007 From: brett at python.org (Brett Cannon) Date: Thu, 11 Jan 2007 11:06:05 -0800 Subject: [Python-checkins] r53379 - sandbox/trunk/2to3/Grammar.txt In-Reply-To: <20070111175408.271D81E400C@bag.python.org> References: <20070111175408.271D81E400C@bag.python.org> Message-ID: Grammar.txt looks to be the same as Grammar/Grammar from the p3yk branch. Is that true? If so, you might want to consider doing an external definition in the 2to3 directory in svn to pull in the Grammar directory (see the dev FAQ on how to do this). That was you always track any changes to the Py3K grammar. -Brett On 1/11/07, guido.van.rossum wrote: > Author: guido.van.rossum > Date: Thu Jan 11 18:54:07 2007 > New Revision: 53379 > > Modified: > sandbox/trunk/2to3/Grammar.txt > Log: > Make the grammar accept 'as' in an except clause, so fix_except can be > idempotent. > > > Modified: sandbox/trunk/2to3/Grammar.txt > ============================================================================== > --- sandbox/trunk/2to3/Grammar.txt (original) > +++ sandbox/trunk/2to3/Grammar.txt Thu Jan 11 18:54:07 2007 > @@ -85,7 +85,7 @@ > with_stmt: 'with' test [ with_var ] ':' suite > with_var: 'as' expr > # NB compile.c makes sure that the default except clause is last > -except_clause: 'except' [test [',' test]] > +except_clause: 'except' [test [(',' | 'as') test]] > suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT > > # Backward compatibility cruft to support: > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From buildbot at python.org Thu Jan 11 20:22:24 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 11 Jan 2007 19:22:24 +0000 Subject: [Python-checkins] buildbot warnings in hppa Ubuntu dapper 2.5 Message-ID: <20070111192224.9F65A1E400B@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/2 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: make: *** [buildbottest] Killed sincerely, -The Buildbot From buildbot at python.org Thu Jan 11 20:24:41 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 11 Jan 2007 19:24:41 +0000 Subject: [Python-checkins] buildbot warnings in alpha Debian 2.5 Message-ID: <20070111192441.5EEB81E400B@bag.python.org> The Buildbot has detected a new failure of alpha Debian 2.5. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Debian%25202.5/builds/2 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: sincerely, -The Buildbot From python-checkins at python.org Thu Jan 11 21:08:56 2007 From: python-checkins at python.org (vinay.sajip) Date: Thu, 11 Jan 2007 21:08:56 +0100 (CET) Subject: [Python-checkins] r53383 - python/branches/release24-maint/Lib/logging/__init__.py Message-ID: <20070111200856.DA2141E400B@bag.python.org> Author: vinay.sajip Date: Thu Jan 11 21:08:56 2007 New Revision: 53383 Modified: python/branches/release24-maint/Lib/logging/__init__.py Log: Backported change in shutdown(); now takes an optional handler-list argument. 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 Thu Jan 11 21:08:56 2007 @@ -1318,14 +1318,14 @@ """ root.manager.disable = level -def shutdown(): +def shutdown(handlerList=_handlerList): """ Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit. """ - for h in _handlerList[:]: # was _handlers.keys(): + for h in handlerList[:]: #errors might occur, for example, if files are locked #we just ignore them if raiseExceptions is not set try: From python-checkins at python.org Thu Jan 11 21:26:06 2007 From: python-checkins at python.org (vinay.sajip) Date: Thu, 11 Jan 2007 21:26:06 +0100 (CET) Subject: [Python-checkins] r53384 - python/branches/release24-maint/Lib/logging/config.py Message-ID: <20070111202606.C23B01E4011@bag.python.org> Author: vinay.sajip Date: Thu Jan 11 21:26:05 2007 New Revision: 53384 Modified: python/branches/release24-maint/Lib/logging/config.py Log: Fixed bug in fileConfig where _handlerList was not being cleared. (SF #1632328) Modified: python/branches/release24-maint/Lib/logging/config.py ============================================================================== --- python/branches/release24-maint/Lib/logging/config.py (original) +++ python/branches/release24-maint/Lib/logging/config.py Thu Jan 11 21:26:05 2007 @@ -97,6 +97,7 @@ try: #first, lose the existing handlers... logging._handlers.clear() + del logging._handlerList[:] #now set up the new ones... hlist = cp.get("handlers", "keys") if len(hlist): From buildbot at python.org Thu Jan 11 21:35:55 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 11 Jan 2007 20:35:55 +0000 Subject: [Python-checkins] buildbot warnings in alpha Debian trunk Message-ID: <20070111203555.2503F1E400B@bag.python.org> The Buildbot has detected a new failure of alpha Debian trunk. Full details are available at: http://www.python.org/dev/buildbot/all/alpha%2520Debian%2520trunk/builds/6 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 python-checkins at python.org Thu Jan 11 21:46:44 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 11 Jan 2007 21:46:44 +0100 (CET) Subject: [Python-checkins] r53385 - python/branches/bcannon-objcap/Python/pythonrun.c Message-ID: <20070111204644.D98231E400B@bag.python.org> Author: brett.cannon Date: Thu Jan 11 21:46:44 2007 New Revision: 53385 Modified: python/branches/bcannon-objcap/Python/pythonrun.c Log: Store away import function in the 'sys' module. Will end up implementing a delegate for the built-in __import__ that calls what is stored there. Modified: python/branches/bcannon-objcap/Python/pythonrun.c ============================================================================== --- python/branches/bcannon-objcap/Python/pythonrun.c (original) +++ python/branches/bcannon-objcap/Python/pythonrun.c Thu Jan 11 21:46:44 2007 @@ -246,6 +246,11 @@ if (!warnings_module) PyErr_Clear(); + /* Store import machinery somewhere so that a reference is held as + needed. */ + PyDict_SetItemString(interp->sysdict, "import_", + PyDict_GetItemString(interp->builtins, "__import__")); + #if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET) /* On Unix, set the file system encoding according to the user's preference, if the CODESET names a well-known From python-checkins at python.org Thu Jan 11 21:58:28 2007 From: python-checkins at python.org (guido.van.rossum) Date: Thu, 11 Jan 2007 21:58:28 +0100 (CET) Subject: [Python-checkins] r53386 - in sandbox/trunk/2to3: example.py fixes/fix_raise.py Message-ID: <20070111205828.475431E400B@bag.python.org> Author: guido.van.rossum Date: Thu Jan 11 21:58:27 2007 New Revision: 53386 Added: sandbox/trunk/2to3/fixes/fix_raise.py (contents, props changed) Modified: sandbox/trunk/2to3/example.py Log: Fixer by Collin Winter to turn raise X, Y into raise X(Y). Modified: sandbox/trunk/2to3/example.py ============================================================================== --- sandbox/trunk/2to3/example.py (original) +++ sandbox/trunk/2to3/example.py Thu Jan 11 21:58:27 2007 @@ -208,6 +208,25 @@ pass except (Exception, SystemExit): pass + +def raise_examples(): + raise Exception, 5 + # + raise Exception,5 + # + raise Exception, (5, 6, 7) + # + # These should not be touched + # + raise Exception + # + raise Exception(5, 6) + # + # These should produce a warning + # + raise Exception, 5, 6 + # + raise Exception,5,6 # This is the last line. Added: sandbox/trunk/2to3/fixes/fix_raise.py ============================================================================== --- (empty file) +++ sandbox/trunk/2to3/fixes/fix_raise.py Thu Jan 11 21:58:27 2007 @@ -0,0 +1,52 @@ +"""Fixer for 'raise E, a1, a2, ...'""" + +# Python imports +import token + +# Local imports +import pytree +from fixes import basefix + +could_not_convert = "At line %d: could not convert: %s" +reason = "At line %d: Python 3's raise will not support providing a traceback" + +def get_lineno(node): + while not isinstance(node, pytree.Leaf): + if not node.children: + return + node = node.children[0] + return node.lineno + +class FixRaise(basefix.BaseFix): + + PATTERN = """ + raise_stmt< 'raise' exc=any ',' a1=any [',' a2=any] > + """ + + def transform(self, node): + syms = self.syms + results = self.match(node) + assert results + + exc = results["exc"].clone() + args = [results["a1"].clone()] + args[0].set_prefix("") + + arg2 = results.get("a2") + if arg2 is not None: + lineno = get_lineno(node) + for_output = node.clone() + for_output.set_prefix("") + self.logger.warning(could_not_convert % (lineno, for_output)) + self.logger.warning(reason % lineno) + 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 From python-checkins at python.org Thu Jan 11 22:09:32 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 11 Jan 2007 22:09:32 +0100 (CET) Subject: [Python-checkins] r53387 - python/branches/bcannon-objcap/Lib/test/test_interpreter.py Message-ID: <20070111210932.8736B1E400B@bag.python.org> Author: brett.cannon Date: Thu Jan 11 22:09:32 2007 New Revision: 53387 Modified: python/branches/bcannon-objcap/Lib/test/test_interpreter.py Log: Since the interpreter module was experimental and will probably be dropped, comment out the execution of tests for now. Modified: python/branches/bcannon-objcap/Lib/test/test_interpreter.py ============================================================================== --- python/branches/bcannon-objcap/Lib/test/test_interpreter.py (original) +++ python/branches/bcannon-objcap/Lib/test/test_interpreter.py Thu Jan 11 22:09:32 2007 @@ -285,5 +285,5 @@ ) -if __name__ == '__main__': - test_main() +#if __name__ == '__main__': + #test_main() From python-checkins at python.org Thu Jan 11 22:18:57 2007 From: python-checkins at python.org (thomas.heller) Date: Thu, 11 Jan 2007 22:18:57 +0100 (CET) Subject: [Python-checkins] r53388 - in python/trunk: Lib/ctypes/test/test_win32.py Lib/ctypes/wintypes.py Misc/NEWS Modules/_ctypes/libffi_msvc/ffi.c Message-ID: <20070111211857.9433E1E400B@bag.python.org> Author: thomas.heller Date: Thu Jan 11 22:18:56 2007 New Revision: 53388 Modified: python/trunk/Lib/ctypes/test/test_win32.py python/trunk/Lib/ctypes/wintypes.py python/trunk/Misc/NEWS python/trunk/Modules/_ctypes/libffi_msvc/ffi.c Log: Fixes for 64-bit Windows: In ctypes.wintypes, correct the definitions of HANDLE, WPARAM, LPARAM data types. Make parameterless foreign function calls work. Modified: python/trunk/Lib/ctypes/test/test_win32.py ============================================================================== --- python/trunk/Lib/ctypes/test/test_win32.py (original) +++ python/trunk/Lib/ctypes/test/test_win32.py Thu Jan 11 22:18:56 2007 @@ -3,6 +3,7 @@ from ctypes import * from ctypes.test import is_resource_enabled import unittest, sys +from ctypes import wintypes import _ctypes_test @@ -32,12 +33,30 @@ # 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): + self.failUnlessEqual(sizeof(wintypes.HWND), sizeof(c_void_p)) + + def test_PARAM(self): + 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/trunk/Lib/ctypes/wintypes.py ============================================================================== --- python/trunk/Lib/ctypes/wintypes.py (original) +++ python/trunk/Lib/ctypes/wintypes.py Thu Jan 11 22:18:56 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 (which is signed) +# LPARAM is defined as LONG_PTR (which is unsigned) +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/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu Jan 11 22:18:56 2007 @@ -109,6 +109,10 @@ Library ------- +- Fixes for 64-bit Windows: In ctypes.wintypes, correct the + definitions of HANDLE, WPARAM, LPARAM data types. Make + parameterless foreign function calls work. + - The version number of the ctypes package changed to "1.1.0". - Bug #1627575: logging: Added _open() method to FileHandler which can Modified: python/trunk/Modules/_ctypes/libffi_msvc/ffi.c ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/ffi.c (original) +++ python/trunk/Modules/_ctypes/libffi_msvc/ffi.c Thu Jan 11 22:18:56 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; From python-checkins at python.org Thu Jan 11 22:19:52 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 11 Jan 2007 22:19:52 +0100 (CET) Subject: [Python-checkins] r53389 - python/branches/bcannon-objcap/Lib/test/_test_interpreter.py python/branches/bcannon-objcap/Lib/test/test_interpreter.py Message-ID: <20070111211952.E39391E400B@bag.python.org> Author: brett.cannon Date: Thu Jan 11 22:19:52 2007 New Revision: 53389 Added: python/branches/bcannon-objcap/Lib/test/_test_interpreter.py - copied unchanged from r53387, python/branches/bcannon-objcap/Lib/test/test_interpreter.py Removed: python/branches/bcannon-objcap/Lib/test/test_interpreter.py Log: regrtest finds test classes in modules and runs them, so completely rename test_interpreter so it isn't run. Deleted: /python/branches/bcannon-objcap/Lib/test/test_interpreter.py ============================================================================== --- /python/branches/bcannon-objcap/Lib/test/test_interpreter.py Thu Jan 11 22:19:52 2007 +++ (empty file) @@ -1,289 +0,0 @@ -?""" Things to protect (and thus test) against: -* Importing - + built-ins - + .pyc/.pyo - + extension modules -* File access - + open() -* Evil methods - + __del__ - + __str__ (for exceptions) - + properties - + something that raises SystemExit - -""" -import interpreter - -import unittest -from test import test_support -import sys -import __builtin__ -import StringIO - -simple_stmt = """ -while True: - 2 + 3 - break -""" - -test_sys_changed = """ -import sys -if sys.version == 'test': - to_return.append(True) -else: - to_return.append(False) -""" - -test_builtins_contains = """ -import __builtin__ -_return.append(__builtin__.__dict__.__contains__("%s")) -""" - - -class BaseInterpTests(unittest.TestCase): - - def setUp(self): - """Create a new interpreter.""" - self.interp = interpreter.Interpreter() - - -class BasicInterpreterTests(BaseInterpTests): - - def test_basic_expression(self): - # Make sure that execucuting a simple expression does not die. - self.interp.execute('2 + 3') - - def test_basic_statement(self): - # Make sure executing a statement does not die. - self.interp.execute(simple_stmt) - - -class BuiltinsTests(BaseInterpTests): - - """Test interpreter.Interpreter().builtins() .""" - - def test_get(self): - # Test the getting of 'builtins'. - builtins = self.interp.builtins() - self.failUnless(isinstance(builtins, dict)) - self.failUnless('object' in builtins) - - def test_remove(self): - # Make sure that something can be removed from built-ins. - builtins = self.interp.builtins() - del builtins['open'] - _return = [] - builtins['_return'] = _return - self.interp.execute(test_builtins_contains % 'open') - self.failUnless(not _return[-1]) - - def test_add_remove(self): - # Make sure you can add to the built-ins and then remove the same - # object. - self.interp.builtins()['test'] = 'test' - _return = [] - self.interp.builtins()['_return'] = _return - self.interp.execute(test_builtins_contains % 'test') - self.failUnless(_return[-1]) - del self.interp.builtins()['test'] - self.interp.execute(test_builtins_contains % 'test') - self.failUnless(not _return[-1]) - - def test_copied(self): - # Make sure built-ins are unique per interpreter. - master_id = id(__builtin__.__dict__) - _return = [] - self.interp.builtins()['_return'] = _return - self.interp.execute('import __builtin__;' - '_return.append(id(__builtin__.__dict__))') - self.failUnless(_return[-1] != master_id) - - -class ModulesTests(BaseInterpTests): - - """Test interpreter.Interpreter().modules .""" - - def test_get(self): - # Make sure a dict is returned. - modules = self.interp.modules - self.failUnless(isinstance(modules, dict)) - master_id = id(modules) - _return = [] - self.interp.builtins()['_return'] = _return - self.interp.execute('import sys; _return.append(id(sys.modules))') - self.failUnlessEqual(_return[-1], master_id) - - def test_set(self): - # Make sure setting 'modules' can be done and has proper type checking. - self.interp.modules = {} - self.failUnlessRaises(TypeError, setattr, self.interp.modules, []) - - def test_mutation(self): - # If a module is added, make sure importing uses that module. - self.interp.modules['test1'] = 'test1' - _return = [] - self.interp.builtins()['_return'] = _return - self.interp.execute('import test1; _return.append(test1)') - self.failUnlessEqual(_return[-1], 'test1') - self.interp.modules['test1'] = 'test2' - self.interp.execute('import test1; _return.append(test1)') - self.failUnlessEqual(_return[-1], 'test2') - - def test_deleting(self): - # Make sure that a module is re-imported if it is removed. - self.failUnless('token' not in self.interp.modules) - self.interp.execute('import token') - del self.interp.modules['token'] - self.interp.execute('import token') - - def test_replacing(self): - # Replacing with a new dict should work. - new_modules = self.interp.modules.copy() - self.interp.modules = new_modules - _return = [] - self.interp.builtins()['_return'] = _return - self.interp.execute('import sys; _return.append(id(sys.modules))') - self.failUnlessEqual(id(new_modules), _return[-1]) - - def test_fresh(self): - # Make sure that imported Python modules are new instances. - import token - token.test = 'test' - _return = [] - self.interp.builtins()['_return'] = _return - self.interp.execute("import token;" - "_return.append(hasattr(token, 'test'))") - self.failUnless(not _return[-1]) - - def test_not_cached(self): - # Make sure that 'modules' dict is not cached. - builtin = self.interp.modules['__builtin__'] - main = self.interp.modules['__main__'] - self.interp.execute("import token") - self.interp.modules = {} - self.interp.modules['__builtin__'] = builtin - self.interp.modules['__main__'] = main - self.interp.execute("import token") - self.failUnless('token' in self.interp.modules) - - -class SysDictTests(BaseInterpTests): - - """Test interpreter.Interpreter().sys_dict .""" - - def test_get(self): - # Make sure a dict is returned. - sys_dict = self.interp.sys_dict() - self.failUnless(isinstance(sys_dict, dict)) - self.failUnless('version' in sys_dict) - - def test_mutating(self): - # Changes to the dict should be reflected in the interpreter. - sys_dict = self.interp.sys_dict() - sys_dict['version'] = 'test' - interp_return = [] - self.interp.builtins()['to_return'] = interp_return - self.interp.execute(test_sys_changed) - self.failUnless(interp_return[-1]) - - def test_deletion(self): - # Make sure removing a value raises the proper exception when accessing - # through the 'sys' module. - del self.interp.sys_dict()['version'] - stdout, stderr = self.interp.redirect_output() - self.failUnlessRaises(RuntimeError, self.interp.execute, - 'import sys; sys.version') - self.failUnless(self.interp.exc_matches(AttributeError)) - - def test_copied(self): - # sys_dict should be unique per interpreter (including mutable data - # structures). - sys_version = sys.version - self.interp.sys_dict()['version'] = 'test' - reload(sys) - self.failUnlessEqual(sys.version, sys_version) - _return = [] - self.interp.builtins()['_return'] = _return - self.interp.execute("import sys; _return.append(sys.version)") - self.failUnlessEqual(_return[-1], 'test') - - -class InputOutputTests(BaseInterpTests): - - """Test stdin/stdout/stderr fiddling.""" - - def test_redirect_output_defaults(self): - # Make sure it sets stdout and stderr. - stdout, stderr = self.interp.redirect_output() - self.interp.execute("print 'test'") - self.failUnlessEqual("test\n", stdout.getvalue()) - self.failUnless(not stderr.getvalue()) - self.interp.execute(r"import sys; sys.stderr.write('test\n')") - self.failUnlessEqual('test\n', stderr.getvalue()) - - def test_redirect_output_arguments(self): - # Test passing in arguments to redirect_output(). - new_stdout = StringIO.StringIO() - new_stderr = StringIO.StringIO() - used_stdout, used_stderr = self.interp.redirect_output(new_stdout, - new_stderr) - self.failUnless(used_stdout is new_stdout) - self.failUnless(used_stderr is new_stderr) - self.failUnlessRaises(RuntimeError, self.interp.execute, '=') - self.failUnlessEqual(new_stderr.getvalue(), used_stderr.getvalue()) - self.interp.execute("print 'test'") - self.failUnlessEqual(new_stdout.getvalue(), used_stdout.getvalue()) - - -class ExceptionsTests(BaseInterpTests): - - """Test exception usage.""" - - def test_execute_failure(self): - # RuntimeError should be raised when something goes bad in execute(). - stdout, stderr = self.interp.redirect_output() - self.failUnlessRaises(RuntimeError, self.interp.execute, "=") - - def test_exc_matches(self): - # Test exc_matches(). - stdout, stderr = self.interp.redirect_output() - self.failUnlessRaises(RuntimeError, self.interp.execute, '=') - self.failUnless(self.interp.exc_matches(SyntaxError)) - self.failUnless(not self.interp.exc_matches(TypeError)) - - def test_exception_cleared(self): - # No exception should be set after a successful execution. - stdout, stderr = self.interp.redirect_output() - self.failUnlessRaises(RuntimeError, self.interp.execute, '=') - self.interp.execute('2 + 3') - self.failUnlessRaises(LookupError, self.interp.exc_matches, Exception) - - def test_multiple_exc_checks(self): - # Be able to check the exception multiple times. - stdout, stderr = self.interp.redirect_output() - self.failUnlessRaises(RuntimeError, self.interp.execute, '=') - for x in range(2): - self.failUnless(self.interp.exc_matches(SyntaxError)) - - def test_SystemExit_safe(self): - # Raising SystemExit should not cause the process to exit. - self.failUnlessRaises(RuntimeError, self.interp.execute, - "raise SystemExit") - self.failUnless(self.interp.exc_matches(SystemExit)) - self.failUnlessRaises(RuntimeError, self.interp.execute, "exit()") - self.failUnless(self.interp.exc_matches(SystemExit)) - - -def test_main(): - test_support.run_unittest( - BasicInterpreterTests, - BuiltinsTests, - ModulesTests, - SysDictTests, - InputOutputTests, - ExceptionsTests, - ) - - -#if __name__ == '__main__': - #test_main() From python-checkins at python.org Thu Jan 11 22:23:12 2007 From: python-checkins at python.org (thomas.heller) Date: Thu, 11 Jan 2007 22:23:12 +0100 (CET) Subject: [Python-checkins] r53390 - python/trunk/Lib/ctypes/wintypes.py Message-ID: <20070111212312.B84BB1E400B@bag.python.org> Author: thomas.heller Date: Thu Jan 11 22:23:12 2007 New Revision: 53390 Modified: python/trunk/Lib/ctypes/wintypes.py Log: Correct the comments: the code is right. Modified: python/trunk/Lib/ctypes/wintypes.py ============================================================================== --- python/trunk/Lib/ctypes/wintypes.py (original) +++ python/trunk/Lib/ctypes/wintypes.py Thu Jan 11 22:23:12 2007 @@ -34,8 +34,8 @@ LPCWSTR = LPWSTR = c_wchar_p LPCSTR = LPSTR = c_char_p -# WPARAM is defined as UINT_PTR (which is signed) -# LPARAM is defined as LONG_PTR (which is unsigned) +# 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 From python-checkins at python.org Thu Jan 11 22:34:16 2007 From: python-checkins at python.org (brett.cannon) Date: Thu, 11 Jan 2007 22:34:16 +0100 (CET) Subject: [Python-checkins] r53391 - python/branches/bcannon-objcap/Python/pythonrun.c python/branches/bcannon-objcap/Python/sysmodule.c Message-ID: <20070111213416.660531E4017@bag.python.org> Author: brett.cannon Date: Thu Jan 11 22:34:15 2007 New Revision: 53391 Modified: python/branches/bcannon-objcap/Python/pythonrun.c python/branches/bcannon-objcap/Python/sysmodule.c Log: Add an import delegate to the sys module that just calls the object stored in sys.import_. This should allow a Python implementation of import to be used safely without exposing dangerous things (e.g., func_globals when the Python code imports things that should be be made available to other 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 Jan 11 22:34:15 2007 @@ -250,6 +250,9 @@ needed. */ PyDict_SetItemString(interp->sysdict, "import_", PyDict_GetItemString(interp->builtins, "__import__")); + PyDict_SetItemString(interp->builtins, "__import__", + PyDict_GetItemString(interp->sysdict, + "import_delegate")); #if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET) /* On Unix, set the file system encoding according to the Modified: python/branches/bcannon-objcap/Python/sysmodule.c ============================================================================== --- python/branches/bcannon-objcap/Python/sysmodule.c (original) +++ python/branches/bcannon-objcap/Python/sysmodule.c Thu Jan 11 22:34:15 2007 @@ -733,6 +733,19 @@ } #endif +static PyObject * +sys_import_delegate(PyObject *self, PyObject *args, PyObject *kwargs) +{ + PyObject *import_object = PySys_GetObject("import_"); + + if (import_object == NULL) { + PyErr_SetString(PyExc_RuntimeError, "sys.import_ not set"); + return NULL; + } + + return PyObject_Call(import_object, args, kwargs); +} + static PyMethodDef sys_methods[] = { /* Might as well keep this in alphabetic order */ {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, @@ -776,6 +789,8 @@ {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, getwindowsversion_doc}, #endif /* MS_WINDOWS */ + {"import_delegate", (PyCFunction)sys_import_delegate, + METH_VARARGS | METH_KEYWORDS, "XXX"}, #ifdef USE_MALLOPT {"mdebug", sys_mdebug, METH_VARARGS}, #endif From buildbot at python.org Thu Jan 11 23:00:32 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 11 Jan 2007 22:00:32 +0000 Subject: [Python-checkins] buildbot warnings in ppc Debian unstable trunk Message-ID: <20070111220032.63FBD1E400B@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/7 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: thomas.heller 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 Thu Jan 11 23:03:15 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 11 Jan 2007 22:03:15 +0000 Subject: [Python-checkins] buildbot warnings in PPC64 Debian trunk Message-ID: <20070111220315.D7FC11E400C@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/7 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: thomas.heller 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 Thu Jan 11 23:10:08 2007 From: buildbot at python.org (buildbot at python.org) Date: Thu, 11 Jan 2007 22:10:08 +0000 Subject: [Python-checkins] buildbot warnings in x86 XP trunk Message-ID: <20070111221008.8AB591E400B@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/133 Buildbot URL: http://www.python.org/dev/buildbot/all/ Build Reason: Build Source Stamp: [branch trunk] HEAD Blamelist: thomas.heller Build had warnings: warnings test Excerpt from the test logfile: 2 tests failed: test_dumbdbm test_uu ====================================================================== FAIL: test_dumbdbm_creation_mode (test.test_dumbdbm.DumbDBMTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\buildbot_py25\trunk.mcintyre-windows\build\lib\test\test_dumbdbm.py", line 55, in test_dumbdbm_creation_mode self.assertEqual(stat.S_IMODE(st.st_mode), 0635) AssertionError: 438 != 413 ====================================================================== FAIL: test_encode (test.test_uu.UUFileTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\buildbot_py25\trunk.mcintyre-windows\build\lib\test\test_uu.py", line 137, in test_encode self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) AssertionError: 'begin 644 @testi\nM5&AE(\'-M;V]T:"US8V%L960@<\'ET:&]N(&-R97!T(&]V97(@=&AE(\'-L965P\n):6YG(&1O9PT*\n \nend\n' != 'begin 644 @testi\nM5&AE(\'-M;V]T:"US8V%L960@<\'ET:&]N(&-R97!T(&]V97(@=&AE(\'-L965P\n(:6YG(&1O9PH \n \nend\n' sincerely, -The Buildbot From python-checkins at python.org Fri Jan 12 01:08:41 2007 From: python-checkins at python.org (guido.van.rossum) Date: Fri, 12 Jan 2007 01:08:41 +0100 (CET) Subject: [Python-checkins] r53392 - in sandbox/trunk/2to3: fixes/basefix.py fixes/fix_except.py fixes/fix_raise.py pytree.py Message-ID: <20070112000841.11C491E400B@bag.python.org> Author: guido.van.rossum Date: Fri Jan 12 01:08:40 2007 New Revision: 53392 Modified: sandbox/trunk/2to3/fixes/basefix.py sandbox/trunk/2to3/fixes/fix_except.py sandbox/trunk/2to3/fixes/fix_raise.py sandbox/trunk/2to3/pytree.py Log: Collin Winter: a) adds a get_lineno() method to pytree.py:Base. fix_except and fix_raise were both using it, and I imagine future fixers will need this functionality. b) adds a cannot_convert() method to BaseFixer. This is a way for fixers to indicate "this code won't work in Python 3, but I can't fix it, and here's why". Both fix_except and fix_raise are modified to use this. Modified: sandbox/trunk/2to3/fixes/basefix.py ============================================================================== --- sandbox/trunk/2to3/fixes/basefix.py (original) +++ sandbox/trunk/2to3/fixes/basefix.py Fri Jan 12 01:08:40 2007 @@ -91,3 +91,12 @@ name = template + str(numbers.next()) self.used_names.add(name) return name + + def cannot_convert(self, node, reason=None): + lineno = node.get_lineno() + for_output = node.clone() + for_output.set_prefix("") + msg = "At line %d: could not convert: %s" + self.logger.warning(msg % (lineno, for_output)) + if reason: + self.logger.warning(reason) Modified: sandbox/trunk/2to3/fixes/fix_except.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_except.py (original) +++ sandbox/trunk/2to3/fixes/fix_except.py Fri Jan 12 01:08:40 2007 @@ -2,19 +2,11 @@ # Python imports import token -import pprint # Local imports import pytree from fixes import basefix -def get_lineno(node): - while not isinstance(node, pytree.Leaf): - if not node.children: - return - node = node.children[0] - return node.lineno - def find_excepts(nodes): for i in range(len(nodes)): n = nodes[i] @@ -22,12 +14,15 @@ if n.children[0].value == 'except': yield (n, nodes[i+2]) +### Common across all transforms 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): PATTERN = """ @@ -49,9 +44,7 @@ comma.replace(as_leaf.clone()) if str(N).strip()[0] == '(': # We're dealing with a tuple - lineno = get_lineno(N) - msg = "At line %d, exception unpacking is going away" - self.logger.warning(msg % lineno) + self.cannot_convert(N, tuple_reason) elif N.type != token.NAME: # Generate a new N for the except clause new_N = pytree.Leaf(token.NAME, self.new_name()) Modified: sandbox/trunk/2to3/fixes/fix_raise.py ============================================================================== --- sandbox/trunk/2to3/fixes/fix_raise.py (original) +++ sandbox/trunk/2to3/fixes/fix_raise.py Fri Jan 12 01:08:40 2007 @@ -7,15 +7,7 @@ import pytree from fixes import basefix -could_not_convert = "At line %d: could not convert: %s" -reason = "At line %d: Python 3's raise will not support providing a traceback" - -def get_lineno(node): - while not isinstance(node, pytree.Leaf): - if not node.children: - return - node = node.children[0] - return node.lineno +reason = "Python 3's raise will not support providing a traceback" class FixRaise(basefix.BaseFix): @@ -34,11 +26,7 @@ arg2 = results.get("a2") if arg2 is not None: - lineno = get_lineno(node) - for_output = node.clone() - for_output.set_prefix("") - self.logger.warning(could_not_convert % (lineno, for_output)) - self.logger.warning(reason % lineno) + self.cannot_convert(node, reason) return node new = pytree.Node(syms.raise_stmt, Modified: sandbox/trunk/2to3/pytree.py ============================================================================== --- sandbox/trunk/2to3/pytree.py (original) +++ sandbox/trunk/2to3/pytree.py Fri Jan 12 01:08:40 2007 @@ -115,6 +115,14 @@ if new is not None: new.parent = self.parent self.parent = None + + def get_lineno(self): + node = self + while not isinstance(node, Leaf): + if not node.children: + return + node = node.children[0] + return node.lineno class Node(Base): From python-checkins at python.org Fri Jan 12 08:27:52 2007 From: python-checkins at python.org (brett.cannon) Date: Fri, 12 Jan 2007 08:27:52 +0100 (CET) Subject: [Python-checkins] r53393 - python/trunk/Doc/lib/libtest.tex Message-ID: <20070112072752.F228B1E4002@bag.python.org> Author: brett.cannon Date: Fri Jan 12 08:27:52 2007 New Revision: 53393 Modified: python/trunk/Doc/lib/libtest.tex Log: Fix error where the end of a funcdesc environment was accidentally moved too far down. Modified: python/trunk/Doc/lib/libtest.tex ============================================================================== --- python/trunk/Doc/lib/libtest.tex (original) +++ python/trunk/Doc/lib/libtest.tex Fri Jan 12 08:27:52 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} From python-checkins at python.org Fri Jan 12 09:03:55 2007 From: python-checkins at python.org (thomas.heller) Date: Fri, 12 Jan 2007 09:03:55 +0100 (CET) Subject: [Python-checkins] r53394 - python/branches/release25-maint/Lib/ctypes Message-ID: <20070112080355.19D441E4002@bag.python.org> Author: thomas.heller Date: Fri Jan 12 09:03:54 2007 New Revision: 53394 Modified: python/branches/release25-maint/Lib/ctypes/ (props changed) Log: Blocked revisions 52945,53358 via svnmerge ........ r52945 | brett.cannon | 2006-12-07 00:38:48 +0100 (Thu, 07 Dec 2006) | 3 lines Fix a bad assumption that all objects assigned to '__loader__' on a module will have a '_files' attribute. ........ 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". ........ From python-checkins at python.org Fri Jan 12 09:05:28 2007 From: python-checkins at python.org (thomas.heller) Date: Fri, 12 Jan 2007 09:05:28 +0100 (CET) Subject: [Python-checkins] r53395 - python/branches/release25-maint/Modules/_ctypes Message-ID: <20070112080528.966621E401A@bag.python.org> Author: thomas.heller Date: Fri Jan 12 09:05:28 2007 New Revision: 53395 Modified: python/branches/release25-maint/Modules/_ctypes/ (props changed) Log: Blocked revisions 52388 via svnmerge ........ r52388 | martin.v.loewis | 2006-10-19 13:00:37 +0200 (Thu, 19 Oct 2006) | 3 lines Fix various minor errors in passing arguments to PyArg_ParseTuple. ........ From python-checkins at python.org Fri Jan 12 09:13:57 2007 From: python-checkins at python.org (thomas.heller) Date: Fri, 12 Jan 2007 09:13:57 +0100 (CET) Subject: [Python-checkins] r53396 - python/branches/release25-maint/Modules/_ctypes Message-ID: <20070112081357.4B75B1E4002@bag.python.org> Author: thomas.heller Date: Fri Jan 12 09:13:57 2007 New Revision: 53396 Modified: python/branches/release25-maint/Modules/_ctypes/ (props changed) Log: Blocked revisions 53361 via svnmerge ........ 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. ........ From python-checkins at python.org Fri Jan 12 10:35:56 2007 From: python-checkins at python.org (anthony.baxter) Date: Fri, 12 Jan 2007 10:35:56 +0100 (CET) Subject: [Python-checkins] r53397 - python/trunk/Makefile.pre.in Message-ID: <20070112093556.8FC311E4002@bag.python.org> Author: anthony.baxter Date: Fri Jan 12 10:35:56 2007 New Revision: 53397 Modified: python/trunk/Makefile.pre.in Log: add parsetok.h as a dependency - previously, changing this file doesn't cause the right files to be rebuilt. Modified: python/trunk/Makefile.pre.in ============================================================================== --- python/trunk/Makefile.pre.in (original) +++ python/trunk/Makefile.pre.in Fri Jan 12 10:35:56 2007 @@ -483,6 +483,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) @@ -535,6 +537,7 @@ Include/moduleobject.h \ Include/object.h \ Include/objimpl.h \ + Include/parsetok.h \ Include/patchlevel.h \ Include/pyarena.h \ Include/pydebug.h \ From neal at metaslash.com Fri Jan 12 11:14:07 2007 From: neal at metaslash.com (Neal Norwitz) Date: Fri, 12 Jan 2007 05:14:07 -0500 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20070112101407.GA18552@python.psfb.org> test_cmd_line leaked [17, -17, 0] references test_ctypes leaked [1, 1, 1] references From python-checkins at python.org Fri Jan 12 18:58:00 2007 From: python-checkins at python.org (paul.dubois) Date: Fri, 12 Jan 2007 18:58:00 +0100 (CET) Subject: [Python-checkins] r53400 - tracker/instances/python-dev/html/issue.index.html tracker/instances/python-dev/html/issue.search.html Message-ID: <20070112175800.BABF61E4002@bag.python.org> Author: paul.dubois Date: Fri Jan 12 18:58:00 2007 New Revision: 53400 Modified: tracker/instances/python-dev/html/issue.index.html tracker/instances/python-dev/html/issue.search.html Log: Fix search display to include all fields whose display box is checked. Remove condition on anonymous user seeing user-based fields. Fix type on actor search, which was 'date'. Resolves meta-tracker issue #65. Modified: tracker/instances/python-dev/html/issue.index.html ============================================================================== --- tracker/instances/python-dev/html/issue.index.html (original) +++ tracker/instances/python-dev/html/issue.index.html Fri Jan 12 18:58:00 2007 @@ -36,6 +36,8 @@ Creator Assigned To Keywords + Depends On + Type     -       +   +   Modified: tracker/instances/python-dev/html/issue.search.html ============================================================================== --- tracker/instances/python-dev/html/issue.search.html (original) +++ tracker/instances/python-dev/html/issue.search.html Fri Jan 12 18:58:00 2007 @@ -68,8 +68,7 @@ + db_content string:username;"> Creator: their changes in a new window." msgstr "" -"Fehler: jemand anders hat dieses %s bearbeitet (%s). Sehen Sie " -"dessen ?nderungen in einem neuen Fenster." +"Fehler: Jemand anders hat dieses %s bearbeitet (%s). Sehen Sie " +"dessen ?nderungen in einem neuen Fenster." #: ../roundup/cgi/actions.py:530 #, python-format @@ -1251,11 +1249,11 @@ #: ../roundup/cgi/actions.py:873 ../roundup/cgi/actions.py:877 msgid "Invalid login" -msgstr "Ung?ltiges Login" +msgstr "Ung?ltiger Benutzername" #: ../roundup/cgi/actions.py:883 msgid "You do not have permission to login" -msgstr "Sie sind nicht berechtigt sich anzumelden" +msgstr "Sie sind nicht berechtigt, sich anzumelden" #: ../roundup/cgi/cgitb.py:49 #, python-format @@ -1264,7 +1262,7 @@ "

%(exc_type)s: %(exc_value)s

\n" "

Debugging information follows

" msgstr "" -"

Templating-Fehler

\n" +"

Fehler in einer Vorlage:

\n" "

%(exc_type)s: %(exc_value)s

\n" "

Es folgen Informationen zum Fehler:

" @@ -1286,7 +1284,7 @@ #: ../roundup/cgi/cgitb.py:76 #, python-format msgid "A problem occurred in your template \"%s\"." -msgstr "Ein Problem ist im Template \"%s\" aufgetreten." +msgstr "Ein Problem ist in der Vorlage \"%s\" aufgetreten." #: ../roundup/cgi/cgitb.py:84 #, python-format @@ -1425,7 +1423,7 @@ "Die Eigenschaft \"%(property)s\" mu? f?r die Klasse \"%(class)s\" angegeben " "werden" msgstr[1] "" -"Die Eigenschaften \"%(property)s\" m?ssen f?r die Klasse \"%(class)s\" " +"Die Eigenschaften \"%(property)\" m?ssen f?r die Klasse \"%(class)s\" " "angegeben werden" #: ../roundup/cgi/form_parser.py:529 @@ -2104,7 +2102,7 @@ #: ../roundup/scripts/roundup_server.py:278 msgid "Can't run as root!" -msgstr "Dieser Proze? kann nicht unter dem Administrator (\"root\") laufen!" +msgstr "Dieser Proze? kann nicht unter dem Administrator-Konto (\"root\") laufen!" #: ../roundup/scripts/roundup_server.py:281 msgid "WARNING: ignoring \"-u\" argument, not root" @@ -2158,7 +2156,7 @@ " -u Startet den Roundup-Server mit dieser Benutzer-Nummer\n" " -g Startet den Roundup-Server mit dieser Gruppen-Nummer\n" " -d Startet den Server als Hintergrundproze? und schreibt\n" -" die Proze?-ID in die Datei PIDDatei\n" +" die Proze?-ID in die Datei PIDDatei.\n" " Die Option -l mu? dann auch angegeben werden." #: ../roundup/scripts/roundup_server.py:521 @@ -2390,9 +2388,9 @@ "

Sie k?nnen hier die Eintr?ge der Klasse \"${classname}\" " "bearbeiten. Hinweise:

" "