From python-3000-checkins at python.org Thu Feb 1 19:02:43 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Thu, 1 Feb 2007 19:02:43 +0100 (CET) Subject: [Python-3000-checkins] r53610 - in python/branches/p3yk: Doc/api/concrete.tex Doc/commontex/license.tex Doc/dist/dist.tex Doc/lib/libmailbox.tex Doc/lib/librandom.tex Doc/lib/libstruct.tex Doc/lib/libtime.tex Doc/ref/ref3.tex Include/Python-ast.h Include/object.h Lib/logging/handlers.py Lib/mailbox.py Lib/ntpath.py Lib/pdb.py Lib/random.py Lib/rfc822.py Lib/smtplib.py Lib/socket.py Lib/tarfile.py Lib/test/crashers/weakref_in_del.py Lib/test/output/test_new Lib/test/output/test_popen Lib/test/output/test_resource Lib/test/test_array.py Lib/test/test_deque.py Lib/test/test_dumbdbm.py Lib/test/test_itertools.py Lib/test/test_mailbox.py Lib/test/test_new.py Lib/test/test_ntpath.py Lib/test/test_old_mailbox.py Lib/test/test_popen.py Lib/test/test_posixpath.py Lib/test/test_random.py Lib/test/test_resource.py Lib/test/test_socket.py Lib/test/test_struct.py Lib/test/test_urllib2net.py Lib/test/test_uu.py Lib/test/test_weakref.py Lib/urllib.py Lib/urllib2.py Modules/_ctypes/_ctypes_test.c Modules/_randommodule.c Modules/_struct.c Modules/arraymodule.c Modules/collectionsmodule.c Modules/itertoolsmodule.c Objects/fileobject.c Objects/object.c Objects/typeobject.c Objects/weakrefobject.c PCbuild/_bsddb.vcproj PCbuild/_elementtree.vcproj PCbuild/_msi.vcproj PCbuild/_socket.vcproj PCbuild/_sqlite3.vcproj PCbuild/_ssl.mak PCbuild/_testcapi.vcproj PCbuild/_tkinter.vcproj PCbuild/build_ssl.py PCbuild/bz2.vcproj PCbuild/pyexpat.vcproj PCbuild/python.vcproj PCbuild/pythoncore.vcproj PCbuild/pythonw.vcproj PCbuild/select.vcproj PCbuild/unicodedata.vcproj PCbuild/winsound.vcproj Parser/asdl_c.py Python/pythonrun.c Python/sysmodule.c Python/traceback.c Tools/msi/uuids.py configure configure.in pyconfig.h.in Message-ID: <20070201180243.BAE911E400E@bag.python.org> Author: thomas.wouters Date: Thu Feb 1 19:02:27 2007 New Revision: 53610 Removed: python/branches/p3yk/Lib/test/output/test_new python/branches/p3yk/Lib/test/output/test_popen python/branches/p3yk/Lib/test/output/test_resource Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/api/concrete.tex python/branches/p3yk/Doc/commontex/license.tex python/branches/p3yk/Doc/dist/dist.tex python/branches/p3yk/Doc/lib/libmailbox.tex python/branches/p3yk/Doc/lib/librandom.tex python/branches/p3yk/Doc/lib/libstruct.tex python/branches/p3yk/Doc/lib/libtime.tex python/branches/p3yk/Doc/ref/ref3.tex python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Include/object.h python/branches/p3yk/Lib/logging/handlers.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/ntpath.py python/branches/p3yk/Lib/pdb.py python/branches/p3yk/Lib/random.py python/branches/p3yk/Lib/rfc822.py python/branches/p3yk/Lib/smtplib.py python/branches/p3yk/Lib/socket.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/test/crashers/weakref_in_del.py python/branches/p3yk/Lib/test/test_array.py python/branches/p3yk/Lib/test/test_deque.py python/branches/p3yk/Lib/test/test_dumbdbm.py python/branches/p3yk/Lib/test/test_itertools.py python/branches/p3yk/Lib/test/test_mailbox.py python/branches/p3yk/Lib/test/test_new.py python/branches/p3yk/Lib/test/test_ntpath.py python/branches/p3yk/Lib/test/test_old_mailbox.py python/branches/p3yk/Lib/test/test_popen.py python/branches/p3yk/Lib/test/test_posixpath.py python/branches/p3yk/Lib/test/test_random.py python/branches/p3yk/Lib/test/test_resource.py python/branches/p3yk/Lib/test/test_socket.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_urllib2net.py python/branches/p3yk/Lib/test/test_uu.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/urllib.py python/branches/p3yk/Lib/urllib2.py python/branches/p3yk/Modules/_ctypes/_ctypes_test.c python/branches/p3yk/Modules/_randommodule.c python/branches/p3yk/Modules/_struct.c python/branches/p3yk/Modules/arraymodule.c python/branches/p3yk/Modules/collectionsmodule.c python/branches/p3yk/Modules/itertoolsmodule.c python/branches/p3yk/Objects/fileobject.c python/branches/p3yk/Objects/object.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/Objects/weakrefobject.c python/branches/p3yk/PCbuild/_bsddb.vcproj python/branches/p3yk/PCbuild/_elementtree.vcproj python/branches/p3yk/PCbuild/_msi.vcproj python/branches/p3yk/PCbuild/_socket.vcproj python/branches/p3yk/PCbuild/_sqlite3.vcproj python/branches/p3yk/PCbuild/_ssl.mak python/branches/p3yk/PCbuild/_testcapi.vcproj python/branches/p3yk/PCbuild/_tkinter.vcproj python/branches/p3yk/PCbuild/build_ssl.py python/branches/p3yk/PCbuild/bz2.vcproj python/branches/p3yk/PCbuild/pyexpat.vcproj python/branches/p3yk/PCbuild/python.vcproj python/branches/p3yk/PCbuild/pythoncore.vcproj python/branches/p3yk/PCbuild/pythonw.vcproj python/branches/p3yk/PCbuild/select.vcproj python/branches/p3yk/PCbuild/unicodedata.vcproj python/branches/p3yk/PCbuild/winsound.vcproj python/branches/p3yk/Parser/asdl_c.py python/branches/p3yk/Python/pythonrun.c python/branches/p3yk/Python/sysmodule.c python/branches/p3yk/Python/traceback.c python/branches/p3yk/Tools/msi/uuids.py python/branches/p3yk/configure python/branches/p3yk/configure.in python/branches/p3yk/pyconfig.h.in Log: Merged revisions 53451-53537 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53454 | brett.cannon | 2007-01-15 20:12:08 +0100 (Mon, 15 Jan 2007) | 3 lines Add a note for strptime that just because strftime supports some extra directive that is not documented that strptime will as well. ........ r53458 | vinay.sajip | 2007-01-16 10:50:07 +0100 (Tue, 16 Jan 2007) | 1 line Updated rotating file handlers to use _open(). ........ r53459 | marc-andre.lemburg | 2007-01-16 14:03:06 +0100 (Tue, 16 Jan 2007) | 2 lines Add news items for the recent pybench and platform changes. ........ r53460 | sjoerd.mullender | 2007-01-16 17:42:38 +0100 (Tue, 16 Jan 2007) | 4 lines Fixed ntpath.expandvars to not replace references to non-existing variables with nothing. Also added tests. This fixes bug #494589. ........ r53464 | neal.norwitz | 2007-01-17 07:23:51 +0100 (Wed, 17 Jan 2007) | 1 line Give Calvin Spealman access for python-dev summaries. ........ r53465 | neal.norwitz | 2007-01-17 09:37:26 +0100 (Wed, 17 Jan 2007) | 1 line Remove Calvin since he only has access to the website currently. ........ r53466 | thomas.heller | 2007-01-17 10:40:34 +0100 (Wed, 17 Jan 2007) | 2 lines Replace C++ comments with C comments. ........ r53472 | andrew.kuchling | 2007-01-17 20:55:06 +0100 (Wed, 17 Jan 2007) | 1 line [Part of bug #1599254] Add suggestion to Mailbox docs to use Maildir, and warn user to lock/unlock mailboxes when modifying them ........ r53475 | georg.brandl | 2007-01-17 22:09:04 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1637967: missing //= operator in list. ........ r53477 | georg.brandl | 2007-01-17 22:19:58 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1629125: fix wrong data type (int -> Py_ssize_t) in PyDict_Next docs. ........ r53481 | neal.norwitz | 2007-01-18 06:40:58 +0100 (Thu, 18 Jan 2007) | 1 line Try reverting part of r53145 that seems to cause the Windows buildbots to fail in test_uu.UUFileTest.test_encode ........ r53482 | fred.drake | 2007-01-18 06:42:30 +0100 (Thu, 18 Jan 2007) | 1 line add missing version entry ........ r53483 | neal.norwitz | 2007-01-18 07:20:55 +0100 (Thu, 18 Jan 2007) | 7 lines This test doesn't pass on Windows. The cause seems to be that chmod doesn't support the same funcationality as on Unix. I'm not sure if this fix is the best (or if it will even work)--it's a test to see if the buildbots start passing again. It might be better to not even run this test if it's windows (or non-posix). ........ r53488 | neal.norwitz | 2007-01-19 06:53:33 +0100 (Fri, 19 Jan 2007) | 1 line SF #1635217, Fix unbalanced paren ........ r53489 | martin.v.loewis | 2007-01-19 07:42:22 +0100 (Fri, 19 Jan 2007) | 3 lines Prefix AST symbols with _Py_. Fixes #1637022. Will backport. ........ r53497 | martin.v.loewis | 2007-01-19 19:01:38 +0100 (Fri, 19 Jan 2007) | 2 lines Add UUIDs for 2.5.1 and 2.5.2 ........ r53499 | raymond.hettinger | 2007-01-19 19:07:18 +0100 (Fri, 19 Jan 2007) | 1 line SF# 1635892: Fix docs for betavariate's input parameters . ........ r53503 | martin.v.loewis | 2007-01-20 15:05:39 +0100 (Sat, 20 Jan 2007) | 2 lines Merge 53501 and 53502 from 25 branch: Add /GS- for AMD64 and Itanium builds where missing. ........ r53504 | walter.doerwald | 2007-01-20 18:28:31 +0100 (Sat, 20 Jan 2007) | 2 lines Port test_resource.py to unittest. ........ r53505 | walter.doerwald | 2007-01-20 19:19:33 +0100 (Sat, 20 Jan 2007) | 2 lines Add argument tests an calls of resource.getrusage(). ........ r53506 | walter.doerwald | 2007-01-20 20:03:17 +0100 (Sat, 20 Jan 2007) | 2 lines resource.RUSAGE_BOTH might not exist. ........ r53507 | walter.doerwald | 2007-01-21 00:07:28 +0100 (Sun, 21 Jan 2007) | 2 lines Port test_new.py to unittest. ........ r53508 | martin.v.loewis | 2007-01-21 10:33:07 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1610575: Add support for _Bool to struct. ........ r53509 | georg.brandl | 2007-01-21 11:28:43 +0100 (Sun, 21 Jan 2007) | 3 lines Bug #1486663: don't reject keyword arguments for subclasses of builtin types. ........ r53511 | georg.brandl | 2007-01-21 11:35:10 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1627441: close sockets properly in urllib2. ........ r53517 | georg.brandl | 2007-01-22 20:40:21 +0100 (Mon, 22 Jan 2007) | 3 lines Use new email module names (#1637162, #1637159, #1637157). ........ r53518 | andrew.kuchling | 2007-01-22 21:26:40 +0100 (Mon, 22 Jan 2007) | 1 line Improve pattern used for mbox 'From' lines; add a simple test ........ r53519 | andrew.kuchling | 2007-01-22 21:27:50 +0100 (Mon, 22 Jan 2007) | 1 line Make comment match the code ........ r53522 | georg.brandl | 2007-01-22 22:10:33 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1249573: fix rfc822.parsedate not accepting a certain date format ........ r53524 | georg.brandl | 2007-01-22 22:23:41 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1627316: handle error in condition/ignore pdb commands more gracefully. ........ r53526 | lars.gustaebel | 2007-01-23 12:17:33 +0100 (Tue, 23 Jan 2007) | 4 lines Patch #1507247: tarfile.py: use current umask for intermediate directories. ........ r53527 | thomas.wouters | 2007-01-23 14:42:00 +0100 (Tue, 23 Jan 2007) | 13 lines SF patch #1630975: Fix crash when replacing sys.stdout in sitecustomize When running the interpreter in an environment that would cause it to set stdout/stderr/stdin's encoding, having a sitecustomize that would replace them with something other than PyFile objects would crash the interpreter. Fix it by simply ignoring the encoding-setting for non-files. This could do with a test, but I can think of no maintainable and portable way to test this bug, short of adding a sitecustomize.py to the buildsystem and have it always run with it (hmmm....) ........ r53528 | thomas.wouters | 2007-01-23 14:50:49 +0100 (Tue, 23 Jan 2007) | 4 lines Add news entry about last checkin (oops.) ........ r53531 | martin.v.loewis | 2007-01-23 22:11:47 +0100 (Tue, 23 Jan 2007) | 4 lines Make PyTraceBack_Here use the current thread, not the frame's thread state. Fixes #1579370. Will backport. ........ r53535 | brett.cannon | 2007-01-24 00:21:22 +0100 (Wed, 24 Jan 2007) | 5 lines Fix crasher for when an object's __del__ creates a new weakref to itself. Patch only fixes new-style classes; classic classes still buggy. Closes bug #1377858. Already backported. ........ r53536 | walter.doerwald | 2007-01-24 01:42:19 +0100 (Wed, 24 Jan 2007) | 2 lines Port test_popen.py to unittest. ........ Modified: python/branches/p3yk/Doc/api/concrete.tex ============================================================================== --- python/branches/p3yk/Doc/api/concrete.tex (original) +++ python/branches/p3yk/Doc/api/concrete.tex Thu Feb 1 19:02:27 2007 @@ -2082,7 +2082,7 @@ \begin{verbatim} PyObject *key, *value; -int pos = 0; +Py_ssize_t pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { /* do something interesting with the values... */ @@ -2097,7 +2097,7 @@ \begin{verbatim} PyObject *key, *value; -int pos = 0; +Py_ssize_t pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { int i = PyInt_AS_LONG(value) + 1; Modified: python/branches/p3yk/Doc/commontex/license.tex ============================================================================== --- python/branches/p3yk/Doc/commontex/license.tex (original) +++ python/branches/p3yk/Doc/commontex/license.tex Thu Feb 1 19:02:27 2007 @@ -50,6 +50,7 @@ \linev{2.4.1}{2.4}{2005}{PSF}{yes} \linev{2.4.2}{2.4.1}{2005}{PSF}{yes} \linev{2.4.3}{2.4.2}{2006}{PSF}{yes} + \linev{2.4.4}{2.4.3}{2006}{PSF}{yes} \linev{2.5}{2.4}{2006}{PSF}{yes} \end{tablev} Modified: python/branches/p3yk/Doc/dist/dist.tex ============================================================================== --- python/branches/p3yk/Doc/dist/dist.tex (original) +++ python/branches/p3yk/Doc/dist/dist.tex Thu Feb 1 19:02:27 2007 @@ -692,7 +692,7 @@ \begin{tableii}{l|l}{code}{Provides Expression}{Explanation} \lineii{mypkg} {Provide \code{mypkg}, using the distribution version} - \lineii{mypkg (1.1} {Provide \code{mypkg} version 1.1, regardless of the + \lineii{mypkg (1.1)} {Provide \code{mypkg} version 1.1, regardless of the distribution version} \end{tableii} Modified: python/branches/p3yk/Doc/lib/libmailbox.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libmailbox.tex (original) +++ python/branches/p3yk/Doc/lib/libmailbox.tex Thu Feb 1 19:02:27 2007 @@ -25,22 +25,29 @@ A mailbox, which may be inspected and modified. \end{classdesc*} +The \class{Mailbox} class defines an interface and +is not intended to be instantiated. Instead, format-specific +subclasses should inherit from \class{Mailbox} and your code +should instantiate a particular subclass. + The \class{Mailbox} interface is dictionary-like, with small keys -corresponding to messages. Keys are issued by the \class{Mailbox} instance -with which they will be used and are only meaningful to that \class{Mailbox} -instance. A key continues to identify a message even if the corresponding -message is modified, such as by replacing it with another message. Messages may -be added to a \class{Mailbox} instance using the set-like method -\method{add()} and removed using a \code{del} statement or the set-like methods -\method{remove()} and \method{discard()}. +corresponding to messages. Keys are issued by the \class{Mailbox} +instance with which they will be used and are only meaningful to that +\class{Mailbox} instance. A key continues to identify a message even +if the corresponding message is modified, such as by replacing it with +another message. + +Messages may be added to a \class{Mailbox} instance using the set-like +method \method{add()} and removed using a \code{del} statement or the +set-like methods \method{remove()} and \method{discard()}. \class{Mailbox} interface semantics differ from dictionary semantics in some -noteworthy ways. Each time a message is requested, a new representation -(typically a \class{Message} instance) is generated, based upon the current -state of the mailbox. Similarly, when a message is added to a \class{Mailbox} -instance, the provided message representation's contents are copied. In neither -case is a reference to the message representation kept by the \class{Mailbox} -instance. +noteworthy ways. Each time a message is requested, a new +representation (typically a \class{Message} instance) is generated +based upon the current state of the mailbox. Similarly, when a message +is added to a \class{Mailbox} instance, the provided message +representation's contents are copied. In neither case is a reference +to the message representation kept by the \class{Mailbox} instance. The default \class{Mailbox} iterator iterates over message representations, not keys as the default dictionary iterator does. Moreover, modification of a @@ -51,9 +58,14 @@ \exception{KeyError} exception if the corresponding message is subsequently removed. -\class{Mailbox} itself is intended to define an interface and to be inherited -from by format-specific subclasses but is not intended to be instantiated. -Instead, you should instantiate a subclass. +Be very cautious when modifying mailboxes that might also be changed +by some other process. The safest mailbox format to use for such +tasks is Maildir; try to avoid using single-file formats such as mbox +for concurrent writing. If you're modifying a mailbox, no matter what +the format, you must lock it by calling the \method{lock()} and +\method{unlock()} methods before making any changes. Failing to lock +the mailbox runs the risk of losing data if some other process makes +changes to the mailbox while your Python code is running. \class{Mailbox} instances have the following methods: @@ -202,15 +214,16 @@ \begin{methoddesc}{flush}{} Write any pending changes to the filesystem. For some \class{Mailbox} -subclasses, changes are always written immediately and this method does -nothing. +subclasses, changes are always written immediately and \method{flush()} does +nothing, but you should still make a habit of calling this method. \end{methoddesc} \begin{methoddesc}{lock}{} Acquire an exclusive advisory lock on the mailbox so that other processes know not to modify it. An \exception{ExternalClashError} is raised if the lock is not available. The particular locking mechanisms used depend upon the mailbox -format. +format. You should \emph{always} lock the mailbox before making any +modifications to its contents. \end{methoddesc} \begin{methoddesc}{unlock}{} @@ -1373,36 +1386,55 @@ \begin{verbatim} import mailbox destination = mailbox.MH('~/Mail') +destination.lock() for message in mailbox.Babyl('~/RMAIL'): destination.add(MHMessage(message)) +destination.flush() +destination.unlock() \end{verbatim} -An example of sorting mail from numerous mailing lists, being careful to avoid -mail corruption due to concurrent modification by other programs, mail loss due -to interruption of the program, or premature termination due to malformed -messages in the mailbox: +This example sorts mail from several mailing lists into different +mailboxes, being careful to avoid mail corruption due to concurrent +modification by other programs, mail loss due to interruption of the +program, or premature termination due to malformed messages in the +mailbox: \begin{verbatim} import mailbox import email.Errors + list_names = ('python-list', 'python-dev', 'python-bugs') + boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names) -inbox = mailbox.Maildir('~/Maildir', None) +inbox = mailbox.Maildir('~/Maildir', factory=None) + for key in inbox.iterkeys(): try: message = inbox[key] except email.Errors.MessageParseError: continue # The message is malformed. Just leave it. + for name in list_names: list_id = message['list-id'] if list_id and name in list_id: + # Get mailbox to use box = boxes[name] + + # Write copy to disk before removing original. + # If there's a crash, you might duplicate a message, but + # that's better than losing a message completely. box.lock() box.add(message) - box.flush() # Write copy to disk before removing original. + box.flush() box.unlock() + + # Remove original message + inbox.lock() inbox.discard(key) + inbox.flush() + inbox.unlock() break # Found destination, so stop looking. + for box in boxes.itervalues(): box.close() \end{verbatim} Modified: python/branches/p3yk/Doc/lib/librandom.tex ============================================================================== --- python/branches/p3yk/Doc/lib/librandom.tex (original) +++ python/branches/p3yk/Doc/lib/librandom.tex Thu Feb 1 19:02:27 2007 @@ -185,7 +185,7 @@ \begin{funcdesc}{betavariate}{alpha, beta} Beta distribution. Conditions on the parameters are - \code{\var{alpha} > -1} and \code{\var{beta} > -1}. + \code{\var{alpha} > 0} and \code{\var{beta} > 0}. Returned values range between 0 and 1. \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/libstruct.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstruct.tex (original) +++ python/branches/p3yk/Doc/lib/libstruct.tex Thu Feb 1 19:02:27 2007 @@ -50,14 +50,15 @@ \lineiv{c}{\ctype{char}}{string of length 1}{} \lineiv{b}{\ctype{signed char}}{integer}{} \lineiv{B}{\ctype{unsigned char}}{integer}{} + \lineiv{t}{\ctype{_Bool}}{bool}{(1)} \lineiv{h}{\ctype{short}}{integer}{} \lineiv{H}{\ctype{unsigned short}}{integer}{} \lineiv{i}{\ctype{int}}{integer}{} \lineiv{I}{\ctype{unsigned int}}{long}{} \lineiv{l}{\ctype{long}}{integer}{} \lineiv{L}{\ctype{unsigned long}}{long}{} - \lineiv{q}{\ctype{long long}}{long}{(1)} - \lineiv{Q}{\ctype{unsigned long long}}{long}{(1)} + \lineiv{q}{\ctype{long long}}{long}{(2)} + \lineiv{Q}{\ctype{unsigned long long}}{long}{(2)} \lineiv{f}{\ctype{float}}{float}{} \lineiv{d}{\ctype{double}}{float}{} \lineiv{s}{\ctype{char[]}}{string}{} @@ -70,6 +71,11 @@ \begin{description} \item[(1)] + The \character{t} conversion code corresponds to the \ctype{_Bool} type + defined by C99. If this type is not available, it is simulated using a + \ctype{char}. In standard mode, it is always represented by one byte. + \versionadded{2.6} +\item[(2)] The \character{q} and \character{Q} conversion codes are available in native mode only if the platform C compiler supports C \ctype{long long}, or, on Windows, \ctype{__int64}. They are always available in standard @@ -118,6 +124,12 @@ meaning a Python long integer will be used to hold the pointer; other platforms use 32-bit pointers and will use a Python integer. +For the \character{t} format character, the return value is either +\constant{True} or \constant{False}. When packing, the truth value +of the argument object is used. Either 0 or 1 in the native or standard +bool representation will be packed, and any non-zero value will be True +when unpacking. + By default, C numbers are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). @@ -151,6 +163,7 @@ \ctype{long long} (\ctype{__int64} on Windows) is 8 bytes; \ctype{float} and \ctype{double} are 32-bit and 64-bit IEEE floating point numbers, respectively. +\ctype{_Bool} is 1 byte. Note the difference between \character{@} and \character{=}: both use native byte order, but the size and alignment of the latter is Modified: python/branches/p3yk/Doc/lib/libtime.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtime.tex (original) +++ python/branches/p3yk/Doc/lib/libtime.tex Thu Feb 1 19:02:27 2007 @@ -324,6 +324,12 @@ it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones). + +Only the directives specified in the documentation are supported. Because +\code{strftime()} is implemented per platform it can sometimes offer more +directives than those listed. But \code{strptime()} is independent of any +platform and thus does not necessarily support all directives available that +are not documented as supported. \end{funcdesc} \begin{datadesc}{struct_time} Modified: python/branches/p3yk/Doc/ref/ref3.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref3.tex (original) +++ python/branches/p3yk/Doc/ref/ref3.tex Thu Feb 1 19:02:27 2007 @@ -1997,8 +1997,8 @@ \methodline[numeric object]{__ixor__}{self, other} \methodline[numeric object]{__ior__}{self, other} These methods are called to implement the augmented arithmetic -operations (\code{+=}, \code{-=}, \code{*=}, \code{/=}, \code{\%=}, -\code{**=}, \code{<<=}, \code{>>=}, \code{\&=}, +operations (\code{+=}, \code{-=}, \code{*=}, \code{/=}, \code{//=}, +\code{\%=}, \code{**=}, \code{<<=}, \code{>>=}, \code{\&=}, \code{\textasciicircum=}, \code{|=}). These methods should attempt to do the operation in-place (modifying \var{self}) and return the result (which could be, but does not have to be, \var{self}). If a specific method Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Thu Feb 1 19:02:27 2007 @@ -366,97 +366,157 @@ }; -mod_ty Module(asdl_seq * body, PyArena *arena); -mod_ty Interactive(asdl_seq * body, PyArena *arena); -mod_ty Expression(expr_ty body, PyArena *arena); -mod_ty Suite(asdl_seq * body, PyArena *arena); -stmt_ty FunctionDef(identifier name, arguments_ty args, asdl_seq * body, - asdl_seq * decorators, expr_ty returns, int lineno, int - col_offset, PyArena *arena); -stmt_ty ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int - lineno, int col_offset, PyArena *arena); -stmt_ty Return(expr_ty value, int lineno, int col_offset, PyArena *arena); -stmt_ty Delete(asdl_seq * targets, int lineno, int col_offset, PyArena *arena); -stmt_ty Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, - PyArena *arena); -stmt_ty AugAssign(expr_ty target, operator_ty op, expr_ty value, int lineno, - int col_offset, PyArena *arena); -stmt_ty Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int - col_offset, PyArena *arena); -stmt_ty For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, - int lineno, int col_offset, PyArena *arena); -stmt_ty While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int - col_offset, PyArena *arena); -stmt_ty If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int - col_offset, PyArena *arena); -stmt_ty With(expr_ty context_expr, expr_ty optional_vars, asdl_seq * body, int - lineno, int col_offset, PyArena *arena); -stmt_ty Raise(expr_ty type, expr_ty inst, expr_ty tback, int lineno, int - col_offset, PyArena *arena); -stmt_ty TryExcept(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, int - lineno, int col_offset, PyArena *arena); -stmt_ty TryFinally(asdl_seq * body, asdl_seq * finalbody, int lineno, int +#define Module(a0, a1) _Py_Module(a0, a1) +mod_ty _Py_Module(asdl_seq * body, PyArena *arena); +#define Interactive(a0, a1) _Py_Interactive(a0, a1) +mod_ty _Py_Interactive(asdl_seq * body, PyArena *arena); +#define Expression(a0, a1) _Py_Expression(a0, a1) +mod_ty _Py_Expression(expr_ty body, PyArena *arena); +#define Suite(a0, a1) _Py_Suite(a0, a1) +mod_ty _Py_Suite(asdl_seq * body, PyArena *arena); +#define FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) _Py_FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) +stmt_ty _Py_FunctionDef(identifier name, arguments_ty args, asdl_seq * body, + asdl_seq * decorators, expr_ty returns, int lineno, int + col_offset, PyArena *arena); +#define ClassDef(a0, a1, a2, a3, a4, a5) _Py_ClassDef(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int + lineno, int col_offset, PyArena *arena); +#define Return(a0, a1, a2, a3) _Py_Return(a0, a1, a2, a3) +stmt_ty _Py_Return(expr_ty value, int lineno, int col_offset, PyArena *arena); +#define Delete(a0, a1, a2, a3) _Py_Delete(a0, a1, a2, a3) +stmt_ty _Py_Delete(asdl_seq * targets, int lineno, int col_offset, PyArena + *arena); +#define Assign(a0, a1, a2, a3, a4) _Py_Assign(a0, a1, a2, a3, a4) +stmt_ty _Py_Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, PyArena *arena); -stmt_ty Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, PyArena - *arena); -stmt_ty Import(asdl_seq * names, int lineno, int col_offset, PyArena *arena); -stmt_ty ImportFrom(identifier module, asdl_seq * names, int level, int lineno, - int col_offset, PyArena *arena); -stmt_ty Global(asdl_seq * names, int lineno, int col_offset, PyArena *arena); -stmt_ty Expr(expr_ty value, int lineno, int col_offset, PyArena *arena); -stmt_ty Pass(int lineno, int col_offset, PyArena *arena); -stmt_ty Break(int lineno, int col_offset, PyArena *arena); -stmt_ty Continue(int lineno, int col_offset, PyArena *arena); -expr_ty BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset, - PyArena *arena); -expr_ty BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int - col_offset, PyArena *arena); -expr_ty UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset, - PyArena *arena); -expr_ty Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset, - PyArena *arena); -expr_ty IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int - col_offset, PyArena *arena); -expr_ty Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, - PyArena *arena); -expr_ty Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena); -expr_ty ListComp(expr_ty elt, asdl_seq * generators, int lineno, int +#define AugAssign(a0, a1, a2, a3, a4, a5) _Py_AugAssign(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_AugAssign(expr_ty target, operator_ty op, expr_ty value, int + lineno, int col_offset, PyArena *arena); +#define Print(a0, a1, a2, a3, a4, a5) _Py_Print(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int + col_offset, PyArena *arena); +#define For(a0, a1, a2, a3, a4, a5, a6) _Py_For(a0, a1, a2, a3, a4, a5, a6) +stmt_ty _Py_For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * + orelse, int lineno, int col_offset, PyArena *arena); +#define While(a0, a1, a2, a3, a4, a5) _Py_While(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, + int col_offset, PyArena *arena); +#define If(a0, a1, a2, a3, a4, a5) _Py_If(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, + int col_offset, PyArena *arena); +#define With(a0, a1, a2, a3, a4, a5) _Py_With(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_With(expr_ty context_expr, expr_ty optional_vars, asdl_seq * body, + int lineno, int col_offset, PyArena *arena); +#define Raise(a0, a1, a2, a3, a4, a5) _Py_Raise(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_Raise(expr_ty type, expr_ty inst, expr_ty tback, int lineno, int + col_offset, PyArena *arena); +#define TryExcept(a0, a1, a2, a3, a4, a5) _Py_TryExcept(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_TryExcept(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, + int lineno, int col_offset, PyArena *arena); +#define TryFinally(a0, a1, a2, a3, a4) _Py_TryFinally(a0, a1, a2, a3, a4) +stmt_ty _Py_TryFinally(asdl_seq * body, asdl_seq * finalbody, int lineno, int + col_offset, PyArena *arena); +#define Assert(a0, a1, a2, a3, a4) _Py_Assert(a0, a1, a2, a3, a4) +stmt_ty _Py_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, + PyArena *arena); +#define Import(a0, a1, a2, a3) _Py_Import(a0, a1, a2, a3) +stmt_ty _Py_Import(asdl_seq * names, int lineno, int col_offset, PyArena + *arena); +#define ImportFrom(a0, a1, a2, a3, a4, a5) _Py_ImportFrom(a0, a1, a2, a3, a4, a5) +stmt_ty _Py_ImportFrom(identifier module, asdl_seq * names, int level, int + lineno, int col_offset, PyArena *arena); +#define Global(a0, a1, a2, a3) _Py_Global(a0, a1, a2, a3) +stmt_ty _Py_Global(asdl_seq * names, int lineno, int col_offset, PyArena + *arena); +#define Expr(a0, a1, a2, a3) _Py_Expr(a0, a1, a2, a3) +stmt_ty _Py_Expr(expr_ty value, int lineno, int col_offset, PyArena *arena); +#define Pass(a0, a1, a2) _Py_Pass(a0, a1, a2) +stmt_ty _Py_Pass(int lineno, int col_offset, PyArena *arena); +#define Break(a0, a1, a2) _Py_Break(a0, a1, a2) +stmt_ty _Py_Break(int lineno, int col_offset, PyArena *arena); +#define Continue(a0, a1, a2) _Py_Continue(a0, a1, a2) +stmt_ty _Py_Continue(int lineno, int col_offset, PyArena *arena); +#define BoolOp(a0, a1, a2, a3, a4) _Py_BoolOp(a0, a1, a2, a3, a4) +expr_ty _Py_BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset, + PyArena *arena); +#define BinOp(a0, a1, a2, a3, a4, a5) _Py_BinOp(a0, a1, a2, a3, a4, a5) +expr_ty _Py_BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int + col_offset, PyArena *arena); +#define UnaryOp(a0, a1, a2, a3, a4) _Py_UnaryOp(a0, a1, a2, a3, a4) +expr_ty _Py_UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset, + PyArena *arena); +#define Lambda(a0, a1, a2, a3, a4) _Py_Lambda(a0, a1, a2, a3, a4) +expr_ty _Py_Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset, + PyArena *arena); +#define IfExp(a0, a1, a2, a3, a4, a5) _Py_IfExp(a0, a1, a2, a3, a4, a5) +expr_ty _Py_IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int + col_offset, PyArena *arena); +#define Dict(a0, a1, a2, a3, a4) _Py_Dict(a0, a1, a2, a3, a4) +expr_ty _Py_Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, PyArena *arena); -expr_ty GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int +#define Set(a0, a1, a2, a3) _Py_Set(a0, a1, a2, a3) +expr_ty _Py_Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena); +#define ListComp(a0, a1, a2, a3, a4) _Py_ListComp(a0, a1, a2, a3, a4) +expr_ty _Py_ListComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena); -expr_ty Yield(expr_ty value, int lineno, int col_offset, PyArena *arena); -expr_ty Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, int - lineno, int col_offset, PyArena *arena); -expr_ty Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty - starargs, expr_ty kwargs, int lineno, int col_offset, PyArena - *arena); -expr_ty Num(object n, int lineno, int col_offset, PyArena *arena); -expr_ty Str(string s, int lineno, int col_offset, PyArena *arena); -expr_ty Ellipsis(int lineno, int col_offset, PyArena *arena); -expr_ty Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int - lineno, int col_offset, PyArena *arena); -expr_ty Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int - lineno, int col_offset, PyArena *arena); -expr_ty Name(identifier id, expr_context_ty ctx, int lineno, int col_offset, - PyArena *arena); -expr_ty List(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, - PyArena *arena); -expr_ty Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, - PyArena *arena); -slice_ty Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena); -slice_ty ExtSlice(asdl_seq * dims, PyArena *arena); -slice_ty Index(expr_ty value, PyArena *arena); -comprehension_ty comprehension(expr_ty target, expr_ty iter, asdl_seq * ifs, - PyArena *arena); -excepthandler_ty excepthandler(expr_ty type, identifier name, asdl_seq * body, - int lineno, int col_offset, PyArena *arena); -arguments_ty arguments(asdl_seq * args, identifier vararg, expr_ty - varargannotation, asdl_seq * kwonlyargs, identifier - kwarg, expr_ty kwargannotation, asdl_seq * defaults, - asdl_seq * kw_defaults, PyArena *arena); -arg_ty SimpleArg(identifier arg, expr_ty annotation, PyArena *arena); -arg_ty NestedArgs(asdl_seq * args, PyArena *arena); -keyword_ty keyword(identifier arg, expr_ty value, PyArena *arena); -alias_ty alias(identifier name, identifier asname, PyArena *arena); +#define GeneratorExp(a0, a1, a2, a3, a4) _Py_GeneratorExp(a0, a1, a2, a3, a4) +expr_ty _Py_GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int + col_offset, PyArena *arena); +#define Yield(a0, a1, a2, a3) _Py_Yield(a0, a1, a2, a3) +expr_ty _Py_Yield(expr_ty value, int lineno, int col_offset, PyArena *arena); +#define Compare(a0, a1, a2, a3, a4, a5) _Py_Compare(a0, a1, a2, a3, a4, a5) +expr_ty _Py_Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, + int lineno, int col_offset, PyArena *arena); +#define Call(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Call(a0, a1, a2, a3, a4, a5, a6, a7) +expr_ty _Py_Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty + starargs, expr_ty kwargs, int lineno, int col_offset, PyArena + *arena); +#define Num(a0, a1, a2, a3) _Py_Num(a0, a1, a2, a3) +expr_ty _Py_Num(object n, int lineno, int col_offset, PyArena *arena); +#define Str(a0, a1, a2, a3) _Py_Str(a0, a1, a2, a3) +expr_ty _Py_Str(string s, int lineno, int col_offset, PyArena *arena); +#define Ellipsis(a0, a1, a2) _Py_Ellipsis(a0, a1, a2) +expr_ty _Py_Ellipsis(int lineno, int col_offset, PyArena *arena); +#define Attribute(a0, a1, a2, a3, a4, a5) _Py_Attribute(a0, a1, a2, a3, a4, a5) +expr_ty _Py_Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int + lineno, int col_offset, PyArena *arena); +#define Subscript(a0, a1, a2, a3, a4, a5) _Py_Subscript(a0, a1, a2, a3, a4, a5) +expr_ty _Py_Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int + lineno, int col_offset, PyArena *arena); +#define Name(a0, a1, a2, a3, a4) _Py_Name(a0, a1, a2, a3, a4) +expr_ty _Py_Name(identifier id, expr_context_ty ctx, int lineno, int + col_offset, PyArena *arena); +#define List(a0, a1, a2, a3, a4) _Py_List(a0, a1, a2, a3, a4) +expr_ty _Py_List(asdl_seq * elts, expr_context_ty ctx, int lineno, int + col_offset, PyArena *arena); +#define Tuple(a0, a1, a2, a3, a4) _Py_Tuple(a0, a1, a2, a3, a4) +expr_ty _Py_Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int + col_offset, PyArena *arena); +#define Slice(a0, a1, a2, a3) _Py_Slice(a0, a1, a2, a3) +slice_ty _Py_Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena); +#define ExtSlice(a0, a1) _Py_ExtSlice(a0, a1) +slice_ty _Py_ExtSlice(asdl_seq * dims, PyArena *arena); +#define Index(a0, a1) _Py_Index(a0, a1) +slice_ty _Py_Index(expr_ty value, PyArena *arena); +#define comprehension(a0, a1, a2, a3) _Py_comprehension(a0, a1, a2, a3) +comprehension_ty _Py_comprehension(expr_ty target, expr_ty iter, asdl_seq * + ifs, PyArena *arena); +#define excepthandler(a0, a1, a2, a3, a4, a5) _Py_excepthandler(a0, a1, a2, a3, a4, a5) +excepthandler_ty _Py_excepthandler(expr_ty type, identifier name, asdl_seq * + body, int lineno, int col_offset, PyArena + *arena); +#define arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8) _Py_arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8) +arguments_ty _Py_arguments(asdl_seq * args, identifier vararg, expr_ty + varargannotation, asdl_seq * kwonlyargs, identifier + kwarg, expr_ty kwargannotation, asdl_seq * defaults, + asdl_seq * kw_defaults, PyArena *arena); +#define SimpleArg(a0, a1, a2) _Py_SimpleArg(a0, a1, a2) +arg_ty _Py_SimpleArg(identifier arg, expr_ty annotation, PyArena *arena); +#define NestedArgs(a0, a1) _Py_NestedArgs(a0, a1) +arg_ty _Py_NestedArgs(asdl_seq * args, PyArena *arena); +#define keyword(a0, a1, a2) _Py_keyword(a0, a1, a2) +keyword_ty _Py_keyword(identifier arg, expr_ty value, PyArena *arena); +#define alias(a0, a1, a2) _Py_alias(a0, a1, a2) +alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); PyObject* PyAST_mod2obj(mod_ty t); Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Thu Feb 1 19:02:27 2007 @@ -368,7 +368,7 @@ /* Generic operations on objects */ PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int); -PyAPI_FUNC(void) _Py_Break(void); +PyAPI_FUNC(void) _Py_BreakPoint(void); PyAPI_FUNC(void) _PyObject_Dump(PyObject *); PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *); PyAPI_FUNC(PyObject *) _PyObject_Str(PyObject *); Modified: python/branches/p3yk/Lib/logging/handlers.py ============================================================================== --- python/branches/p3yk/Lib/logging/handlers.py (original) +++ python/branches/p3yk/Lib/logging/handlers.py Thu Feb 1 19:02:27 2007 @@ -1,4 +1,4 @@ -# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, @@ -22,7 +22,7 @@ Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. -Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ @@ -135,10 +135,8 @@ os.remove(dfn) os.rename(self.baseFilename, dfn) #print "%s -> %s" % (self.baseFilename, dfn) - if self.encoding: - self.stream = codecs.open(self.baseFilename, 'w', self.encoding) - else: - self.stream = open(self.baseFilename, 'w') + self.mode = 'w' + self.stream = self._open() def shouldRollover(self, record): """ @@ -281,10 +279,8 @@ s.sort() os.remove(s[0]) #print "%s -> %s" % (self.baseFilename, dfn) - if self.encoding: - self.stream = codecs.open(self.baseFilename, 'w', self.encoding) - else: - self.stream = open(self.baseFilename, 'w') + self.mode = 'w' + self.stream = self._open() self.rolloverAt = self.rolloverAt + self.interval class WatchedFileHandler(logging.FileHandler): @@ -786,7 +782,7 @@ try: import smtplib try: - from email.Utils import formatdate + from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Thu Feb 1 19:02:27 2007 @@ -16,8 +16,8 @@ import errno import copy import email -import email.Message -import email.Generator +import email.message +import email.generator import rfc822 import StringIO try: @@ -193,9 +193,9 @@ # To get native line endings on disk, the user-friendly \n line endings # used in strings and by email.Message are translated here. """Dump message contents to target file.""" - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): buffer = StringIO.StringIO() - gen = email.Generator.Generator(buffer, mangle_from_, 0) + gen = email.generator.Generator(buffer, mangle_from_, 0) gen.flatten(message) buffer.seek(0) target.write(buffer.read().replace('\n', os.linesep)) @@ -704,7 +704,7 @@ message = '' elif isinstance(message, _mboxMMDFMessage): from_line = 'From ' + message.get_from() - elif isinstance(message, email.Message.Message): + elif isinstance(message, email.message.Message): from_line = message.get_unixfrom() # May be None. if from_line is None: from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime()) @@ -1254,9 +1254,9 @@ self._file.write(os.linesep) else: self._file.write('1,,' + os.linesep) - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): orig_buffer = StringIO.StringIO() - orig_generator = email.Generator.Generator(orig_buffer, False, 0) + orig_generator = email.generator.Generator(orig_buffer, False, 0) orig_generator.flatten(message) orig_buffer.seek(0) while True: @@ -1267,7 +1267,7 @@ self._file.write('*** EOOH ***' + os.linesep) if isinstance(message, BabylMessage): vis_buffer = StringIO.StringIO() - vis_generator = email.Generator.Generator(vis_buffer, False, 0) + vis_generator = email.generator.Generator(vis_buffer, False, 0) vis_generator.flatten(message.get_visible()) while True: line = vis_buffer.readline() @@ -1323,12 +1323,12 @@ return (start, stop) -class Message(email.Message.Message): +class Message(email.message.Message): """Message with mailbox-format-specific properties.""" def __init__(self, message=None): """Initialize a Message instance.""" - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): self._become_message(copy.deepcopy(message)) if isinstance(message, Message): message._explain_to(self) @@ -1337,7 +1337,7 @@ elif hasattr(message, "read"): self._become_message(email.message_from_file(message)) elif message is None: - email.Message.Message.__init__(self) + email.message.Message.__init__(self) else: raise TypeError('Invalid message type: %s' % type(message)) @@ -1468,7 +1468,7 @@ def __init__(self, message=None): """Initialize an mboxMMDFMessage instance.""" self.set_from('MAILER-DAEMON', True) - if isinstance(message, email.Message.Message): + if isinstance(message, email.message.Message): unixfrom = message.get_unixfrom() if unixfrom is not None and unixfrom.startswith('From '): self.set_from(unixfrom[5:]) @@ -1990,10 +1990,12 @@ # that the two characters preceding "From " are \n\n or the beginning of # the file. Fixing this would require a more extensive rewrite than is # necessary. For convenience, we've added a PortableUnixMailbox class - # which uses the more lenient _fromlinepattern regular expression. + # which does no checking of the format of the 'From' line. - _fromlinepattern = r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" \ - r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*$" + _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" + r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*" + r"[^\s]*\s*" + "$") _regexp = None def _strict_isrealfromline(self, line): Modified: python/branches/p3yk/Lib/ntpath.py ============================================================================== --- python/branches/p3yk/Lib/ntpath.py (original) +++ python/branches/p3yk/Lib/ntpath.py Thu Feb 1 19:02:27 2007 @@ -344,8 +344,10 @@ var = path[:index] if var in os.environ: res = res + os.environ[var] + else: + res = res + '${' + var + '}' except ValueError: - res = res + path + res = res + '${' + path index = pathlen - 1 else: var = '' @@ -357,8 +359,10 @@ c = path[index:index + 1] if var in os.environ: res = res + os.environ[var] + else: + res = res + '$' + var if c != '': - res = res + c + index = index - 1 else: res = res + c index = index + 1 Modified: python/branches/p3yk/Lib/pdb.py ============================================================================== --- python/branches/p3yk/Lib/pdb.py (original) +++ python/branches/p3yk/Lib/pdb.py Thu Feb 1 19:02:27 2007 @@ -479,7 +479,12 @@ def do_condition(self, arg): # arg is breakpoint number and condition args = arg.split(' ', 1) - bpnum = int(args[0].strip()) + try: + bpnum = int(args[0].strip()) + except ValueError: + # something went wrong + print >>self.stdout, \ + 'Breakpoint index %r is not a number' % args[0] try: cond = args[1] except: @@ -494,7 +499,12 @@ def do_ignore(self,arg): """arg is bp number followed by ignore count.""" args = arg.split() - bpnum = int(args[0].strip()) + try: + bpnum = int(args[0].strip()) + except ValueError: + # something went wrong + print >>self.stdout, \ + 'Breakpoint index %r is not a number' % args[0] try: count = int(args[1].strip()) except: Modified: python/branches/p3yk/Lib/random.py ============================================================================== --- python/branches/p3yk/Lib/random.py (original) +++ python/branches/p3yk/Lib/random.py Thu Feb 1 19:02:27 2007 @@ -569,7 +569,7 @@ def betavariate(self, alpha, beta): """Beta distribution. - Conditions on the parameters are alpha > -1 and beta} > -1. + Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. """ Modified: python/branches/p3yk/Lib/rfc822.py ============================================================================== --- python/branches/p3yk/Lib/rfc822.py (original) +++ python/branches/p3yk/Lib/rfc822.py Thu Feb 1 19:02:27 2007 @@ -850,6 +850,11 @@ if data[0][-1] in (',', '.') or data[0].lower() in _daynames: # There's a dayname here. Skip it del data[0] + else: + # no space after the "weekday,"? + i = data[0].rfind(',') + if i >= 0: + data[0] = data[0][i+1:] if len(data) == 3: # RFC 850 date, deprecated stuff = data[0].split('-') if len(stuff) == 3: Modified: python/branches/p3yk/Lib/smtplib.py ============================================================================== --- python/branches/p3yk/Lib/smtplib.py (original) +++ python/branches/p3yk/Lib/smtplib.py Thu Feb 1 19:02:27 2007 @@ -43,10 +43,10 @@ import socket import re -import email.Utils +import email.utils import base64 import hmac -from email.base64MIME import encode as encode_base64 +from email.base64mime import encode as encode_base64 from sys import stderr __all__ = ["SMTPException","SMTPServerDisconnected","SMTPResponseException", @@ -172,7 +172,7 @@ """ m = (None, None) try: - m = email.Utils.parseaddr(addr)[1] + m = email.utils.parseaddr(addr)[1] except AttributeError: pass if m == (None, None): # Indicates parse failure or AttributeError Modified: python/branches/p3yk/Lib/socket.py ============================================================================== --- python/branches/p3yk/Lib/socket.py (original) +++ python/branches/p3yk/Lib/socket.py Thu Feb 1 19:02:27 2007 @@ -204,9 +204,10 @@ __slots__ = ["mode", "bufsize", "softspace", # "closed" is a property, see below - "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"] + "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", + "_close"] - def __init__(self, sock, mode='rb', bufsize=-1): + def __init__(self, sock, mode='rb', bufsize=-1, close=False): self._sock = sock self.mode = mode # Not actually used in this version if bufsize < 0: @@ -222,6 +223,7 @@ self._wbufsize = bufsize self._rbuf = "" # A string self._wbuf = [] # A list of strings + self._close = close def _getclosed(self): return self._sock is None @@ -232,6 +234,8 @@ if self._sock: self.flush() finally: + if self._close: + self._sock.close() self._sock = None def __del__(self): Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Thu Feb 1 19:02:27 2007 @@ -1632,19 +1632,7 @@ # Create all upper directories. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): - ti = TarInfo() - ti.name = upperdirs - ti.type = DIRTYPE - ti.mode = 0777 - ti.mtime = tarinfo.mtime - ti.uid = tarinfo.uid - ti.gid = tarinfo.gid - ti.uname = tarinfo.uname - ti.gname = tarinfo.gname - try: - self._extract_member(ti, ti.name) - except: - pass + os.makedirs(upperdirs) if tarinfo.islnk() or tarinfo.issym(): self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) Modified: python/branches/p3yk/Lib/test/crashers/weakref_in_del.py ============================================================================== --- python/branches/p3yk/Lib/test/crashers/weakref_in_del.py (original) +++ python/branches/p3yk/Lib/test/crashers/weakref_in_del.py Thu Feb 1 19:02:27 2007 @@ -1,11 +1,12 @@ import weakref # http://python.org/sf/1377858 +# Fixed for new-style classes in 2.5c1. ref = None def test_weakref_in_del(): - class Target(object): + class Target(): def __del__(self): global ref ref = weakref.ref(self) Deleted: /python/branches/p3yk/Lib/test/output/test_new ============================================================================== --- /python/branches/p3yk/Lib/test/output/test_new Thu Feb 1 19:02:27 2007 +++ (empty file) @@ -1,6 +0,0 @@ -test_new -new.module() -new.classobj() -new.instancemethod() -new.function() -new.code() Deleted: /python/branches/p3yk/Lib/test/output/test_popen ============================================================================== --- /python/branches/p3yk/Lib/test/output/test_popen Thu Feb 1 19:02:27 2007 +++ (empty file) @@ -1,3 +0,0 @@ -test_popen -Test popen: -popen seemed to process the command-line correctly Deleted: /python/branches/p3yk/Lib/test/output/test_resource ============================================================================== --- /python/branches/p3yk/Lib/test/output/test_resource Thu Feb 1 19:02:27 2007 +++ (empty file) @@ -1,2 +0,0 @@ -test_resource -True Modified: python/branches/p3yk/Lib/test/test_array.py ============================================================================== --- python/branches/p3yk/Lib/test/test_array.py (original) +++ python/branches/p3yk/Lib/test/test_array.py Thu Feb 1 19:02:27 2007 @@ -12,6 +12,10 @@ class ArraySubclass(array.array): pass +class ArraySubclassWithKwargs(array.array): + def __init__(self, typecode, newarg=None): + array.array.__init__(typecode) + tests = [] # list to accumulate all tests typecodes = "cubBhHiIlLfd" @@ -683,6 +687,9 @@ b = array.array('B', range(64)) self.assertEqual(rc, sys.getrefcount(10)) + def test_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError + ArraySubclassWithKwargs('b', newarg=1) class StringTest(BaseTest): Modified: python/branches/p3yk/Lib/test/test_deque.py ============================================================================== --- python/branches/p3yk/Lib/test/test_deque.py (original) +++ python/branches/p3yk/Lib/test/test_deque.py Thu Feb 1 19:02:27 2007 @@ -486,6 +486,16 @@ d1 == d2 # not clear if this is supposed to be True or False, # but it used to give a SystemError + +class SubclassWithKwargs(deque): + def __init__(self, newarg=1): + deque.__init__(self) + +class TestSubclassWithKwargs(unittest.TestCase): + def test_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError + SubclassWithKwargs(newarg=1) + #============================================================================== libreftest = """ @@ -599,6 +609,7 @@ TestBasic, TestVariousIteratorArgs, TestSubclass, + TestSubclassWithKwargs, ) test_support.run_unittest(*test_classes) Modified: python/branches/p3yk/Lib/test/test_dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dumbdbm.py (original) +++ python/branches/p3yk/Lib/test/test_dumbdbm.py Thu Feb 1 19:02:27 2007 @@ -50,11 +50,17 @@ finally: os.umask(old_umask) + expected_mode = 0635 + if os.name != 'posix': + # Windows only supports setting the read-only attribute. + # This shouldn't fail, but doesn't work like Unix either. + expected_mode = 0666 + import stat st = os.stat(_fname + '.dat') - self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) st = os.stat(_fname + '.dir') - self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) def test_close_twice(self): f = dumbdbm.open(_fname) Modified: python/branches/p3yk/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_itertools.py (original) +++ python/branches/p3yk/Lib/test/test_itertools.py Thu Feb 1 19:02:27 2007 @@ -744,6 +744,21 @@ self.assertRaises(AssertionError, list, cycle(gen1())) self.assertEqual(hist, [0,1]) +class SubclassWithKwargsTest(unittest.TestCase): + def test_keywords_in_subclass(self): + # count is not subclassable... + for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap, + starmap, islice, takewhile, dropwhile, cycle): + class Subclass(cls): + def __init__(self, newarg=None, *args): + cls.__init__(self, *args) + try: + Subclass(newarg=1) + except TypeError as err: + # we expect type errors because of wrong argument count + self.failIf("does not take keyword arguments" in err.args[0]) + + libreftest = """ Doctest for examples in the library reference: libitertools.tex @@ -938,7 +953,8 @@ def test_main(verbose=None): test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC, - RegressionTests, LengthTransparency) + RegressionTests, LengthTransparency, + SubclassWithKwargsTest) test_support.run_unittest(*test_classes) # verify reference counting Modified: python/branches/p3yk/Lib/test/test_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_mailbox.py Thu Feb 1 19:02:27 2007 @@ -4,7 +4,7 @@ import stat import socket import email -import email.Message +import email.message import rfc822 import re import StringIO @@ -22,7 +22,7 @@ def _check_sample(self, msg): # Inspect a mailbox.Message representation of the sample message - self.assert_(isinstance(msg, email.Message.Message)) + self.assert_(isinstance(msg, email.message.Message)) self.assert_(isinstance(msg, mailbox.Message)) for key, value in _sample_headers.iteritems(): self.assert_(value in msg.get_all(key)) @@ -30,7 +30,7 @@ self.assert_(len(msg.get_payload()) == len(_sample_payloads)) for i, payload in enumerate(_sample_payloads): part = msg.get_payload(i) - self.assert_(isinstance(part, email.Message.Message)) + self.assert_(isinstance(part, email.message.Message)) self.assert_(not isinstance(part, mailbox.Message)) self.assert_(part.get_payload() == payload) @@ -939,7 +939,7 @@ self._delete_recursively(self._path) def test_initialize_with_eMM(self): - # Initialize based on email.Message.Message instance + # Initialize based on email.message.Message instance eMM = email.message_from_string(_sample_message) msg = self._factory(eMM) self._post_initialize_hook(msg) @@ -965,7 +965,7 @@ # Initialize without arguments msg = self._factory() self._post_initialize_hook(msg) - self.assert_(isinstance(msg, email.Message.Message)) + self.assert_(isinstance(msg, email.message.Message)) self.assert_(isinstance(msg, mailbox.Message)) self.assert_(isinstance(msg, self._factory)) self.assert_(msg.keys() == []) @@ -992,7 +992,7 @@ mailbox.BabylMessage, mailbox.MMDFMessage): other_msg = class_() msg._explain_to(other_msg) - other_msg = email.Message.Message() + other_msg = email.message.Message() self.assertRaises(TypeError, lambda: msg._explain_to(other_msg)) def _post_initialize_hook(self, msg): @@ -1732,11 +1732,11 @@ def test_unix_mbox(self): ### should be better! - import email.Parser + import email.parser fname = self.createMessage("cur", True) n = 0 for msg in mailbox.PortableUnixMailbox(open(fname), - email.Parser.Parser().parse): + email.parser.Parser().parse): n += 1 self.assertEqual(msg["subject"], "Simple Test") self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE)) Modified: python/branches/p3yk/Lib/test/test_new.py ============================================================================== --- python/branches/p3yk/Lib/test/test_new.py (original) +++ python/branches/p3yk/Lib/test/test_new.py Thu Feb 1 19:02:27 2007 @@ -1,180 +1,158 @@ -from test.test_support import verbose, verify, TestFailed -import sys -import new - -class Eggs: - def get_yolks(self): - return self.yolks - -print 'new.module()' -m = new.module('Spam') -if verbose: - print m -m.Eggs = Eggs -sys.modules['Spam'] = m -import Spam - -def get_more_yolks(self): - return self.yolks + 3 - -print 'new.classobj()' -C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks}) -if verbose: - print C - -def break_yolks(self): - self.yolks = self.yolks - 2 -print 'new.instancemethod()' -c = C() -c.yolks = 3 -im = new.instancemethod(break_yolks, c, C) -if verbose: - print im - -verify(c.get_yolks() == 3 and c.get_more_yolks() == 6, - 'Broken call of hand-crafted class instance') -im() -verify(c.get_yolks() == 1 and c.get_more_yolks() == 4, - 'Broken call of hand-crafted instance method') - -im = new.instancemethod(break_yolks, c) -im() -verify(c.get_yolks() == -1) -try: - new.instancemethod(break_yolks, None) -except TypeError: - pass -else: - raise TestFailed, "dangerous instance method creation allowed" - -# Verify that instancemethod() doesn't allow keyword args -try: - new.instancemethod(break_yolks, c, kw=1) -except TypeError: - pass -else: - raise TestFailed, "instancemethod shouldn't accept keyword args" - -# It's unclear what the semantics should be for a code object compiled at -# module scope, but bound and run in a function. In CPython, `c' is global -# (by accident?) while in Jython, `c' is local. The intent of the test -# clearly is to make `c' global, so let's be explicit about it. -codestr = ''' -global c -a = 1 -b = 2 -c = a + b -''' - -ccode = compile(codestr, '', 'exec') -# Jython doesn't have a __builtins__, so use a portable alternative -import __builtin__ -g = {'c': 0, '__builtins__': __builtin__} -# this test could be more robust -print 'new.function()' -func = new.function(ccode, g) -if verbose: - print func -func() -verify(g['c'] == 3, - 'Could not create a proper function object') - -# test the various extended flavors of function.new -def f(x): - def g(y): - return x + y - return g -g = f(4) -new.function(f.func_code, {}, "blah") -g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure) -verify(g2() == 6) -g3 = new.function(g.func_code, {}, "blah", None, g.func_closure) -verify(g3(5) == 9) -def test_closure(func, closure, exc): - try: - new.function(func.func_code, {}, "", None, closure) - except exc: - pass - else: - print "corrupt closure accepted" - -test_closure(g, None, TypeError) # invalid closure -test_closure(g, (1,), TypeError) # non-cell in closure -test_closure(g, (1, 1), ValueError) # closure is wrong size -test_closure(f, g.func_closure, ValueError) # no closure needed - -print 'new.code()' -# bogus test of new.code() -# Note: Jython will never have new.code() -if hasattr(new, 'code'): - def f(a): pass - - c = f.func_code - argcount = c.co_argcount - kwonlyargcount = c.co_kwonlyargcount - nlocals = c.co_nlocals - stacksize = c.co_stacksize - flags = c.co_flags - codestring = c.co_code - constants = c.co_consts - names = c.co_names - varnames = c.co_varnames - filename = c.co_filename - name = c.co_name - firstlineno = c.co_firstlineno - lnotab = c.co_lnotab - freevars = c.co_freevars - cellvars = c.co_cellvars - - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab, freevars, cellvars) - - # test backwards-compatibility version with no freevars or cellvars - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab) - - try: # this used to trigger a SystemError - d = new.code(-argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab) - except ValueError: - pass - else: - raise TestFailed, "negative co_argcount didn't trigger an exception" - - try: # this used to trigger a SystemError - d = new.code(argcount, kwonlyargcount, - -nlocals, stacksize, flags, codestring, - constants, names, varnames, filename, name, - firstlineno, lnotab) - except ValueError: - pass - else: - raise TestFailed, "negative co_nlocals didn't trigger an exception" - - try: # this used to trigger a Py_FatalError! - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, (5,), varnames, filename, name, - firstlineno, lnotab) - except TypeError: - pass - else: - raise TestFailed, "non-string co_name didn't trigger an exception" - - # new.code used to be a way to mutate a tuple... - class S(str): pass - t = (S("ab"),) - d = new.code(argcount, kwonlyargcount, - nlocals, stacksize, flags, codestring, - constants, t, varnames, filename, name, - firstlineno, lnotab) - verify(type(t[0]) is S, "eek, tuple changed under us!") +import unittest +from test import test_support +import sys, new + +class NewTest(unittest.TestCase): + def test_spam(self): + class Eggs: + def get_yolks(self): + return self.yolks + + m = new.module('Spam') + m.Eggs = Eggs + sys.modules['Spam'] = m + import Spam + + def get_more_yolks(self): + return self.yolks + 3 + + # new.classobj() + C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks}) + + def break_yolks(self): + self.yolks = self.yolks - 2 + + # new.instancemethod() + c = C() + c.yolks = 3 + im = new.instancemethod(break_yolks, c, C) + + self.assertEqual(c.get_yolks(), 3, + 'Broken call of hand-crafted class instance') + self.assertEqual(c.get_more_yolks(), 6, + 'Broken call of hand-crafted class instance') + + im() + self.assertEqual(c.get_yolks(), 1, + 'Broken call of hand-crafted instance method') + self.assertEqual(c.get_more_yolks(), 4, + 'Broken call of hand-crafted instance method') + + im = new.instancemethod(break_yolks, c) + im() + self.assertEqual(c.get_yolks(), -1) + + # Verify that dangerous instance method creation is forbidden + self.assertRaises(TypeError, new.instancemethod, break_yolks, None) + + # Verify that instancemethod() doesn't allow keyword args + self.assertRaises(TypeError, new.instancemethod, break_yolks, c, kw=1) + + def test_scope(self): + # It's unclear what the semantics should be for a code object compiled + # at module scope, but bound and run in a function. In CPython, `c' is + # global (by accident?) while in Jython, `c' is local. The intent of + # the test clearly is to make `c' global, so let's be explicit about it. + codestr = ''' + global c + a = 1 + b = 2 + c = a + b + ''' + + codestr = "\n".join(l.strip() for l in codestr.splitlines()) + + ccode = compile(codestr, '', 'exec') + # Jython doesn't have a __builtins__, so use a portable alternative + import __builtin__ + g = {'c': 0, '__builtins__': __builtin__} + + # this test could be more robust + func = new.function(ccode, g) + func() + self.assertEqual(g['c'], 3, 'Could not create a proper function object') + + def test_function(self): + # test the various extended flavors of function.new + def f(x): + def g(y): + return x + y + return g + g = f(4) + new.function(f.func_code, {}, "blah") + g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure) + self.assertEqual(g2(), 6) + g3 = new.function(g.func_code, {}, "blah", None, g.func_closure) + self.assertEqual(g3(5), 9) + def test_closure(func, closure, exc): + self.assertRaises(exc, new.function, func.func_code, {}, "", None, closure) + + test_closure(g, None, TypeError) # invalid closure + test_closure(g, (1,), TypeError) # non-cell in closure + test_closure(g, (1, 1), ValueError) # closure is wrong size + test_closure(f, g.func_closure, ValueError) # no closure needed + + # Note: Jython will never have new.code() + if hasattr(new, 'code'): + def test_code(self): + # bogus test of new.code() + def f(a): pass + + c = f.func_code + argcount = c.co_argcount + kwonlyargcount = c.co_kwonlyargcount + nlocals = c.co_nlocals + stacksize = c.co_stacksize + flags = c.co_flags + codestring = c.co_code + constants = c.co_consts + names = c.co_names + varnames = c.co_varnames + filename = c.co_filename + name = c.co_name + firstlineno = c.co_firstlineno + lnotab = c.co_lnotab + freevars = c.co_freevars + cellvars = c.co_cellvars + + d = new.code(argcount, kwonlyargcount, nlocals, stacksize, flags, + codestring, constants, names, varnames, filename, + name, firstlineno, lnotab, freevars, cellvars) + + # test backwards-compatibility version with no freevars or cellvars + d = new.code(argcount, kwonlyargcount, nlocals, stacksize, + flags, codestring, constants, names, varnames, + filename, name, firstlineno, lnotab) + + # negative co_argcount used to trigger a SystemError + self.assertRaises(ValueError, new.code, + -argcount, kwonlyargcount, nlocals, stacksize, flags, + codestring, constants, names, varnames, filename, name, + firstlineno, lnotab) + + # negative co_nlocals used to trigger a SystemError + self.assertRaises(ValueError, new.code, + argcount, kwonlyargcount, -nlocals, stacksize, flags, + codestring, constants, names, varnames, filename, name, + firstlineno, lnotab) + + # non-string co_name used to trigger a Py_FatalError + self.assertRaises(TypeError, new.code, + argcount, kwonlyargcount, nlocals, stacksize, flags, + codestring, constants, (5,), varnames, filename, name, + firstlineno, lnotab) + + # new.code used to be a way to mutate a tuple... + class S(str): + pass + t = (S("ab"),) + d = new.code(argcount, kwonlyargcount, nlocals, stacksize, + flags, codestring, constants, t, varnames, + filename, name, firstlineno, lnotab) + self.assert_(type(t[0]) is S, "eek, tuple changed under us!") - if verbose: - print d +def test_main(): + test_support.run_unittest(NewTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk/Lib/test/test_ntpath.py ============================================================================== --- python/branches/p3yk/Lib/test/test_ntpath.py (original) +++ python/branches/p3yk/Lib/test/test_ntpath.py Thu Feb 1 19:02:27 2007 @@ -115,6 +115,28 @@ tester("ntpath.normpath('C:////a/b')", r'C:\a\b') tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b') +oldenv = os.environ.copy() +try: + os.environ.clear() + os.environ["foo"] = "bar" + os.environ["{foo"] = "baz1" + os.environ["{foo}"] = "baz2" + tester('ntpath.expandvars("foo")', "foo") + tester('ntpath.expandvars("$foo bar")', "bar bar") + tester('ntpath.expandvars("${foo}bar")', "barbar") + tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar") + tester('ntpath.expandvars("$bar bar")', "$bar bar") + tester('ntpath.expandvars("$?bar")', "$?bar") + tester('ntpath.expandvars("${foo}bar")', "barbar") + tester('ntpath.expandvars("$foo}bar")', "bar}bar") + tester('ntpath.expandvars("${foo")', "${foo") + tester('ntpath.expandvars("${{foo}}")', "baz1}") + tester('ntpath.expandvars("$foo$foo")', "barbar") + tester('ntpath.expandvars("$bar$bar")', "$bar$bar") +finally: + os.environ.clear() + os.environ.update(oldenv) + # ntpath.abspath() can only be used on a system with the "nt" module # (reasonably), so we protect this test with "import nt". This allows # the rest of the tests for the ntpath module to be run to completion Modified: python/branches/p3yk/Lib/test/test_old_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_old_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_old_mailbox.py Thu Feb 1 19:02:27 2007 @@ -109,11 +109,44 @@ self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE)) self.assertEqual(n, 1) +class MboxTestCase(unittest.TestCase): + def setUp(self): + # create a new maildir mailbox to work with: + self._path = test_support.TESTFN + + def tearDown(self): + os.unlink(self._path) + + def test_from_regex (self): + # Testing new regex from bug #1633678 + f = open(self._path, 'w') + f.write("""From fred at example.com Mon May 31 13:24:50 2004 +0200 +Subject: message 1 + +body1 +From fred at example.com Mon May 31 13:24:50 2004 -0200 +Subject: message 2 + +body2 +From fred at example.com Mon May 31 13:24:50 2004 +Subject: message 3 + +body3 +From fred at example.com Mon May 31 13:24:50 2004 +Subject: message 4 + +body4 +""") + f.close() + box = mailbox.UnixMailbox(open(self._path, 'r')) + self.assert_(len(list(iter(box))) == 4) + + # XXX We still need more tests! def test_main(): - test_support.run_unittest(MaildirTestCase) + test_support.run_unittest(MaildirTestCase, MboxTestCase) if __name__ == "__main__": Modified: python/branches/p3yk/Lib/test/test_popen.py ============================================================================== --- python/branches/p3yk/Lib/test/test_popen.py (original) +++ python/branches/p3yk/Lib/test/test_popen.py Thu Feb 1 19:02:27 2007 @@ -4,10 +4,9 @@ Particularly useful for platforms that fake popen. """ -import os -import sys -from test.test_support import TestSkipped, reap_children -from os import popen +import unittest +from test import test_support +import os, sys # Test that command-lines get down as we expect. # To do this we execute: @@ -17,24 +16,32 @@ python = sys.executable if ' ' in python: python = '"' + python + '"' # quote embedded space for cmdline -def _do_test_commandline(cmdline, expected): - cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline) - data = popen(cmd).read() - got = eval(data)[1:] # strip off argv[0] - if got != expected: - print "Error in popen commandline handling." - print " executed '%s', expected '%r', but got '%r'" \ - % (cmdline, expected, got) - -def _test_commandline(): - _do_test_commandline("foo bar", ["foo", "bar"]) - _do_test_commandline('foo "spam and eggs" "silly walk"', ["foo", "spam and eggs", "silly walk"]) - _do_test_commandline('foo "a \\"quoted\\" arg" bar', ["foo", 'a "quoted" arg', "bar"]) - print "popen seemed to process the command-line correctly" - -def main(): - print "Test popen:" - _test_commandline() - reap_children() -main() +class PopenTest(unittest.TestCase): + def _do_test_commandline(self, cmdline, expected): + cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline) + data = os.popen(cmd).read() + got = eval(data)[1:] # strip off argv[0] + self.assertEqual(got, expected) + + def test_popen(self): + self.assertRaises(TypeError, os.popen) + self._do_test_commandline( + "foo bar", + ["foo", "bar"] + ) + self._do_test_commandline( + 'foo "spam and eggs" "silly walk"', + ["foo", "spam and eggs", "silly walk"] + ) + self._do_test_commandline( + 'foo "a \\"quoted\\" arg" bar', + ["foo", 'a "quoted" arg', "bar"] + ) + test_support.reap_children() + +def test_main(): + test_support.run_unittest(PopenTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk/Lib/test/test_posixpath.py ============================================================================== --- python/branches/p3yk/Lib/test/test_posixpath.py (original) +++ python/branches/p3yk/Lib/test/test_posixpath.py Thu Feb 1 19:02:27 2007 @@ -374,6 +374,8 @@ self.assertEqual(posixpath.expandvars("$foo}bar"), "bar}bar") self.assertEqual(posixpath.expandvars("${foo"), "${foo") self.assertEqual(posixpath.expandvars("${{foo}}"), "baz1}") + self.assertEqual(posixpath.expandvars("$foo$foo"), "barbar") + self.assertEqual(posixpath.expandvars("$bar$bar"), "$bar$bar") finally: os.environ.clear() os.environ.update(oldenv) Modified: python/branches/p3yk/Lib/test/test_random.py ============================================================================== --- python/branches/p3yk/Lib/test/test_random.py (original) +++ python/branches/p3yk/Lib/test/test_random.py Thu Feb 1 19:02:27 2007 @@ -517,6 +517,14 @@ # tests validity but not completeness of the __all__ list self.failUnless(set(random.__all__) <= set(dir(random))) + def test_random_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError + class Subclass(random.Random): + def __init__(self, newarg=None): + random.Random.__init__(self) + Subclass(newarg=1) + + def test_main(verbose=None): testclasses = [WichmannHill_TestBasicOps, MersenneTwister_TestBasicOps, Modified: python/branches/p3yk/Lib/test/test_resource.py ============================================================================== --- python/branches/p3yk/Lib/test/test_resource.py (original) +++ python/branches/p3yk/Lib/test/test_resource.py Thu Feb 1 19:02:27 2007 @@ -1,56 +1,96 @@ -import os -import resource +import unittest +from test import test_support -from test.test_support import TESTFN -# This test is checking a few specific problem spots. RLIMIT_FSIZE -# should be RLIM_INFINITY, which will be a really big number on a -# platform with large file support. On these platforms, we need to -# test that the get/setrlimit functions properly convert the number to -# a C long long and that the conversion doesn't raise an error. - -try: - cur, max = resource.getrlimit(resource.RLIMIT_FSIZE) -except AttributeError: - pass -else: - print resource.RLIM_INFINITY == max - resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) - -# Now check to see what happens when the RLIMIT_FSIZE is small. Some -# versions of Python were terminated by an uncaught SIGXFSZ, but -# pythonrun.c has been fixed to ignore that exception. If so, the -# write() should return EFBIG when the limit is exceeded. - -# At least one platform has an unlimited RLIMIT_FSIZE and attempts to -# change it raise ValueError instead. - -try: - try: - resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max)) - limit_set = 1 - except ValueError: - limit_set = 0 - f = open(TESTFN, "wb") - f.write("X" * 1024) - try: - f.write("Y") - f.flush() - except IOError: - if not limit_set: - raise - f.close() - os.unlink(TESTFN) -finally: - resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) - -# And be sure that setrlimit is checking for really large values -too_big = 10**50 -try: - resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max)) -except (OverflowError, ValueError): - pass -try: - resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big)) -except (OverflowError, ValueError): - pass +import os, resource + +# This test is checking a few specific problem spots with the resource module. + +class ResourceTest(unittest.TestCase): + + def test_args(self): + self.assertRaises(TypeError, resource.getrlimit) + self.assertRaises(TypeError, resource.getrlimit, 42, 42) + self.assertRaises(TypeError, resource.setrlimit) + self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42) + + def test_fsize_ismax(self): + + try: + (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) + except AttributeError: + pass + else: + # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really big + # number on a platform with large file support. On these platforms, + # we need to test that the get/setrlimit functions properly convert + # the number to a C long long and that the conversion doesn't raise + # an error. + self.assertEqual(resource.RLIM_INFINITY, max) + resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) + + def test_fsize_enforced(self): + try: + (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) + except AttributeError: + pass + else: + # Check to see what happens when the RLIMIT_FSIZE is small. Some + # versions of Python were terminated by an uncaught SIGXFSZ, but + # pythonrun.c has been fixed to ignore that exception. If so, the + # write() should return EFBIG when the limit is exceeded. + + # At least one platform has an unlimited RLIMIT_FSIZE and attempts + # to change it raise ValueError instead. + try: + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max)) + limit_set = True + except ValueError: + limit_set = False + f = open(test_support.TESTFN, "wb") + f.write("X" * 1024) + try: + f.write("Y") + f.flush() + except IOError: + if not limit_set: + raise + f.close() + os.unlink(test_support.TESTFN) + finally: + resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) + + def test_fsize_toobig(self): + # Be sure that setrlimit is checking for really large values + too_big = 10**50 + try: + (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) + except AttributeError: + pass + else: + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max)) + except (OverflowError, ValueError): + pass + try: + resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big)) + except (OverflowError, ValueError): + pass + + def test_getrusage(self): + self.assertRaises(TypeError, resource.getrusage) + self.assertRaises(TypeError, resource.getrusage, 42, 42) + usageself = resource.getrusage(resource.RUSAGE_SELF) + usagechildren = resource.getrusage(resource.RUSAGE_CHILDREN) + # May not be available on all systems. + try: + usageboth = resource.getrusage(resource.RUSAGE_BOTH) + except (ValueError, AttributeError): + pass + +def test_main(verbose=None): + test_support.run_unittest(ResourceTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk/Lib/test/test_socket.py ============================================================================== --- python/branches/p3yk/Lib/test/test_socket.py (original) +++ python/branches/p3yk/Lib/test/test_socket.py Thu Feb 1 19:02:27 2007 @@ -809,6 +809,31 @@ bufsize = 2 # Exercise the buffering code + +class Urllib2FileobjectTest(unittest.TestCase): + + # urllib2.HTTPHandler has "borrowed" socket._fileobject, and requires that + # it close the socket if the close c'tor argument is true + + def testClose(self): + class MockSocket: + closed = False + def flush(self): pass + def close(self): self.closed = True + + # must not close unless we request it: the original use of _fileobject + # by module socket requires that the underlying socket not be closed until + # the _socketobject that created the _fileobject is closed + s = MockSocket() + f = socket._fileobject(s) + f.close() + self.assert_(not s.closed) + + s = MockSocket() + f = socket._fileobject(s, close=True) + f.close() + self.assert_(s.closed) + class TCPTimeoutTest(SocketTCPTest): def testTCPTimeout(self): @@ -961,7 +986,8 @@ FileObjectClassTestCase, UnbufferedFileObjectClassTestCase, LineBufferedFileObjectClassTestCase, - SmallBufferedFileObjectClassTestCase + SmallBufferedFileObjectClassTestCase, + Urllib2FileobjectTest, ]) if hasattr(socket, "socketpair"): tests.append(BasicSocketPairTest) Modified: python/branches/p3yk/Lib/test/test_struct.py ============================================================================== --- python/branches/p3yk/Lib/test/test_struct.py (original) +++ python/branches/p3yk/Lib/test/test_struct.py Thu Feb 1 19:02:27 2007 @@ -84,8 +84,8 @@ if sz * 3 != struct.calcsize('iii'): raise TestFailed, 'inconsistent sizes' -fmt = 'cbxxxxxxhhhhiillffd' -fmt3 = '3c3b18x12h6i6l6f3d' +fmt = 'cbxxxxxxhhhhiillffdt' +fmt3 = '3c3b18x12h6i6l6f3d3t' sz = struct.calcsize(fmt) sz3 = struct.calcsize(fmt3) if sz * 3 != sz3: @@ -108,19 +108,21 @@ l = 65536 f = 3.1415 d = 3.1415 +t = True for prefix in ('', '@', '<', '>', '=', '!'): - for format in ('xcbhilfd', 'xcBHILfd'): + for format in ('xcbhilfdt', 'xcBHILfdt'): format = prefix + format if verbose: print "trying:", format - s = struct.pack(format, c, b, h, i, l, f, d) - cp, bp, hp, ip, lp, fp, dp = struct.unpack(format, s) + s = struct.pack(format, c, b, h, i, l, f, d, t) + cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s) if (cp != c or bp != b or hp != h or ip != i or lp != l or - int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d)): + int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d) or + tp != t): # ^^^ calculate only to two decimal places raise TestFailed, "unpack/pack not transitive (%s, %s)" % ( - str(format), str((cp, bp, hp, ip, lp, fp, dp))) + str(format), str((cp, bp, hp, ip, lp, fp, dp, tp))) # Test some of the new features in detail @@ -158,6 +160,11 @@ ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0), ('d', -2.0, '\300\000\000\000\000\000\000\000', '\000\000\000\000\000\000\000\300', 0), + ('t', 0, '\0', '\0', 0), + ('t', 3, '\1', '\1', 1), + ('t', True, '\1', '\1', 0), + ('t', [], '\0', '\0', 1), + ('t', (1,), '\1', '\1', 1), ] for fmt, arg, big, lil, asy in tests: @@ -612,3 +619,50 @@ test_unpack_from() test_pack_into() test_pack_into_fn() + +def test_bool(): + for prefix in tuple("<>!=")+('',): + false = (), [], [], '', 0 + true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2 + + falseFormat = prefix + 't' * len(false) + if verbose: + print 'trying bool pack/unpack on', false, 'using format', falseFormat + packedFalse = struct.pack(falseFormat, *false) + unpackedFalse = struct.unpack(falseFormat, packedFalse) + + trueFormat = prefix + 't' * len(true) + if verbose: + print 'trying bool pack/unpack on', true, 'using format', trueFormat + packedTrue = struct.pack(trueFormat, *true) + unpackedTrue = struct.unpack(trueFormat, packedTrue) + + if len(true) != len(unpackedTrue): + raise TestFailed('unpacked true array is not of same size as input') + if len(false) != len(unpackedFalse): + raise TestFailed('unpacked false array is not of same size as input') + + for t in unpackedFalse: + if t is not False: + raise TestFailed('%r did not unpack as False' % t) + for t in unpackedTrue: + if t is not True: + raise TestFailed('%r did not unpack as false' % t) + + if prefix and verbose: + print 'trying size of bool with format %r' % (prefix+'t') + packed = struct.pack(prefix+'t', 1) + + if len(packed) != struct.calcsize(prefix+'t'): + raise TestFailed('packed length is not equal to calculated size') + + if len(packed) != 1 and prefix: + raise TestFailed('encoded bool is not one byte: %r' % packed) + elif not prefix and verbose: + print 'size of bool in native format is %i' % (len(packed)) + + for c in '\x01\x7f\xff\x0f\xf0': + if struct.unpack('>t', c)[0] is not True: + raise TestFailed('%c did not unpack as True' % c) + +test_bool() Modified: python/branches/p3yk/Lib/test/test_urllib2net.py ============================================================================== --- python/branches/p3yk/Lib/test/test_urllib2net.py (original) +++ python/branches/p3yk/Lib/test/test_urllib2net.py Thu Feb 1 19:02:27 2007 @@ -64,6 +64,27 @@ # urllib2.urlopen, "http://evil:thing at example.com") +class CloseSocketTest(unittest.TestCase): + + def test_close(self): + import socket, httplib, gc + + # calling .close() on urllib2's response objects should close the + # underlying socket + + # delve deep into response to fetch socket._socketobject + response = urllib2.urlopen("http://www.python.org/") + abused_fileobject = response.fp + self.assert_(abused_fileobject.__class__ is socket._fileobject) + httpresponse = abused_fileobject._sock + self.assert_(httpresponse.__class__ is httplib.HTTPResponse) + fileobject = httpresponse.fp + self.assert_(fileobject.__class__ is socket._fileobject) + + self.assert_(not fileobject.closed) + response.close() + self.assert_(fileobject.closed) + class urlopenNetworkTests(unittest.TestCase): """Tests urllib2.urlopen using the network. @@ -263,8 +284,12 @@ def test_main(): test_support.requires("network") - test_support.run_unittest(URLTimeoutTest, urlopenNetworkTests, - AuthTests, OtherNetworkTests) + test_support.run_unittest(URLTimeoutTest, + urlopenNetworkTests, + AuthTests, + OtherNetworkTests, + CloseSocketTest, + ) if __name__ == "__main__": test_main() Modified: python/branches/p3yk/Lib/test/test_uu.py ============================================================================== --- python/branches/p3yk/Lib/test/test_uu.py (original) +++ python/branches/p3yk/Lib/test/test_uu.py Thu Feb 1 19:02:27 2007 @@ -114,11 +114,11 @@ def test_encode(self): try: - fin = open(self.tmpin, 'w') + fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() - fin = open(self.tmpin, 'r') + fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() Modified: python/branches/p3yk/Lib/test/test_weakref.py ============================================================================== --- python/branches/p3yk/Lib/test/test_weakref.py (original) +++ python/branches/p3yk/Lib/test/test_weakref.py Thu Feb 1 19:02:27 2007 @@ -6,6 +6,8 @@ from test import test_support +# Used in ReferencesTestCase.test_ref_created_during_del() . +ref_from_del = None class C: def method(self): @@ -630,6 +632,18 @@ finally: gc.set_threshold(*thresholds) + def test_ref_created_during_del(self): + # Bug #1377858 + # A weakref created in an object's __del__() would crash the + # interpreter when the weakref was cleaned up since it would refer to + # non-existent memory. This test should not segfault the interpreter. + class Target(object): + def __del__(self): + global ref_from_del + ref_from_del = weakref.ref(self) + + w = Target() + class SubclassableWeakrefTestCase(unittest.TestCase): Modified: python/branches/p3yk/Lib/urllib.py ============================================================================== --- python/branches/p3yk/Lib/urllib.py (original) +++ python/branches/p3yk/Lib/urllib.py Thu Feb 1 19:02:27 2007 @@ -452,7 +452,7 @@ def open_local_file(self, url): """Use local file.""" - import mimetypes, mimetools, email.Utils + import mimetypes, mimetools, email.utils try: from cStringIO import StringIO except ImportError: @@ -464,7 +464,7 @@ except OSError as e: raise IOError(e.errno, e.strerror, e.filename) size = stats.st_size - modified = email.Utils.formatdate(stats.st_mtime, usegmt=True) + modified = email.utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % Modified: python/branches/p3yk/Lib/urllib2.py ============================================================================== --- python/branches/p3yk/Lib/urllib2.py (original) +++ python/branches/p3yk/Lib/urllib2.py Thu Feb 1 19:02:27 2007 @@ -1087,7 +1087,7 @@ # out of socket._fileobject() and into a base class. r.recv = r.read - fp = socket._fileobject(r) + fp = socket._fileobject(r, close=True) resp = addinfourl(fp, r.msg, req.get_full_url()) resp.code = r.status @@ -1209,14 +1209,14 @@ # not entirely sure what the rules are here def open_local_file(self, req): - import email.Utils + import email.utils import mimetypes host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats.st_size - modified = email.Utils.formatdate(stats.st_mtime, usegmt=True) + modified = email.utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(file)[0] headers = mimetools.Message(StringIO( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % Modified: python/branches/p3yk/Modules/_ctypes/_ctypes_test.c ============================================================================== --- python/branches/p3yk/Modules/_ctypes/_ctypes_test.c (original) +++ python/branches/p3yk/Modules/_ctypes/_ctypes_test.c Thu Feb 1 19:02:27 2007 @@ -68,22 +68,25 @@ EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d) { -// printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", -// b, h, i, l, f, d); +/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ return (int)(b + h + i + l + f + d); } EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d) { -// printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", -// b, h, i, l, f, d); +/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ return (float)(b + h + i + l + f + d); } EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d) { -// printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", -// b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ return (double)(b + h + i + l + f + d); } @@ -378,8 +381,9 @@ } PyMethodDef module_methods[] = { -// {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, -// {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, + {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +*/ {"func_si", py_func_si, METH_VARARGS}, {"func", py_func, METH_NOARGS}, { NULL, NULL, 0, NULL}, Modified: python/branches/p3yk/Modules/_randommodule.c ============================================================================== --- python/branches/p3yk/Modules/_randommodule.c (original) +++ python/branches/p3yk/Modules/_randommodule.c Thu Feb 1 19:02:27 2007 @@ -481,7 +481,7 @@ RandomObject *self; PyObject *tmp; - if (!_PyArg_NoKeywords("Random()", kwds)) + if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds)) return NULL; self = (RandomObject *)type->tp_alloc(type, 0); Modified: python/branches/p3yk/Modules/_struct.c ============================================================================== --- python/branches/p3yk/Modules/_struct.c (original) +++ python/branches/p3yk/Modules/_struct.c Thu Feb 1 19:02:27 2007 @@ -104,6 +104,15 @@ #define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG)) #endif +#ifdef HAVE_C99_BOOL +#define BOOL_TYPE _Bool +typedef struct { char c; _Bool x; } s_bool; +#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE)) +#else +#define BOOL_TYPE char +#define BOOL_ALIGN 0 +#endif + #define STRINGIFY(x) #x #ifdef __powerc @@ -534,6 +543,15 @@ #endif static PyObject * +nu_bool(const char *p, const formatdef *f) +{ + BOOL_TYPE x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); +} + + +static PyObject * nu_float(const char *p, const formatdef *f) { float x; @@ -709,6 +727,16 @@ } #endif + +static int +np_bool(char *p, PyObject *v, const formatdef *f) +{ + BOOL_TYPE y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; +} + static int np_float(char *p, PyObject *v, const formatdef *f) { @@ -769,6 +797,7 @@ {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, #endif + {'t', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, @@ -863,6 +892,14 @@ return unpack_double(p, 0); } +static PyObject * +bu_bool(const char *p, const formatdef *f) +{ + char x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); +} + static int bp_int(char *p, PyObject *v, const formatdef *f) { @@ -967,6 +1004,15 @@ return _PyFloat_Pack8(x, (unsigned char *)p, 0); } +static int +bp_bool(char *p, PyObject *v, const formatdef *f) +{ + char y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; +} + static formatdef bigendian_table[] = { {'x', 1, 0, NULL}, #ifdef PY_STRUCT_OVERFLOW_MASKING @@ -988,6 +1034,7 @@ {'L', 4, 0, bu_uint, bp_uint}, {'q', 8, 0, bu_longlong, bp_longlong}, {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, + {'t', 1, 0, bu_bool, bp_bool}, {'f', 4, 0, bu_float, bp_float}, {'d', 8, 0, bu_double, bp_double}, {0} @@ -1206,6 +1253,8 @@ {'L', 4, 0, lu_uint, lp_uint}, {'q', 8, 0, lu_longlong, lp_longlong}, {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, + {'t', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, + but potentially different from native rep -- reuse bx_bool funcs. */ {'f', 4, 0, lu_float, lp_float}, {'d', 8, 0, lu_double, lp_double}, {0} Modified: python/branches/p3yk/Modules/arraymodule.c ============================================================================== --- python/branches/p3yk/Modules/arraymodule.c (original) +++ python/branches/p3yk/Modules/arraymodule.c Thu Feb 1 19:02:27 2007 @@ -1797,7 +1797,7 @@ PyObject *initial = NULL, *it = NULL; struct arraydescr *descr; - if (!_PyArg_NoKeywords("array.array()", kwds)) + if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds)) return NULL; if (!PyArg_ParseTuple(args, "c|O:array", &c, &initial)) Modified: python/branches/p3yk/Modules/collectionsmodule.c ============================================================================== --- python/branches/p3yk/Modules/collectionsmodule.c (original) +++ python/branches/p3yk/Modules/collectionsmodule.c Thu Feb 1 19:02:27 2007 @@ -95,7 +95,7 @@ dequeobject *deque; block *b; - if (!_PyArg_NoKeywords("deque()", kwds)) + if (type == &deque_type && !_PyArg_NoKeywords("deque()", kwds)) return NULL; /* create dequeobject structure */ Modified: python/branches/p3yk/Modules/itertoolsmodule.c ============================================================================== --- python/branches/p3yk/Modules/itertoolsmodule.c (original) +++ python/branches/p3yk/Modules/itertoolsmodule.c Thu Feb 1 19:02:27 2007 @@ -681,7 +681,7 @@ PyObject *saved; cycleobject *lz; - if (!_PyArg_NoKeywords("cycle()", kwds)) + if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable)) @@ -831,7 +831,7 @@ PyObject *it; dropwhileobject *lz; - if (!_PyArg_NoKeywords("dropwhile()", kwds)) + if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq)) @@ -975,7 +975,7 @@ PyObject *it; takewhileobject *lz; - if (!_PyArg_NoKeywords("takewhile()", kwds)) + if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq)) @@ -1120,7 +1120,7 @@ Py_ssize_t numargs; isliceobject *lz; - if (!_PyArg_NoKeywords("islice()", kwds)) + if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3)) @@ -1311,7 +1311,7 @@ PyObject *it; starmapobject *lz; - if (!_PyArg_NoKeywords("starmap()", kwds)) + if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq)) @@ -1443,7 +1443,7 @@ imapobject *lz; Py_ssize_t numargs, i; - if (!_PyArg_NoKeywords("imap()", kwds)) + if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds)) return NULL; numargs = PyTuple_Size(args); @@ -1625,7 +1625,7 @@ Py_ssize_t i; PyObject *ittuple; - if (!_PyArg_NoKeywords("chain()", kwds)) + if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) return NULL; /* obtain iterators */ @@ -1768,7 +1768,7 @@ PyObject *it; ifilterobject *lz; - if (!_PyArg_NoKeywords("ifilter()", kwds)) + if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq)) @@ -1912,7 +1912,8 @@ PyObject *it; ifilterfalseobject *lz; - if (!_PyArg_NoKeywords("ifilterfalse()", kwds)) + if (type == &ifilterfalse_type && + !_PyArg_NoKeywords("ifilterfalse()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq)) @@ -2054,7 +2055,7 @@ countobject *lz; Py_ssize_t cnt = 0; - if (!_PyArg_NoKeywords("count()", kwds)) + if (type == &count_type && !_PyArg_NoKeywords("count()", kwds)) return NULL; if (!PyArg_ParseTuple(args, "|n:count", &cnt)) @@ -2153,7 +2154,7 @@ PyObject *result; Py_ssize_t tuplesize = PySequence_Length(args); - if (!_PyArg_NoKeywords("izip()", kwds)) + if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds)) return NULL; /* args must be a tuple */ @@ -2336,7 +2337,7 @@ PyObject *element; Py_ssize_t cnt = -1; - if (!_PyArg_NoKeywords("repeat()", kwds)) + if (type == &repeat_type && !_PyArg_NoKeywords("repeat()", kwds)) return NULL; if (!PyArg_ParseTuple(args, "O|n:repeat", &element, &cnt)) Modified: python/branches/p3yk/Objects/fileobject.c ============================================================================== --- python/branches/p3yk/Objects/fileobject.c (original) +++ python/branches/p3yk/Objects/fileobject.c Thu Feb 1 19:02:27 2007 @@ -354,6 +354,8 @@ { PyFileObject *file = (PyFileObject*)f; PyObject *str = PyString_FromString(enc); + + assert(PyFile_Check(f)); if (!str) return 0; Py_DECREF(file->f_encoding); Modified: python/branches/p3yk/Objects/object.c ============================================================================== --- python/branches/p3yk/Objects/object.c (original) +++ python/branches/p3yk/Objects/object.c Thu Feb 1 19:02:27 2007 @@ -314,7 +314,7 @@ /* For debugging convenience. Set a breakpoint here and call it from your DLL */ void -_Py_Break(void) +_Py_BreakPoint(void) { } Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Thu Feb 1 19:02:27 2007 @@ -655,6 +655,17 @@ goto endlabel; /* resurrected */ else _PyObject_GC_UNTRACK(self); + /* New weakrefs could be created during the finalizer call. + If this occurs, clear them out without calling their + finalizers since they might rely on part of the object + being finalized that has already been destroyed. */ + if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { + /* Modeled after GET_WEAKREFS_LISTPTR() */ + PyWeakReference **list = (PyWeakReference **) \ + PyObject_GET_WEAKREFS_LISTPTR(self); + while (*list) + _PyWeakref_ClearRef(*list); + } } /* Clear slots up to the nearest base with a different tp_dealloc */ Modified: python/branches/p3yk/Objects/weakrefobject.c ============================================================================== --- python/branches/p3yk/Objects/weakrefobject.c (original) +++ python/branches/p3yk/Objects/weakrefobject.c Thu Feb 1 19:02:27 2007 @@ -57,6 +57,9 @@ PyWeakref_GET_OBJECT(self)); if (*list == self) + /* If 'self' is the end of the list (and thus self->wr_next == NULL) + then the weakref list itself (and thus the value of *list) will + end up being set to NULL. */ *list = self->wr_next; self->wr_object = Py_None; if (self->wr_prev != NULL) Modified: python/branches/p3yk/PCbuild/_bsddb.vcproj ============================================================================== --- python/branches/p3yk/PCbuild/_bsddb.vcproj (original) +++ python/branches/p3yk/PCbuild/_bsddb.vcproj Thu Feb 1 19:02:27 2007 @@ -130,7 +130,7 @@ ATLMinimizesCRunTimeLibraryUsage="FALSE"> f_tstate; + PyThreadState *tstate = PyThreadState_GET(); PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback; PyTracebackObject *tb = newtracebackobject(oldtb, frame); if (tb == NULL) Modified: python/branches/p3yk/Tools/msi/uuids.py ============================================================================== --- python/branches/p3yk/Tools/msi/uuids.py (original) +++ python/branches/p3yk/Tools/msi/uuids.py Thu Feb 1 19:02:27 2007 @@ -33,4 +33,8 @@ '2.5.121': '{8e9321bc-6b24-48a3-8fd4-c95f8e531e5f}', # 2.5c1 '2.5.122': '{a6cd508d-9599-45da-a441-cbffa9f7e070}', # 2.5c2 '2.5.150': '{0a2c5854-557e-48c8-835a-3b9f074bdcaa}', # 2.5.0 + '2.5.1121':'{0378b43e-6184-4c2f-be1a-4a367781cd54}', # 2.5.1c1 + '2.5.1150':'{31800004-6386-4999-a519-518f2d78d8f0}', # 2.5.1 + '2.5.2150':'{6304a7da-1132-4e91-a343-a296269eab8a}', # 2.5.2c1 + '2.5.2150':'{6b976adf-8ae8-434e-b282-a06c7f624d2f}', # 2.5.2 } Modified: python/branches/p3yk/configure ============================================================================== --- python/branches/p3yk/configure (original) +++ python/branches/p3yk/configure Thu Feb 1 19:02:27 2007 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 51211 . +# From configure.in Revision: 53017 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -10608,6 +10608,467 @@ fi +{ echo "$as_me:$LINENO: checking for _Bool support" >&5 +echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; } +have_c99_bool=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +_Bool x; x = (_Bool)0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + + +cat >>confdefs.h <<\_ACEOF +#define HAVE_C99_BOOL 1 +_ACEOF + + have_c99_bool=yes + +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5 +echo "${ECHO_T}$have_c99_bool" >&6; } +if test "$have_c99_bool" = yes ; then +{ echo "$as_me:$LINENO: checking for _Bool" >&5 +echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } +if test "${ac_cv_type__Bool+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +typedef _Bool ac__type_new_; +int +main () +{ +if ((ac__type_new_ *) 0) + return 0; +if (sizeof (ac__type_new_)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type__Bool=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type__Bool=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 +echo "${ECHO_T}$ac_cv_type__Bool" >&6; } + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ echo "$as_me:$LINENO: checking size of _Bool" >&5 +echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; } +if test "${ac_cv_sizeof__Bool+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then + # Depending upon the size, compute the lo and hi bounds. +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_lo=0 ac_mid=0 + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=$ac_mid; break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo=`expr $ac_mid + 1` + if test $ac_lo -le $ac_mid; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid + 1` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=-1 ac_mid=-1 + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_lo=$ac_mid; break +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_hi=`expr '(' $ac_mid ')' - 1` + if test $ac_mid -le $ac_hi; then + ac_lo= ac_hi= + break + fi + ac_mid=`expr 2 '*' $ac_mid` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo= ac_hi= +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# Binary search between lo and hi bounds. +while test "x$ac_lo" != "x$ac_hi"; do + ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +int +main () +{ +static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +test_array [0] = 0 + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_hi=$ac_mid +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_lo=`expr '(' $ac_mid ')' + 1` +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +done +case $ac_lo in +?*) ac_cv_sizeof__Bool=$ac_lo;; +'') if test "$ac_cv_type__Bool" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } + else + ac_cv_sizeof__Bool=0 + fi ;; +esac +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + typedef _Bool ac__type_sizeof_; +static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } +static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +#include +#include +int +main () +{ + + FILE *f = fopen ("conftest.val", "w"); + if (! f) + return 1; + if (((long int) (sizeof (ac__type_sizeof_))) < 0) + { + long int i = longval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; + fprintf (f, "%ld\n", i); + } + else + { + unsigned long int i = ulongval (); + if (i != ((long int) (sizeof (ac__type_sizeof_)))) + return 1; + fprintf (f, "%lu\n", i); + } + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_sizeof__Bool=`cat conftest.val` +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +if test "$ac_cv_type__Bool" = yes; then + { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute sizeof (_Bool) +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } + else + ac_cv_sizeof__Bool=0 + fi +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi +rm -f conftest.val +fi +{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 +echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF__BOOL $ac_cv_sizeof__Bool +_ACEOF + + +fi + { echo "$as_me:$LINENO: checking for uintptr_t" >&5 echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } if test "${ac_cv_type_uintptr_t+set}" = set; then Modified: python/branches/p3yk/configure.in ============================================================================== --- python/branches/p3yk/configure.in (original) +++ python/branches/p3yk/configure.in Thu Feb 1 19:02:27 2007 @@ -1218,6 +1218,17 @@ AC_CHECK_SIZEOF(long long, 8) fi +AC_MSG_CHECKING(for _Bool support) +have_c99_bool=no +AC_TRY_COMPILE([], [_Bool x; x = (_Bool)0;], [ + AC_DEFINE(HAVE_C99_BOOL, 1, [Define this if you have the type _Bool.]) + have_c99_bool=yes +]) +AC_MSG_RESULT($have_c99_bool) +if test "$have_c99_bool" = yes ; then +AC_CHECK_SIZEOF(_Bool, 1) +fi + AC_CHECK_TYPES(uintptr_t, [AC_CHECK_SIZEOF(uintptr_t, 4)], [], [#ifdef HAVE_STDINT_H Modified: python/branches/p3yk/pyconfig.h.in ============================================================================== --- python/branches/p3yk/pyconfig.h.in (original) +++ python/branches/p3yk/pyconfig.h.in Thu Feb 1 19:02:27 2007 @@ -64,6 +64,9 @@ /* Define if pthread_sigmask() does not work on your system. */ #undef HAVE_BROKEN_PTHREAD_SIGMASK +/* Define this if you have the type _Bool. */ +#undef HAVE_C99_BOOL + /* Define to 1 if you have the `chown' function. */ #undef HAVE_CHOWN @@ -835,6 +838,9 @@ /* The size of a `wchar_t', as computed by sizeof. */ #undef SIZEOF_WCHAR_T +/* The size of a `_Bool', as computed by sizeof. */ +#undef SIZEOF__BOOL + /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS From python-3000-checkins at python.org Sat Feb 3 22:49:08 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Sat, 3 Feb 2007 22:49:08 +0100 (CET) Subject: [Python-3000-checkins] r53627 - in python/branches/p3yk/Lib: pydoc.py test/test_pyclbr.py Message-ID: <20070203214908.134871E400A@bag.python.org> Author: thomas.wouters Date: Sat Feb 3 22:49:06 2007 New Revision: 53627 Modified: python/branches/p3yk/Lib/pydoc.py python/branches/p3yk/Lib/test/test_pyclbr.py Log: - Fix conversion glitch in test_pyclbr, which caused a test to not fail when it should. - Remove unneeded classic-class support from pydoc (which would otherwise cause test_pyclbr to fail.) Modified: python/branches/p3yk/Lib/pydoc.py ============================================================================== --- python/branches/p3yk/Lib/pydoc.py (original) +++ python/branches/p3yk/Lib/pydoc.py Sat Feb 3 22:49:06 2007 @@ -1448,9 +1448,6 @@ text = TextDoc() html = HTMLDoc() -class _OldStyleClass: pass -_OLD_INSTANCE_TYPE = type(_OldStyleClass()) - def resolve(thing, forceload=0): """Given an object or a path to an object, get the object and its name.""" if isinstance(thing, str): @@ -1471,10 +1468,6 @@ desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ - if type(object) is _OLD_INSTANCE_TYPE: - # If the passed object is an instance of an old-style class, - # document its available methods instead of its value. - object = object.__class__ elif not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or Modified: python/branches/p3yk/Lib/test/test_pyclbr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pyclbr.py (original) +++ python/branches/p3yk/Lib/test/test_pyclbr.py Sat Feb 3 22:49:06 2007 @@ -44,7 +44,7 @@ if key in ignore: return if key not in obj: print >>sys.stderr, "***",key - self.failUnless(key) in obj + self.failUnless(key in obj) def assertEqualsOrIgnored(self, a, b, ignore): ''' succeed iff a == b or a in ignore or b in ignore ''' From python-3000-checkins at python.org Mon Feb 5 02:24:28 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Mon, 5 Feb 2007 02:24:28 +0100 (CET) Subject: [Python-3000-checkins] r53634 - in python/branches/p3yk: Doc/howto/TODO Doc/howto/curses.tex Doc/howto/doanddont.tex Doc/howto/regex.tex Doc/lib/libexcs.tex Doc/lib/libimageop.tex Doc/lib/libmailbox.tex Doc/ref/ref4.tex Doc/tut/tut.tex Doc/whatsnew/whatsnew26.tex Lib/CGIHTTPServer.py Lib/_strptime.py Lib/compiler/pycodegen.py Lib/compiler/transformer.py Lib/cookielib.py Lib/dumbdbm.py Lib/dummy_thread.py Lib/dummy_threading.py Lib/email/charset.py Lib/encodings/aliases.py Lib/ftplib.py Lib/httplib.py Lib/idlelib/CodeContext.py Lib/lib-tk/tkSimpleDialog.py Lib/mailbox.py Lib/platform.py Lib/pty.py Lib/subprocess.py Lib/test/test_cfgparser.py Lib/test/test_compiler.py Lib/test/test_dumbdbm.py Lib/test/test_exceptions.py Lib/test/test_gzip.py Lib/test/test_mailbox.py Lib/test/test_old_mailbox.py Lib/test/test_pep352.py Lib/test/test_pty.py Lib/test/test_resource.py Lib/test/test_set.py Lib/test/test_strptime.py Lib/test/test_struct.py Lib/test/test_support.py Modules/_ctypes/cfield.c Modules/posixmodule.c Objects/setobject.c Python/ceval.c Message-ID: <20070205012428.AE80B1E400E@bag.python.org> Author: thomas.wouters Date: Mon Feb 5 02:24:16 2007 New Revision: 53634 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/howto/TODO python/branches/p3yk/Doc/howto/curses.tex python/branches/p3yk/Doc/howto/doanddont.tex python/branches/p3yk/Doc/howto/regex.tex python/branches/p3yk/Doc/lib/libexcs.tex python/branches/p3yk/Doc/lib/libimageop.tex python/branches/p3yk/Doc/lib/libmailbox.tex python/branches/p3yk/Doc/ref/ref4.tex python/branches/p3yk/Doc/tut/tut.tex python/branches/p3yk/Doc/whatsnew/whatsnew26.tex python/branches/p3yk/Lib/CGIHTTPServer.py python/branches/p3yk/Lib/_strptime.py python/branches/p3yk/Lib/compiler/pycodegen.py python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/cookielib.py python/branches/p3yk/Lib/dumbdbm.py python/branches/p3yk/Lib/dummy_thread.py python/branches/p3yk/Lib/dummy_threading.py python/branches/p3yk/Lib/email/charset.py python/branches/p3yk/Lib/encodings/aliases.py python/branches/p3yk/Lib/ftplib.py python/branches/p3yk/Lib/httplib.py python/branches/p3yk/Lib/idlelib/CodeContext.py python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/platform.py python/branches/p3yk/Lib/pty.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/test/test_cfgparser.py python/branches/p3yk/Lib/test/test_compiler.py python/branches/p3yk/Lib/test/test_dumbdbm.py python/branches/p3yk/Lib/test/test_exceptions.py python/branches/p3yk/Lib/test/test_gzip.py python/branches/p3yk/Lib/test/test_mailbox.py python/branches/p3yk/Lib/test/test_old_mailbox.py python/branches/p3yk/Lib/test/test_pep352.py python/branches/p3yk/Lib/test/test_pty.py python/branches/p3yk/Lib/test/test_resource.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Lib/test/test_strptime.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_support.py python/branches/p3yk/Modules/_ctypes/cfield.c python/branches/p3yk/Modules/posixmodule.c python/branches/p3yk/Objects/setobject.c python/branches/p3yk/Python/ceval.c Log: Merged revisions 53538-53622 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53545 | andrew.kuchling | 2007-01-24 21:06:41 +0100 (Wed, 24 Jan 2007) | 1 line Strengthen warning about using lock() ........ r53556 | thomas.heller | 2007-01-25 19:34:14 +0100 (Thu, 25 Jan 2007) | 3 lines Fix for #1643874: When calling SysAllocString, create a PyCObject which will eventually call SysFreeString to free the BSTR resource. ........ r53563 | andrew.kuchling | 2007-01-25 21:02:13 +0100 (Thu, 25 Jan 2007) | 1 line Add item ........ r53564 | brett.cannon | 2007-01-25 21:22:02 +0100 (Thu, 25 Jan 2007) | 8 lines Fix time.strptime's %U support. Basically rewrote the algorithm to be more generic so that one only has to shift certain values based on whether the week was specified to start on Monday or Sunday. Cut out a lot of edge case code compared to the previous version. Also broke algorithm out into its own function (that is private to the module). Fixes bug #1643943 (thanks Biran Nahas for the report). ........ r53570 | brett.cannon | 2007-01-26 00:30:39 +0100 (Fri, 26 Jan 2007) | 4 lines Remove specific mention of my name and email address from modules. Not really needed and all bug reports should go to the bug tracker, not directly to me. Plus I am not the only person to have edited these files at this point. ........ r53573 | fred.drake | 2007-01-26 17:28:44 +0100 (Fri, 26 Jan 2007) | 1 line fix typo (extraneous ")") ........ r53575 | georg.brandl | 2007-01-27 18:43:02 +0100 (Sat, 27 Jan 2007) | 4 lines Patch #1638243: the compiler package is now able to correctly compile a with statement; previously, executing code containing a with statement compiled by the compiler package crashed the interpreter. ........ r53578 | georg.brandl | 2007-01-27 18:59:42 +0100 (Sat, 27 Jan 2007) | 3 lines Patch #1634778: add missing encoding aliases for iso8859_15 and iso8859_16. ........ r53579 | georg.brandl | 2007-01-27 20:38:50 +0100 (Sat, 27 Jan 2007) | 2 lines Bug #1645944: os.access now returns bool but docstring is not updated ........ r53590 | brett.cannon | 2007-01-28 21:58:00 +0100 (Sun, 28 Jan 2007) | 2 lines Use the thread lock's context manager instead of a try/finally statement. ........ r53591 | brett.cannon | 2007-01-29 05:41:44 +0100 (Mon, 29 Jan 2007) | 2 lines Add a test for slicing an exception. ........ r53594 | andrew.kuchling | 2007-01-29 21:21:43 +0100 (Mon, 29 Jan 2007) | 1 line Minor edits to the curses HOWTO ........ r53596 | andrew.kuchling | 2007-01-29 21:55:40 +0100 (Mon, 29 Jan 2007) | 1 line Various minor edits ........ r53597 | andrew.kuchling | 2007-01-29 22:28:48 +0100 (Mon, 29 Jan 2007) | 1 line More edits ........ r53601 | tim.peters | 2007-01-30 04:03:46 +0100 (Tue, 30 Jan 2007) | 2 lines Whitespace normalization. ........ r53603 | georg.brandl | 2007-01-30 21:21:30 +0100 (Tue, 30 Jan 2007) | 2 lines Bug #1648191: typo in docs. ........ r53605 | brett.cannon | 2007-01-30 22:34:36 +0100 (Tue, 30 Jan 2007) | 8 lines No more raising of string exceptions! The next step of PEP 352 (for 2.6) causes raising a string exception to trigger a TypeError. Trying to catch a string exception raises a DeprecationWarning. References to string exceptions has been removed from the docs since they are now just an error. ........ r53618 | raymond.hettinger | 2007-02-01 22:02:59 +0100 (Thu, 01 Feb 2007) | 1 line Bug #1648179: set.update() not recognizing __iter__ overrides in dict subclasses. ........ Modified: python/branches/p3yk/Doc/howto/TODO ============================================================================== --- python/branches/p3yk/Doc/howto/TODO (original) +++ python/branches/p3yk/Doc/howto/TODO Mon Feb 5 02:24:16 2007 @@ -1,7 +1,7 @@ Short-term tasks: - Quick revision pass to make HOWTOs match the current state of Python: -curses doanddont regex sockets sorting + Quick revision pass to make HOWTOs match the current state of Python +doanddont regex sockets Medium-term tasks: Revisit the regex howto. Modified: python/branches/p3yk/Doc/howto/curses.tex ============================================================================== --- python/branches/p3yk/Doc/howto/curses.tex (original) +++ python/branches/p3yk/Doc/howto/curses.tex Mon Feb 5 02:24:16 2007 @@ -2,7 +2,7 @@ \title{Curses Programming with Python} -\release{2.01} +\release{2.02} \author{A.M. Kuchling, Eric S. Raymond} \authoraddress{\email{amk at amk.ca}, \email{esr at thyrsus.com}} @@ -147,10 +147,10 @@ In Python you can avoid these complications and make debugging much easier by importing the module \module{curses.wrapper}. It supplies a -function \function{wrapper} that takes a hook argument. It does the +\function{wrapper()} function that takes a callable. It does the initializations described above, and also initializes colors if color -support is present. It then runs your hook, and then finally -deinitializes appropriately. The hook is called inside a try-catch +support is present. It then runs your provided callable and finally +deinitializes appropriately. The callable is called inside a try-catch clause which catches exceptions, performs curses deinitialization, and then passes the exception upwards. Thus, your terminal won't be left in a funny state on exception. @@ -159,7 +159,7 @@ Windows are the basic abstraction in curses. A window object represents a rectangular area of the screen, and supports various - methods to display text, erase it, allow the user to input strings, +methods to display text, erase it, allow the user to input strings, and so forth. The \code{stdscr} object returned by the \function{initscr()} function @@ -223,14 +223,14 @@ The \function{refresh()} call displays a section of the pad in the rectangle extending from coordinate (5,5) to coordinate (20,75) on the -screen;the upper left corner of the displayed section is coordinate +screen; the upper left corner of the displayed section is coordinate (0,0) on the pad. Beyond that difference, pads are exactly like ordinary windows and support the same methods. If you have multiple windows and pads on screen there is a more efficient way to go, which will prevent annoying screen flicker at -refresh time. Use the methods \method{noutrefresh()} and/or -\method{noutrefresh()} of each window to update the data structure +refresh time. Use the \method{noutrefresh()} method +of each window to update the data structure representing the desired state of the screen; then change the physical screen to match the desired state in one go with the function \function{doupdate()}. The normal \method{refresh()} method calls @@ -254,9 +254,9 @@ \begin{tableii}{|c|l|}{textrm}{Form}{Description} \lineii{\var{str} or \var{ch}}{Display the string \var{str} or -character \var{ch}} +character \var{ch} at the current position} \lineii{\var{str} or \var{ch}, \var{attr}}{Display the string \var{str} or -character \var{ch}, using attribute \var{attr}} +character \var{ch}, using attribute \var{attr} at the current position} \lineii{\var{y}, \var{x}, \var{str} or \var{ch}} {Move to position \var{y,x} within the window, and display \var{str} or \var{ch}} @@ -271,7 +271,7 @@ The \function{addstr()} function takes a Python string as the value to be displayed, while the \function{addch()} functions take a character, -which can be either a Python string of length 1, or an integer. If +which can be either a Python string of length 1 or an integer. If it's a string, you're limited to displaying characters between 0 and 255. SVr4 curses provides constants for extension characters; these constants are integers greater than 255. For example, @@ -331,15 +331,15 @@ provide it, The most common such terminal is probably the Linux console, followed by color xterms. -To use color, you must call the \function{start_color()} function -soon after calling \function{initscr()}, to initialize the default -color set (the \function{curses.wrapper.wrapper()} function does this +To use color, you must call the \function{start_color()} function soon +after calling \function{initscr()}, to initialize the default color +set (the \function{curses.wrapper.wrapper()} function does this automatically). Once that's done, the \function{has_colors()} function returns TRUE if the terminal in use can actually display -color. (Note from AMK: curses uses the American spelling -'color', instead of the Canadian/British spelling 'colour'. If you're -like me, you'll have to resign yourself to misspelling it for the sake -of these functions.) +color. (Note: curses uses the American spelling 'color', instead of +the Canadian/British spelling 'colour'. If you're used to the British +spelling, you'll have to resign yourself to misspelling it for the +sake of these functions.) The curses library maintains a finite number of color pairs, containing a foreground (or text) color and a background color. You @@ -400,18 +400,19 @@ lack. The most common way to get input to a window is to use its -\method{getch()} method. that pauses, and waits for the user to hit -a key, displaying it if \function{echo()} has been called earlier. -You can optionally specify a coordinate to which the cursor should be -moved before pausing. +\method{getch()} method. \method{getch()} pauses and waits for the +user to hit a key, displaying it if \function{echo()} has been called +earlier. You can optionally specify a coordinate to which the cursor +should be moved before pausing. It's possible to change this behavior with the method \method{nodelay()}. After \method{nodelay(1)}, \method{getch()} for -the window becomes non-blocking and returns ERR (-1) when no input is -ready. There's also a \function{halfdelay()} function, which can be -used to (in effect) set a timer on each \method{getch()}; if no input -becomes available within the number of milliseconds specified as the -argument to \function{halfdelay()}, curses throws an exception. +the window becomes non-blocking and returns \code{curses.ERR} (a value +of -1) when no input is ready. There's also a \function{halfdelay()} +function, which can be used to (in effect) set a timer on each +\method{getch()}; if no input becomes available within the number of +milliseconds specified as the argument to \function{halfdelay()}, +curses raises an exception. The \method{getch()} method returns an integer; if it's between 0 and 255, it represents the ASCII code of the key pressed. Values greater Modified: python/branches/p3yk/Doc/howto/doanddont.tex ============================================================================== --- python/branches/p3yk/Doc/howto/doanddont.tex (original) +++ python/branches/p3yk/Doc/howto/doanddont.tex Mon Feb 5 02:24:16 2007 @@ -32,7 +32,7 @@ \subsubsection{Inside Function Definitions} \code{from module import *} is {\em invalid} inside function definitions. -While many versions of Python do no check for the invalidity, it does not +While many versions of Python do not check for the invalidity, it does not make it more valid, no more then having a smart lawyer makes a man innocent. Do not use it like that ever. Even in versions where it was accepted, it made the function execution slower, because the compiler could not be certain Modified: python/branches/p3yk/Doc/howto/regex.tex ============================================================================== --- python/branches/p3yk/Doc/howto/regex.tex (original) +++ python/branches/p3yk/Doc/howto/regex.tex Mon Feb 5 02:24:16 2007 @@ -34,17 +34,18 @@ The \module{re} module was added in Python 1.5, and provides Perl-style regular expression patterns. Earlier versions of Python came with the \module{regex} module, which provided Emacs-style -patterns. \module{regex} module was removed in Python 2.5. +patterns. The \module{regex} module was removed completely in Python 2.5. -Regular expressions (or REs) are essentially a tiny, highly -specialized programming language embedded inside Python and made -available through the \module{re} module. Using this little language, -you specify the rules for the set of possible strings that you want to -match; this set might contain English sentences, or e-mail addresses, -or TeX commands, or anything you like. You can then ask questions -such as ``Does this string match the pattern?'', or ``Is there a match -for the pattern anywhere in this string?''. You can also use REs to -modify a string or to split it apart in various ways. +Regular expressions (called REs, or regexes, or regex patterns) are +essentially a tiny, highly specialized programming language embedded +inside Python and made available through the \module{re} module. +Using this little language, you specify the rules for the set of +possible strings that you want to match; this set might contain +English sentences, or e-mail addresses, or TeX commands, or anything +you like. You can then ask questions such as ``Does this string match +the pattern?'', or ``Is there a match for the pattern anywhere in this +string?''. You can also use REs to modify a string or to split it +apart in various ways. Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For @@ -80,11 +81,12 @@ would let this RE match \samp{Test} or \samp{TEST} as well; more about this later.) -There are exceptions to this rule; some characters are -special, and don't match themselves. Instead, they signal that some -out-of-the-ordinary thing should be matched, or they affect other -portions of the RE by repeating them. Much of this document is -devoted to discussing various metacharacters and what they do. +There are exceptions to this rule; some characters are special +\dfn{metacharacters}, and don't match themselves. Instead, they +signal that some out-of-the-ordinary thing should be matched, or they +affect other portions of the RE by repeating them or changing their +meaning. Much of this document is devoted to discussing various +metacharacters and what they do. Here's a complete list of the metacharacters; their meanings will be discussed in the rest of this HOWTO. @@ -111,9 +113,10 @@ usually a metacharacter, but inside a character class it's stripped of its special nature. -You can match the characters not within a range by \dfn{complementing} -the set. This is indicated by including a \character{\^} as the first -character of the class; \character{\^} elsewhere will simply match the +You can match the characters not listed within the class by +\dfn{complementing} the set. This is indicated by including a +\character{\^} as the first character of the class; \character{\^} +outside a character class will simply match the \character{\^} character. For example, \verb|[^5]| will match any character except \character{5}. @@ -176,7 +179,7 @@ For example, \regexp{ca*t} will match \samp{ct} (0 \samp{a} characters), \samp{cat} (1 \samp{a}), \samp{caaat} (3 \samp{a} characters), and so forth. The RE engine has various internal -limitations stemming from the size of C's \code{int} type, that will +limitations stemming from the size of C's \code{int} type that will prevent it from matching over 2 billion \samp{a} characters; you probably don't have enough memory to construct a string that large, so you shouldn't run into that limit. @@ -238,9 +241,9 @@ You can omit either \var{m} or \var{n}; in that case, a reasonable value is assumed for the missing value. Omitting \var{m} is -interpreted as a lower limit of 0, while omitting \var{n} results in an -upper bound of infinity --- actually, the 2 billion limit mentioned -earlier, but that might as well be infinity. +interpreted as a lower limit of 0, while omitting \var{n} results in +an upper bound of infinity --- actually, the upper bound is the +2-billion limit mentioned earlier, but that might as well be infinity. Readers of a reductionist bent may notice that the three other qualifiers can all be expressed using this notation. \regexp{\{0,\}} is the same @@ -285,7 +288,7 @@ no need to bloat the language specification by including them.) Instead, the \module{re} module is simply a C extension module included with Python, just like the \module{socket} or \module{zlib} -module. +modules. Putting REs in strings keeps the Python language simpler, but has one disadvantage which is the topic of the next section. @@ -326,7 +329,7 @@ a string literal prefixed with \character{r}, so \code{r"\e n"} is a two-character string containing \character{\e} and \character{n}, while \code{"\e n"} is a one-character string containing a newline. -Frequently regular expressions will be expressed in Python +Regular expressions will often be written in Python code using this raw string notation. \begin{tableii}{c|c}{code}{Regular String}{Raw string} @@ -368,9 +371,9 @@ \file{redemo.py} can be quite useful when trying to debug a complicated RE. Phil Schwartz's \ulink{Kodos}{http://www.phil-schwartz.com/kodos.spy} is also an interactive -tool for developing and testing RE patterns. This HOWTO will use the -standard Python interpreter for its examples. +tool for developing and testing RE patterns. +This HOWTO uses the standard Python interpreter for its examples. First, run the Python interpreter, import the \module{re} module, and compile a RE: @@ -401,7 +404,7 @@ later use. \begin{verbatim} ->>> m = p.match( 'tempo') +>>> m = p.match('tempo') >>> print m <_sre.SRE_Match object at 80c4f68> \end{verbatim} @@ -472,9 +475,9 @@ \end{verbatim} \method{findall()} has to create the entire list before it can be -returned as the result. In Python 2.2, the \method{finditer()} method -is also available, returning a sequence of \class{MatchObject} instances -as an iterator. +returned as the result. The \method{finditer()} method returns a +sequence of \class{MatchObject} instances as an +iterator.\footnote{Introduced in Python 2.2.2.} \begin{verbatim} >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...') @@ -491,13 +494,13 @@ \subsection{Module-Level Functions} -You don't have to produce a \class{RegexObject} and call its methods; +You don't have to create a \class{RegexObject} and call its methods; the \module{re} module also provides top-level functions called -\function{match()}, \function{search()}, \function{sub()}, and so -forth. These functions take the same arguments as the corresponding -\class{RegexObject} method, with the RE string added as the first -argument, and still return either \code{None} or a \class{MatchObject} -instance. +\function{match()}, \function{search()}, \function{findall()}, +\function{sub()}, and so forth. These functions take the same +arguments as the corresponding \class{RegexObject} method, with the RE +string added as the first argument, and still return either +\code{None} or a \class{MatchObject} instance. \begin{verbatim} >>> print re.match(r'From\s+', 'Fromage amk') @@ -514,7 +517,7 @@ Should you use these module-level functions, or should you get the \class{RegexObject} and call its methods yourself? That choice depends on how frequently the RE will be used, and on your personal -coding style. If a RE is being used at only one point in the code, +coding style. If the RE is being used at only one point in the code, then the module functions are probably more convenient. If a program contains a lot of regular expressions, or re-uses the same ones in several locations, then it might be worthwhile to collect all the @@ -537,7 +540,7 @@ Compilation flags let you modify some aspects of how regular expressions work. Flags are available in the \module{re} module under -two names, a long name such as \constant{IGNORECASE}, and a short, +two names, a long name such as \constant{IGNORECASE} and a short, one-letter form such as \constant{I}. (If you're familiar with Perl's pattern modifiers, the one-letter forms use the same letters; the short form of \constant{re.VERBOSE} is \constant{re.X}, for example.) @@ -617,7 +620,7 @@ format them. When this flag has been specified, whitespace within the RE string is ignored, except when the whitespace is in a character class or preceded by an unescaped backslash; this lets you organize -and indent the RE more clearly. It also enables you to put comments +and indent the RE more clearly. This flag also lets you put comments within a RE that will be ignored by the engine; comments are marked by a \character{\#} that's neither in a character class or preceded by an unescaped backslash. @@ -629,18 +632,19 @@ charref = re.compile(r""" &[#] # Start of a numeric entity reference ( - [0-9]+[^0-9] # Decimal form - | 0[0-7]+[^0-7] # Octal form - | x[0-9a-fA-F]+[^0-9a-fA-F] # Hexadecimal form + 0[0-7]+ # Octal form + | [0-9]+ # Decimal form + | x[0-9a-fA-F]+ # Hexadecimal form ) + ; # Trailing semicolon """, re.VERBOSE) \end{verbatim} Without the verbose setting, the RE would look like this: \begin{verbatim} -charref = re.compile("&#([0-9]+[^0-9]" - "|0[0-7]+[^0-7]" - "|x[0-9a-fA-F]+[^0-9a-fA-F])") +charref = re.compile("&#(0[0-7]+" + "|[0-9]+" + "|x[0-9a-fA-F]+);") \end{verbatim} In the above example, Python's automatic concatenation of string @@ -722,12 +726,12 @@ \item[\regexp{\e A}] Matches only at the start of the string. When not in \constant{MULTILINE} mode, \regexp{\e A} and \regexp{\^} are -effectively the same. In \constant{MULTILINE} mode, however, they're -different; \regexp{\e A} still matches only at the beginning of the +effectively the same. In \constant{MULTILINE} mode, they're +different: \regexp{\e A} still matches only at the beginning of the string, but \regexp{\^} may match at any location inside the string that follows a newline character. -\item[\regexp{\e Z}]Matches only at the end of the string. +\item[\regexp{\e Z}] Matches only at the end of the string. \item[\regexp{\e b}] Word boundary. This is a zero-width assertion that matches only at the @@ -782,14 +786,23 @@ strings by writing a RE divided into several subgroups which match different components of interest. For example, an RFC-822 header line is divided into a header name and a value, separated by a -\character{:}. This can be handled by writing a regular expression +\character{:}, like this: + +\begin{verbatim} +From: author at example.com +User-Agent: Thunderbird 1.5.0.9 (X11/20061227) +MIME-Version: 1.0 +To: editor at example.com +\end{verbatim} + +This can be handled by writing a regular expression which matches an entire header line, and has one group which matches the header name, and another group which matches the header's value. Groups are marked by the \character{(}, \character{)} metacharacters. \character{(} and \character{)} have much the same meaning as they do in mathematical expressions; they group together the expressions -contained inside them. For example, you can repeat the contents of a +contained inside them, and you can repeat the contents of a group with a repeating qualifier, such as \regexp{*}, \regexp{+}, \regexp{?}, or \regexp{\{\var{m},\var{n}\}}. For example, \regexp{(ab)*} will match zero or more repetitions of \samp{ab}. @@ -881,12 +894,13 @@ syntax for regular expression extensions, so we'll look at that first. Perl 5 added several additional features to standard regular -expressions, and the Python \module{re} module supports most of them. -It would have been difficult to choose new single-keystroke -metacharacters or new special sequences beginning with \samp{\e} to -represent the new features without making Perl's regular expressions -confusingly different from standard REs. If you chose \samp{\&} as a -new metacharacter, for example, old expressions would be assuming that +expressions, and the Python \module{re} module supports most of them. +It would have been difficult to choose new +single-keystroke metacharacters or new special sequences beginning +with \samp{\e} to represent the new features without making Perl's +regular expressions confusingly different from standard REs. If you +chose \samp{\&} as a new metacharacter, for example, old expressions +would be assuming that \samp{\&} was a regular character and wouldn't have escaped it by writing \regexp{\e \&} or \regexp{[\&]}. @@ -913,15 +927,15 @@ to the features that simplify working with groups in complex REs. Since groups are numbered from left to right and a complex expression may use many groups, it can become difficult to keep track of the -correct numbering, and modifying such a complex RE is annoying. -Insert a new group near the beginning, and you change the numbers of +correct numbering. Modifying such a complex RE is annoying, too: +insert a new group near the beginning and you change the numbers of everything that follows it. -First, sometimes you'll want to use a group to collect a part of a -regular expression, but aren't interested in retrieving the group's -contents. You can make this fact explicit by using a non-capturing -group: \regexp{(?:...)}, where you can put any other regular -expression inside the parentheses. +Sometimes you'll want to use a group to collect a part of a regular +expression, but aren't interested in retrieving the group's contents. +You can make this fact explicit by using a non-capturing group: +\regexp{(?:...)}, where you can replace the \regexp{...} +with any other regular expression. \begin{verbatim} >>> m = re.match("([abc])+", "abc") @@ -937,23 +951,23 @@ capturing group; you can put anything inside it, repeat it with a repetition metacharacter such as \samp{*}, and nest it within other groups (capturing or non-capturing). \regexp{(?:...)} is particularly -useful when modifying an existing group, since you can add new groups +useful when modifying an existing pattern, since you can add new groups without changing how all the other groups are numbered. It should be mentioned that there's no performance difference in searching between capturing and non-capturing groups; neither form is any faster than the other. -The second, and more significant, feature is named groups; instead of +A more significant feature is named groups: instead of referring to them by numbers, groups can be referenced by a name. The syntax for a named group is one of the Python-specific extensions: \regexp{(?P<\var{name}>...)}. \var{name} is, obviously, the name of -the group. Except for associating a name with a group, named groups -also behave identically to capturing groups. The \class{MatchObject} -methods that deal with capturing groups all accept either integers, to -refer to groups by number, or a string containing the group name. -Named groups are still given numbers, so you can retrieve information -about a group in two ways: +the group. Named groups also behave exactly like capturing groups, +and additionally associate a name with a group. The +\class{MatchObject} methods that deal with capturing groups all accept +either integers that refer to the group by number or strings that +contain the desired group's name. Named groups are still given +numbers, so you can retrieve information about a group in two ways: \begin{verbatim} >>> p = re.compile(r'(?P\b\w+\b)') @@ -980,11 +994,11 @@ It's obviously much easier to retrieve \code{m.group('zonem')}, instead of having to remember to retrieve group 9. -Since the syntax for backreferences, in an expression like -\regexp{(...)\e 1}, refers to the number of the group there's +The syntax for backreferences in an expression such as +\regexp{(...)\e 1} refers to the number of the group. There's naturally a variant that uses the group name instead of the number. -This is also a Python extension: \regexp{(?P=\var{name})} indicates -that the contents of the group called \var{name} should again be found +This is another Python extension: \regexp{(?P=\var{name})} indicates +that the contents of the group called \var{name} should again be matched at the current point. The regular expression for finding doubled words, \regexp{(\e b\e w+)\e s+\e 1} can also be written as \regexp{(?P\e b\e w+)\e s+(?P=word)}: @@ -1014,11 +1028,11 @@ \emph{doesn't} match at the current position in the string. \end{itemize} -An example will help make this concrete by demonstrating a case -where a lookahead is useful. Consider a simple pattern to match a -filename and split it apart into a base name and an extension, -separated by a \samp{.}. For example, in \samp{news.rc}, \samp{news} -is the base name, and \samp{rc} is the filename's extension. +To make this concrete, let's look at a case where a lookahead is +useful. Consider a simple pattern to match a filename and split it +apart into a base name and an extension, separated by a \samp{.}. For +example, in \samp{news.rc}, \samp{news} is the base name, and +\samp{rc} is the filename's extension. The pattern to match this is quite simple: @@ -1065,12 +1079,12 @@ exclude both \samp{bat} and \samp{exe} as extensions, the pattern would get even more complicated and confusing. -A negative lookahead cuts through all this: +A negative lookahead cuts through all this confusion: \regexp{.*[.](?!bat\$).*\$} % $ -The lookahead means: if the expression \regexp{bat} doesn't match at +The negative lookahead means: if the expression \regexp{bat} doesn't match at this point, try the rest of the pattern; if \regexp{bat\$} does match, the whole pattern will fail. The trailing \regexp{\$} is required to ensure that something like \samp{sample.batch}, where the extension @@ -1087,7 +1101,7 @@ \section{Modifying Strings} Up to this point, we've simply performed searches against a static -string. Regular expressions are also commonly used to modify a string +string. Regular expressions are also commonly used to modify strings in various ways, using the following \class{RegexObject} methods: \begin{tableii}{c|l}{code}{Method/Attribute}{Purpose} Modified: python/branches/p3yk/Doc/lib/libexcs.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libexcs.tex (original) +++ python/branches/p3yk/Doc/lib/libexcs.tex Mon Feb 5 02:24:16 2007 @@ -10,22 +10,6 @@ provided in the built-in namespace as well as the \module{exceptions} module. -\begin{notice} -In past versions of Python string exceptions were supported. In -Python 1.5 and newer versions, all standard exceptions have been -converted to class objects and users are encouraged to do the same. -String exceptions will raise a \code{DeprecationWarning} in Python 2.5 and -newer. -In future versions, support for string exceptions will be removed. - -Two distinct string objects with the same value are considered different -exceptions. This is done to force programmers to use exception names -rather than their string value when specifying exception handlers. -The string value of all built-in exceptions is their name, but this is -not a requirement for user-defined exceptions or exceptions defined by -library modules. -\end{notice} - For class exceptions, in a \keyword{try}\stindex{try} statement with an \keyword{except}\stindex{except} clause that mentions a particular class, that clause also handles any exception classes derived from Modified: python/branches/p3yk/Doc/lib/libimageop.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libimageop.tex (original) +++ python/branches/p3yk/Doc/lib/libimageop.tex Mon Feb 5 02:24:16 2007 @@ -19,7 +19,7 @@ \begin{funcdesc}{crop}{image, psize, width, height, x0, y0, x1, y1} -Return the selected part of \var{image}, which should by +Return the selected part of \var{image}, which should be \var{width} by \var{height} in size and consist of pixels of \var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like the \function{gl.lrectread()} parameters, i.e.\ the boundary is Modified: python/branches/p3yk/Doc/lib/libmailbox.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libmailbox.tex (original) +++ python/branches/p3yk/Doc/lib/libmailbox.tex Mon Feb 5 02:24:16 2007 @@ -58,14 +58,18 @@ \exception{KeyError} exception if the corresponding message is subsequently removed. -Be very cautious when modifying mailboxes that might also be changed -by some other process. The safest mailbox format to use for such -tasks is Maildir; try to avoid using single-file formats such as mbox -for concurrent writing. If you're modifying a mailbox, no matter what -the format, you must lock it by calling the \method{lock()} and -\method{unlock()} methods before making any changes. Failing to lock -the mailbox runs the risk of losing data if some other process makes -changes to the mailbox while your Python code is running. +\begin{notice}[warning] +Be very cautious when modifying mailboxes that might be +simultaneously changed by some other process. The safest mailbox +format to use for such tasks is Maildir; try to avoid using +single-file formats such as mbox for concurrent writing. If you're +modifying a mailbox, you +\emph{must} lock it by calling the \method{lock()} and +\method{unlock()} methods \emph{before} reading any messages in the file +or making any changes by adding or deleting a message. Failing to +lock the mailbox runs the risk of losing messages or corrupting the entire +mailbox. +\end{notice} \class{Mailbox} instances have the following methods: Modified: python/branches/p3yk/Doc/ref/ref4.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref4.tex (original) +++ python/branches/p3yk/Doc/ref/ref4.tex Mon Feb 5 02:24:16 2007 @@ -197,10 +197,6 @@ value can be raised along with the identifying string which can be passed to the handler. -\deprecated{2.5}{String exceptions should not be used in new code. -They will not be supported in a future version of Python. Old code -should be rewritten to use class exceptions instead.} - \begin{notice}[warning] Messages to exceptions are not part of the Python API. Their contents may change from one version of Python to the next without warning and should not Modified: python/branches/p3yk/Doc/tut/tut.tex ============================================================================== --- python/branches/p3yk/Doc/tut/tut.tex (original) +++ python/branches/p3yk/Doc/tut/tut.tex Mon Feb 5 02:24:16 2007 @@ -1991,7 +1991,7 @@ There is a way to remove an item from a list given its index instead of its value: the \keyword{del} statement. This differs from the -\method{pop()}) method which returns a value. The \keyword{del} +\method{pop()} method which returns a value. The \keyword{del} statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example: Modified: python/branches/p3yk/Doc/whatsnew/whatsnew26.tex ============================================================================== --- python/branches/p3yk/Doc/whatsnew/whatsnew26.tex (original) +++ python/branches/p3yk/Doc/whatsnew/whatsnew26.tex Mon Feb 5 02:24:16 2007 @@ -72,6 +72,12 @@ This class supports an interface identical to the existing \class{SMTP} class. (Contributed by Monty Taylor.) +\item The \module{test.test_support} module now contains a +\function{EnvironmentVarGuard} context manager that +supports temporarily changing environment variables and +automatically restores them to their old values. +(Contributed by Brett Cannon.) + \end{itemize} Modified: python/branches/p3yk/Lib/CGIHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/CGIHTTPServer.py (original) +++ python/branches/p3yk/Lib/CGIHTTPServer.py Mon Feb 5 02:24:16 2007 @@ -107,7 +107,7 @@ """Execute a CGI script.""" path = self.path dir, rest = self.cgi_info - + i = path.find('/', len(dir) + 1) while i >= 0: nextdir = path[:i] Modified: python/branches/p3yk/Lib/_strptime.py ============================================================================== --- python/branches/p3yk/Lib/_strptime.py (original) +++ python/branches/p3yk/Lib/_strptime.py Mon Feb 5 02:24:16 2007 @@ -22,9 +22,6 @@ except: from dummy_thread import allocate_lock as _thread_allocate_lock -__author__ = "Brett Cannon" -__email__ = "brett at python.org" - __all__ = ['strptime'] def _getlang(): @@ -273,11 +270,31 @@ _CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache _regex_cache = {} +def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon): + """Calculate the Julian day based on the year, week of the year, and day of + the week, with week_start_day representing whether the week of the year + assumes the week starts on Sunday or Monday (6 or 0).""" + first_weekday = datetime_date(year, 1, 1).weekday() + # If we are dealing with the %U directive (week starts on Sunday), it's + # easier to just shift the view to Sunday being the first day of the + # week. + if not week_starts_Mon: + first_weekday = (first_weekday + 1) % 7 + day_of_week = (day_of_week + 1) % 7 + # Need to watch out for a week 0 (when the first day of the year is not + # the same as that specified by %U or %W). + week_0_length = (7 - first_weekday) % 7 + if week_of_year == 0: + return 1 + day_of_week - first_weekday + else: + days_to_week = week_0_length + (7 * (week_of_year - 1)) + return 1 + days_to_week + day_of_week + + def strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a time struct based on the input string and the format string.""" global _TimeRE_cache, _regex_cache - _cache_lock.acquire() - try: + with _cache_lock: time_re = _TimeRE_cache locale_time = time_re.locale_time if _getlang() != locale_time.lang: @@ -302,8 +319,6 @@ except IndexError: raise ValueError("stray %% in format '%s'" % format) _regex_cache[format] = format_regex - finally: - _cache_lock.release() found = format_regex.match(data_string) if not found: raise ValueError("time data %r does not match format %r" % @@ -385,10 +400,10 @@ elif group_key in ('U', 'W'): week_of_year = int(found_dict[group_key]) if group_key == 'U': - # U starts week on Sunday + # U starts week on Sunday. week_of_year_start = 6 else: - # W starts week on Monday + # W starts week on Monday. week_of_year_start = 0 elif group_key == 'Z': # Since -1 is default value only need to worry about setting tz if @@ -406,42 +421,20 @@ tz = value break # If we know the week of the year and what day of that week, we can figure - # out the Julian day of the year - # Calculations below assume 0 is a Monday + # out the Julian day of the year. if julian == -1 and week_of_year != -1 and weekday != -1: - # Calculate how many days in week 0 - first_weekday = datetime_date(year, 1, 1).weekday() - preceeding_days = 7 - first_weekday - if preceeding_days == 7: - preceeding_days = 0 - # Adjust for U directive so that calculations are not dependent on - # directive used to figure out week of year - if weekday == 6 and week_of_year_start == 6: - week_of_year -= 1 - # If a year starts and ends on a Monday but a week is specified to - # start on a Sunday we need to up the week to counter-balance the fact - # that with %W that first Monday starts week 1 while with %U that is - # week 0 and thus shifts everything by a week - if weekday == 0 and first_weekday == 0 and week_of_year_start == 6: - week_of_year += 1 - # If in week 0, then just figure out how many days from Jan 1 to day of - # week specified, else calculate by multiplying week of year by 7, - # adding in days in week 0, and the number of days from Monday to the - # day of the week - if week_of_year == 0: - julian = 1 + weekday - first_weekday - else: - days_to_week = preceeding_days + (7 * (week_of_year - 1)) - julian = 1 + days_to_week + weekday + week_starts_Mon = True if week_of_year_start == 0 else False + julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, + week_starts_Mon) # Cannot pre-calculate datetime_date() since can change in Julian - #calculation and thus could have different value for the day of the week - #calculation + # calculation and thus could have different value for the day of the week + # calculation. if julian == -1: # Need to add 1 to result since first day of the year is 1, not 0. julian = datetime_date(year, month, day).toordinal() - \ datetime_date(year, 1, 1).toordinal() + 1 else: # Assume that if they bothered to include Julian day it will - #be accurate + # be accurate. datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal()) year = datetime_result.year month = datetime_result.month Modified: python/branches/p3yk/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk/Lib/compiler/pycodegen.py Mon Feb 5 02:24:16 2007 @@ -914,6 +914,8 @@ self.emit('LOAD_CONST', None) self.nextBlock(final) self.setups.push((END_FINALLY, final)) + self._implicitNameOp('LOAD', exitvar) + self._implicitNameOp('DELETE', exitvar) self.emit('WITH_CLEANUP') self.emit('END_FINALLY') self.setups.pop() Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Mon Feb 5 02:24:16 2007 @@ -1018,7 +1018,7 @@ if nodelist[2][0] == token.COLON: var = None else: - var = self.com_node(nodelist[2]) + var = self.com_assign(nodelist[2][2], OP_ASSIGN) return With(expr, var, body, lineno=nodelist[0][2]) def com_with_var(self, nodelist): Modified: python/branches/p3yk/Lib/cookielib.py ============================================================================== --- python/branches/p3yk/Lib/cookielib.py (original) +++ python/branches/p3yk/Lib/cookielib.py Mon Feb 5 02:24:16 2007 @@ -1318,26 +1318,26 @@ self._cookies_lock.acquire() try: - self._policy._now = self._now = int(time.time()) + self._policy._now = self._now = int(time.time()) + + cookies = self._cookies_for_request(request) - cookies = self._cookies_for_request(request) + attrs = self._cookie_attrs(cookies) + if attrs: + if not request.has_header("Cookie"): + request.add_unredirected_header( + "Cookie", "; ".join(attrs)) + + # if necessary, advertise that we know RFC 2965 + if (self._policy.rfc2965 and not self._policy.hide_cookie2 and + not request.has_header("Cookie2")): + for cookie in cookies: + if cookie.version != 1: + request.add_unredirected_header("Cookie2", '$Version="1"') + break - attrs = self._cookie_attrs(cookies) - if attrs: - if not request.has_header("Cookie"): - request.add_unredirected_header( - "Cookie", "; ".join(attrs)) - - # if necessary, advertise that we know RFC 2965 - if (self._policy.rfc2965 and not self._policy.hide_cookie2 and - not request.has_header("Cookie2")): - for cookie in cookies: - if cookie.version != 1: - request.add_unredirected_header("Cookie2", '$Version="1"') - break - finally: - self._cookies_lock.release() + self._cookies_lock.release() self.clear_expired_cookies() @@ -1609,7 +1609,7 @@ if self._policy.set_ok(cookie, request): self.set_cookie(cookie) - + finally: self._cookies_lock.release() @@ -1632,14 +1632,14 @@ _debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() try: - self._policy._now = self._now = int(time.time()) + self._policy._now = self._now = int(time.time()) - for cookie in self.make_cookies(response, request): - if self._policy.set_ok(cookie, request): - _debug(" setting cookie: %s", cookie) - self.set_cookie(cookie) + for cookie in self.make_cookies(response, request): + if self._policy.set_ok(cookie, request): + _debug(" setting cookie: %s", cookie) + self.set_cookie(cookie) finally: - self._cookies_lock.release() + self._cookies_lock.release() def clear(self, domain=None, path=None, name=None): """Clear some cookies. @@ -1677,11 +1677,11 @@ """ self._cookies_lock.acquire() try: - for cookie in self: - if cookie.discard: - self.clear(cookie.domain, cookie.path, cookie.name) + for cookie in self: + if cookie.discard: + self.clear(cookie.domain, cookie.path, cookie.name) finally: - self._cookies_lock.release() + self._cookies_lock.release() def clear_expired_cookies(self): """Discard all expired cookies. @@ -1695,12 +1695,12 @@ """ self._cookies_lock.acquire() try: - now = time.time() - for cookie in self: - if cookie.is_expired(now): - self.clear(cookie.domain, cookie.path, cookie.name) + now = time.time() + for cookie in self: + if cookie.is_expired(now): + self.clear(cookie.domain, cookie.path, cookie.name) finally: - self._cookies_lock.release() + self._cookies_lock.release() def __iter__(self): return deepvalues(self._cookies) @@ -1774,16 +1774,16 @@ self._cookies_lock.acquire() try: - old_state = copy.deepcopy(self._cookies) - self._cookies = {} - try: - self.load(filename, ignore_discard, ignore_expires) - except (LoadError, IOError): - self._cookies = old_state - raise + old_state = copy.deepcopy(self._cookies) + self._cookies = {} + try: + self.load(filename, ignore_discard, ignore_expires) + except (LoadError, IOError): + self._cookies = old_state + raise finally: - self._cookies_lock.release() + self._cookies_lock.release() from _LWPCookieJar import LWPCookieJar, lwp_cookie_str from _MozillaCookieJar import MozillaCookieJar Modified: python/branches/p3yk/Lib/dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/dumbdbm.py (original) +++ python/branches/p3yk/Lib/dumbdbm.py Mon Feb 5 02:24:16 2007 @@ -243,5 +243,5 @@ else: # Turn off any bits that are set in the umask mode = mode & (~um) - + return _Database(file, mode) Modified: python/branches/p3yk/Lib/dummy_thread.py ============================================================================== --- python/branches/p3yk/Lib/dummy_thread.py (original) +++ python/branches/p3yk/Lib/dummy_thread.py Mon Feb 5 02:24:16 2007 @@ -11,11 +11,8 @@ import dummy_thread as thread """ -__author__ = "Brett Cannon" -__email__ = "brett at python.org" - -# Exports only things specified by thread documentation -# (skipping obsolete synonyms allocate(), start_new(), exit_thread()) +# Exports only things specified by thread documentation; +# skipping obsolete synonyms allocate(), start_new(), exit_thread(). __all__ = ['error', 'start_new_thread', 'exit', 'get_ident', 'allocate_lock', 'interrupt_main', 'LockType'] Modified: python/branches/p3yk/Lib/dummy_threading.py ============================================================================== --- python/branches/p3yk/Lib/dummy_threading.py (original) +++ python/branches/p3yk/Lib/dummy_threading.py Mon Feb 5 02:24:16 2007 @@ -5,11 +5,6 @@ directly imported it would have made all subsequent imports succeed regardless of whether ``thread`` was available which is not desired. -:Author: Brett Cannon -:Contact: brett at python.org - -XXX: Try to get rid of ``_dummy_threading``. - """ from sys import modules as sys_modules Modified: python/branches/p3yk/Lib/email/charset.py ============================================================================== --- python/branches/p3yk/Lib/email/charset.py (original) +++ python/branches/p3yk/Lib/email/charset.py Mon Feb 5 02:24:16 2007 @@ -46,6 +46,7 @@ 'iso-8859-13': (QP, QP, None), 'iso-8859-14': (QP, QP, None), 'iso-8859-15': (QP, QP, None), + 'iso-8859-16': (QP, QP, None), 'windows-1252':(QP, QP, None), 'viscii': (QP, QP, None), 'us-ascii': (None, None, None), @@ -81,6 +82,8 @@ 'latin-8': 'iso-8859-14', 'latin_9': 'iso-8859-15', 'latin-9': 'iso-8859-15', + 'latin_10':'iso-8859-16', + 'latin-10':'iso-8859-16', 'cp949': 'ks_c_5601-1987', 'euc_jp': 'euc-jp', 'euc_kr': 'euc-kr', Modified: python/branches/p3yk/Lib/encodings/aliases.py ============================================================================== --- python/branches/p3yk/Lib/encodings/aliases.py (original) +++ python/branches/p3yk/Lib/encodings/aliases.py Mon Feb 5 02:24:16 2007 @@ -301,6 +301,8 @@ # iso8859_13 codec 'iso_8859_13' : 'iso8859_13', + 'l7' : 'iso8859_13', + 'latin7' : 'iso8859_13', # iso8859_14 codec 'iso_8859_14' : 'iso8859_14', @@ -312,6 +314,8 @@ # iso8859_15 codec 'iso_8859_15' : 'iso8859_15', + 'l9' : 'iso8859_15', + 'latin9' : 'iso8859_15', # iso8859_16 codec 'iso_8859_16' : 'iso8859_16', Modified: python/branches/p3yk/Lib/ftplib.py ============================================================================== --- python/branches/p3yk/Lib/ftplib.py (original) +++ python/branches/p3yk/Lib/ftplib.py Mon Feb 5 02:24:16 2007 @@ -333,7 +333,7 @@ # 1xx or error messages for LIST), so we just discard # this response. if resp[0] == '2': - resp = self.getresp() + resp = self.getresp() if resp[0] != '1': raise error_reply, resp else: @@ -343,7 +343,7 @@ resp = self.sendcmd(cmd) # See above. if resp[0] == '2': - resp = self.getresp() + resp = self.getresp() if resp[0] != '1': raise error_reply, resp conn, sockaddr = sock.accept() Modified: python/branches/p3yk/Lib/httplib.py ============================================================================== --- python/branches/p3yk/Lib/httplib.py (original) +++ python/branches/p3yk/Lib/httplib.py Mon Feb 5 02:24:16 2007 @@ -899,7 +899,7 @@ except (AttributeError, OSError): # Don't send a length if this failed if self.debuglevel > 0: print "Cannot stat!!" - + if thelen is not None: self.putheader('Content-Length',thelen) for hdr, value in headers.iteritems(): Modified: python/branches/p3yk/Lib/idlelib/CodeContext.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/CodeContext.py (original) +++ python/branches/p3yk/Lib/idlelib/CodeContext.py Mon Feb 5 02:24:16 2007 @@ -71,7 +71,7 @@ # # To avoid possible errors, all references to the inner workings # of Tk are executed inside try/except blocks. - + widgets_for_width_calc = self.editwin.text, self.editwin.text_frame # calculate the required vertical padding @@ -113,7 +113,7 @@ # above it. self.label.pack(side="top", fill="x", expand=False, before=self.editwin.text_frame) - + else: self.label.destroy() self.label = None Modified: python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py (original) +++ python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py Mon Feb 5 02:24:16 2007 @@ -50,9 +50,9 @@ # If the master is not viewable, don't # make the child transient, or else it # would be opened withdrawn - if parent.winfo_viewable(): + if parent.winfo_viewable(): self.transient(parent) - + if title: self.title(title) Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Mon Feb 5 02:24:16 2007 @@ -569,7 +569,7 @@ # already have been generated (and presumably has been modified # by adding or deleting an item). assert self._toc is not None - + # Check length of self._file; if it's changed, some other process # has modified the mailbox since we scanned it. self._file.seek(0, 2) @@ -578,7 +578,7 @@ raise ExternalClashError('Size of mailbox file changed ' '(expected %i, found %i)' % (self._file_length, cur_len)) - + new_file = _create_temporary(self._path) try: new_toc = {} @@ -1219,7 +1219,7 @@ self._next_key = len(self._toc) self._file.seek(0, 2) self._file_length = self._file.tell() - + def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' % Modified: python/branches/p3yk/Lib/platform.py ============================================================================== --- python/branches/p3yk/Lib/platform.py (original) +++ python/branches/p3yk/Lib/platform.py Mon Feb 5 02:24:16 2007 @@ -236,7 +236,7 @@ '[^(]*(?:\((.+)\))?') # See also http://www.novell.com/coolsolutions/feature/11251.html -# and http://linuxmafia.com/faq/Admin/release-files.html +# and http://linuxmafia.com/faq/Admin/release-files.html # and http://data.linux-ntfs.org/rpm/whichrpm # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html @@ -245,7 +245,7 @@ 'gentoo', 'UnitedLinux') def _parse_release_file(firstline): - + # Parse the first line m = _lsb_release_version.match(firstline) if m is not None: @@ -268,7 +268,7 @@ return '', version, id def _test_parse_release_file(): - + for input, output in ( # Examples of release file contents: ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64')) @@ -324,7 +324,7 @@ break else: return _dist_try_harder(distname,version,id) - + # Read the first line f = open('/etc/'+file, 'r') firstline = f.readline() @@ -340,7 +340,7 @@ return distname, version, id # To maintain backwards compatibility: - + def dist(distname='',version='',id='', supported_dists=_supported_dists): @@ -1358,7 +1358,7 @@ If not available, an empty string is returned. """ - + return _sys_version()[2] def python_revision(): Modified: python/branches/p3yk/Lib/pty.py ============================================================================== --- python/branches/p3yk/Lib/pty.py (original) +++ python/branches/p3yk/Lib/pty.py Mon Feb 5 02:24:16 2007 @@ -123,7 +123,7 @@ os.close(tmp_fd) else: os.close(slave_fd) - + # Parent and child process. return pid, master_fd Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Mon Feb 5 02:24:16 2007 @@ -1121,7 +1121,7 @@ # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) - input_offset += bytes_written + input_offset += bytes_written if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) Modified: python/branches/p3yk/Lib/test/test_cfgparser.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cfgparser.py (original) +++ python/branches/p3yk/Lib/test/test_cfgparser.py Mon Feb 5 02:24:16 2007 @@ -15,7 +15,7 @@ result = self.data.keys() result.sort() return result - + def values(self): result = self.items() return [i[1] for i in values] @@ -446,12 +446,12 @@ "o2=3\n" "o1=4\n" "[a]\n" - "k=v\n") + "k=v\n") output = StringIO.StringIO() self.cf.write(output) self.assertEquals(output.getvalue(), "[a]\n" - "k = v\n\n" + "k = v\n\n" "[b]\n" "o1 = 4\n" "o2 = 3\n" Modified: python/branches/p3yk/Lib/test/test_compiler.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compiler.py (original) +++ python/branches/p3yk/Lib/test/test_compiler.py Mon Feb 5 02:24:16 2007 @@ -7,6 +7,12 @@ # How much time in seconds can pass before we print a 'Still working' message. _PRINT_WORKING_MSG_INTERVAL = 5 * 60 +class TrivialContext(object): + def __enter__(self): + return self + def __exit__(self, *exc_info): + pass + class CompilerTest(unittest.TestCase): def testCompileLibrary(self): @@ -157,6 +163,31 @@ exec(c, dct) self.assertEquals(dct['f'].func_annotations, expected) + def testWith(self): + # SF bug 1638243 + c = compiler.compile('from __future__ import with_statement\n' + 'def f():\n' + ' with TrivialContext():\n' + ' return 1\n' + 'result = f()', + '', + 'exec' ) + dct = {'TrivialContext': TrivialContext} + exec(c, dct) + self.assertEquals(dct.get('result'), 1) + + def testWithAss(self): + c = compiler.compile('from __future__ import with_statement\n' + 'def f():\n' + ' with TrivialContext() as tc:\n' + ' return 1\n' + 'result = f()', + '', + 'exec' ) + dct = {'TrivialContext': TrivialContext} + exec(c, dct) + self.assertEquals(dct.get('result'), 1) + NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard) Modified: python/branches/p3yk/Lib/test/test_dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dumbdbm.py (original) +++ python/branches/p3yk/Lib/test/test_dumbdbm.py Mon Feb 5 02:24:16 2007 @@ -49,7 +49,7 @@ f.close() finally: os.umask(old_umask) - + expected_mode = 0635 if os.name != 'posix': # Windows only supports setting the read-only attribute. @@ -61,7 +61,7 @@ self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) st = os.stat(_fname + '.dir') self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) - + def test_close_twice(self): f = dumbdbm.open(_fname) f['a'] = 'b' Modified: python/branches/p3yk/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk/Lib/test/test_exceptions.py Mon Feb 5 02:24:16 2007 @@ -311,6 +311,13 @@ 'pickled "%r", attribute "%s' % (e, checkArgName)) + def testSlicing(self): + # Test that you can slice an exception directly instead of requiring + # going through the 'args' attribute. + args = (1, 2, 3) + exc = BaseException(*args) + self.failUnlessEqual(exc[:], args) + def testKeywordArgs(self): # test that builtin exception don't take keyword args, # but user-defined subclasses can if they want Modified: python/branches/p3yk/Lib/test/test_gzip.py ============================================================================== --- python/branches/p3yk/Lib/test/test_gzip.py (original) +++ python/branches/p3yk/Lib/test/test_gzip.py Mon Feb 5 02:24:16 2007 @@ -138,7 +138,7 @@ y = f.read(10) f.close() self.assertEquals(y, data1[20:30]) - + def test_seek_write(self): # Try seek, write test f = gzip.GzipFile(self.filename, 'w') Modified: python/branches/p3yk/Lib/test/test_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_mailbox.py Mon Feb 5 02:24:16 2007 @@ -674,11 +674,11 @@ box = self._factory(self._path, factory=dummy_factory) folder = box.add_folder('folder1') self.assert_(folder._factory is dummy_factory) - + folder1_alias = box.get_folder('folder1') self.assert_(folder1_alias._factory is dummy_factory) - + class _TestMboxMMDF(TestMailbox): @@ -798,7 +798,7 @@ def dummy_factory (s): return None self._box = self._factory(self._path, dummy_factory) - + new_folder = self._box.add_folder('foo.bar') folder0 = self._box.get_folder('foo.bar') folder0.add(self._template % 'bar') @@ -894,7 +894,7 @@ self.assert_(self._box.get_sequences() == {'foo':[1, 2, 3, 4, 5], 'unseen':[1], 'bar':[3], 'replied':[3]}) - + def _get_lock_path(self): return os.path.join(self._path, '.mh_sequences.lock') Modified: python/branches/p3yk/Lib/test/test_old_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_old_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_old_mailbox.py Mon Feb 5 02:24:16 2007 @@ -116,7 +116,7 @@ def tearDown(self): os.unlink(self._path) - + def test_from_regex (self): # Testing new regex from bug #1633678 f = open(self._path, 'w') Modified: python/branches/p3yk/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep352.py (original) +++ python/branches/p3yk/Lib/test/test_pep352.py Mon Feb 5 02:24:16 2007 @@ -2,7 +2,7 @@ import __builtin__ import exceptions import warnings -from test.test_support import run_unittest +from test.test_support import run_unittest, guard_warnings_filter import os from platform import system as platform_system @@ -113,13 +113,11 @@ """Test usage of exceptions""" - def setUp(self): - self._filters = warnings.filters[:] - - def tearDown(self): - warnings.filters = self._filters[:] - def test_raise_new_style_non_exception(self): + # You cannot raise a new-style class that does not inherit from + # BaseException; the ability was not possible until BaseException's + # introduction so no need to support new-style objects that do not + # inherit from it. class NewStyleClass(object): pass try: @@ -127,13 +125,51 @@ except TypeError: pass except: - self.fail("unable to raise new-style class") + self.fail("able to raise new-style class") try: raise NewStyleClass() except TypeError: pass except: - self.fail("unable to raise new-style class instance") + self.fail("able to raise new-style class instance") + + def test_raise_string(self): + # Raising a string raises TypeError. + try: + raise "spam" + except TypeError: + pass + except: + self.fail("was able to raise a string exception") + + def test_catch_string(self): + # Catching a string should trigger a DeprecationWarning. + with guard_warnings_filter(): + warnings.resetwarnings() + warnings.filterwarnings("error") + str_exc = "spam" + try: + try: + raise StandardError + except str_exc: + pass + except DeprecationWarning: + pass + except StandardError: + self.fail("catching a string exception did not raise " + "DeprecationWarning") + # Make sure that even if the string exception is listed in a tuple + # that a warning is raised. + try: + try: + raise StandardError + except (AssertionError, str_exc): + pass + except DeprecationWarning: + pass + except StandardError: + self.fail("catching a string exception specified in a tuple did " + "not raise DeprecationWarning") def test_main(): run_unittest(ExceptionClassTests, UsageTests) Modified: python/branches/p3yk/Lib/test/test_pty.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pty.py (original) +++ python/branches/p3yk/Lib/test/test_pty.py Mon Feb 5 02:24:16 2007 @@ -120,7 +120,7 @@ ##if False and lines != ['In child, calling os.setsid()', ## 'Good: OSError was raised.', '']: ## raise TestFailed("Unexpected output from child: %r" % line) - + (pid, status) = os.waitpid(pid, 0) res = status >> 8 debug("Child (%d) exited with status %d (%d)."%(pid, res, status)) @@ -140,8 +140,8 @@ ## pass ##else: ## raise TestFailed("Read from master_fd did not raise exception") - - + + os.close(master_fd) # pty.fork() passed. Modified: python/branches/p3yk/Lib/test/test_resource.py ============================================================================== --- python/branches/p3yk/Lib/test/test_resource.py (original) +++ python/branches/p3yk/Lib/test/test_resource.py Mon Feb 5 02:24:16 2007 @@ -15,7 +15,7 @@ self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42) def test_fsize_ismax(self): - + try: (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) except AttributeError: @@ -39,7 +39,7 @@ # versions of Python were terminated by an uncaught SIGXFSZ, but # pythonrun.c has been fixed to ignore that exception. If so, the # write() should return EFBIG when the limit is exceeded. - + # At least one platform has an unlimited RLIMIT_FSIZE and attempts # to change it raise ValueError instead. try: Modified: python/branches/p3yk/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk/Lib/test/test_set.py (original) +++ python/branches/p3yk/Lib/test/test_set.py Mon Feb 5 02:24:16 2007 @@ -481,7 +481,7 @@ set.__init__(self, iterable) class TestSetSubclassWithKeywordArgs(TestSet): - + def test_keywords_in_subclass(self): 'SF bug #1486663 -- this used to erroneously raise a TypeError' SetSubclassWithKeywordArgs(newarg=1) @@ -1464,7 +1464,7 @@ test_classes = ( TestSet, TestSetSubclass, - TestSetSubclassWithKeywordArgs, + TestSetSubclassWithKeywordArgs, TestFrozenSet, TestFrozenSetSubclass, TestSetOfSets, Modified: python/branches/p3yk/Lib/test/test_strptime.py ============================================================================== --- python/branches/p3yk/Lib/test/test_strptime.py (original) +++ python/branches/p3yk/Lib/test/test_strptime.py Mon Feb 5 02:24:16 2007 @@ -463,6 +463,10 @@ "of the year") test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and " "ending on Monday") + test_helper((2007, 01, 07), "First Sunday of 2007") + test_helper((2007, 01, 14), "Second Sunday of 2007") + test_helper((2006, 12, 31), "Last Sunday of 2006") + test_helper((2006, 12, 24), "Second to last Sunday of 2006") class CacheTests(unittest.TestCase): Modified: python/branches/p3yk/Lib/test/test_struct.py ============================================================================== --- python/branches/p3yk/Lib/test/test_struct.py (original) +++ python/branches/p3yk/Lib/test/test_struct.py Mon Feb 5 02:24:16 2007 @@ -119,7 +119,7 @@ cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s) if (cp != c or bp != b or hp != h or ip != i or lp != l or int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d) or - tp != t): + tp != t): # ^^^ calculate only to two decimal places raise TestFailed, "unpack/pack not transitive (%s, %s)" % ( str(format), str((cp, bp, hp, ip, lp, fp, dp, tp))) @@ -160,11 +160,11 @@ ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0), ('d', -2.0, '\300\000\000\000\000\000\000\000', '\000\000\000\000\000\000\000\300', 0), - ('t', 0, '\0', '\0', 0), - ('t', 3, '\1', '\1', 1), - ('t', True, '\1', '\1', 0), - ('t', [], '\0', '\0', 1), - ('t', (1,), '\1', '\1', 1), + ('t', 0, '\0', '\0', 0), + ('t', 3, '\1', '\1', 1), + ('t', True, '\1', '\1', 0), + ('t', [], '\0', '\0', 1), + ('t', (1,), '\1', '\1', 1), ] for fmt, arg, big, lil, asy in tests: @@ -621,48 +621,48 @@ test_pack_into_fn() def test_bool(): - for prefix in tuple("<>!=")+('',): - false = (), [], [], '', 0 - true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2 - - falseFormat = prefix + 't' * len(false) - if verbose: - print 'trying bool pack/unpack on', false, 'using format', falseFormat - packedFalse = struct.pack(falseFormat, *false) - unpackedFalse = struct.unpack(falseFormat, packedFalse) - - trueFormat = prefix + 't' * len(true) - if verbose: - print 'trying bool pack/unpack on', true, 'using format', trueFormat - packedTrue = struct.pack(trueFormat, *true) - unpackedTrue = struct.unpack(trueFormat, packedTrue) - - if len(true) != len(unpackedTrue): - raise TestFailed('unpacked true array is not of same size as input') - if len(false) != len(unpackedFalse): - raise TestFailed('unpacked false array is not of same size as input') - - for t in unpackedFalse: - if t is not False: - raise TestFailed('%r did not unpack as False' % t) - for t in unpackedTrue: - if t is not True: - raise TestFailed('%r did not unpack as false' % t) - - if prefix and verbose: - print 'trying size of bool with format %r' % (prefix+'t') - packed = struct.pack(prefix+'t', 1) - - if len(packed) != struct.calcsize(prefix+'t'): - raise TestFailed('packed length is not equal to calculated size') - - if len(packed) != 1 and prefix: - raise TestFailed('encoded bool is not one byte: %r' % packed) - elif not prefix and verbose: - print 'size of bool in native format is %i' % (len(packed)) - - for c in '\x01\x7f\xff\x0f\xf0': - if struct.unpack('>t', c)[0] is not True: - raise TestFailed('%c did not unpack as True' % c) + for prefix in tuple("<>!=")+('',): + false = (), [], [], '', 0 + true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2 + + falseFormat = prefix + 't' * len(false) + if verbose: + print 'trying bool pack/unpack on', false, 'using format', falseFormat + packedFalse = struct.pack(falseFormat, *false) + unpackedFalse = struct.unpack(falseFormat, packedFalse) + + trueFormat = prefix + 't' * len(true) + if verbose: + print 'trying bool pack/unpack on', true, 'using format', trueFormat + packedTrue = struct.pack(trueFormat, *true) + unpackedTrue = struct.unpack(trueFormat, packedTrue) + + if len(true) != len(unpackedTrue): + raise TestFailed('unpacked true array is not of same size as input') + if len(false) != len(unpackedFalse): + raise TestFailed('unpacked false array is not of same size as input') + + for t in unpackedFalse: + if t is not False: + raise TestFailed('%r did not unpack as False' % t) + for t in unpackedTrue: + if t is not True: + raise TestFailed('%r did not unpack as false' % t) + + if prefix and verbose: + print 'trying size of bool with format %r' % (prefix+'t') + packed = struct.pack(prefix+'t', 1) + + if len(packed) != struct.calcsize(prefix+'t'): + raise TestFailed('packed length is not equal to calculated size') + + if len(packed) != 1 and prefix: + raise TestFailed('encoded bool is not one byte: %r' % packed) + elif not prefix and verbose: + print 'size of bool in native format is %i' % (len(packed)) + + for c in '\x01\x7f\xff\x0f\xf0': + if struct.unpack('>t', c)[0] is not True: + raise TestFailed('%c did not unpack as True' % c) test_bool() Modified: python/branches/p3yk/Lib/test/test_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_support.py (original) +++ python/branches/p3yk/Lib/test/test_support.py Mon Feb 5 02:24:16 2007 @@ -270,7 +270,7 @@ print >> get_original_stdout(), '\tfetching %s ...' % url fn, _ = urllib.urlretrieve(url, filename) return open(fn) - + @contextmanager def guard_warnings_filter(): """Guard the warnings filter from being permanently changed.""" Modified: python/branches/p3yk/Modules/_ctypes/cfield.c ============================================================================== --- python/branches/p3yk/Modules/_ctypes/cfield.c (original) +++ python/branches/p3yk/Modules/_ctypes/cfield.c Mon Feb 5 02:24:16 2007 @@ -1432,10 +1432,19 @@ #endif #ifdef MS_WIN32 +/* We cannot use SysFreeString as the PyCObject_FromVoidPtr + because of different calling convention +*/ +static void _my_SysFreeString(void *p) +{ + SysFreeString((BSTR)p); +} + static PyObject * BSTR_set(void *ptr, PyObject *value, unsigned size) { BSTR bstr; + PyObject *result; /* convert value into a PyUnicodeObject or NULL */ if (Py_None == value) { @@ -1463,15 +1472,19 @@ } else bstr = NULL; - /* free the previous contents, if any */ - if (*(BSTR *)ptr) - SysFreeString(*(BSTR *)ptr); - - /* and store it */ - *(BSTR *)ptr = bstr; + if (bstr) { + result = PyCObject_FromVoidPtr((void *)bstr, _my_SysFreeString); + if (result == NULL) { + SysFreeString(bstr); + return NULL; + } + } else { + result = Py_None; + Py_INCREF(result); + } - /* We don't need to keep any other object */ - _RET(value); + *(BSTR *)ptr = bstr; + return result; } Modified: python/branches/p3yk/Modules/posixmodule.c ============================================================================== --- python/branches/p3yk/Modules/posixmodule.c (original) +++ python/branches/p3yk/Modules/posixmodule.c Mon Feb 5 02:24:16 2007 @@ -1462,7 +1462,7 @@ /* POSIX methods */ PyDoc_STRVAR(posix_access__doc__, -"access(path, mode) -> 1 if granted, 0 otherwise\n\n\ +"access(path, mode) -> True if granted, False otherwise\n\n\ Use the real uid/gid to test for access to a path. Note that most\n\ operations will use the effective uid/gid, therefore this routine can\n\ be used in a suid/sgid environment to test if the invoking user has the\n\ Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Mon Feb 5 02:24:16 2007 @@ -935,7 +935,7 @@ if (PyAnySet_Check(other)) return set_merge(so, other); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; while (PyDict_Next(other, &pos, &key, &value)) { @@ -1383,7 +1383,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other) && !PyDict_Check(other)) { + if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1397,7 +1397,7 @@ if (result == NULL) return NULL; - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { while (set_next(so, &pos, &entry)) { setentry entrycopy; entrycopy.hash = entry->hash; @@ -1470,7 +1470,7 @@ if ((PyObject *)so == other) return set_clear(so); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; int rv; while (PyDict_Next(other, &pos, &key, &value)) { Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Mon Feb 5 02:24:16 2007 @@ -2174,8 +2174,9 @@ case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: - /* NOTE: If you add any new block-setup opcodes that are not try/except/finally - handlers, you may need to update the PyGen_NeedsFinalizing() function. */ + /* NOTE: If you add any new block-setup opcodes that are + not try/except/finally handlers, you may need to + update the PyGen_NeedsFinalizing() function. */ PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, STACK_LEVEL()); @@ -4010,6 +4011,35 @@ res = !res; break; case PyCmp_EXC_MATCH: + if (PyTuple_Check(w)) { + Py_ssize_t i, length; + length = PyTuple_Size(w); + for (i = 0; i < length; i += 1) { + PyObject *exc = PyTuple_GET_ITEM(w, i); + if (PyString_Check(exc)) { + int ret_val; + ret_val = PyErr_WarnEx( + PyExc_DeprecationWarning, + "catching of string " + "exceptions is " + "deprecated", 1); + if (ret_val == -1) + return NULL; + } + } + } + else { + if (PyString_Check(w)) { + int ret_val; + ret_val = PyErr_WarnEx( + PyExc_DeprecationWarning, + "catching of string " + "exceptions is deprecated", + 1); + if (ret_val == -1) + return NULL; + } + } res = PyErr_GivenExceptionMatches(v, w); break; default: From python-3000-checkins at python.org Tue Feb 6 22:05:31 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Tue, 6 Feb 2007 22:05:31 +0100 (CET) Subject: [Python-3000-checkins] r53651 - python/branches/p3yk/Objects/longobject.c Message-ID: <20070206210531.234AE1E4022@bag.python.org> Author: martin.v.loewis Date: Tue Feb 6 22:05:30 2007 New Revision: 53651 Modified: python/branches/p3yk/Objects/longobject.c Log: Fix refcounting bugs related to CONVERT_BINOP. Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Tue Feb 6 22:05:30 2007 @@ -2147,8 +2147,12 @@ long_richcompare(PyObject *self, PyObject *other, int op) { PyLongObject *a, *b; + PyObject *result; CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b); - return Py_CmpToRich(op, long_compare(a, b)); + result = Py_CmpToRich(op, long_compare(a, b)); + Py_DECREF(a); + Py_DECREF(b); + return result; } static long @@ -2283,9 +2287,13 @@ CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); - if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) - return PyInt_FromLong(MEDIUM_VALUE(a) + - MEDIUM_VALUE(b)); + if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) { + PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) + + MEDIUM_VALUE(b)); + Py_DECREF(a); + Py_DECREF(b); + return result; + } if (a->ob_size < 0) { if (b->ob_size < 0) { z = x_add(a, b); @@ -2313,8 +2321,13 @@ CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); - if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) - return PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); + if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) { + PyObject* r; + r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); + Py_DECREF(a); + Py_DECREF(b); + return r; + } if (a->ob_size < 0) { if (b->ob_size < 0) z = x_sub(a, b); @@ -2744,8 +2757,13 @@ return Py_NotImplemented; } - if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) - return PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w)); + if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) { + PyObject *r; + r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w)); + Py_DECREF(a); + Py_DECREF(b); + return r; + } z = k_mul(a, b); /* Negate if exactly one of the inputs is negative. */ From python-3000-checkins at python.org Tue Feb 6 22:31:00 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Tue, 6 Feb 2007 22:31:00 +0100 (CET) Subject: [Python-3000-checkins] r53652 - python/branches/p3yk/Objects/iterobject.c Message-ID: <20070206213100.5FF611E4022@bag.python.org> Author: martin.v.loewis Date: Tue Feb 6 22:30:59 2007 New Revision: 53652 Modified: python/branches/p3yk/Objects/iterobject.c Log: Remove bogus INCREF of ziptuple: it is a freshly-allocated tuple object. Modified: python/branches/p3yk/Objects/iterobject.c ============================================================================== --- python/branches/p3yk/Objects/iterobject.c (original) +++ python/branches/p3yk/Objects/iterobject.c Tue Feb 6 22:30:59 2007 @@ -302,7 +302,6 @@ zipiter->result = (PyTupleObject*) result; zipiter->resultsize = tuplesize; - Py_INCREF(ziptuple); zipiter->it_tuple = (PyTupleObject *) ziptuple; _PyObject_GC_TRACK(zipiter); return (PyObject *)zipiter; From python-3000-checkins at python.org Fri Feb 9 06:32:51 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 06:32:51 +0100 (CET) Subject: [Python-3000-checkins] r53685 - in python/branches/p3yk: Grammar/Grammar Include/graminit.h Makefile.pre.in Modules/parsermodule.c Python/ast.c Python/bltinmodule.c Python/graminit.c Python/import.c setup.py Message-ID: <20070209053251.71BCE1E4010@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 06:32:43 2007 New Revision: 53685 Modified: python/branches/p3yk/Grammar/Grammar python/branches/p3yk/Include/graminit.h python/branches/p3yk/Makefile.pre.in python/branches/p3yk/Modules/parsermodule.c python/branches/p3yk/Python/ast.c python/branches/p3yk/Python/bltinmodule.c python/branches/p3yk/Python/graminit.c python/branches/p3yk/Python/import.c python/branches/p3yk/setup.py Log: Essential changes for print function changes. Lib will be changed in a separate run. Modified: python/branches/p3yk/Grammar/Grammar ============================================================================== --- python/branches/p3yk/Grammar/Grammar (original) +++ python/branches/p3yk/Grammar/Grammar Fri Feb 9 06:32:43 2007 @@ -38,15 +38,13 @@ stmt: simple_stmt | compound_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE -small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | +small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | assert_stmt) expr_stmt: testlist (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=') # For normal assignments, additional restrictions enforced by the interpreter -print_stmt: 'print' ( [ test (',' test)* [','] ] | - '>>' test [ (',' test)+ [','] ] ) del_stmt: 'del' exprlist pass_stmt: 'pass' flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt Modified: python/branches/p3yk/Include/graminit.h ============================================================================== --- python/branches/p3yk/Include/graminit.h (original) +++ python/branches/p3yk/Include/graminit.h Fri Feb 9 06:32:43 2007 @@ -18,71 +18,70 @@ #define small_stmt 273 #define expr_stmt 274 #define augassign 275 -#define print_stmt 276 -#define del_stmt 277 -#define pass_stmt 278 -#define flow_stmt 279 -#define break_stmt 280 -#define continue_stmt 281 -#define return_stmt 282 -#define yield_stmt 283 -#define raise_stmt 284 -#define import_stmt 285 -#define import_name 286 -#define import_from 287 -#define import_as_name 288 -#define dotted_as_name 289 -#define import_as_names 290 -#define dotted_as_names 291 -#define dotted_name 292 -#define global_stmt 293 -#define assert_stmt 294 -#define compound_stmt 295 -#define if_stmt 296 -#define while_stmt 297 -#define for_stmt 298 -#define try_stmt 299 -#define with_stmt 300 -#define with_var 301 -#define except_clause 302 -#define suite 303 -#define testlist_safe 304 -#define old_test 305 -#define old_lambdef 306 -#define test 307 -#define or_test 308 -#define and_test 309 -#define not_test 310 -#define comparison 311 -#define comp_op 312 -#define expr 313 -#define xor_expr 314 -#define and_expr 315 -#define shift_expr 316 -#define arith_expr 317 -#define term 318 -#define factor 319 -#define power 320 -#define atom 321 -#define listmaker 322 -#define testlist_gexp 323 -#define lambdef 324 -#define trailer 325 -#define subscriptlist 326 -#define subscript 327 -#define sliceop 328 -#define exprlist 329 -#define testlist 330 -#define dictsetmaker 331 -#define classdef 332 -#define arglist 333 -#define argument 334 -#define list_iter 335 -#define list_for 336 -#define list_if 337 -#define gen_iter 338 -#define gen_for 339 -#define gen_if 340 -#define testlist1 341 -#define encoding_decl 342 -#define yield_expr 343 +#define del_stmt 276 +#define pass_stmt 277 +#define flow_stmt 278 +#define break_stmt 279 +#define continue_stmt 280 +#define return_stmt 281 +#define yield_stmt 282 +#define raise_stmt 283 +#define import_stmt 284 +#define import_name 285 +#define import_from 286 +#define import_as_name 287 +#define dotted_as_name 288 +#define import_as_names 289 +#define dotted_as_names 290 +#define dotted_name 291 +#define global_stmt 292 +#define assert_stmt 293 +#define compound_stmt 294 +#define if_stmt 295 +#define while_stmt 296 +#define for_stmt 297 +#define try_stmt 298 +#define with_stmt 299 +#define with_var 300 +#define except_clause 301 +#define suite 302 +#define testlist_safe 303 +#define old_test 304 +#define old_lambdef 305 +#define test 306 +#define or_test 307 +#define and_test 308 +#define not_test 309 +#define comparison 310 +#define comp_op 311 +#define expr 312 +#define xor_expr 313 +#define and_expr 314 +#define shift_expr 315 +#define arith_expr 316 +#define term 317 +#define factor 318 +#define power 319 +#define atom 320 +#define listmaker 321 +#define testlist_gexp 322 +#define lambdef 323 +#define trailer 324 +#define subscriptlist 325 +#define subscript 326 +#define sliceop 327 +#define exprlist 328 +#define testlist 329 +#define dictsetmaker 330 +#define classdef 331 +#define arglist 332 +#define argument 333 +#define list_iter 334 +#define list_for 335 +#define list_if 336 +#define gen_iter 337 +#define gen_for 338 +#define gen_if 339 +#define testlist1 340 +#define encoding_decl 341 +#define yield_expr 342 Modified: python/branches/p3yk/Makefile.pre.in ============================================================================== --- python/branches/p3yk/Makefile.pre.in (original) +++ python/branches/p3yk/Makefile.pre.in Fri Feb 9 06:32:43 2007 @@ -341,7 +341,7 @@ $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) platform: $(BUILDPYTHON) - $(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from distutils.util import get_platform ; print get_platform()+"-"+sys.version[0:3]' >platform + $(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from distutils.util import get_platform ; print(get_platform()+"-"+sys.version[0:3])' >platform # Build the shared modules Modified: python/branches/p3yk/Modules/parsermodule.c ============================================================================== --- python/branches/p3yk/Modules/parsermodule.c (original) +++ python/branches/p3yk/Modules/parsermodule.c Fri Feb 9 06:32:43 2007 @@ -857,7 +857,7 @@ VALIDATER(vfpdef); VALIDATER(vfplist); VALIDATER(stmt); VALIDATER(simple_stmt); VALIDATER(expr_stmt); VALIDATER(power); -VALIDATER(print_stmt); VALIDATER(del_stmt); +VALIDATER(del_stmt); VALIDATER(return_stmt); VALIDATER(list_iter); VALIDATER(raise_stmt); VALIDATER(import_stmt); VALIDATER(import_name); VALIDATER(import_from); @@ -1545,7 +1545,6 @@ int ntype = TYPE(CHILD(tree, 0)); if ( (ntype == expr_stmt) - || (ntype == print_stmt) || (ntype == del_stmt) || (ntype == pass_stmt) || (ntype == flow_stmt) @@ -1650,54 +1649,6 @@ } -/* print_stmt: - * - * 'print' ( [ test (',' test)* [','] ] - * | '>>' test [ (',' test)+ [','] ] ) - */ -static int -validate_print_stmt(node *tree) -{ - int nch = NCH(tree); - int res = (validate_ntype(tree, print_stmt) - && (nch > 0) - && validate_name(CHILD(tree, 0), "print")); - - if (res && nch > 1) { - int sym = TYPE(CHILD(tree, 1)); - int i = 1; - int allow_trailing_comma = 1; - - if (sym == test) - res = validate_test(CHILD(tree, i++)); - else { - if (nch < 3) - res = validate_numnodes(tree, 3, "print_stmt"); - else { - res = (validate_ntype(CHILD(tree, i), RIGHTSHIFT) - && validate_test(CHILD(tree, i+1))); - i += 2; - allow_trailing_comma = 0; - } - } - if (res) { - /* ... (',' test)* [','] */ - while (res && i+2 <= nch) { - res = (validate_comma(CHILD(tree, i)) - && validate_test(CHILD(tree, i+1))); - allow_trailing_comma = 1; - i += 2; - } - if (res && !allow_trailing_comma) - res = validate_numnodes(tree, i, "print_stmt"); - else if (res && i < nch) - res = validate_comma(CHILD(tree, i)); - } - } - return (res); -} - - static int validate_del_stmt(node *tree) { @@ -2977,7 +2928,7 @@ break; case small_stmt: /* - * expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt + * expr_stmt | del_stmt | pass_stmt | flow_stmt * | import_stmt | global_stmt | assert_stmt */ res = validate_small_stmt(tree); @@ -3012,9 +2963,6 @@ case expr_stmt: res = validate_expr_stmt(tree); break; - case print_stmt: - res = validate_print_stmt(tree); - break; case del_stmt: res = validate_del_stmt(tree); break; Modified: python/branches/p3yk/Python/ast.c ============================================================================== --- python/branches/p3yk/Python/ast.c (original) +++ python/branches/p3yk/Python/ast.c Fri Feb 9 06:32:43 2007 @@ -2218,37 +2218,6 @@ } } -static stmt_ty -ast_for_print_stmt(struct compiling *c, const node *n) -{ - /* print_stmt: 'print' ( [ test (',' test)* [','] ] - | '>>' test [ (',' test)+ [','] ] ) - */ - expr_ty dest = NULL, expression; - asdl_seq *seq; - bool nl; - int i, j, start = 1; - - REQ(n, print_stmt); - if (NCH(n) >= 2 && TYPE(CHILD(n, 1)) == RIGHTSHIFT) { - dest = ast_for_expr(c, CHILD(n, 2)); - if (!dest) - return NULL; - start = 4; - } - seq = asdl_seq_new((NCH(n) + 1 - start) / 2, c->c_arena); - if (!seq) - return NULL; - for (i = start, j = 0; i < NCH(n); i += 2, ++j) { - expression = ast_for_expr(c, CHILD(n, i)); - if (!expression) - return NULL; - asdl_seq_SET(seq, j, expression); - } - nl = (TYPE(CHILD(n, NCH(n) - 1)) == COMMA) ? false : true; - return Print(dest, seq, nl, LINENO(n), n->n_col_offset, c->c_arena); -} - static asdl_seq * ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context) { @@ -3089,14 +3058,12 @@ if (TYPE(n) == small_stmt) { REQ(n, small_stmt); n = CHILD(n, 0); - /* small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt + /* small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | assert_stmt */ switch (TYPE(n)) { case expr_stmt: return ast_for_expr_stmt(c, n); - case print_stmt: - return ast_for_print_stmt(c, n); case del_stmt: return ast_for_del_stmt(c, n); case pass_stmt: Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Fri Feb 9 06:32:43 2007 @@ -1446,7 +1446,7 @@ } PyDoc_STRVAR(print_doc, -"Print(value, ..., file=None, sep=' ', end='\\n')\n\ +"print(value, ..., file=None, sep=' ', end='\\n')\n\ \n\ Prints the values to a stream, or to sys.stdout by default.\n\ Optional keyword arguments:\n\ @@ -2056,7 +2056,7 @@ {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc}, {"ord", builtin_ord, METH_O, ord_doc}, {"pow", builtin_pow, METH_VARARGS, pow_doc}, - {"Print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, + {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, {"range", builtin_range, METH_VARARGS, range_doc}, {"reload", builtin_reload, METH_O, reload_doc}, {"repr", builtin_repr, METH_O, repr_doc}, Modified: python/branches/p3yk/Python/graminit.c ============================================================================== --- python/branches/p3yk/Python/graminit.c (original) +++ python/branches/p3yk/Python/graminit.c Fri Feb 9 06:32:43 2007 @@ -403,7 +403,7 @@ {2, arcs_16_2}, {1, arcs_16_3}, }; -static arc arcs_17_0[8] = { +static arc arcs_17_0[7] = { {39, 1}, {40, 1}, {41, 1}, @@ -411,29 +411,28 @@ {43, 1}, {44, 1}, {45, 1}, - {46, 1}, }; static arc arcs_17_1[1] = { {0, 1}, }; static state states_17[2] = { - {8, arcs_17_0}, + {7, arcs_17_0}, {1, arcs_17_1}, }; static arc arcs_18_0[1] = { {9, 1}, }; static arc arcs_18_1[3] = { - {47, 2}, + {46, 2}, {27, 3}, {0, 1}, }; static arc arcs_18_2[2] = { - {48, 4}, + {47, 4}, {9, 4}, }; static arc arcs_18_3[2] = { - {48, 5}, + {47, 5}, {9, 5}, }; static arc arcs_18_4[1] = { @@ -452,6 +451,7 @@ {2, arcs_18_5}, }; static arc arcs_19_0[12] = { + {48, 1}, {49, 1}, {50, 1}, {51, 1}, @@ -463,7 +463,6 @@ {57, 1}, {58, 1}, {59, 1}, - {60, 1}, }; static arc arcs_19_1[1] = { {0, 1}, @@ -473,90 +472,55 @@ {1, arcs_19_1}, }; static arc arcs_20_0[1] = { - {61, 1}, + {60, 1}, }; -static arc arcs_20_1[3] = { - {22, 2}, - {62, 3}, - {0, 1}, +static arc arcs_20_1[1] = { + {61, 2}, }; -static arc arcs_20_2[2] = { - {28, 4}, +static arc arcs_20_2[1] = { {0, 2}, }; -static arc arcs_20_3[1] = { - {22, 5}, -}; -static arc arcs_20_4[2] = { - {22, 2}, - {0, 4}, -}; -static arc arcs_20_5[2] = { - {28, 6}, - {0, 5}, -}; -static arc arcs_20_6[1] = { - {22, 7}, -}; -static arc arcs_20_7[2] = { - {28, 8}, - {0, 7}, -}; -static arc arcs_20_8[2] = { - {22, 7}, - {0, 8}, -}; -static state states_20[9] = { +static state states_20[3] = { {1, arcs_20_0}, - {3, arcs_20_1}, - {2, arcs_20_2}, - {1, arcs_20_3}, - {2, arcs_20_4}, - {2, arcs_20_5}, - {1, arcs_20_6}, - {2, arcs_20_7}, - {2, arcs_20_8}, + {1, arcs_20_1}, + {1, arcs_20_2}, }; static arc arcs_21_0[1] = { - {63, 1}, + {62, 1}, }; static arc arcs_21_1[1] = { - {64, 2}, -}; -static arc arcs_21_2[1] = { - {0, 2}, + {0, 1}, }; -static state states_21[3] = { +static state states_21[2] = { {1, arcs_21_0}, {1, arcs_21_1}, - {1, arcs_21_2}, }; -static arc arcs_22_0[1] = { +static arc arcs_22_0[5] = { + {63, 1}, + {64, 1}, {65, 1}, + {66, 1}, + {67, 1}, }; static arc arcs_22_1[1] = { {0, 1}, }; static state states_22[2] = { - {1, arcs_22_0}, + {5, arcs_22_0}, {1, arcs_22_1}, }; -static arc arcs_23_0[5] = { - {66, 1}, - {67, 1}, +static arc arcs_23_0[1] = { {68, 1}, - {69, 1}, - {70, 1}, }; static arc arcs_23_1[1] = { {0, 1}, }; static state states_23[2] = { - {5, arcs_23_0}, + {1, arcs_23_0}, {1, arcs_23_1}, }; static arc arcs_24_0[1] = { - {71, 1}, + {69, 1}, }; static arc arcs_24_1[1] = { {0, 1}, @@ -566,142 +530,151 @@ {1, arcs_24_1}, }; static arc arcs_25_0[1] = { - {72, 1}, + {70, 1}, }; -static arc arcs_25_1[1] = { +static arc arcs_25_1[2] = { + {9, 2}, {0, 1}, }; -static state states_25[2] = { +static arc arcs_25_2[1] = { + {0, 2}, +}; +static state states_25[3] = { {1, arcs_25_0}, - {1, arcs_25_1}, + {2, arcs_25_1}, + {1, arcs_25_2}, }; static arc arcs_26_0[1] = { - {73, 1}, + {47, 1}, }; -static arc arcs_26_1[2] = { - {9, 2}, +static arc arcs_26_1[1] = { {0, 1}, }; -static arc arcs_26_2[1] = { - {0, 2}, -}; -static state states_26[3] = { +static state states_26[2] = { {1, arcs_26_0}, - {2, arcs_26_1}, - {1, arcs_26_2}, + {1, arcs_26_1}, }; static arc arcs_27_0[1] = { - {48, 1}, -}; -static arc arcs_27_1[1] = { - {0, 1}, -}; -static state states_27[2] = { - {1, arcs_27_0}, - {1, arcs_27_1}, -}; -static arc arcs_28_0[1] = { - {74, 1}, + {71, 1}, }; -static arc arcs_28_1[2] = { +static arc arcs_27_1[2] = { {22, 2}, {0, 1}, }; -static arc arcs_28_2[2] = { +static arc arcs_27_2[2] = { {28, 3}, {0, 2}, }; -static arc arcs_28_3[1] = { +static arc arcs_27_3[1] = { {22, 4}, }; -static arc arcs_28_4[2] = { +static arc arcs_27_4[2] = { {28, 5}, {0, 4}, }; -static arc arcs_28_5[1] = { +static arc arcs_27_5[1] = { {22, 6}, }; -static arc arcs_28_6[1] = { +static arc arcs_27_6[1] = { {0, 6}, }; -static state states_28[7] = { - {1, arcs_28_0}, - {2, arcs_28_1}, - {2, arcs_28_2}, - {1, arcs_28_3}, - {2, arcs_28_4}, - {1, arcs_28_5}, - {1, arcs_28_6}, +static state states_27[7] = { + {1, arcs_27_0}, + {2, arcs_27_1}, + {2, arcs_27_2}, + {1, arcs_27_3}, + {2, arcs_27_4}, + {1, arcs_27_5}, + {1, arcs_27_6}, }; -static arc arcs_29_0[2] = { - {75, 1}, - {76, 1}, +static arc arcs_28_0[2] = { + {72, 1}, + {73, 1}, }; -static arc arcs_29_1[1] = { +static arc arcs_28_1[1] = { {0, 1}, }; -static state states_29[2] = { - {2, arcs_29_0}, - {1, arcs_29_1}, +static state states_28[2] = { + {2, arcs_28_0}, + {1, arcs_28_1}, }; -static arc arcs_30_0[1] = { - {77, 1}, +static arc arcs_29_0[1] = { + {74, 1}, }; -static arc arcs_30_1[1] = { - {78, 2}, +static arc arcs_29_1[1] = { + {75, 2}, }; -static arc arcs_30_2[1] = { +static arc arcs_29_2[1] = { {0, 2}, }; -static state states_30[3] = { - {1, arcs_30_0}, - {1, arcs_30_1}, - {1, arcs_30_2}, +static state states_29[3] = { + {1, arcs_29_0}, + {1, arcs_29_1}, + {1, arcs_29_2}, }; -static arc arcs_31_0[1] = { - {79, 1}, +static arc arcs_30_0[1] = { + {76, 1}, }; -static arc arcs_31_1[2] = { - {80, 2}, +static arc arcs_30_1[2] = { + {77, 2}, {12, 3}, }; -static arc arcs_31_2[3] = { - {80, 2}, +static arc arcs_30_2[3] = { + {77, 2}, {12, 3}, - {77, 4}, + {74, 4}, }; -static arc arcs_31_3[1] = { - {77, 4}, +static arc arcs_30_3[1] = { + {74, 4}, }; -static arc arcs_31_4[3] = { +static arc arcs_30_4[3] = { {29, 5}, {13, 6}, - {81, 5}, + {78, 5}, }; -static arc arcs_31_5[1] = { +static arc arcs_30_5[1] = { {0, 5}, }; -static arc arcs_31_6[1] = { - {81, 7}, +static arc arcs_30_6[1] = { + {78, 7}, }; -static arc arcs_31_7[1] = { +static arc arcs_30_7[1] = { {15, 5}, }; -static state states_31[8] = { +static state states_30[8] = { + {1, arcs_30_0}, + {2, arcs_30_1}, + {3, arcs_30_2}, + {1, arcs_30_3}, + {3, arcs_30_4}, + {1, arcs_30_5}, + {1, arcs_30_6}, + {1, arcs_30_7}, +}; +static arc arcs_31_0[1] = { + {19, 1}, +}; +static arc arcs_31_1[2] = { + {80, 2}, + {0, 1}, +}; +static arc arcs_31_2[1] = { + {19, 3}, +}; +static arc arcs_31_3[1] = { + {0, 3}, +}; +static state states_31[4] = { {1, arcs_31_0}, {2, arcs_31_1}, - {3, arcs_31_2}, + {1, arcs_31_2}, {1, arcs_31_3}, - {3, arcs_31_4}, - {1, arcs_31_5}, - {1, arcs_31_6}, - {1, arcs_31_7}, }; static arc arcs_32_0[1] = { - {19, 1}, + {12, 1}, }; static arc arcs_32_1[2] = { - {83, 2}, + {80, 2}, {0, 1}, }; static arc arcs_32_2[1] = { @@ -717,45 +690,37 @@ {1, arcs_32_3}, }; static arc arcs_33_0[1] = { - {12, 1}, + {79, 1}, }; static arc arcs_33_1[2] = { - {83, 2}, + {28, 2}, {0, 1}, }; -static arc arcs_33_2[1] = { - {19, 3}, -}; -static arc arcs_33_3[1] = { - {0, 3}, +static arc arcs_33_2[2] = { + {79, 1}, + {0, 2}, }; -static state states_33[4] = { +static state states_33[3] = { {1, arcs_33_0}, {2, arcs_33_1}, - {1, arcs_33_2}, - {1, arcs_33_3}, + {2, arcs_33_2}, }; static arc arcs_34_0[1] = { - {82, 1}, + {81, 1}, }; static arc arcs_34_1[2] = { - {28, 2}, + {28, 0}, {0, 1}, }; -static arc arcs_34_2[2] = { - {82, 1}, - {0, 2}, -}; -static state states_34[3] = { +static state states_34[2] = { {1, arcs_34_0}, {2, arcs_34_1}, - {2, arcs_34_2}, }; static arc arcs_35_0[1] = { - {84, 1}, + {19, 1}, }; static arc arcs_35_1[2] = { - {28, 0}, + {77, 0}, {0, 1}, }; static state states_35[2] = { @@ -763,69 +728,94 @@ {2, arcs_35_1}, }; static arc arcs_36_0[1] = { - {19, 1}, + {82, 1}, }; -static arc arcs_36_1[2] = { - {80, 0}, - {0, 1}, +static arc arcs_36_1[1] = { + {19, 2}, }; -static state states_36[2] = { +static arc arcs_36_2[2] = { + {28, 1}, + {0, 2}, +}; +static state states_36[3] = { {1, arcs_36_0}, - {2, arcs_36_1}, + {1, arcs_36_1}, + {2, arcs_36_2}, }; static arc arcs_37_0[1] = { - {85, 1}, + {83, 1}, }; static arc arcs_37_1[1] = { - {19, 2}, + {22, 2}, }; static arc arcs_37_2[2] = { - {28, 1}, + {28, 3}, {0, 2}, }; -static state states_37[3] = { +static arc arcs_37_3[1] = { + {22, 4}, +}; +static arc arcs_37_4[1] = { + {0, 4}, +}; +static state states_37[5] = { {1, arcs_37_0}, {1, arcs_37_1}, {2, arcs_37_2}, + {1, arcs_37_3}, + {1, arcs_37_4}, }; -static arc arcs_38_0[1] = { +static arc arcs_38_0[7] = { + {84, 1}, + {85, 1}, {86, 1}, + {87, 1}, + {88, 1}, + {17, 1}, + {89, 1}, }; static arc arcs_38_1[1] = { + {0, 1}, +}; +static state states_38[2] = { + {7, arcs_38_0}, + {1, arcs_38_1}, +}; +static arc arcs_39_0[1] = { + {90, 1}, +}; +static arc arcs_39_1[1] = { {22, 2}, }; -static arc arcs_38_2[2] = { - {28, 3}, - {0, 2}, +static arc arcs_39_2[1] = { + {23, 3}, }; -static arc arcs_38_3[1] = { - {22, 4}, +static arc arcs_39_3[1] = { + {24, 4}, }; -static arc arcs_38_4[1] = { +static arc arcs_39_4[3] = { + {91, 1}, + {92, 5}, {0, 4}, }; -static state states_38[5] = { - {1, arcs_38_0}, - {1, arcs_38_1}, - {2, arcs_38_2}, - {1, arcs_38_3}, - {1, arcs_38_4}, +static arc arcs_39_5[1] = { + {23, 6}, }; -static arc arcs_39_0[7] = { - {87, 1}, - {88, 1}, - {89, 1}, - {90, 1}, - {91, 1}, - {17, 1}, - {92, 1}, +static arc arcs_39_6[1] = { + {24, 7}, }; -static arc arcs_39_1[1] = { - {0, 1}, +static arc arcs_39_7[1] = { + {0, 7}, }; -static state states_39[2] = { - {7, arcs_39_0}, +static state states_39[8] = { + {1, arcs_39_0}, {1, arcs_39_1}, + {1, arcs_39_2}, + {1, arcs_39_3}, + {3, arcs_39_4}, + {1, arcs_39_5}, + {1, arcs_39_6}, + {1, arcs_39_7}, }; static arc arcs_40_0[1] = { {93, 1}, @@ -839,9 +829,8 @@ static arc arcs_40_3[1] = { {24, 4}, }; -static arc arcs_40_4[3] = { - {94, 1}, - {95, 5}, +static arc arcs_40_4[2] = { + {92, 5}, {0, 4}, }; static arc arcs_40_5[1] = { @@ -858,404 +847,380 @@ {1, arcs_40_1}, {1, arcs_40_2}, {1, arcs_40_3}, - {3, arcs_40_4}, + {2, arcs_40_4}, {1, arcs_40_5}, {1, arcs_40_6}, {1, arcs_40_7}, }; static arc arcs_41_0[1] = { - {96, 1}, + {94, 1}, }; static arc arcs_41_1[1] = { - {22, 2}, + {61, 2}, }; static arc arcs_41_2[1] = { - {23, 3}, + {95, 3}, }; static arc arcs_41_3[1] = { - {24, 4}, + {9, 4}, }; -static arc arcs_41_4[2] = { - {95, 5}, - {0, 4}, +static arc arcs_41_4[1] = { + {23, 5}, }; static arc arcs_41_5[1] = { - {23, 6}, + {24, 6}, }; -static arc arcs_41_6[1] = { - {24, 7}, +static arc arcs_41_6[2] = { + {92, 7}, + {0, 6}, }; static arc arcs_41_7[1] = { - {0, 7}, + {23, 8}, +}; +static arc arcs_41_8[1] = { + {24, 9}, +}; +static arc arcs_41_9[1] = { + {0, 9}, }; -static state states_41[8] = { +static state states_41[10] = { {1, arcs_41_0}, {1, arcs_41_1}, {1, arcs_41_2}, {1, arcs_41_3}, - {2, arcs_41_4}, + {1, arcs_41_4}, {1, arcs_41_5}, - {1, arcs_41_6}, + {2, arcs_41_6}, {1, arcs_41_7}, + {1, arcs_41_8}, + {1, arcs_41_9}, }; static arc arcs_42_0[1] = { - {97, 1}, + {96, 1}, }; static arc arcs_42_1[1] = { - {64, 2}, + {23, 2}, }; static arc arcs_42_2[1] = { - {98, 3}, + {24, 3}, }; -static arc arcs_42_3[1] = { - {9, 4}, +static arc arcs_42_3[2] = { + {97, 4}, + {98, 5}, }; static arc arcs_42_4[1] = { - {23, 5}, + {23, 6}, }; static arc arcs_42_5[1] = { - {24, 6}, + {23, 7}, }; -static arc arcs_42_6[2] = { - {95, 7}, - {0, 6}, +static arc arcs_42_6[1] = { + {24, 8}, }; static arc arcs_42_7[1] = { - {23, 8}, -}; -static arc arcs_42_8[1] = { {24, 9}, }; +static arc arcs_42_8[4] = { + {97, 4}, + {92, 10}, + {98, 5}, + {0, 8}, +}; static arc arcs_42_9[1] = { {0, 9}, }; -static state states_42[10] = { +static arc arcs_42_10[1] = { + {23, 11}, +}; +static arc arcs_42_11[1] = { + {24, 12}, +}; +static arc arcs_42_12[2] = { + {98, 5}, + {0, 12}, +}; +static state states_42[13] = { {1, arcs_42_0}, {1, arcs_42_1}, {1, arcs_42_2}, - {1, arcs_42_3}, + {2, arcs_42_3}, {1, arcs_42_4}, {1, arcs_42_5}, - {2, arcs_42_6}, + {1, arcs_42_6}, {1, arcs_42_7}, - {1, arcs_42_8}, + {4, arcs_42_8}, {1, arcs_42_9}, + {1, arcs_42_10}, + {1, arcs_42_11}, + {2, arcs_42_12}, }; static arc arcs_43_0[1] = { {99, 1}, }; static arc arcs_43_1[1] = { - {23, 2}, + {22, 2}, }; -static arc arcs_43_2[1] = { - {24, 3}, +static arc arcs_43_2[2] = { + {100, 3}, + {23, 4}, }; -static arc arcs_43_3[2] = { - {100, 4}, - {101, 5}, +static arc arcs_43_3[1] = { + {23, 4}, }; static arc arcs_43_4[1] = { - {23, 6}, + {24, 5}, }; static arc arcs_43_5[1] = { - {23, 7}, -}; -static arc arcs_43_6[1] = { - {24, 8}, -}; -static arc arcs_43_7[1] = { - {24, 9}, -}; -static arc arcs_43_8[4] = { - {100, 4}, - {95, 10}, - {101, 5}, - {0, 8}, -}; -static arc arcs_43_9[1] = { - {0, 9}, -}; -static arc arcs_43_10[1] = { - {23, 11}, -}; -static arc arcs_43_11[1] = { - {24, 12}, -}; -static arc arcs_43_12[2] = { - {101, 5}, - {0, 12}, + {0, 5}, }; -static state states_43[13] = { +static state states_43[6] = { {1, arcs_43_0}, {1, arcs_43_1}, - {1, arcs_43_2}, - {2, arcs_43_3}, + {2, arcs_43_2}, + {1, arcs_43_3}, {1, arcs_43_4}, {1, arcs_43_5}, - {1, arcs_43_6}, - {1, arcs_43_7}, - {4, arcs_43_8}, - {1, arcs_43_9}, - {1, arcs_43_10}, - {1, arcs_43_11}, - {2, arcs_43_12}, }; static arc arcs_44_0[1] = { - {102, 1}, + {80, 1}, }; static arc arcs_44_1[1] = { - {22, 2}, -}; -static arc arcs_44_2[2] = { - {103, 3}, - {23, 4}, + {101, 2}, }; -static arc arcs_44_3[1] = { - {23, 4}, -}; -static arc arcs_44_4[1] = { - {24, 5}, -}; -static arc arcs_44_5[1] = { - {0, 5}, +static arc arcs_44_2[1] = { + {0, 2}, }; -static state states_44[6] = { +static state states_44[3] = { {1, arcs_44_0}, {1, arcs_44_1}, - {2, arcs_44_2}, - {1, arcs_44_3}, - {1, arcs_44_4}, - {1, arcs_44_5}, + {1, arcs_44_2}, }; static arc arcs_45_0[1] = { - {83, 1}, + {102, 1}, }; -static arc arcs_45_1[1] = { - {104, 2}, +static arc arcs_45_1[2] = { + {22, 2}, + {0, 1}, }; -static arc arcs_45_2[1] = { +static arc arcs_45_2[2] = { + {80, 3}, {0, 2}, }; -static state states_45[3] = { +static arc arcs_45_3[1] = { + {19, 4}, +}; +static arc arcs_45_4[1] = { + {0, 4}, +}; +static state states_45[5] = { {1, arcs_45_0}, - {1, arcs_45_1}, - {1, arcs_45_2}, + {2, arcs_45_1}, + {2, arcs_45_2}, + {1, arcs_45_3}, + {1, arcs_45_4}, }; -static arc arcs_46_0[1] = { - {105, 1}, +static arc arcs_46_0[2] = { + {3, 1}, + {2, 2}, }; -static arc arcs_46_1[2] = { - {22, 2}, +static arc arcs_46_1[1] = { {0, 1}, }; -static arc arcs_46_2[2] = { - {83, 3}, - {0, 2}, +static arc arcs_46_2[1] = { + {103, 3}, }; static arc arcs_46_3[1] = { - {19, 4}, + {6, 4}, }; -static arc arcs_46_4[1] = { - {0, 4}, +static arc arcs_46_4[2] = { + {6, 4}, + {104, 1}, }; static state states_46[5] = { - {1, arcs_46_0}, - {2, arcs_46_1}, - {2, arcs_46_2}, + {2, arcs_46_0}, + {1, arcs_46_1}, + {1, arcs_46_2}, {1, arcs_46_3}, - {1, arcs_46_4}, + {2, arcs_46_4}, }; -static arc arcs_47_0[2] = { - {3, 1}, - {2, 2}, +static arc arcs_47_0[1] = { + {106, 1}, }; -static arc arcs_47_1[1] = { +static arc arcs_47_1[2] = { + {28, 2}, {0, 1}, }; static arc arcs_47_2[1] = { {106, 3}, }; -static arc arcs_47_3[1] = { - {6, 4}, +static arc arcs_47_3[2] = { + {28, 4}, + {0, 3}, }; static arc arcs_47_4[2] = { - {6, 4}, - {107, 1}, + {106, 3}, + {0, 4}, }; static state states_47[5] = { - {2, arcs_47_0}, - {1, arcs_47_1}, + {1, arcs_47_0}, + {2, arcs_47_1}, {1, arcs_47_2}, - {1, arcs_47_3}, + {2, arcs_47_3}, {2, arcs_47_4}, }; -static arc arcs_48_0[1] = { - {109, 1}, +static arc arcs_48_0[2] = { + {107, 1}, + {108, 1}, }; -static arc arcs_48_1[2] = { - {28, 2}, +static arc arcs_48_1[1] = { {0, 1}, }; -static arc arcs_48_2[1] = { - {109, 3}, +static state states_48[2] = { + {2, arcs_48_0}, + {1, arcs_48_1}, }; -static arc arcs_48_3[2] = { - {28, 4}, - {0, 3}, +static arc arcs_49_0[1] = { + {109, 1}, }; -static arc arcs_48_4[2] = { - {109, 3}, - {0, 4}, +static arc arcs_49_1[2] = { + {33, 2}, + {23, 3}, }; -static state states_48[5] = { - {1, arcs_48_0}, - {2, arcs_48_1}, - {1, arcs_48_2}, - {2, arcs_48_3}, - {2, arcs_48_4}, +static arc arcs_49_2[1] = { + {23, 3}, }; -static arc arcs_49_0[2] = { - {110, 1}, - {111, 1}, +static arc arcs_49_3[1] = { + {106, 4}, }; -static arc arcs_49_1[1] = { - {0, 1}, +static arc arcs_49_4[1] = { + {0, 4}, }; -static state states_49[2] = { - {2, arcs_49_0}, - {1, arcs_49_1}, +static state states_49[5] = { + {1, arcs_49_0}, + {2, arcs_49_1}, + {1, arcs_49_2}, + {1, arcs_49_3}, + {1, arcs_49_4}, }; -static arc arcs_50_0[1] = { - {112, 1}, +static arc arcs_50_0[2] = { + {107, 1}, + {110, 2}, }; static arc arcs_50_1[2] = { - {33, 2}, - {23, 3}, + {90, 3}, + {0, 1}, }; static arc arcs_50_2[1] = { - {23, 3}, + {0, 2}, }; static arc arcs_50_3[1] = { - {109, 4}, + {107, 4}, }; static arc arcs_50_4[1] = { - {0, 4}, + {92, 5}, +}; +static arc arcs_50_5[1] = { + {22, 2}, }; -static state states_50[5] = { - {1, arcs_50_0}, +static state states_50[6] = { + {2, arcs_50_0}, {2, arcs_50_1}, {1, arcs_50_2}, {1, arcs_50_3}, {1, arcs_50_4}, + {1, arcs_50_5}, }; -static arc arcs_51_0[2] = { - {110, 1}, - {113, 2}, +static arc arcs_51_0[1] = { + {111, 1}, }; static arc arcs_51_1[2] = { - {93, 3}, + {112, 0}, {0, 1}, }; -static arc arcs_51_2[1] = { - {0, 2}, -}; -static arc arcs_51_3[1] = { - {110, 4}, -}; -static arc arcs_51_4[1] = { - {95, 5}, -}; -static arc arcs_51_5[1] = { - {22, 2}, -}; -static state states_51[6] = { - {2, arcs_51_0}, +static state states_51[2] = { + {1, arcs_51_0}, {2, arcs_51_1}, - {1, arcs_51_2}, - {1, arcs_51_3}, - {1, arcs_51_4}, - {1, arcs_51_5}, }; static arc arcs_52_0[1] = { - {114, 1}, + {113, 1}, }; static arc arcs_52_1[2] = { - {115, 0}, + {114, 0}, {0, 1}, }; static state states_52[2] = { {1, arcs_52_0}, {2, arcs_52_1}, }; -static arc arcs_53_0[1] = { - {116, 1}, -}; -static arc arcs_53_1[2] = { - {117, 0}, - {0, 1}, -}; -static state states_53[2] = { - {1, arcs_53_0}, - {2, arcs_53_1}, -}; -static arc arcs_54_0[2] = { - {118, 1}, - {119, 2}, -}; -static arc arcs_54_1[1] = { +static arc arcs_53_0[2] = { + {115, 1}, {116, 2}, }; -static arc arcs_54_2[1] = { +static arc arcs_53_1[1] = { + {113, 2}, +}; +static arc arcs_53_2[1] = { {0, 2}, }; -static state states_54[3] = { - {2, arcs_54_0}, - {1, arcs_54_1}, - {1, arcs_54_2}, +static state states_53[3] = { + {2, arcs_53_0}, + {1, arcs_53_1}, + {1, arcs_53_2}, }; -static arc arcs_55_0[1] = { - {104, 1}, +static arc arcs_54_0[1] = { + {101, 1}, }; -static arc arcs_55_1[2] = { - {120, 0}, +static arc arcs_54_1[2] = { + {117, 0}, {0, 1}, }; -static state states_55[2] = { - {1, arcs_55_0}, - {2, arcs_55_1}, +static state states_54[2] = { + {1, arcs_54_0}, + {2, arcs_54_1}, }; -static arc arcs_56_0[9] = { +static arc arcs_55_0[9] = { + {118, 1}, + {119, 1}, + {120, 1}, {121, 1}, {122, 1}, {123, 1}, - {124, 1}, - {125, 1}, - {126, 1}, - {98, 1}, - {118, 2}, - {127, 3}, + {95, 1}, + {115, 2}, + {124, 3}, }; -static arc arcs_56_1[1] = { +static arc arcs_55_1[1] = { {0, 1}, }; -static arc arcs_56_2[1] = { - {98, 1}, +static arc arcs_55_2[1] = { + {95, 1}, }; -static arc arcs_56_3[2] = { - {118, 1}, +static arc arcs_55_3[2] = { + {115, 1}, {0, 3}, }; -static state states_56[4] = { - {9, arcs_56_0}, - {1, arcs_56_1}, - {1, arcs_56_2}, - {2, arcs_56_3}, +static state states_55[4] = { + {9, arcs_55_0}, + {1, arcs_55_1}, + {1, arcs_55_2}, + {2, arcs_55_3}, +}; +static arc arcs_56_0[1] = { + {125, 1}, +}; +static arc arcs_56_1[2] = { + {126, 0}, + {0, 1}, +}; +static state states_56[2] = { + {1, arcs_56_0}, + {2, arcs_56_1}, }; static arc arcs_57_0[1] = { - {128, 1}, + {127, 1}, }; static arc arcs_57_1[2] = { - {129, 0}, + {128, 0}, {0, 1}, }; static state states_57[2] = { @@ -1263,10 +1228,10 @@ {2, arcs_57_1}, }; static arc arcs_58_0[1] = { - {130, 1}, + {129, 1}, }; static arc arcs_58_1[2] = { - {131, 0}, + {130, 0}, {0, 1}, }; static state states_58[2] = { @@ -1274,22 +1239,23 @@ {2, arcs_58_1}, }; static arc arcs_59_0[1] = { - {132, 1}, + {131, 1}, }; -static arc arcs_59_1[2] = { +static arc arcs_59_1[3] = { + {132, 0}, {133, 0}, {0, 1}, }; static state states_59[2] = { {1, arcs_59_0}, - {2, arcs_59_1}, + {3, arcs_59_1}, }; static arc arcs_60_0[1] = { {134, 1}, }; static arc arcs_60_1[3] = { {135, 0}, - {62, 0}, + {136, 0}, {0, 1}, }; static state states_60[2] = { @@ -1297,300 +1263,304 @@ {3, arcs_60_1}, }; static arc arcs_61_0[1] = { - {136, 1}, + {137, 1}, }; -static arc arcs_61_1[3] = { - {137, 0}, +static arc arcs_61_1[5] = { + {29, 0}, {138, 0}, + {139, 0}, + {140, 0}, {0, 1}, }; static state states_61[2] = { {1, arcs_61_0}, - {3, arcs_61_1}, + {5, arcs_61_1}, }; -static arc arcs_62_0[1] = { - {139, 1}, -}; -static arc arcs_62_1[5] = { - {29, 0}, - {140, 0}, - {141, 0}, - {142, 0}, - {0, 1}, -}; -static state states_62[2] = { - {1, arcs_62_0}, - {5, arcs_62_1}, -}; -static arc arcs_63_0[4] = { - {137, 1}, - {138, 1}, - {143, 1}, - {144, 2}, +static arc arcs_62_0[4] = { + {135, 1}, + {136, 1}, + {141, 1}, + {142, 2}, }; -static arc arcs_63_1[1] = { - {139, 2}, +static arc arcs_62_1[1] = { + {137, 2}, }; -static arc arcs_63_2[1] = { +static arc arcs_62_2[1] = { {0, 2}, }; -static state states_63[3] = { - {4, arcs_63_0}, - {1, arcs_63_1}, - {1, arcs_63_2}, +static state states_62[3] = { + {4, arcs_62_0}, + {1, arcs_62_1}, + {1, arcs_62_2}, }; -static arc arcs_64_0[1] = { - {145, 1}, +static arc arcs_63_0[1] = { + {143, 1}, }; -static arc arcs_64_1[3] = { - {146, 1}, +static arc arcs_63_1[3] = { + {144, 1}, {31, 2}, {0, 1}, }; -static arc arcs_64_2[1] = { - {139, 3}, +static arc arcs_63_2[1] = { + {137, 3}, }; -static arc arcs_64_3[1] = { +static arc arcs_63_3[1] = { {0, 3}, }; -static state states_64[4] = { - {1, arcs_64_0}, - {3, arcs_64_1}, - {1, arcs_64_2}, - {1, arcs_64_3}, +static state states_63[4] = { + {1, arcs_63_0}, + {3, arcs_63_1}, + {1, arcs_63_2}, + {1, arcs_63_3}, }; -static arc arcs_65_0[7] = { +static arc arcs_64_0[7] = { {13, 1}, - {148, 2}, - {151, 3}, + {146, 2}, + {149, 3}, {19, 4}, - {154, 4}, - {155, 5}, - {80, 6}, + {152, 4}, + {153, 5}, + {77, 6}, }; -static arc arcs_65_1[3] = { - {48, 7}, - {147, 7}, +static arc arcs_64_1[3] = { + {47, 7}, + {145, 7}, {15, 4}, }; -static arc arcs_65_2[2] = { - {149, 8}, - {150, 4}, -}; -static arc arcs_65_3[2] = { - {152, 9}, - {153, 4}, +static arc arcs_64_2[2] = { + {147, 8}, + {148, 4}, +}; +static arc arcs_64_3[2] = { + {150, 9}, + {151, 4}, }; -static arc arcs_65_4[1] = { +static arc arcs_64_4[1] = { {0, 4}, }; -static arc arcs_65_5[2] = { - {155, 5}, +static arc arcs_64_5[2] = { + {153, 5}, {0, 5}, }; -static arc arcs_65_6[1] = { - {80, 10}, +static arc arcs_64_6[1] = { + {77, 10}, }; -static arc arcs_65_7[1] = { +static arc arcs_64_7[1] = { {15, 4}, }; -static arc arcs_65_8[1] = { - {150, 4}, +static arc arcs_64_8[1] = { + {148, 4}, }; -static arc arcs_65_9[1] = { - {153, 4}, +static arc arcs_64_9[1] = { + {151, 4}, }; -static arc arcs_65_10[1] = { - {80, 4}, +static arc arcs_64_10[1] = { + {77, 4}, }; -static state states_65[11] = { - {7, arcs_65_0}, - {3, arcs_65_1}, - {2, arcs_65_2}, - {2, arcs_65_3}, - {1, arcs_65_4}, - {2, arcs_65_5}, - {1, arcs_65_6}, - {1, arcs_65_7}, - {1, arcs_65_8}, - {1, arcs_65_9}, - {1, arcs_65_10}, +static state states_64[11] = { + {7, arcs_64_0}, + {3, arcs_64_1}, + {2, arcs_64_2}, + {2, arcs_64_3}, + {1, arcs_64_4}, + {2, arcs_64_5}, + {1, arcs_64_6}, + {1, arcs_64_7}, + {1, arcs_64_8}, + {1, arcs_64_9}, + {1, arcs_64_10}, }; -static arc arcs_66_0[1] = { +static arc arcs_65_0[1] = { {22, 1}, }; -static arc arcs_66_1[3] = { - {156, 2}, +static arc arcs_65_1[3] = { + {154, 2}, {28, 3}, {0, 1}, }; -static arc arcs_66_2[1] = { +static arc arcs_65_2[1] = { {0, 2}, }; -static arc arcs_66_3[2] = { +static arc arcs_65_3[2] = { {22, 4}, {0, 3}, }; -static arc arcs_66_4[2] = { +static arc arcs_65_4[2] = { {28, 3}, {0, 4}, }; -static state states_66[5] = { - {1, arcs_66_0}, - {3, arcs_66_1}, - {1, arcs_66_2}, - {2, arcs_66_3}, - {2, arcs_66_4}, +static state states_65[5] = { + {1, arcs_65_0}, + {3, arcs_65_1}, + {1, arcs_65_2}, + {2, arcs_65_3}, + {2, arcs_65_4}, }; -static arc arcs_67_0[1] = { +static arc arcs_66_0[1] = { {22, 1}, }; -static arc arcs_67_1[3] = { - {157, 2}, +static arc arcs_66_1[3] = { + {155, 2}, {28, 3}, {0, 1}, }; -static arc arcs_67_2[1] = { +static arc arcs_66_2[1] = { {0, 2}, }; -static arc arcs_67_3[2] = { +static arc arcs_66_3[2] = { {22, 4}, {0, 3}, }; -static arc arcs_67_4[2] = { +static arc arcs_66_4[2] = { {28, 3}, {0, 4}, }; -static state states_67[5] = { - {1, arcs_67_0}, - {3, arcs_67_1}, - {1, arcs_67_2}, - {2, arcs_67_3}, - {2, arcs_67_4}, +static state states_66[5] = { + {1, arcs_66_0}, + {3, arcs_66_1}, + {1, arcs_66_2}, + {2, arcs_66_3}, + {2, arcs_66_4}, }; -static arc arcs_68_0[1] = { - {112, 1}, +static arc arcs_67_0[1] = { + {109, 1}, }; -static arc arcs_68_1[2] = { +static arc arcs_67_1[2] = { {33, 2}, {23, 3}, }; -static arc arcs_68_2[1] = { +static arc arcs_67_2[1] = { {23, 3}, }; -static arc arcs_68_3[1] = { +static arc arcs_67_3[1] = { {22, 4}, }; -static arc arcs_68_4[1] = { +static arc arcs_67_4[1] = { {0, 4}, }; -static state states_68[5] = { - {1, arcs_68_0}, - {2, arcs_68_1}, - {1, arcs_68_2}, - {1, arcs_68_3}, - {1, arcs_68_4}, +static state states_67[5] = { + {1, arcs_67_0}, + {2, arcs_67_1}, + {1, arcs_67_2}, + {1, arcs_67_3}, + {1, arcs_67_4}, }; -static arc arcs_69_0[3] = { +static arc arcs_68_0[3] = { {13, 1}, - {148, 2}, - {80, 3}, + {146, 2}, + {77, 3}, }; -static arc arcs_69_1[2] = { +static arc arcs_68_1[2] = { {14, 4}, {15, 5}, }; -static arc arcs_69_2[1] = { - {158, 6}, +static arc arcs_68_2[1] = { + {156, 6}, }; -static arc arcs_69_3[1] = { +static arc arcs_68_3[1] = { {19, 5}, }; -static arc arcs_69_4[1] = { +static arc arcs_68_4[1] = { {15, 5}, }; -static arc arcs_69_5[1] = { +static arc arcs_68_5[1] = { {0, 5}, }; -static arc arcs_69_6[1] = { - {150, 5}, +static arc arcs_68_6[1] = { + {148, 5}, }; -static state states_69[7] = { - {3, arcs_69_0}, - {2, arcs_69_1}, - {1, arcs_69_2}, - {1, arcs_69_3}, - {1, arcs_69_4}, - {1, arcs_69_5}, - {1, arcs_69_6}, +static state states_68[7] = { + {3, arcs_68_0}, + {2, arcs_68_1}, + {1, arcs_68_2}, + {1, arcs_68_3}, + {1, arcs_68_4}, + {1, arcs_68_5}, + {1, arcs_68_6}, }; -static arc arcs_70_0[1] = { - {159, 1}, +static arc arcs_69_0[1] = { + {157, 1}, }; -static arc arcs_70_1[2] = { +static arc arcs_69_1[2] = { {28, 2}, {0, 1}, }; -static arc arcs_70_2[2] = { - {159, 1}, +static arc arcs_69_2[2] = { + {157, 1}, {0, 2}, }; -static state states_70[3] = { - {1, arcs_70_0}, - {2, arcs_70_1}, - {2, arcs_70_2}, +static state states_69[3] = { + {1, arcs_69_0}, + {2, arcs_69_1}, + {2, arcs_69_2}, }; -static arc arcs_71_0[2] = { +static arc arcs_70_0[2] = { {22, 1}, {23, 2}, }; -static arc arcs_71_1[2] = { +static arc arcs_70_1[2] = { {23, 2}, {0, 1}, }; -static arc arcs_71_2[3] = { +static arc arcs_70_2[3] = { {22, 3}, - {160, 4}, + {158, 4}, {0, 2}, }; -static arc arcs_71_3[2] = { - {160, 4}, +static arc arcs_70_3[2] = { + {158, 4}, {0, 3}, }; -static arc arcs_71_4[1] = { +static arc arcs_70_4[1] = { {0, 4}, }; -static state states_71[5] = { - {2, arcs_71_0}, +static state states_70[5] = { + {2, arcs_70_0}, + {2, arcs_70_1}, + {3, arcs_70_2}, + {2, arcs_70_3}, + {1, arcs_70_4}, +}; +static arc arcs_71_0[1] = { + {23, 1}, +}; +static arc arcs_71_1[2] = { + {22, 2}, + {0, 1}, +}; +static arc arcs_71_2[1] = { + {0, 2}, +}; +static state states_71[3] = { + {1, arcs_71_0}, {2, arcs_71_1}, - {3, arcs_71_2}, - {2, arcs_71_3}, - {1, arcs_71_4}, + {1, arcs_71_2}, }; static arc arcs_72_0[1] = { - {23, 1}, + {101, 1}, }; static arc arcs_72_1[2] = { - {22, 2}, + {28, 2}, {0, 1}, }; -static arc arcs_72_2[1] = { +static arc arcs_72_2[2] = { + {101, 1}, {0, 2}, }; static state states_72[3] = { {1, arcs_72_0}, {2, arcs_72_1}, - {1, arcs_72_2}, + {2, arcs_72_2}, }; static arc arcs_73_0[1] = { - {104, 1}, + {22, 1}, }; static arc arcs_73_1[2] = { {28, 2}, {0, 1}, }; static arc arcs_73_2[2] = { - {104, 1}, + {22, 1}, {0, 2}, }; static state states_73[3] = { @@ -1601,500 +1571,482 @@ static arc arcs_74_0[1] = { {22, 1}, }; -static arc arcs_74_1[2] = { - {28, 2}, - {0, 1}, -}; -static arc arcs_74_2[2] = { - {22, 1}, - {0, 2}, -}; -static state states_74[3] = { - {1, arcs_74_0}, - {2, arcs_74_1}, - {2, arcs_74_2}, -}; -static arc arcs_75_0[1] = { - {22, 1}, -}; -static arc arcs_75_1[3] = { +static arc arcs_74_1[3] = { {23, 2}, {28, 3}, {0, 1}, }; -static arc arcs_75_2[1] = { +static arc arcs_74_2[1] = { {22, 4}, }; -static arc arcs_75_3[2] = { +static arc arcs_74_3[2] = { {22, 5}, {0, 3}, }; -static arc arcs_75_4[2] = { +static arc arcs_74_4[2] = { {28, 6}, {0, 4}, }; -static arc arcs_75_5[2] = { +static arc arcs_74_5[2] = { {28, 3}, {0, 5}, }; -static arc arcs_75_6[2] = { +static arc arcs_74_6[2] = { {22, 7}, {0, 6}, }; -static arc arcs_75_7[1] = { +static arc arcs_74_7[1] = { {23, 2}, }; -static state states_75[8] = { - {1, arcs_75_0}, - {3, arcs_75_1}, - {1, arcs_75_2}, - {2, arcs_75_3}, - {2, arcs_75_4}, - {2, arcs_75_5}, - {2, arcs_75_6}, - {1, arcs_75_7}, +static state states_74[8] = { + {1, arcs_74_0}, + {3, arcs_74_1}, + {1, arcs_74_2}, + {2, arcs_74_3}, + {2, arcs_74_4}, + {2, arcs_74_5}, + {2, arcs_74_6}, + {1, arcs_74_7}, }; -static arc arcs_76_0[1] = { - {161, 1}, +static arc arcs_75_0[1] = { + {159, 1}, }; -static arc arcs_76_1[1] = { +static arc arcs_75_1[1] = { {19, 2}, }; -static arc arcs_76_2[2] = { +static arc arcs_75_2[2] = { {13, 3}, {23, 4}, }; -static arc arcs_76_3[2] = { +static arc arcs_75_3[2] = { {9, 5}, {15, 6}, }; -static arc arcs_76_4[1] = { +static arc arcs_75_4[1] = { {24, 7}, }; -static arc arcs_76_5[1] = { +static arc arcs_75_5[1] = { {15, 6}, }; -static arc arcs_76_6[1] = { +static arc arcs_75_6[1] = { {23, 4}, }; -static arc arcs_76_7[1] = { +static arc arcs_75_7[1] = { {0, 7}, }; -static state states_76[8] = { - {1, arcs_76_0}, - {1, arcs_76_1}, - {2, arcs_76_2}, - {2, arcs_76_3}, - {1, arcs_76_4}, - {1, arcs_76_5}, - {1, arcs_76_6}, - {1, arcs_76_7}, +static state states_75[8] = { + {1, arcs_75_0}, + {1, arcs_75_1}, + {2, arcs_75_2}, + {2, arcs_75_3}, + {1, arcs_75_4}, + {1, arcs_75_5}, + {1, arcs_75_6}, + {1, arcs_75_7}, }; -static arc arcs_77_0[3] = { - {162, 1}, +static arc arcs_76_0[3] = { + {160, 1}, {29, 2}, {31, 3}, }; -static arc arcs_77_1[2] = { +static arc arcs_76_1[2] = { {28, 4}, {0, 1}, }; -static arc arcs_77_2[1] = { +static arc arcs_76_2[1] = { {22, 5}, }; -static arc arcs_77_3[1] = { +static arc arcs_76_3[1] = { {22, 6}, }; -static arc arcs_77_4[4] = { - {162, 1}, +static arc arcs_76_4[4] = { + {160, 1}, {29, 2}, {31, 3}, {0, 4}, }; -static arc arcs_77_5[2] = { +static arc arcs_76_5[2] = { {28, 7}, {0, 5}, }; -static arc arcs_77_6[1] = { +static arc arcs_76_6[1] = { {0, 6}, }; -static arc arcs_77_7[1] = { +static arc arcs_76_7[1] = { {31, 3}, }; -static state states_77[8] = { - {3, arcs_77_0}, - {2, arcs_77_1}, - {1, arcs_77_2}, - {1, arcs_77_3}, - {4, arcs_77_4}, - {2, arcs_77_5}, - {1, arcs_77_6}, - {1, arcs_77_7}, +static state states_76[8] = { + {3, arcs_76_0}, + {2, arcs_76_1}, + {1, arcs_76_2}, + {1, arcs_76_3}, + {4, arcs_76_4}, + {2, arcs_76_5}, + {1, arcs_76_6}, + {1, arcs_76_7}, }; -static arc arcs_78_0[1] = { +static arc arcs_77_0[1] = { {22, 1}, }; -static arc arcs_78_1[3] = { - {157, 2}, +static arc arcs_77_1[3] = { + {155, 2}, {27, 3}, {0, 1}, }; -static arc arcs_78_2[1] = { +static arc arcs_77_2[1] = { {0, 2}, }; -static arc arcs_78_3[1] = { +static arc arcs_77_3[1] = { {22, 2}, }; -static state states_78[4] = { - {1, arcs_78_0}, - {3, arcs_78_1}, - {1, arcs_78_2}, - {1, arcs_78_3}, +static state states_77[4] = { + {1, arcs_77_0}, + {3, arcs_77_1}, + {1, arcs_77_2}, + {1, arcs_77_3}, }; -static arc arcs_79_0[2] = { - {156, 1}, - {164, 1}, +static arc arcs_78_0[2] = { + {154, 1}, + {162, 1}, }; -static arc arcs_79_1[1] = { +static arc arcs_78_1[1] = { {0, 1}, }; -static state states_79[2] = { - {2, arcs_79_0}, - {1, arcs_79_1}, +static state states_78[2] = { + {2, arcs_78_0}, + {1, arcs_78_1}, }; -static arc arcs_80_0[1] = { - {97, 1}, +static arc arcs_79_0[1] = { + {94, 1}, }; -static arc arcs_80_1[1] = { - {64, 2}, +static arc arcs_79_1[1] = { + {61, 2}, }; -static arc arcs_80_2[1] = { - {98, 3}, +static arc arcs_79_2[1] = { + {95, 3}, }; -static arc arcs_80_3[1] = { - {108, 4}, +static arc arcs_79_3[1] = { + {105, 4}, }; -static arc arcs_80_4[2] = { - {163, 5}, +static arc arcs_79_4[2] = { + {161, 5}, {0, 4}, }; -static arc arcs_80_5[1] = { +static arc arcs_79_5[1] = { {0, 5}, }; -static state states_80[6] = { - {1, arcs_80_0}, - {1, arcs_80_1}, - {1, arcs_80_2}, - {1, arcs_80_3}, - {2, arcs_80_4}, - {1, arcs_80_5}, +static state states_79[6] = { + {1, arcs_79_0}, + {1, arcs_79_1}, + {1, arcs_79_2}, + {1, arcs_79_3}, + {2, arcs_79_4}, + {1, arcs_79_5}, }; -static arc arcs_81_0[1] = { - {93, 1}, +static arc arcs_80_0[1] = { + {90, 1}, }; -static arc arcs_81_1[1] = { - {109, 2}, +static arc arcs_80_1[1] = { + {106, 2}, }; -static arc arcs_81_2[2] = { - {163, 3}, +static arc arcs_80_2[2] = { + {161, 3}, {0, 2}, }; -static arc arcs_81_3[1] = { +static arc arcs_80_3[1] = { {0, 3}, }; -static state states_81[4] = { - {1, arcs_81_0}, - {1, arcs_81_1}, - {2, arcs_81_2}, - {1, arcs_81_3}, +static state states_80[4] = { + {1, arcs_80_0}, + {1, arcs_80_1}, + {2, arcs_80_2}, + {1, arcs_80_3}, }; -static arc arcs_82_0[2] = { - {157, 1}, - {166, 1}, +static arc arcs_81_0[2] = { + {155, 1}, + {164, 1}, }; -static arc arcs_82_1[1] = { +static arc arcs_81_1[1] = { {0, 1}, }; -static state states_82[2] = { - {2, arcs_82_0}, - {1, arcs_82_1}, +static state states_81[2] = { + {2, arcs_81_0}, + {1, arcs_81_1}, }; -static arc arcs_83_0[1] = { - {97, 1}, +static arc arcs_82_0[1] = { + {94, 1}, }; -static arc arcs_83_1[1] = { - {64, 2}, +static arc arcs_82_1[1] = { + {61, 2}, }; -static arc arcs_83_2[1] = { - {98, 3}, +static arc arcs_82_2[1] = { + {95, 3}, }; -static arc arcs_83_3[1] = { - {110, 4}, +static arc arcs_82_3[1] = { + {107, 4}, }; -static arc arcs_83_4[2] = { - {165, 5}, +static arc arcs_82_4[2] = { + {163, 5}, {0, 4}, }; -static arc arcs_83_5[1] = { +static arc arcs_82_5[1] = { {0, 5}, }; -static state states_83[6] = { - {1, arcs_83_0}, - {1, arcs_83_1}, - {1, arcs_83_2}, - {1, arcs_83_3}, - {2, arcs_83_4}, - {1, arcs_83_5}, +static state states_82[6] = { + {1, arcs_82_0}, + {1, arcs_82_1}, + {1, arcs_82_2}, + {1, arcs_82_3}, + {2, arcs_82_4}, + {1, arcs_82_5}, }; -static arc arcs_84_0[1] = { - {93, 1}, +static arc arcs_83_0[1] = { + {90, 1}, }; -static arc arcs_84_1[1] = { - {109, 2}, +static arc arcs_83_1[1] = { + {106, 2}, }; -static arc arcs_84_2[2] = { - {165, 3}, +static arc arcs_83_2[2] = { + {163, 3}, {0, 2}, }; -static arc arcs_84_3[1] = { +static arc arcs_83_3[1] = { {0, 3}, }; -static state states_84[4] = { - {1, arcs_84_0}, - {1, arcs_84_1}, - {2, arcs_84_2}, - {1, arcs_84_3}, +static state states_83[4] = { + {1, arcs_83_0}, + {1, arcs_83_1}, + {2, arcs_83_2}, + {1, arcs_83_3}, }; -static arc arcs_85_0[1] = { +static arc arcs_84_0[1] = { {22, 1}, }; -static arc arcs_85_1[2] = { +static arc arcs_84_1[2] = { {28, 0}, {0, 1}, }; -static state states_85[2] = { - {1, arcs_85_0}, - {2, arcs_85_1}, +static state states_84[2] = { + {1, arcs_84_0}, + {2, arcs_84_1}, }; -static arc arcs_86_0[1] = { +static arc arcs_85_0[1] = { {19, 1}, }; -static arc arcs_86_1[1] = { +static arc arcs_85_1[1] = { {0, 1}, }; -static state states_86[2] = { - {1, arcs_86_0}, - {1, arcs_86_1}, +static state states_85[2] = { + {1, arcs_85_0}, + {1, arcs_85_1}, }; -static arc arcs_87_0[1] = { - {169, 1}, +static arc arcs_86_0[1] = { + {167, 1}, }; -static arc arcs_87_1[2] = { +static arc arcs_86_1[2] = { {9, 2}, {0, 1}, }; -static arc arcs_87_2[1] = { +static arc arcs_86_2[1] = { {0, 2}, }; -static state states_87[3] = { - {1, arcs_87_0}, - {2, arcs_87_1}, - {1, arcs_87_2}, +static state states_86[3] = { + {1, arcs_86_0}, + {2, arcs_86_1}, + {1, arcs_86_2}, }; -static dfa dfas[88] = { +static dfa dfas[87] = { {256, "single_input", 0, 3, states_0, - "\004\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"}, + "\004\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"}, {257, "file_input", 0, 2, states_1, - "\204\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"}, + "\204\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"}, {258, "eval_input", 0, 3, states_2, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, {259, "decorator", 0, 7, states_3, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {260, "decorators", 0, 2, states_4, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {261, "funcdef", 0, 9, states_5, - "\000\010\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\010\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {262, "parameters", 0, 4, states_6, - "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {263, "typedargslist", 0, 12, states_7, - "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {264, "tname", 0, 4, states_8, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {265, "tfpdef", 0, 4, states_9, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {266, "tfplist", 0, 3, states_10, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {267, "varargslist", 0, 12, states_11, - "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {268, "vname", 0, 2, states_12, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {269, "vfpdef", 0, 4, states_13, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {270, "vfplist", 0, 3, states_14, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {271, "stmt", 0, 2, states_15, - "\000\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"}, + "\000\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"}, {272, "simple_stmt", 0, 4, states_16, - "\000\040\010\000\000\000\000\240\202\247\141\000\000\000\101\000\000\206\220\014\000\002"}, + "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"}, {273, "small_stmt", 0, 2, states_17, - "\000\040\010\000\000\000\000\240\202\247\141\000\000\000\101\000\000\206\220\014\000\002"}, + "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"}, {274, "expr_stmt", 0, 6, states_18, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, {275, "augassign", 0, 2, states_19, - "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {276, "print_stmt", 0, 9, states_20, - "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {277, "del_stmt", 0, 3, states_21, - "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "pass_stmt", 0, 2, states_22, - "\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {279, "flow_stmt", 0, 2, states_23, - "\000\000\000\000\000\000\000\000\200\007\000\000\000\000\000\000\000\000\000\000\000\002"}, - {280, "break_stmt", 0, 2, states_24, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {281, "continue_stmt", 0, 2, states_25, - "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "return_stmt", 0, 3, states_26, - "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000"}, - {283, "yield_stmt", 0, 2, states_27, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, - {284, "raise_stmt", 0, 7, states_28, - "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, - {285, "import_stmt", 0, 2, states_29, - "\000\000\000\000\000\000\000\000\000\240\000\000\000\000\000\000\000\000\000\000\000\000"}, - {286, "import_name", 0, 3, states_30, - "\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, - {287, "import_from", 0, 8, states_31, - "\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, - {288, "import_as_name", 0, 4, states_32, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {289, "dotted_as_name", 0, 4, states_33, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {290, "import_as_names", 0, 3, states_34, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {291, "dotted_as_names", 0, 2, states_35, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {292, "dotted_name", 0, 2, states_36, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {293, "global_stmt", 0, 3, states_37, - "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000"}, - {294, "assert_stmt", 0, 5, states_38, - "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000"}, - {295, "compound_stmt", 0, 2, states_39, - "\000\010\004\000\000\000\000\000\000\000\000\040\113\000\000\000\000\000\000\000\002\000"}, - {296, "if_stmt", 0, 8, states_40, - "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {297, "while_stmt", 0, 8, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, - {298, "for_stmt", 0, 10, states_42, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, - {299, "try_stmt", 0, 13, states_43, - "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"}, - {300, "with_stmt", 0, 6, states_44, - "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {301, "with_var", 0, 3, states_45, - "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000"}, - {302, "except_clause", 0, 5, states_46, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000"}, - {303, "suite", 0, 5, states_47, - "\004\040\010\000\000\000\000\240\202\247\141\000\000\000\101\000\000\206\220\014\000\002"}, - {304, "testlist_safe", 0, 5, states_48, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {305, "old_test", 0, 2, states_49, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {306, "old_lambdef", 0, 5, states_50, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, - {307, "test", 0, 6, states_51, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {308, "or_test", 0, 2, states_52, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\100\000\000\206\220\014\000\000"}, - {309, "and_test", 0, 2, states_53, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\100\000\000\206\220\014\000\000"}, - {310, "not_test", 0, 3, states_54, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\100\000\000\206\220\014\000\000"}, - {311, "comparison", 0, 2, states_55, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {312, "comp_op", 0, 4, states_56, - "\000\000\000\000\000\000\000\000\000\000\000\000\004\000\100\376\000\000\000\000\000\000"}, - {313, "expr", 0, 2, states_57, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {314, "xor_expr", 0, 2, states_58, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {315, "and_expr", 0, 2, states_59, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {316, "shift_expr", 0, 2, states_60, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {317, "arith_expr", 0, 2, states_61, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {318, "term", 0, 2, states_62, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {319, "factor", 0, 3, states_63, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {320, "power", 0, 4, states_64, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\220\014\000\000"}, - {321, "atom", 0, 11, states_65, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\220\014\000\000"}, - {322, "listmaker", 0, 5, states_66, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {323, "testlist_gexp", 0, 5, states_67, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {324, "lambdef", 0, 5, states_68, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, - {325, "trailer", 0, 7, states_69, - "\000\040\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\020\000\000\000"}, - {326, "subscriptlist", 0, 3, states_70, - "\000\040\210\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {327, "subscript", 0, 5, states_71, - "\000\040\210\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {328, "sliceop", 0, 3, states_72, - "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {329, "exprlist", 0, 3, states_73, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"}, - {330, "testlist", 0, 3, states_74, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {331, "dictsetmaker", 0, 8, states_75, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {332, "classdef", 0, 8, states_76, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002\000"}, - {333, "arglist", 0, 8, states_77, - "\000\040\010\240\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {334, "argument", 0, 4, states_78, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {335, "list_iter", 0, 2, states_79, - "\000\000\000\000\000\000\000\000\000\000\000\040\002\000\000\000\000\000\000\000\000\000"}, - {336, "list_for", 0, 6, states_80, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, - {337, "list_if", 0, 4, states_81, - "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {338, "gen_iter", 0, 2, states_82, - "\000\000\000\000\000\000\000\000\000\000\000\040\002\000\000\000\000\000\000\000\000\000"}, - {339, "gen_for", 0, 6, states_83, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, - {340, "gen_if", 0, 4, states_84, - "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {341, "testlist1", 0, 2, states_85, - "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"}, - {342, "encoding_decl", 0, 2, states_86, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {343, "yield_expr", 0, 3, states_87, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, + "\000\000\000\000\000\000\377\017\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {276, "del_stmt", 0, 3, states_20, + "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {277, "pass_stmt", 0, 2, states_21, + "\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {278, "flow_stmt", 0, 2, states_22, + "\000\000\000\000\000\000\000\000\360\000\000\000\000\000\000\000\000\000\000\000\200"}, + {279, "break_stmt", 0, 2, states_23, + "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, + {280, "continue_stmt", 0, 2, states_24, + "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, + {281, "return_stmt", 0, 3, states_25, + "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, + {282, "yield_stmt", 0, 2, states_26, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {283, "raise_stmt", 0, 7, states_27, + "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, + {284, "import_stmt", 0, 2, states_28, + "\000\000\000\000\000\000\000\000\000\024\000\000\000\000\000\000\000\000\000\000\000"}, + {285, "import_name", 0, 3, states_29, + "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, + {286, "import_from", 0, 8, states_30, + "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"}, + {287, "import_as_name", 0, 4, states_31, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {288, "dotted_as_name", 0, 4, states_32, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {289, "import_as_names", 0, 3, states_33, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {290, "dotted_as_names", 0, 2, states_34, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {291, "dotted_name", 0, 2, states_35, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {292, "global_stmt", 0, 3, states_36, + "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000"}, + {293, "assert_stmt", 0, 5, states_37, + "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000"}, + {294, "compound_stmt", 0, 2, states_38, + "\000\010\004\000\000\000\000\000\000\000\000\144\011\000\000\000\000\000\000\200\000"}, + {295, "if_stmt", 0, 8, states_39, + "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, + {296, "while_stmt", 0, 8, states_40, + "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"}, + {297, "for_stmt", 0, 10, states_41, + "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {298, "try_stmt", 0, 13, states_42, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, + {299, "with_stmt", 0, 6, states_43, + "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000"}, + {300, "with_var", 0, 3, states_44, + "\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000"}, + {301, "except_clause", 0, 5, states_45, + "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000"}, + {302, "suite", 0, 5, states_46, + "\004\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"}, + {303, "testlist_safe", 0, 5, states_47, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {304, "old_test", 0, 2, states_48, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {305, "old_lambdef", 0, 5, states_49, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, + {306, "test", 0, 6, states_50, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {307, "or_test", 0, 2, states_51, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"}, + {308, "and_test", 0, 2, states_52, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"}, + {309, "not_test", 0, 3, states_53, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"}, + {310, "comparison", 0, 2, states_54, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {311, "comp_op", 0, 4, states_55, + "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\310\037\000\000\000\000\000"}, + {312, "expr", 0, 2, states_56, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {313, "xor_expr", 0, 2, states_57, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {314, "and_expr", 0, 2, states_58, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {315, "shift_expr", 0, 2, states_59, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {316, "arith_expr", 0, 2, states_60, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {317, "term", 0, 2, states_61, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {318, "factor", 0, 3, states_62, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {319, "power", 0, 4, states_63, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"}, + {320, "atom", 0, 11, states_64, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"}, + {321, "listmaker", 0, 5, states_65, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {322, "testlist_gexp", 0, 5, states_66, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {323, "lambdef", 0, 5, states_67, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, + {324, "trailer", 0, 7, states_68, + "\000\040\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\004\000\000"}, + {325, "subscriptlist", 0, 3, states_69, + "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {326, "subscript", 0, 5, states_70, + "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {327, "sliceop", 0, 3, states_71, + "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {328, "exprlist", 0, 3, states_72, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, + {329, "testlist", 0, 3, states_73, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {330, "dictsetmaker", 0, 8, states_74, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {331, "classdef", 0, 8, states_75, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000"}, + {332, "arglist", 0, 8, states_76, + "\000\040\010\240\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {333, "argument", 0, 4, states_77, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {334, "list_iter", 0, 2, states_78, + "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"}, + {335, "list_for", 0, 6, states_79, + "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {336, "list_if", 0, 4, states_80, + "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, + {337, "gen_iter", 0, 2, states_81, + "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"}, + {338, "gen_for", 0, 6, states_82, + "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {339, "gen_if", 0, 4, states_83, + "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, + {340, "testlist1", 0, 2, states_84, + "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + {341, "encoding_decl", 0, 2, states_85, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {342, "yield_expr", 0, 3, states_86, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, }; -static label labels[170] = { +static label labels[168] = { {0, "EMPTY"}, {256, 0}, {4, 0}, {272, 0}, - {295, 0}, + {294, 0}, {257, 0}, {271, 0}, {0, 0}, {258, 0}, - {330, 0}, + {329, 0}, {259, 0}, {50, 0}, - {292, 0}, + {291, 0}, {7, 0}, - {333, 0}, + {332, 0}, {8, 0}, {260, 0}, {261, 0}, @@ -2102,9 +2054,9 @@ {1, 0}, {262, 0}, {51, 0}, - {307, 0}, + {306, 0}, {11, 0}, - {303, 0}, + {302, 0}, {263, 0}, {265, 0}, {22, 0}, @@ -2123,12 +2075,11 @@ {276, 0}, {277, 0}, {278, 0}, - {279, 0}, - {285, 0}, + {284, 0}, + {292, 0}, {293, 0}, - {294, 0}, {275, 0}, - {343, 0}, + {342, 0}, {37, 0}, {38, 0}, {39, 0}, @@ -2141,38 +2092,36 @@ {46, 0}, {47, 0}, {49, 0}, - {1, "print"}, - {35, 0}, {1, "del"}, - {329, 0}, + {328, 0}, {1, "pass"}, + {279, 0}, {280, 0}, {281, 0}, - {282, 0}, - {284, 0}, {283, 0}, + {282, 0}, {1, "break"}, {1, "continue"}, {1, "return"}, {1, "raise"}, + {285, 0}, {286, 0}, - {287, 0}, {1, "import"}, - {291, 0}, + {290, 0}, {1, "from"}, {23, 0}, - {290, 0}, - {288, 0}, - {1, "as"}, {289, 0}, + {287, 0}, + {1, "as"}, + {288, 0}, {1, "global"}, {1, "assert"}, + {295, 0}, {296, 0}, {297, 0}, {298, 0}, {299, 0}, - {300, 0}, - {332, 0}, + {331, 0}, {1, "if"}, {1, "elif"}, {1, "else"}, @@ -2180,27 +2129,27 @@ {1, "for"}, {1, "in"}, {1, "try"}, - {302, 0}, + {301, 0}, {1, "finally"}, {1, "with"}, - {301, 0}, - {313, 0}, + {300, 0}, + {312, 0}, {1, "except"}, {5, 0}, {6, 0}, + {303, 0}, {304, 0}, + {307, 0}, {305, 0}, - {308, 0}, - {306, 0}, {1, "lambda"}, - {324, 0}, - {309, 0}, + {323, 0}, + {308, 0}, {1, "or"}, - {310, 0}, + {309, 0}, {1, "and"}, {1, "not"}, + {310, 0}, {311, 0}, - {312, 0}, {20, 0}, {21, 0}, {28, 0}, @@ -2208,52 +2157,53 @@ {30, 0}, {29, 0}, {1, "is"}, - {314, 0}, + {313, 0}, {18, 0}, - {315, 0}, + {314, 0}, {33, 0}, - {316, 0}, + {315, 0}, {19, 0}, - {317, 0}, + {316, 0}, {34, 0}, - {318, 0}, + {35, 0}, + {317, 0}, {14, 0}, {15, 0}, - {319, 0}, + {318, 0}, {17, 0}, {24, 0}, {48, 0}, {32, 0}, + {319, 0}, {320, 0}, - {321, 0}, - {325, 0}, - {323, 0}, - {9, 0}, + {324, 0}, {322, 0}, + {9, 0}, + {321, 0}, {10, 0}, {26, 0}, - {331, 0}, + {330, 0}, {27, 0}, {2, 0}, {3, 0}, - {336, 0}, - {339, 0}, + {335, 0}, + {338, 0}, + {325, 0}, {326, 0}, {327, 0}, - {328, 0}, {1, "class"}, + {333, 0}, {334, 0}, - {335, 0}, + {336, 0}, {337, 0}, - {338, 0}, + {339, 0}, {340, 0}, {341, 0}, - {342, 0}, {1, "yield"}, }; grammar _PyParser_Grammar = { - 88, + 87, dfas, - {170, labels}, + {168, labels}, 256 }; Modified: python/branches/p3yk/Python/import.c ============================================================================== --- python/branches/p3yk/Python/import.c (original) +++ python/branches/p3yk/Python/import.c Fri Feb 9 06:32:43 2007 @@ -71,9 +71,10 @@ 3020 (added BUILD_SET) 3030 (added keyword-only parameters) 3040 (added signature annotations) + 3050 (print becomes a function) . */ -#define MAGIC (3040 | ((long)'\r'<<16) | ((long)'\n'<<24)) +#define MAGIC (3050 | ((long)'\r'<<16) | ((long)'\n'<<24)) /* Magic word as global; note that _PyImport_Init() can change the value of this global to accommodate for alterations of how the Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Fri Feb 9 06:32:43 2007 @@ -664,7 +664,7 @@ # search path. for d in inc_dirs + db_inc_paths: f = os.path.join(d, "db.h") - if db_setup_debug: print "db: looking for db.h in", f + if db_setup_debug: print("db: looking for db.h in", f) if os.path.exists(f): f = open(f).read() m = re.search(r"#define\WDB_VERSION_MAJOR\W(\d+)", f) @@ -680,13 +680,13 @@ # (first occurrance only) db_ver_inc_map[db_ver] = d if db_setup_debug: - print "db.h: found", db_ver, "in", d + print("db.h: found", db_ver, "in", d) else: # we already found a header for this library version - if db_setup_debug: print "db.h: ignoring", d + if db_setup_debug: print("db.h: ignoring", d) else: # ignore this header, it didn't contain a version number - if db_setup_debug: print "db.h: unsupported version", db_ver, "in", d + if db_setup_debug: print("db.h: unsupported version", db_ver, "in", d) db_found_vers = db_ver_inc_map.keys() db_found_vers.sort() @@ -717,12 +717,12 @@ dblib_dir = [ os.path.abspath(os.path.dirname(dblib_file)) ] raise db_found else: - if db_setup_debug: print "db lib: ", dblib, "not found" + if db_setup_debug: print("db lib: ", dblib, "not found") except db_found: if db_setup_debug: - print "db lib: using", db_ver, dblib - print "db: lib dir", dblib_dir, "inc dir", db_incdir + print("db lib: using", db_ver, dblib) + print("db: lib dir", dblib_dir, "inc dir", db_incdir) db_incs = [db_incdir] dblibs = [dblib] # We add the runtime_library_dirs argument because the @@ -737,7 +737,7 @@ include_dirs=db_incs, libraries=dblibs)) else: - if db_setup_debug: print "db: no appropriate library found" + if db_setup_debug: print("db: no appropriate library found") db_incs = None dblibs = [] dblib_dir = None @@ -765,7 +765,7 @@ for d in inc_dirs + sqlite_inc_paths: f = os.path.join(d, "sqlite3.h") if os.path.exists(f): - if sqlite_setup_debug: print "sqlite: found %s"%f + if sqlite_setup_debug: print("sqlite: found %s"%f) incf = open(f).read() m = re.search( r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"(.*)"', incf) @@ -776,15 +776,15 @@ if sqlite_version_tuple >= MIN_SQLITE_VERSION_NUMBER: # we win! if sqlite_setup_debug: - print "%s/sqlite3.h: version %s"%(d, sqlite_version) + print("%s/sqlite3.h: version %s"%(d, sqlite_version)) sqlite_incdir = d break else: if sqlite_setup_debug: - print "%s: version %d is too old, need >= %s"%(d, - sqlite_version, MIN_SQLITE_VERSION) + print("%s: version %d is too old, need >= %s"%(d, + sqlite_version, MIN_SQLITE_VERSION)) elif sqlite_setup_debug: - print "sqlite: %s had no SQLITE_VERSION"%(f,) + print("sqlite: %s had no SQLITE_VERSION"%(f,)) if sqlite_incdir: sqlite_dirs_to_check = [ @@ -1333,7 +1333,7 @@ res = os.system(cmd) if res or not os.path.exists(ffi_configfile): - print "Failed to configure _ctypes module" + print("Failed to configure _ctypes module") return False fficonfig = {} From python-3000-checkins at python.org Fri Feb 9 06:42:39 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 06:42:39 +0100 (CET) Subject: [Python-3000-checkins] r53688 - python/branches/p3yk/Misc/NEWS Message-ID: <20070209054239.495321E4010@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 06:42:38 2007 New Revision: 53688 Modified: python/branches/p3yk/Misc/NEWS Log: Note that print is a function now. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Fri Feb 9 06:42:38 2007 @@ -36,6 +36,8 @@ Core and Builtins ----------------- +- PEP 3105: print is now a function. + - PEP 3102: keyword-only arguments. - Int/Long unification is mostly complete. The 'long' built-in type From python-3000-checkins at python.org Fri Feb 9 06:39:01 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 06:39:01 +0100 (CET) Subject: [Python-3000-checkins] r53686 - in python/branches/p3yk/Lib: BaseHTTPServer.py Bastion.py Cookie.py DocXMLRPCServer.py SimpleXMLRPCServer.py SocketServer.py StringIO.py aifc.py asyncore.py atexit.py audiodev.py base64.py bdb.py bsddb/dbtables.py bsddb/test/test_all.py bsddb/test/test_associate.py bsddb/test/test_basics.py bsddb/test/test_compat.py bsddb/test/test_dbshelve.py bsddb/test/test_dbtables.py bsddb/test/test_join.py bsddb/test/test_lock.py bsddb/test/test_queue.py bsddb/test/test_recno.py bsddb/test/test_thread.py cProfile.py calendar.py cgi.py code.py compileall.py compiler/future.py compiler/pyassem.py compiler/pycodegen.py compiler/symbols.py compiler/syntax.py compiler/transformer.py compiler/visitor.py copy.py ctypes/test/__init__.py ctypes/test/test_byteswap.py ctypes/test/test_find.py ctypes/test/test_keeprefs.py ctypes/test/test_loading.py ctypes/test/test_numbers.py ctypes/test/test_strings.py ctypes/util.py curses/has_key.py curses/textpad.py difflib.py dis.py distutils/bcppcompiler.py distutils/ccompiler.py distutils/cmd.py distutils/command/bdist_rpm.py distutils/command/config.py distutils/command/install.py distutils/command/register.py distutils/command/upload.py distutils/core.py distutils/dist.py distutils/fancy_getopt.py distutils/filelist.py distutils/log.py distutils/mwerkscompiler.py distutils/spawn.py distutils/tests/test_dist.py distutils/text_file.py doctest.py email/generator.py email/iterators.py email/test/test_email.py email/test/test_email_renamed.py filecmp.py fileinput.py formatter.py fpformat.py ftplib.py getopt.py getpass.py gopherlib.py gzip.py heapq.py hotshot/log.py hotshot/stones.py htmllib.py httplib.py idlelib/CallTips.py idlelib/ColorDelegator.py idlelib/Delegator.py idlelib/EditorWindow.py idlelib/FileList.py idlelib/GrepDialog.py idlelib/MultiCall.py idlelib/Percolator.py idlelib/PyShell.py idlelib/ScrolledList.py idlelib/UndoDelegator.py idlelib/WidgetRedirector.py idlelib/WindowList.py idlelib/configHandler.py idlelib/configHelpSourceEdit.py idlelib/configSectionNameDialog.py idlelib/keybindingDialog.py idlelib/rpc.py idlelib/run.py ihooks.py imaplib.py imghdr.py imputil.py lib-tk/Dialog.py lib-tk/FileDialog.py lib-tk/SimpleDialog.py lib-tk/Tkinter.py lib-tk/tkColorChooser.py lib-tk/tkFileDialog.py lib-tk/tkFont.py lib-tk/tkMessageBox.py lib-tk/tkSimpleDialog.py locale.py logging/handlers.py macurl2path.py mailcap.py mhlib.py mimetypes.py mimify.py modulefinder.py msilib/__init__.py netrc.py nntplib.py optparse.py pdb.py pickletools.py pipes.py plat-irix5/cddb.py plat-irix5/cdplayer.py plat-irix5/flp.py plat-irix5/panel.py plat-irix6/cddb.py plat-irix6/cdplayer.py plat-irix6/flp.py plat-irix6/panel.py plat-mac/Audio_mac.py plat-mac/EasyDialogs.py plat-mac/FrameWork.py plat-mac/MiniAEFrame.py plat-mac/aetools.py plat-mac/applesingle.py plat-mac/argvemulator.py plat-mac/bundlebuilder.py plat-mac/findertools.py plat-mac/gensuitemodule.py plat-mac/ic.py plat-mac/macresource.py plat-mac/pimp.py plat-mac/videoreader.py plat-os2emx/_emx_link.py plat-riscos/rourl2path.py platform.py popen2.py poplib.py pprint.py profile.py pstats.py pyclbr.py pydoc.py quopri.py random.py rexec.py rfc822.py robotparser.py runpy.py sgmllib.py shlex.py site.py smtpd.py smtplib.py sndhdr.py sqlite3/test/dbapi.py sre_constants.py sre_parse.py subprocess.py sunaudio.py symtable.py tabnanny.py tarfile.py telnetlib.py test/badsyntax_future8.py test/badsyntax_future9.py test/crashers/bogus_sre_bytecode.py test/crashers/borrowed_ref_1.py test/crashers/borrowed_ref_2.py test/crashers/gc_inspection.py test/crashers/loosing_mro_ref.py test/crashers/modify_dict_attr.py test/crashers/nasty_eq_vs_dict.py test/inspect_fodder2.py test/list_tests.py test/pydocfodder.py test/pystone.py test/regrtest.py test/reperf.py test/sortperf.py test/test_al.py test/test_array.py test/test_ast.py test/test_atexit.py test/test_audioop.py test/test_bisect.py test/test_bool.py test/test_bsddb.py test/test_bsddb3.py test/test_builtin.py test/test_capi.py test/test_cd.py test/test_cl.py test/test_class.py test/test_cmath.py test/test_code.py test/test_codecs.py test/test_compiler.py test/test_complex.py test/test_crypt.py test/test_csv.py test/test_curses.py test/test_datetime.py test/test_dbm.py test/test_decimal.py test/test_defaultdict.py test/test_deque.py test/test_descr.py test/test_dis.py test/test_dl.py test/test_doctest.py test/test_dummy_thread.py test/test_dummy_threading.py test/test_enumerate.py test/test_errno.py test/test_extcall.py test/test_fcntl.py test/test_file.py test/test_fileinput.py test/test_format.py test/test_funcattrs.py test/test_functools.py test/test_gc.py test/test_gdbm.py test/test_generators.py test/test_genexps.py test/test_getopt.py test/test_gl.py test/test_grammar.py test/test_heapq.py test/test_imageop.py test/test_imgfile.py test/test_import.py test/test_itertools.py test/test_largefile.py test/test_linuxaudiodev.py test/test_list.py test/test_locale.py test/test_long_future.py test/test_minidom.py test/test_module.py test/test_multibytecodec.py test/test_mutants.py test/test_normalization.py test/test_ntpath.py test/test_operations.py test/test_operator.py test/test_ossaudiodev.py test/test_peepholer.py test/test_pep247.py test/test_pep277.py test/test_pkg.py test/test_popen2.py test/test_pty.py test/test_pyclbr.py test/test_pyexpat.py test/test_queue.py test/test_random.py test/test_re.py test/test_rfc822.py test/test_rgbimg.py test/test_runpy.py test/test_sax.py test/test_scope.py test/test_select.py test/test_signal.py test/test_site.py test/test_socket_ssl.py test/test_socketserver.py test/test_softspace.py test/test_sort.py test/test_strftime.py test/test_struct.py test/test_sundry.py test/test_support.py test/test_thread.py test/test_threaded_import.py test/test_threadedtempfile.py test/test_threading.py test/test_tokenize.py test/test_trace.py test/test_traceback.py test/test_unicode.py test/test_userdict.py test/test_uuid.py test/test_winreg.py test/test_xml_etree.py test/test_xml_etree_c.py test/test_zipfile64.py test/time_hashlib.py textwrap.py this.py threading.py timeit.py tokenize.py trace.py unittest.py urllib.py urlparse.py uu.py warnings.py webbrowser.py whichdb.py wsgiref/simple_server.py xml/dom/pulldom.py xml/sax/handler.py xmllib.py xmlrpclib.py zipfile.py Message-ID: <20070209053901.119C81E4010@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 06:37:30 2007 New Revision: 53686 Modified: python/branches/p3yk/Lib/BaseHTTPServer.py python/branches/p3yk/Lib/Bastion.py python/branches/p3yk/Lib/Cookie.py python/branches/p3yk/Lib/DocXMLRPCServer.py python/branches/p3yk/Lib/SimpleXMLRPCServer.py python/branches/p3yk/Lib/SocketServer.py python/branches/p3yk/Lib/StringIO.py python/branches/p3yk/Lib/aifc.py python/branches/p3yk/Lib/asyncore.py python/branches/p3yk/Lib/atexit.py python/branches/p3yk/Lib/audiodev.py python/branches/p3yk/Lib/base64.py python/branches/p3yk/Lib/bdb.py python/branches/p3yk/Lib/bsddb/dbtables.py python/branches/p3yk/Lib/bsddb/test/test_all.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_compat.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_join.py python/branches/p3yk/Lib/bsddb/test/test_lock.py python/branches/p3yk/Lib/bsddb/test/test_queue.py python/branches/p3yk/Lib/bsddb/test/test_recno.py python/branches/p3yk/Lib/bsddb/test/test_thread.py python/branches/p3yk/Lib/cProfile.py python/branches/p3yk/Lib/calendar.py python/branches/p3yk/Lib/cgi.py python/branches/p3yk/Lib/code.py python/branches/p3yk/Lib/compileall.py python/branches/p3yk/Lib/compiler/future.py python/branches/p3yk/Lib/compiler/pyassem.py python/branches/p3yk/Lib/compiler/pycodegen.py python/branches/p3yk/Lib/compiler/symbols.py python/branches/p3yk/Lib/compiler/syntax.py python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/compiler/visitor.py python/branches/p3yk/Lib/copy.py python/branches/p3yk/Lib/ctypes/test/__init__.py python/branches/p3yk/Lib/ctypes/test/test_byteswap.py python/branches/p3yk/Lib/ctypes/test/test_find.py python/branches/p3yk/Lib/ctypes/test/test_keeprefs.py python/branches/p3yk/Lib/ctypes/test/test_loading.py python/branches/p3yk/Lib/ctypes/test/test_numbers.py python/branches/p3yk/Lib/ctypes/test/test_strings.py python/branches/p3yk/Lib/ctypes/util.py python/branches/p3yk/Lib/curses/has_key.py python/branches/p3yk/Lib/curses/textpad.py python/branches/p3yk/Lib/difflib.py python/branches/p3yk/Lib/dis.py python/branches/p3yk/Lib/distutils/bcppcompiler.py python/branches/p3yk/Lib/distutils/ccompiler.py python/branches/p3yk/Lib/distutils/cmd.py python/branches/p3yk/Lib/distutils/command/bdist_rpm.py python/branches/p3yk/Lib/distutils/command/config.py python/branches/p3yk/Lib/distutils/command/install.py python/branches/p3yk/Lib/distutils/command/register.py python/branches/p3yk/Lib/distutils/command/upload.py python/branches/p3yk/Lib/distutils/core.py python/branches/p3yk/Lib/distutils/dist.py python/branches/p3yk/Lib/distutils/fancy_getopt.py python/branches/p3yk/Lib/distutils/filelist.py python/branches/p3yk/Lib/distutils/log.py python/branches/p3yk/Lib/distutils/mwerkscompiler.py python/branches/p3yk/Lib/distutils/spawn.py python/branches/p3yk/Lib/distutils/tests/test_dist.py python/branches/p3yk/Lib/distutils/text_file.py python/branches/p3yk/Lib/doctest.py python/branches/p3yk/Lib/email/generator.py python/branches/p3yk/Lib/email/iterators.py python/branches/p3yk/Lib/email/test/test_email.py python/branches/p3yk/Lib/email/test/test_email_renamed.py python/branches/p3yk/Lib/filecmp.py python/branches/p3yk/Lib/fileinput.py python/branches/p3yk/Lib/formatter.py python/branches/p3yk/Lib/fpformat.py python/branches/p3yk/Lib/ftplib.py python/branches/p3yk/Lib/getopt.py python/branches/p3yk/Lib/getpass.py python/branches/p3yk/Lib/gopherlib.py python/branches/p3yk/Lib/gzip.py python/branches/p3yk/Lib/heapq.py python/branches/p3yk/Lib/hotshot/log.py python/branches/p3yk/Lib/hotshot/stones.py python/branches/p3yk/Lib/htmllib.py python/branches/p3yk/Lib/httplib.py python/branches/p3yk/Lib/idlelib/CallTips.py python/branches/p3yk/Lib/idlelib/ColorDelegator.py python/branches/p3yk/Lib/idlelib/Delegator.py python/branches/p3yk/Lib/idlelib/EditorWindow.py python/branches/p3yk/Lib/idlelib/FileList.py python/branches/p3yk/Lib/idlelib/GrepDialog.py python/branches/p3yk/Lib/idlelib/MultiCall.py python/branches/p3yk/Lib/idlelib/Percolator.py python/branches/p3yk/Lib/idlelib/PyShell.py python/branches/p3yk/Lib/idlelib/ScrolledList.py python/branches/p3yk/Lib/idlelib/UndoDelegator.py python/branches/p3yk/Lib/idlelib/WidgetRedirector.py python/branches/p3yk/Lib/idlelib/WindowList.py python/branches/p3yk/Lib/idlelib/configHandler.py python/branches/p3yk/Lib/idlelib/configHelpSourceEdit.py python/branches/p3yk/Lib/idlelib/configSectionNameDialog.py python/branches/p3yk/Lib/idlelib/keybindingDialog.py python/branches/p3yk/Lib/idlelib/rpc.py python/branches/p3yk/Lib/idlelib/run.py python/branches/p3yk/Lib/ihooks.py python/branches/p3yk/Lib/imaplib.py python/branches/p3yk/Lib/imghdr.py python/branches/p3yk/Lib/imputil.py python/branches/p3yk/Lib/lib-tk/Dialog.py python/branches/p3yk/Lib/lib-tk/FileDialog.py python/branches/p3yk/Lib/lib-tk/SimpleDialog.py python/branches/p3yk/Lib/lib-tk/Tkinter.py python/branches/p3yk/Lib/lib-tk/tkColorChooser.py python/branches/p3yk/Lib/lib-tk/tkFileDialog.py python/branches/p3yk/Lib/lib-tk/tkFont.py python/branches/p3yk/Lib/lib-tk/tkMessageBox.py python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py python/branches/p3yk/Lib/locale.py python/branches/p3yk/Lib/logging/handlers.py python/branches/p3yk/Lib/macurl2path.py python/branches/p3yk/Lib/mailcap.py python/branches/p3yk/Lib/mhlib.py python/branches/p3yk/Lib/mimetypes.py python/branches/p3yk/Lib/mimify.py python/branches/p3yk/Lib/modulefinder.py python/branches/p3yk/Lib/msilib/__init__.py python/branches/p3yk/Lib/netrc.py python/branches/p3yk/Lib/nntplib.py python/branches/p3yk/Lib/optparse.py python/branches/p3yk/Lib/pdb.py python/branches/p3yk/Lib/pickletools.py python/branches/p3yk/Lib/pipes.py python/branches/p3yk/Lib/plat-irix5/cddb.py python/branches/p3yk/Lib/plat-irix5/cdplayer.py python/branches/p3yk/Lib/plat-irix5/flp.py python/branches/p3yk/Lib/plat-irix5/panel.py python/branches/p3yk/Lib/plat-irix6/cddb.py python/branches/p3yk/Lib/plat-irix6/cdplayer.py python/branches/p3yk/Lib/plat-irix6/flp.py python/branches/p3yk/Lib/plat-irix6/panel.py python/branches/p3yk/Lib/plat-mac/Audio_mac.py python/branches/p3yk/Lib/plat-mac/EasyDialogs.py python/branches/p3yk/Lib/plat-mac/FrameWork.py python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py python/branches/p3yk/Lib/plat-mac/aetools.py python/branches/p3yk/Lib/plat-mac/applesingle.py python/branches/p3yk/Lib/plat-mac/argvemulator.py python/branches/p3yk/Lib/plat-mac/bundlebuilder.py python/branches/p3yk/Lib/plat-mac/findertools.py python/branches/p3yk/Lib/plat-mac/gensuitemodule.py python/branches/p3yk/Lib/plat-mac/ic.py python/branches/p3yk/Lib/plat-mac/macresource.py python/branches/p3yk/Lib/plat-mac/pimp.py python/branches/p3yk/Lib/plat-mac/videoreader.py python/branches/p3yk/Lib/plat-os2emx/_emx_link.py python/branches/p3yk/Lib/plat-riscos/rourl2path.py python/branches/p3yk/Lib/platform.py python/branches/p3yk/Lib/popen2.py python/branches/p3yk/Lib/poplib.py python/branches/p3yk/Lib/pprint.py python/branches/p3yk/Lib/profile.py python/branches/p3yk/Lib/pstats.py python/branches/p3yk/Lib/pyclbr.py python/branches/p3yk/Lib/pydoc.py python/branches/p3yk/Lib/quopri.py python/branches/p3yk/Lib/random.py python/branches/p3yk/Lib/rexec.py python/branches/p3yk/Lib/rfc822.py python/branches/p3yk/Lib/robotparser.py python/branches/p3yk/Lib/runpy.py python/branches/p3yk/Lib/sgmllib.py python/branches/p3yk/Lib/shlex.py python/branches/p3yk/Lib/site.py python/branches/p3yk/Lib/smtpd.py python/branches/p3yk/Lib/smtplib.py python/branches/p3yk/Lib/sndhdr.py python/branches/p3yk/Lib/sqlite3/test/dbapi.py python/branches/p3yk/Lib/sre_constants.py python/branches/p3yk/Lib/sre_parse.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/sunaudio.py python/branches/p3yk/Lib/symtable.py python/branches/p3yk/Lib/tabnanny.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/telnetlib.py python/branches/p3yk/Lib/test/badsyntax_future8.py python/branches/p3yk/Lib/test/badsyntax_future9.py python/branches/p3yk/Lib/test/crashers/bogus_sre_bytecode.py python/branches/p3yk/Lib/test/crashers/borrowed_ref_1.py python/branches/p3yk/Lib/test/crashers/borrowed_ref_2.py python/branches/p3yk/Lib/test/crashers/gc_inspection.py python/branches/p3yk/Lib/test/crashers/loosing_mro_ref.py python/branches/p3yk/Lib/test/crashers/modify_dict_attr.py python/branches/p3yk/Lib/test/crashers/nasty_eq_vs_dict.py python/branches/p3yk/Lib/test/inspect_fodder2.py python/branches/p3yk/Lib/test/list_tests.py python/branches/p3yk/Lib/test/pydocfodder.py python/branches/p3yk/Lib/test/pystone.py python/branches/p3yk/Lib/test/regrtest.py python/branches/p3yk/Lib/test/reperf.py python/branches/p3yk/Lib/test/sortperf.py python/branches/p3yk/Lib/test/test_al.py python/branches/p3yk/Lib/test/test_array.py python/branches/p3yk/Lib/test/test_ast.py python/branches/p3yk/Lib/test/test_atexit.py python/branches/p3yk/Lib/test/test_audioop.py python/branches/p3yk/Lib/test/test_bisect.py python/branches/p3yk/Lib/test/test_bool.py python/branches/p3yk/Lib/test/test_bsddb.py python/branches/p3yk/Lib/test/test_bsddb3.py python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_capi.py python/branches/p3yk/Lib/test/test_cd.py python/branches/p3yk/Lib/test/test_cl.py python/branches/p3yk/Lib/test/test_class.py python/branches/p3yk/Lib/test/test_cmath.py python/branches/p3yk/Lib/test/test_code.py python/branches/p3yk/Lib/test/test_codecs.py python/branches/p3yk/Lib/test/test_compiler.py python/branches/p3yk/Lib/test/test_complex.py python/branches/p3yk/Lib/test/test_crypt.py python/branches/p3yk/Lib/test/test_csv.py python/branches/p3yk/Lib/test/test_curses.py python/branches/p3yk/Lib/test/test_datetime.py python/branches/p3yk/Lib/test/test_dbm.py python/branches/p3yk/Lib/test/test_decimal.py python/branches/p3yk/Lib/test/test_defaultdict.py python/branches/p3yk/Lib/test/test_deque.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_dis.py python/branches/p3yk/Lib/test/test_dl.py python/branches/p3yk/Lib/test/test_doctest.py python/branches/p3yk/Lib/test/test_dummy_thread.py python/branches/p3yk/Lib/test/test_dummy_threading.py python/branches/p3yk/Lib/test/test_enumerate.py python/branches/p3yk/Lib/test/test_errno.py python/branches/p3yk/Lib/test/test_extcall.py python/branches/p3yk/Lib/test/test_fcntl.py python/branches/p3yk/Lib/test/test_file.py python/branches/p3yk/Lib/test/test_fileinput.py python/branches/p3yk/Lib/test/test_format.py python/branches/p3yk/Lib/test/test_funcattrs.py python/branches/p3yk/Lib/test/test_functools.py python/branches/p3yk/Lib/test/test_gc.py python/branches/p3yk/Lib/test/test_gdbm.py python/branches/p3yk/Lib/test/test_generators.py python/branches/p3yk/Lib/test/test_genexps.py python/branches/p3yk/Lib/test/test_getopt.py python/branches/p3yk/Lib/test/test_gl.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_heapq.py python/branches/p3yk/Lib/test/test_imageop.py python/branches/p3yk/Lib/test/test_imgfile.py python/branches/p3yk/Lib/test/test_import.py python/branches/p3yk/Lib/test/test_itertools.py python/branches/p3yk/Lib/test/test_largefile.py python/branches/p3yk/Lib/test/test_linuxaudiodev.py python/branches/p3yk/Lib/test/test_list.py python/branches/p3yk/Lib/test/test_locale.py python/branches/p3yk/Lib/test/test_long_future.py python/branches/p3yk/Lib/test/test_minidom.py python/branches/p3yk/Lib/test/test_module.py python/branches/p3yk/Lib/test/test_multibytecodec.py python/branches/p3yk/Lib/test/test_mutants.py python/branches/p3yk/Lib/test/test_normalization.py python/branches/p3yk/Lib/test/test_ntpath.py python/branches/p3yk/Lib/test/test_operations.py python/branches/p3yk/Lib/test/test_operator.py python/branches/p3yk/Lib/test/test_ossaudiodev.py python/branches/p3yk/Lib/test/test_peepholer.py python/branches/p3yk/Lib/test/test_pep247.py python/branches/p3yk/Lib/test/test_pep277.py python/branches/p3yk/Lib/test/test_pkg.py python/branches/p3yk/Lib/test/test_popen2.py python/branches/p3yk/Lib/test/test_pty.py python/branches/p3yk/Lib/test/test_pyclbr.py python/branches/p3yk/Lib/test/test_pyexpat.py python/branches/p3yk/Lib/test/test_queue.py python/branches/p3yk/Lib/test/test_random.py python/branches/p3yk/Lib/test/test_re.py python/branches/p3yk/Lib/test/test_rfc822.py python/branches/p3yk/Lib/test/test_rgbimg.py python/branches/p3yk/Lib/test/test_runpy.py python/branches/p3yk/Lib/test/test_sax.py python/branches/p3yk/Lib/test/test_scope.py python/branches/p3yk/Lib/test/test_select.py python/branches/p3yk/Lib/test/test_signal.py python/branches/p3yk/Lib/test/test_site.py python/branches/p3yk/Lib/test/test_socket_ssl.py python/branches/p3yk/Lib/test/test_socketserver.py python/branches/p3yk/Lib/test/test_softspace.py python/branches/p3yk/Lib/test/test_sort.py python/branches/p3yk/Lib/test/test_strftime.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_sundry.py python/branches/p3yk/Lib/test/test_support.py python/branches/p3yk/Lib/test/test_thread.py python/branches/p3yk/Lib/test/test_threaded_import.py python/branches/p3yk/Lib/test/test_threadedtempfile.py python/branches/p3yk/Lib/test/test_threading.py python/branches/p3yk/Lib/test/test_tokenize.py python/branches/p3yk/Lib/test/test_trace.py python/branches/p3yk/Lib/test/test_traceback.py python/branches/p3yk/Lib/test/test_unicode.py python/branches/p3yk/Lib/test/test_userdict.py python/branches/p3yk/Lib/test/test_uuid.py python/branches/p3yk/Lib/test/test_winreg.py python/branches/p3yk/Lib/test/test_xml_etree.py python/branches/p3yk/Lib/test/test_xml_etree_c.py python/branches/p3yk/Lib/test/test_zipfile64.py python/branches/p3yk/Lib/test/time_hashlib.py python/branches/p3yk/Lib/textwrap.py python/branches/p3yk/Lib/this.py python/branches/p3yk/Lib/threading.py python/branches/p3yk/Lib/timeit.py python/branches/p3yk/Lib/tokenize.py python/branches/p3yk/Lib/trace.py python/branches/p3yk/Lib/unittest.py python/branches/p3yk/Lib/urllib.py python/branches/p3yk/Lib/urlparse.py python/branches/p3yk/Lib/uu.py python/branches/p3yk/Lib/warnings.py python/branches/p3yk/Lib/webbrowser.py python/branches/p3yk/Lib/whichdb.py python/branches/p3yk/Lib/wsgiref/simple_server.py python/branches/p3yk/Lib/xml/dom/pulldom.py python/branches/p3yk/Lib/xml/sax/handler.py python/branches/p3yk/Lib/xmllib.py python/branches/p3yk/Lib/xmlrpclib.py python/branches/p3yk/Lib/zipfile.py Log: Fix most trivially-findable print statements. There's one major and one minor category still unfixed: doctests are the major category (and I hope to be able to augment the refactoring tool to refactor bona fide doctests soon); other code generating print statements in strings is the minor category. (Oh, and I don't know if the compiler package works.) Modified: python/branches/p3yk/Lib/BaseHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/BaseHTTPServer.py (original) +++ python/branches/p3yk/Lib/BaseHTTPServer.py Fri Feb 9 06:37:30 2007 @@ -570,7 +570,7 @@ httpd = ServerClass(server_address, HandlerClass) sa = httpd.socket.getsockname() - print "Serving HTTP on", sa[0], "port", sa[1], "..." + print("Serving HTTP on", sa[0], "port", sa[1], "...") httpd.serve_forever() Modified: python/branches/p3yk/Lib/Bastion.py ============================================================================== --- python/branches/p3yk/Lib/Bastion.py (original) +++ python/branches/p3yk/Lib/Bastion.py Fri Feb 9 06:37:30 2007 @@ -165,7 +165,7 @@ print "accessible" \n""" exec(testcode) - print '='*20, "Using rexec:", '='*20 + print('='*20, "Using rexec:", '='*20) import rexec r = rexec.RExec() m = r.add_module('__main__') Modified: python/branches/p3yk/Lib/Cookie.py ============================================================================== --- python/branches/p3yk/Lib/Cookie.py (original) +++ python/branches/p3yk/Lib/Cookie.py Fri Feb 9 06:37:30 2007 @@ -80,9 +80,9 @@ >>> C = Cookie.SmartCookie() >>> C["rocky"] = "road" >>> C["rocky"]["path"] = "/cookie" - >>> print C.output(header="Cookie:") + >>> print(C.output(header="Cookie:")) Cookie: rocky=road; Path=/cookie - >>> print C.output(attrs=[], header="Cookie:") + >>> print(C.output(attrs=[], header="Cookie:")) Cookie: rocky=road The load() method of a Cookie extracts cookies from a string. In a @@ -100,7 +100,7 @@ >>> C = Cookie.SmartCookie() >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') - >>> print C + >>> print(C) Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" Each element of the Cookie also supports all of the RFC 2109 @@ -110,7 +110,7 @@ >>> C = Cookie.SmartCookie() >>> C["oreo"] = "doublestuff" >>> C["oreo"]["path"] = "/" - >>> print C + >>> print(C) Set-Cookie: oreo=doublestuff; Path=/ Each dictionary element has a 'value' attribute, which gives you @@ -198,7 +198,7 @@ fact, this simply returns a SmartCookie. >>> C = Cookie.Cookie() - >>> print C.__class__.__name__ + >>> print(C.__class__.__name__) SmartCookie Modified: python/branches/p3yk/Lib/DocXMLRPCServer.py ============================================================================== --- python/branches/p3yk/Lib/DocXMLRPCServer.py (original) +++ python/branches/p3yk/Lib/DocXMLRPCServer.py Fri Feb 9 06:37:30 2007 @@ -270,9 +270,9 @@ response = self.generate_html_documentation() - print 'Content-Type: text/html' - print 'Content-Length: %d' % len(response) - print + print('Content-Type: text/html') + print('Content-Length: %d' % len(response)) + print() sys.stdout.write(response) def __init__(self): Modified: python/branches/p3yk/Lib/SimpleXMLRPCServer.py ============================================================================== --- python/branches/p3yk/Lib/SimpleXMLRPCServer.py (original) +++ python/branches/p3yk/Lib/SimpleXMLRPCServer.py Fri Feb 9 06:37:30 2007 @@ -543,9 +543,9 @@ response = self._marshaled_dispatch(request_text) - print 'Content-Type: text/xml' - print 'Content-Length: %d' % len(response) - print + print('Content-Type: text/xml') + print('Content-Length: %d' % len(response)) + print() sys.stdout.write(response) def handle_get(self): @@ -565,10 +565,10 @@ 'message' : message, 'explain' : explain } - print 'Status: %d %s' % (code, message) - print 'Content-Type: text/html' - print 'Content-Length: %d' % len(response) - print + print('Status: %d %s' % (code, message)) + print('Content-Type: text/html') + print('Content-Length: %d' % len(response)) + print() sys.stdout.write(response) def handle_request(self, request_text = None): @@ -590,7 +590,7 @@ self.handle_xmlrpc(request_text) if __name__ == '__main__': - print 'Running XML-RPC server on port 8000' + print('Running XML-RPC server on port 8000') server = SimpleXMLRPCServer(("localhost", 8000)) server.register_function(pow) server.register_function(lambda x,y: x+y, 'add') Modified: python/branches/p3yk/Lib/SocketServer.py ============================================================================== --- python/branches/p3yk/Lib/SocketServer.py (original) +++ python/branches/p3yk/Lib/SocketServer.py Fri Feb 9 06:37:30 2007 @@ -263,12 +263,12 @@ The default is to print a traceback and continue. """ - print '-'*40 - print 'Exception happened during processing of request from', - print client_address + print('-'*40) + print('Exception happened during processing of request from', end=' ') + print(client_address) import traceback traceback.print_exc() # XXX But this goes to stderr! - print '-'*40 + print('-'*40) class TCPServer(BaseServer): Modified: python/branches/p3yk/Lib/StringIO.py ============================================================================== --- python/branches/p3yk/Lib/StringIO.py (original) +++ python/branches/p3yk/Lib/StringIO.py Fri Feb 9 06:37:30 2007 @@ -291,14 +291,14 @@ if f.getvalue() != text: raise RuntimeError, 'write failed' length = f.tell() - print 'File length =', length + print('File length =', length) f.seek(len(lines[0])) f.write(lines[1]) f.seek(0) - print 'First line =', repr(f.readline()) - print 'Position =', f.tell() + print('First line =', repr(f.readline())) + print('Position =', f.tell()) line = f.readline() - print 'Second line =', repr(line) + print('Second line =', repr(line)) f.seek(-len(line), 1) line2 = f.read(len(line)) if line != line2: @@ -310,13 +310,13 @@ line2 = f.read() if line != line2: raise RuntimeError, 'bad result after seek back from EOF' - print 'Read', len(list), 'more lines' - print 'File length =', f.tell() + print('Read', len(list), 'more lines') + print('File length =', f.tell()) if f.tell() != length: raise RuntimeError, 'bad length' f.truncate(length/2) f.seek(0, 2) - print 'Truncated length =', f.tell() + print('Truncated length =', f.tell()) if f.tell() != length/2: raise RuntimeError, 'truncate did not adjust length' f.close() Modified: python/branches/p3yk/Lib/aifc.py ============================================================================== --- python/branches/p3yk/Lib/aifc.py (original) +++ python/branches/p3yk/Lib/aifc.py Fri Feb 9 06:37:30 2007 @@ -453,7 +453,7 @@ kludge = 0 if chunk.chunksize == 18: kludge = 1 - print 'Warning: bad COMM chunk size' + print('Warning: bad COMM chunk size') chunk.chunksize = 23 #DEBUG end self._comptype = chunk.read(4) @@ -518,11 +518,11 @@ # a position 0 and name '' self._markers.append((id, pos, name)) except EOFError: - print 'Warning: MARK chunk contains only', - print len(self._markers), - if len(self._markers) == 1: print 'marker', - else: print 'markers', - print 'instead of', nmarkers + print('Warning: MARK chunk contains only', end=' ') + print(len(self._markers), end=' ') + if len(self._markers) == 1: print('marker', end=' ') + else: print('markers', end=' ') + print('instead of', nmarkers) class Aifc_write: # Variables used in this class: @@ -939,16 +939,16 @@ sys.argv.append('/usr/demos/data/audio/bach.aiff') fn = sys.argv[1] f = open(fn, 'r') - print "Reading", fn - print "nchannels =", f.getnchannels() - print "nframes =", f.getnframes() - print "sampwidth =", f.getsampwidth() - print "framerate =", f.getframerate() - print "comptype =", f.getcomptype() - print "compname =", f.getcompname() + print("Reading", fn) + print("nchannels =", f.getnchannels()) + print("nframes =", f.getnframes()) + print("sampwidth =", f.getsampwidth()) + print("framerate =", f.getframerate()) + print("comptype =", f.getcomptype()) + print("compname =", f.getcompname()) if sys.argv[2:]: gn = sys.argv[2] - print "Writing", gn + print("Writing", gn) g = open(gn, 'w') g.setparams(f.getparams()) while 1: @@ -958,4 +958,4 @@ g.writeframes(data) g.close() f.close() - print "Done." + print("Done.") Modified: python/branches/p3yk/Lib/asyncore.py ============================================================================== --- python/branches/p3yk/Lib/asyncore.py (original) +++ python/branches/p3yk/Lib/asyncore.py Fri Feb 9 06:37:30 2007 @@ -373,7 +373,7 @@ def log_info(self, message, type='info'): if __debug__ or type != 'info': - print '%s: %s' % (type, message) + print('%s: %s' % (type, message)) def handle_read_event(self): if self.accepting: Modified: python/branches/p3yk/Lib/atexit.py ============================================================================== --- python/branches/p3yk/Lib/atexit.py (original) +++ python/branches/p3yk/Lib/atexit.py Fri Feb 9 06:37:30 2007 @@ -26,7 +26,7 @@ exc_info = sys.exc_info() except: import traceback - print >> sys.stderr, "Error in atexit._run_exitfuncs:" + print("Error in atexit._run_exitfuncs:", file=sys.stderr) traceback.print_exc() exc_info = sys.exc_info() @@ -53,11 +53,11 @@ if __name__ == "__main__": def x1(): - print "running x1" + print("running x1") def x2(n): - print "running x2(%r)" % (n,) + print("running x2(%r)" % (n,)) def x3(n, kwd=None): - print "running x3(%r, kwd=%r)" % (n, kwd) + print("running x3(%r, kwd=%r)" % (n, kwd)) register(x1) register(x2, 12) Modified: python/branches/p3yk/Lib/audiodev.py ============================================================================== --- python/branches/p3yk/Lib/audiodev.py (original) +++ python/branches/p3yk/Lib/audiodev.py Fri Feb 9 06:37:30 2007 @@ -240,7 +240,7 @@ fn = 'f:just samples:just.aif' import aifc af = aifc.open(fn, 'r') - print fn, af.getparams() + print(fn, af.getparams()) p = AudioDev() p.setoutrate(af.getframerate()) p.setsampwidth(af.getsampwidth()) @@ -249,7 +249,7 @@ while 1: data = af.readframes(BUFSIZ) if not data: break - print len(data) + print(len(data)) p.writeframes(data) p.wait() Modified: python/branches/p3yk/Lib/base64.py ============================================================================== --- python/branches/p3yk/Lib/base64.py (original) +++ python/branches/p3yk/Lib/base64.py Fri Feb 9 06:37:30 2007 @@ -330,11 +330,11 @@ opts, args = getopt.getopt(sys.argv[1:], 'deut') except getopt.error as msg: sys.stdout = sys.stderr - print msg - print """usage: %s [-d|-e|-u|-t] [file|-] + print(msg) + print("""usage: %s [-d|-e|-u|-t] [file|-] -d, -u: decode -e: encode (default) - -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0] + -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]) sys.exit(2) func = encode for o, a in opts: @@ -352,7 +352,7 @@ s0 = "Aladdin:open sesame" s1 = encodestring(s0) s2 = decodestring(s1) - print s0, repr(s1), s2 + print(s0, repr(s1), s2) if __name__ == '__main__': Modified: python/branches/p3yk/Lib/bdb.py ============================================================================== --- python/branches/p3yk/Lib/bdb.py (original) +++ python/branches/p3yk/Lib/bdb.py Fri Feb 9 06:37:30 2007 @@ -58,7 +58,7 @@ return self.trace_dispatch if event == 'c_return': return self.trace_dispatch - print 'bdb.Bdb.dispatch: unknown debugging event:', repr(event) + print('bdb.Bdb.dispatch: unknown debugging event:', repr(event)) return self.trace_dispatch def dispatch_line(self, frame): @@ -483,17 +483,17 @@ disp = disp + 'yes ' else: disp = disp + 'no ' - print >>out, '%-4dbreakpoint %s at %s:%d' % (self.number, disp, - self.file, self.line) + print('%-4dbreakpoint %s at %s:%d' % (self.number, disp, + self.file, self.line), file=out) if self.cond: - print >>out, '\tstop only if %s' % (self.cond,) + print('\tstop only if %s' % (self.cond,), file=out) if self.ignore: - print >>out, '\tignore next %d hits' % (self.ignore) + print('\tignore next %d hits' % (self.ignore), file=out) if (self.hits): if (self.hits > 1): ss = 's' else: ss = '' - print >>out, ('\tbreakpoint already hit %d time%s' % - (self.hits, ss)) + print(('\tbreakpoint already hit %d time%s' % + (self.hits, ss)), file=out) # -----------end of Breakpoint class---------- @@ -582,27 +582,27 @@ def user_call(self, frame, args): name = frame.f_code.co_name if not name: name = '???' - print '+++ call', name, args + print('+++ call', name, args) def user_line(self, frame): import linecache name = frame.f_code.co_name if not name: name = '???' fn = self.canonic(frame.f_code.co_filename) line = linecache.getline(fn, frame.f_lineno) - print '+++', fn, frame.f_lineno, name, ':', line.strip() + print('+++', fn, frame.f_lineno, name, ':', line.strip()) def user_return(self, frame, retval): - print '+++ return', retval + print('+++ return', retval) def user_exception(self, frame, exc_stuff): - print '+++ exception', exc_stuff + print('+++ exception', exc_stuff) self.set_continue() def foo(n): - print 'foo(', n, ')' + print('foo(', n, ')') x = bar(n*10) - print 'bar returned', x + print('bar returned', x) def bar(a): - print 'bar(', a, ')' + print('bar(', a, ')') return a/2 def test(): Modified: python/branches/p3yk/Lib/bsddb/dbtables.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbtables.py (original) +++ python/branches/p3yk/Lib/bsddb/dbtables.py Fri Feb 9 06:37:30 2007 @@ -208,12 +208,12 @@ def _db_print(self) : """Print the database to stdout for debugging""" - print "******** Printing raw database for debugging ********" + print("******** Printing raw database for debugging ********") cur = self.db.cursor() try: key, data = cur.first() while 1: - print repr({key: data}) + print(repr({key: data})) next = cur.next() if next: key, data = next Modified: python/branches/p3yk/Lib/bsddb/test/test_all.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_all.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_all.py Fri Feb 9 06:37:30 2007 @@ -22,15 +22,15 @@ def print_versions(): - print - print '-=' * 38 - print db.DB_VERSION_STRING - print 'bsddb.db.version(): %s' % (db.version(), ) - print 'bsddb.db.__version__: %s' % db.__version__ - print 'bsddb.db.cvsid: %s' % db.cvsid - print 'python version: %s' % sys.version - print 'My pid: %s' % os.getpid() - print '-=' * 38 + print() + print('-=' * 38) + print(db.DB_VERSION_STRING) + print('bsddb.db.version(): %s' % (db.version(), )) + print('bsddb.db.__version__: %s' % db.__version__) + print('bsddb.db.cvsid: %s' % db.cvsid) + print('python version: %s' % sys.version) + print('My pid: %s' % os.getpid()) + print('-=' * 38) class PrintInfoFakeTest(unittest.TestCase): Modified: python/branches/p3yk/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 Fri Feb 9 06:37:30 2007 @@ -114,9 +114,9 @@ def test00_associateDBError(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test00_associateDBError..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test00_associateDBError..." % \ + self.__class__.__name__) dupDB = db.DB(self.env) dupDB.set_flags(db.DB_DUP) @@ -207,9 +207,9 @@ def test01_associateWithDB(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_associateWithDB..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_associateWithDB..." % \ + self.__class__.__name__) self.createDB() @@ -227,9 +227,9 @@ def test02_associateAfterDB(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_associateAfterDB..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_associateAfterDB..." % \ + self.__class__.__name__) self.createDB() self.addDataToDB(self.getDB()) @@ -257,7 +257,7 @@ vals[1].index('unknown') if verbose: - print "Primary key traversal:" + print("Primary key traversal:") self.cur = self.getDB().cursor(txn) count = 0 rec = self.cur.first() @@ -268,13 +268,13 @@ assert rec[0] and type(rec[0]) == type(0) count = count + 1 if verbose: - print rec + print(rec) rec = self.cur.next() assert count == len(musicdata) # all items accounted for if verbose: - print "Secondary key traversal:" + print("Secondary key traversal:") self.cur = secDB.cursor(txn) count = 0 @@ -294,7 +294,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) rec = self.cur.next() # all items accounted for EXCEPT for 1 with "Blues" genre assert count == len(musicdata)-1 @@ -304,7 +304,7 @@ def getGenre(self, priKey, priData): assert type(priData) == type("") if verbose: - print 'getGenre key: %r data: %r' % (priKey, priData) + print('getGenre key: %r data: %r' % (priKey, priData)) genre = string.split(priData, '|')[2] if genre == 'Blues': return db.DB_DONOTINDEX @@ -343,9 +343,9 @@ def test13_associate_in_transaction(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test13_associateAutoCommit..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test13_associateAutoCommit..." % \ + self.__class__.__name__) txn = self.env.txn_begin() try: @@ -389,7 +389,7 @@ def getGenre(self, priKey, priData): assert type(priData) == type(()) if verbose: - print 'getGenre key: %r data: %r' % (priKey, priData) + print('getGenre key: %r data: %r' % (priKey, priData)) genre = priData[2] if genre == 'Blues': return db.DB_DONOTINDEX Modified: python/branches/p3yk/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 Fri Feb 9 06:37:30 2007 @@ -31,10 +31,10 @@ def test00_version(self): info = db.version() if verbose: - print '\n', '-=' * 20 - print 'bsddb.db.version(): %s' % (info, ) - print db.DB_VERSION_STRING - print '-=' * 20 + print('\n', '-=' * 20) + print('bsddb.db.version(): %s' % (info, )) + print(db.DB_VERSION_STRING) + print('-=' * 20) assert info == (db.DB_VERSION_MAJOR, db.DB_VERSION_MINOR, db.DB_VERSION_PATCH) @@ -131,7 +131,7 @@ num = len(d) if verbose: - print "created %d records" % num + print("created %d records" % num) def makeData(self, key): @@ -145,13 +145,13 @@ d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_GetsAndPuts..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_GetsAndPuts..." % self.__class__.__name__) for key in ['0001', '0100', '0400', '0700', '0999']: data = d.get(key) if verbose: - print data + print(data) assert d.get('0321') == '0321-0321-0321-0321-0321' @@ -164,7 +164,7 @@ d.delete('abcd') except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) else: self.fail("expected exception") @@ -183,7 +183,7 @@ d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE) except db.DBKeyExistError as val: assert val[0] == db.DB_KEYEXIST - if verbose: print val + if verbose: print(val) else: self.fail("expected exception") @@ -212,7 +212,7 @@ rec = d.get_both('0555', '0555-0555-0555-0555-0555') if verbose: - print rec + print(rec) assert d.get_both('0555', 'bad data') == None @@ -227,7 +227,7 @@ s = d.stat() assert type(s) == type({}) if verbose: - print 'd.stat() returned this dictionary:' + print('d.stat() returned this dictionary:') pprint(s) @@ -237,15 +237,15 @@ d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_DictionaryMethods..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_DictionaryMethods..." % \ + self.__class__.__name__) for key in ['0002', '0101', '0401', '0701', '0998']: data = d[key] assert data == self.makeData(key) if verbose: - print data + print(data) assert len(d) == self._numKeys keys = d.keys() @@ -263,7 +263,7 @@ assert len(keys) == self._numKeys+1 if verbose: - print "the first 10 keys are:" + print("the first 10 keys are:") pprint(keys[:10]) assert d['new record'] == 'a replacement record' @@ -278,7 +278,7 @@ assert len(items[0]) == 2 if verbose: - print "the first 10 items are:" + print("the first 10 items are:") pprint(items[:10]) values = d.values() @@ -286,7 +286,7 @@ assert type(values) == type([]) if verbose: - print "the first 10 values are:" + print("the first 10 values are:") pprint(values[:10]) @@ -295,9 +295,9 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0): if verbose: - print '\n', '-=' * 30 - print "Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \ - (self.__class__.__name__, get_raises_error, set_raises_error) + print('\n', '-=' * 30) + print("Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \ + (self.__class__.__name__, get_raises_error, set_raises_error)) if self.env and self.dbopenflags & db.DB_AUTO_COMMIT: txn = self.env.txn_begin() @@ -310,13 +310,13 @@ while rec is not None: count = count + 1 if verbose and count % 100 == 0: - print rec + print(rec) try: rec = c.next() except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) rec = None else: self.fail("unexpected DBNotFoundError") @@ -330,13 +330,13 @@ while rec is not None: count = count + 1 if verbose and count % 100 == 0: - print rec + print(rec) try: rec = c.prev() except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) rec = None else: self.fail("unexpected DBNotFoundError") @@ -359,7 +359,7 @@ n = c.set('bad key') except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) else: if set_raises_error: self.fail("expected exception") @@ -373,7 +373,7 @@ n = c.get_both('0404', 'bad data') except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND - if verbose: print val + if verbose: print(val) else: if get_raises_error: self.fail("expected exception") @@ -383,16 +383,16 @@ if self.d.get_type() == db.DB_BTREE: rec = c.set_range('011') if verbose: - print "searched for '011', found: ", rec + print("searched for '011', found: ", rec) rec = c.set_range('011',dlen=0,doff=0) if verbose: - print "searched (partial) for '011', found: ", rec + print("searched (partial) for '011', found: ", rec) if rec[1] != '': self.fail('expected empty data portion') ev = c.set_range('empty value') if verbose: - print "search for 'empty value' returned", ev + print("search for 'empty value' returned", ev) if ev[1] != '': self.fail('empty value lookup failed') c.set('0499') @@ -402,7 +402,7 @@ except db.DBKeyEmptyError as val: if get_raises_error: assert val[0] == db.DB_KEYEMPTY - if verbose: print val + if verbose: print(val) else: self.fail("unexpected DBKeyEmptyError") else: @@ -441,13 +441,13 @@ for method, args in methods_to_test.items(): try: if verbose: - print "attempting to use a closed cursor's %s method" % \ - method + print("attempting to use a closed cursor's %s method" % \ + method) # a bug may cause a NULL pointer dereference... getattr(c, method)(*args) except db.DBError as val: assert val[0] == 0 - if verbose: print val + if verbose: print(val) else: self.fail("no exception raised when using a buggy cursor's" "%s method" % method) @@ -466,9 +466,9 @@ def test03b_SimpleCursorWithoutGetReturnsNone0(self): # same test but raise exceptions instead of returning None if verbose: - print '\n', '-=' * 30 - print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ + self.__class__.__name__) old = self.d.set_get_returns_none(0) assert old == 2 @@ -477,9 +477,9 @@ def test03b_SimpleCursorWithGetReturnsNone1(self): # same test but raise exceptions instead of returning None if verbose: - print '\n', '-=' * 30 - print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ + self.__class__.__name__) old = self.d.set_get_returns_none(1) self.test03_SimpleCursorStuff(get_raises_error=0, set_raises_error=1) @@ -488,9 +488,9 @@ def test03c_SimpleCursorGetReturnsNone2(self): # same test but raise exceptions instead of returning None if verbose: - print '\n', '-=' * 30 - print "Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \ + self.__class__.__name__) old = self.d.set_get_returns_none(1) assert old == 2 @@ -503,9 +503,9 @@ def test04_PartialGetAndPut(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test04_PartialGetAndPut..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test04_PartialGetAndPut..." % \ + self.__class__.__name__) key = "partialTest" data = "1" * 1000 + "2" * 1000 @@ -533,8 +533,8 @@ def test05_GetSize(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test05_GetSize..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test05_GetSize..." % self.__class__.__name__) for i in range(1, 50000, 500): key = "size%s" % i @@ -553,8 +553,8 @@ d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test99_Truncate..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test99_Truncate..." % self.__class__.__name__) d.put("abcde", "ABCDE"); num = d.truncate() @@ -598,8 +598,8 @@ return if verbose: - print '\n', '-=' * 30 - print "Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__) # can't rename or remove an open DB self.d.close() @@ -647,8 +647,8 @@ def test06_Transactions(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test06_Transactions..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test06_Transactions..." % self.__class__.__name__) assert d.get('new rec', txn=self.txn) == None d.put('new rec', 'this is a new record', self.txn) @@ -671,7 +671,7 @@ while rec is not None: count = count + 1 if verbose and count % 100 == 0: - print rec + print(rec) rec = c.next() assert count == self._numKeys+1 @@ -696,7 +696,7 @@ assert logs != None for log in logs: if verbose: - print 'log file: ' + log + print('log file: ' + log) if db.version() >= (4,2): logs = self.env.log_archive(db.DB_ARCH_REMOVE) assert not logs @@ -712,8 +712,8 @@ d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test07_TxnTruncate..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test07_TxnTruncate..." % self.__class__.__name__) d.put("abcde", "ABCDE"); txn = self.env.txn_begin() @@ -762,21 +762,21 @@ def test07_RecnoInBTree(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test07_RecnoInBTree..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test07_RecnoInBTree..." % self.__class__.__name__) rec = d.get(200) assert type(rec) == type(()) assert len(rec) == 2 if verbose: - print "Record #200 is ", rec + print("Record #200 is ", rec) c = d.cursor() c.set('0200') num = c.get_recno() assert type(num) == type(1) if verbose: - print "recno of d['0200'] is ", num + print("recno of d['0200'] is ", num) rec = c.current() assert c.set_recno(num) == rec @@ -796,9 +796,9 @@ def test08_DuplicateKeys(self): d = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test08_DuplicateKeys..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test08_DuplicateKeys..." % \ + self.__class__.__name__) d.put("dup0", "before") for x in "The quick brown fox jumped over the lazy dog.".split(): @@ -808,7 +808,7 @@ data = d.get("dup1") assert data == "The" if verbose: - print data + print(data) c = d.cursor() rec = c.set("dup1") @@ -827,14 +827,14 @@ rec = c.set('dup1') while rec is not None: if verbose: - print rec + print(rec) rec = c.next_dup() c.set('dup1') rec = c.next_nodup() assert rec[0] != 'dup1' if verbose: - print rec + print(rec) c.close() @@ -869,8 +869,8 @@ def test09_MultiDB(self): d1 = self.d if verbose: - print '\n', '-=' * 30 - print "Running %s.test09_MultiDB..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test09_MultiDB..." % self.__class__.__name__) d2 = db.DB(self.env) d2.open(self.filename, "second", self.dbtype, @@ -910,7 +910,7 @@ while rec is not None: count = count + 1 if verbose and (count % 50) == 0: - print rec + print(rec) rec = c1.next() assert count == self._numKeys @@ -919,7 +919,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) rec = c2.next() assert count == 9 @@ -928,7 +928,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) rec = c3.next() assert count == 52 Modified: python/branches/p3yk/Lib/bsddb/test/test_compat.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_compat.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_compat.py Fri Feb 9 06:37:30 2007 @@ -37,7 +37,7 @@ def test03_rnopen(self): data = string.split("The quick brown fox jumped over the lazy dog.") if verbose: - print "\nTesting: rnopen" + print("\nTesting: rnopen") f = rnopen(self.filename, 'c') for x in range(len(data)): @@ -45,7 +45,7 @@ getTest = (f[1], f[2], f[3]) if verbose: - print '%s %s %s' % getTest + print('%s %s %s' % getTest) assert getTest[1] == 'quick', 'data mismatch!' @@ -73,7 +73,7 @@ rec = f.first() while rec: if verbose: - print rec + print(rec) try: rec = f.next() except KeyError: @@ -89,17 +89,17 @@ def do_bthash_test(self, factory, what): if verbose: - print '\nTesting: ', what + print('\nTesting: ', what) f = factory(self.filename, 'c') if verbose: - print 'creation...' + print('creation...') # truth test if f: - if verbose: print "truth test: true" + if verbose: print("truth test: true") else: - if verbose: print "truth test: false" + if verbose: print("truth test: false") f['0'] = '' f['a'] = 'Guido' @@ -109,10 +109,10 @@ # 'e' intentionally left out f['f'] = 'Python' if verbose: - print '%s %s %s' % (f['a'], f['b'], f['c']) + print('%s %s %s' % (f['a'], f['b'], f['c'])) if verbose: - print 'key ordering...' + print('key ordering...') start = f.set_location(f.first()[0]) if start != ('0', ''): self.fail("incorrect first() result: "+repr(start)) @@ -124,7 +124,7 @@ f.previous() break if verbose: - print rec + print(rec) assert f.has_key('f'), 'Error, missing key!' @@ -147,9 +147,9 @@ # truth test try: if f: - if verbose: print "truth test: true" + if verbose: print("truth test: true") else: - if verbose: print "truth test: false" + if verbose: print("truth test: false") except db.DBError: pass else: @@ -158,16 +158,16 @@ del f if verbose: - print 'modification...' + print('modification...') f = factory(self.filename, 'w') f['d'] = 'discovered' if verbose: - print 'access...' + print('access...') for key in f.keys(): word = f[key] if verbose: - print word + print(word) def noRec(f): rec = f['no such key'] Modified: python/branches/p3yk/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 Fri Feb 9 06:37:30 2007 @@ -79,8 +79,8 @@ def test01_basics(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_basics..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_basics..." % self.__class__.__name__) self.populateDB(self.d) self.d.sync() @@ -94,9 +94,9 @@ f = d.fd() if verbose: - print "length:", l - print "keys:", k - print "stats:", s + print("length:", l) + print("keys:", k) + print("stats:", s) assert 0 == d.has_key('bad key') assert 1 == d.has_key('IA') @@ -113,7 +113,7 @@ value = d[key] values.append(value) if verbose: - print "%s: %s" % (key, value) + print("%s: %s" % (key, value)) self.checkrec(key, value) dbvalues = sorted(d.values(), key=lambda x: (str(type(x)), x)) @@ -144,8 +144,8 @@ def test02_cursors(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_cursors..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_cursors..." % self.__class__.__name__) self.populateDB(self.d) d = self.d @@ -156,7 +156,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) key, value = rec self.checkrec(key, value) rec = c.next() @@ -170,7 +170,7 @@ while rec is not None: count = count + 1 if verbose: - print rec + print(rec) key, value = rec self.checkrec(key, value) rec = c.prev() Modified: python/branches/p3yk/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 Fri Feb 9 06:37:30 2007 @@ -110,7 +110,7 @@ assert values[1]['Species'] == 'Penguin' else : if verbose: - print "values= %r" % (values,) + print("values= %r" % (values,)) raise "Wrong values returned!" def test03(self): @@ -120,15 +120,15 @@ except dbtables.TableDBError: pass if verbose: - print '...before CreateTable...' + print('...before CreateTable...') self.tdb._db_print() self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e']) if verbose: - print '...after CreateTable...' + print('...after CreateTable...') self.tdb._db_print() self.tdb.Drop(tabname) if verbose: - print '...after Drop...' + print('...after Drop...') self.tdb._db_print() self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e']) 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 Fri Feb 9 06:37:30 2007 @@ -65,9 +65,9 @@ def test01_join(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_join..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_join..." % \ + self.__class__.__name__) # create and populate primary index priDB = db.DB(self.env) Modified: python/branches/p3yk/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 Fri Feb 9 06:37:30 2007 @@ -49,27 +49,27 @@ def test01_simple(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_simple..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_simple..." % self.__class__.__name__) anID = self.env.lock_id() if verbose: - print "locker ID: %s" % anID + print("locker ID: %s" % anID) lock = self.env.lock_get(anID, "some locked thing", db.DB_LOCK_WRITE) if verbose: - print "Aquired lock: %s" % lock + print("Aquired lock: %s" % lock) time.sleep(1) self.env.lock_put(lock) if verbose: - print "Released lock: %s" % lock + print("Released lock: %s" % lock) def test02_threaded(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_threaded..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_threaded..." % self.__class__.__name__) threads = [] threads.append(Thread(target = self.theThread, @@ -113,17 +113,17 @@ anID = self.env.lock_id() if verbose: - print "%s: locker ID: %s" % (name, anID) + print("%s: locker ID: %s" % (name, anID)) lock = self.env.lock_get(anID, "some locked thing", lockType) if verbose: - print "%s: Aquired %s lock: %s" % (name, lt, lock) + print("%s: Aquired %s lock: %s" % (name, lt, lock)) time.sleep(sleepTime) self.env.lock_put(lock) if verbose: - print "%s: Released %s lock: %s" % (name, lt, lock) + print("%s: Released %s lock: %s" % (name, lt, lock)) #---------------------------------------------------------------------- Modified: python/branches/p3yk/Lib/bsddb/test/test_queue.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_queue.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_queue.py Fri Feb 9 06:37:30 2007 @@ -34,15 +34,15 @@ # Basic Queue tests using the deprecated DBCursor.consume method. if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_basic..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_basic..." % self.__class__.__name__) d = db.DB() d.set_re_len(40) # Queues must be fixed length d.open(self.filename, db.DB_QUEUE, db.DB_CREATE) if verbose: - print "before appends" + '-' * 30 + print("before appends" + '-' * 30) pprint(d.stat()) for x in string.letters: @@ -58,7 +58,7 @@ assert len(d) == 55 if verbose: - print "before close" + '-' * 30 + print("before close" + '-' * 30) pprint(d.stat()) d.close() @@ -67,25 +67,25 @@ d.open(self.filename) if verbose: - print "after open" + '-' * 30 + print("after open" + '-' * 30) pprint(d.stat()) d.append("one more") c = d.cursor() if verbose: - print "after append" + '-' * 30 + print("after append" + '-' * 30) pprint(d.stat()) rec = c.consume() while rec: if verbose: - print rec + print(rec) rec = c.consume() c.close() if verbose: - print "after consume loop" + '-' * 30 + print("after consume loop" + '-' * 30) pprint(d.stat()) assert len(d) == 0, \ @@ -101,12 +101,12 @@ # (No cursor needed) if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_basicPost32..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_basicPost32..." % self.__class__.__name__) if db.version() < (3, 2, 0): if verbose: - print "Test not run, DB not new enough..." + print("Test not run, DB not new enough...") return d = db.DB() @@ -114,7 +114,7 @@ d.open(self.filename, db.DB_QUEUE, db.DB_CREATE) if verbose: - print "before appends" + '-' * 30 + print("before appends" + '-' * 30) pprint(d.stat()) for x in string.letters: @@ -130,7 +130,7 @@ assert len(d) == 55 if verbose: - print "before close" + '-' * 30 + print("before close" + '-' * 30) pprint(d.stat()) d.close() @@ -140,23 +140,23 @@ #d.set_get_returns_none(true) if verbose: - print "after open" + '-' * 30 + print("after open" + '-' * 30) pprint(d.stat()) d.append("one more") if verbose: - print "after append" + '-' * 30 + print("after append" + '-' * 30) pprint(d.stat()) rec = d.consume() while rec: if verbose: - print rec + print(rec) rec = d.consume() if verbose: - print "after consume loop" + '-' * 30 + print("after consume loop" + '-' * 30) pprint(d.stat()) d.close() Modified: python/branches/p3yk/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 Fri Feb 9 06:37:30 2007 @@ -45,9 +45,9 @@ assert type(recno) == type(0) assert recno >= 1 if verbose: - print recno, + print(recno, end=' ') - if verbose: print + if verbose: print() stat = d.stat() if verbose: @@ -56,7 +56,7 @@ for recno in range(1, len(d)+1): data = d[recno] if verbose: - print data + print(data) assert type(data) == type("") assert data == d.get(recno) @@ -65,7 +65,7 @@ data = d[0] # This should raise a KeyError!?!?! except db.DBInvalidArgError as val: assert val[0] == db.EINVAL - if verbose: print val + if verbose: print(val) else: self.fail("expected exception") @@ -94,7 +94,7 @@ keys = d.keys() if verbose: - print keys + print(keys) assert type(keys) == type([]) assert type(keys[0]) == type(123) assert len(keys) == len(d) @@ -120,23 +120,23 @@ data = d.get_both(26, "z" * 60) assert data == "z" * 60 if verbose: - print data + print(data) fd = d.fd() if verbose: - print fd + print(fd) c = d.cursor() rec = c.first() while rec: if verbose: - print rec + print(rec) rec = c.next() c.set(50) rec = c.current() if verbose: - print rec + print(rec) c.put(-1, "a replacement record", db.DB_CURRENT) @@ -144,18 +144,18 @@ rec = c.current() assert rec == (50, "a replacement record") if verbose: - print rec + print(rec) rec = c.set_range(30) if verbose: - print rec + print(rec) # test that non-existant key lookups work (and that # DBC_set_range doesn't have a memleak under valgrind) rec = c.set_range(999999) assert rec == None if verbose: - print rec + print(rec) c.close() d.close() @@ -182,7 +182,7 @@ self.fail("unexpected DBKeyEmptyError exception") else: assert val[0] == db.DB_KEYEMPTY - if verbose: print val + if verbose: print(val) else: if not get_returns_none: self.fail("expected exception") @@ -190,7 +190,7 @@ rec = c.set(40) while rec: if verbose: - print rec + print(rec) rec = c.next() c.close() @@ -227,9 +227,9 @@ text = open(source, 'r').read() text = text.strip() if verbose: - print text - print data - print text.split('\n') + print(text) + print(data) + print(text.split('\n')) assert text.split('\n') == data @@ -247,8 +247,8 @@ text = open(source, 'r').read() text = text.strip() if verbose: - print text - print text.split('\n') + print(text) + print(text.split('\n')) assert text.split('\n') == \ "The quick reddish-brown fox jumped over the comatose dog".split() @@ -269,7 +269,7 @@ d.append('bad' * 20) except db.DBInvalidArgError as val: assert val[0] == db.EINVAL - if verbose: print val + if verbose: print(val) else: self.fail("expected exception") @@ -277,7 +277,7 @@ rec = c.first() while rec: if verbose: - print rec + print(rec) rec = c.next() c.close() Modified: python/branches/p3yk/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 Fri Feb 9 06:37:30 2007 @@ -93,9 +93,9 @@ def test01_1WriterMultiReaders(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test01_1WriterMultiReaders..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test01_1WriterMultiReaders..." % \ + self.__class__.__name__) threads = [] for x in range(self.writers): @@ -123,17 +123,17 @@ start = howMany * writerNum stop = howMany * (writerNum + 1) - 1 if verbose: - print "%s: creating records %d - %d" % (name, start, stop) + print("%s: creating records %d - %d" % (name, start, stop)) for x in range(start, stop): key = '%04d' % x dbutils.DeadlockWrap(d.put, key, self.makeData(key), max_retries=12) if verbose and x % 100 == 0: - print "%s: records %d - %d finished" % (name, start, x) + print("%s: records %d - %d finished" % (name, start, x)) if verbose: - print "%s: finished creating records" % name + print("%s: finished creating records" % name) ## # Each write-cursor will be exclusive, the only one that can update the DB... ## if verbose: print "%s: deleting a few records" % name @@ -147,7 +147,7 @@ ## c.close() if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) def readerThread(self, d, readerNum): time.sleep(0.01 * readerNum) @@ -163,12 +163,12 @@ self.assertEqual(self.makeData(key), data) rec = c.next() if verbose: - print "%s: found %d records" % (name, count) + print("%s: found %d records" % (name, count)) c.close() time.sleep(0.05) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) class BTreeConcurrentDataStore(ConcurrentDataStoreBase): @@ -199,8 +199,8 @@ def test02_SimpleLocks(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test02_SimpleLocks..." % self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test02_SimpleLocks..." % self.__class__.__name__) threads = [] for x in range(self.writers): @@ -226,7 +226,7 @@ start = howMany * writerNum stop = howMany * (writerNum + 1) - 1 if verbose: - print "%s: creating records %d - %d" % (name, start, stop) + print("%s: creating records %d - %d" % (name, start, stop)) # create a bunch of records for x in xrange(start, stop): @@ -235,7 +235,7 @@ max_retries=12) if verbose and x % 100 == 0: - print "%s: records %d - %d finished" % (name, start, x) + print("%s: records %d - %d finished" % (name, start, x)) # do a bit or reading too if random() <= 0.05: @@ -249,22 +249,22 @@ dbutils.DeadlockWrap(d.sync, max_retries=12) except db.DBIncompleteError as val: if verbose: - print "could not complete sync()..." + print("could not complete sync()...") # read them back, deleting a few for x in xrange(start, stop): key = '%04d' % x data = dbutils.DeadlockWrap(d.get, key, max_retries=12) if verbose and x % 100 == 0: - print "%s: fetched record (%s, %s)" % (name, key, data) + print("%s: fetched record (%s, %s)" % (name, key, data)) self.assertEqual(data, self.makeData(key)) if random() <= 0.10: dbutils.DeadlockWrap(d.delete, key, max_retries=12) if verbose: - print "%s: deleted record %s" % (name, key) + print("%s: deleted record %s" % (name, key)) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) def readerThread(self, d, readerNum): time.sleep(0.01 * readerNum) @@ -280,12 +280,12 @@ self.assertEqual(self.makeData(key), data) rec = dbutils.DeadlockWrap(c.next, max_retries=10) if verbose: - print "%s: found %d records" % (name, count) + print("%s: found %d records" % (name, count)) c.close() time.sleep(0.05) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) class BTreeSimpleThreaded(SimpleThreadedBase): @@ -318,9 +318,9 @@ def test03_ThreadedTransactions(self): if verbose: - print '\n', '-=' * 30 - print "Running %s.test03_ThreadedTransactions..." % \ - self.__class__.__name__ + print('\n', '-=' * 30) + print("Running %s.test03_ThreadedTransactions..." % \ + self.__class__.__name__) threads = [] for x in range(self.writers): @@ -357,12 +357,12 @@ key = '%04d' % x d.put(key, self.makeData(key), txn) if verbose and x % 100 == 0: - print "%s: records %d - %d finished" % (name, start, x) + print("%s: records %d - %d finished" % (name, start, x)) txn.commit() finished = True except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: - print "%s: Aborting transaction (%s)" % (name, val[1]) + print("%s: Aborting transaction (%s)" % (name, val[1])) txn.abort() time.sleep(0.05) @@ -371,16 +371,16 @@ start = howMany * writerNum stop = howMany * (writerNum + 1) - 1 if verbose: - print "%s: creating records %d - %d" % (name, start, stop) + print("%s: creating records %d - %d" % (name, start, stop)) step = 100 for x in range(start, stop, step): self.doWrite(d, name, x, min(stop, x+step)) if verbose: - print "%s: finished creating records" % name + print("%s: finished creating records" % name) if verbose: - print "%s: deleting a few records" % name + print("%s: deleting a few records" % name) finished = False while not finished: @@ -397,15 +397,15 @@ txn.commit() finished = True if verbose: - print "%s: deleted records %s" % (name, recs) + print("%s: deleted records %s" % (name, recs)) except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: - print "%s: Aborting transaction (%s)" % (name, val[1]) + print("%s: Aborting transaction (%s)" % (name, val[1])) txn.abort() time.sleep(0.05) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) def readerThread(self, d, readerNum): time.sleep(0.01 * readerNum + 0.05) @@ -424,13 +424,13 @@ key, data = rec self.assertEqual(self.makeData(key), data) rec = c.next() - if verbose: print "%s: found %d records" % (name, count) + if verbose: print("%s: found %d records" % (name, count)) c.close() txn.commit() finished = True except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: - print "%s: Aborting transaction (%s)" % (name, val[1]) + print("%s: Aborting transaction (%s)" % (name, val[1])) c.close() txn.abort() time.sleep(0.05) @@ -438,7 +438,7 @@ time.sleep(0.05) if verbose: - print "%s: thread finished" % name + print("%s: thread finished" % name) def deadlockThread(self): self.doLockDetect = True @@ -448,8 +448,8 @@ aborted = self.env.lock_detect( db.DB_LOCK_RANDOM, db.DB_LOCK_CONFLICT) if verbose and aborted: - print "deadlock: Aborted %d deadlocked transaction(s)" \ - % aborted + print("deadlock: Aborted %d deadlocked transaction(s)" \ + % aborted) except db.DBError: pass @@ -497,7 +497,7 @@ suite.addTest(unittest.makeSuite(HashThreadedNoWaitTransactions)) else: - print "Threads not available, skipping thread tests." + print("Threads not available, skipping thread tests.") return suite Modified: python/branches/p3yk/Lib/cProfile.py ============================================================================== --- python/branches/p3yk/Lib/cProfile.py (original) +++ python/branches/p3yk/Lib/cProfile.py Fri Feb 9 06:37:30 2007 @@ -58,8 +58,8 @@ # Backwards compatibility. def help(): - print "Documentation for the profile/cProfile modules can be found " - print "in the Python Library Reference, section 'The Python Profiler'." + print("Documentation for the profile/cProfile modules can be found ") + print("in the Python Library Reference, section 'The Python Profiler'.") # ____________________________________________________________ Modified: python/branches/p3yk/Lib/calendar.py ============================================================================== --- python/branches/p3yk/Lib/calendar.py (original) +++ python/branches/p3yk/Lib/calendar.py Fri Feb 9 06:37:30 2007 @@ -261,7 +261,7 @@ """ Print a single week (no newline). """ - print self.week(theweek, width), + print(self.week(theweek, width), end=' ') def formatday(self, day, weekday, width): """ @@ -308,7 +308,7 @@ """ Print a month's calendar. """ - print self.formatmonth(theyear, themonth, w, l), + print(self.formatmonth(theyear, themonth, w, l), end=' ') def formatmonth(self, theyear, themonth, w=0, l=0): """ @@ -365,7 +365,7 @@ def pryear(self, theyear, w=0, l=0, c=6, m=3): """Print a year's calendar.""" - print self.formatyear(theyear, w, l, c, m) + print(self.formatyear(theyear, w, l, c, m)) class HTMLCalendar(Calendar): @@ -584,7 +584,7 @@ def format(cols, colwidth=_colwidth, spacing=_spacing): """Prints multi-column formatting for year calendars""" - print formatstring(cols, colwidth, spacing) + print(formatstring(cols, colwidth, spacing)) def formatstring(cols, colwidth=_colwidth, spacing=_spacing): @@ -668,9 +668,9 @@ encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: - print cal.formatyearpage(datetime.date.today().year, **optdict) + print(cal.formatyearpage(datetime.date.today().year, **optdict)) elif len(args) == 2: - print cal.formatyearpage(int(args[1]), **optdict) + print(cal.formatyearpage(int(args[1]), **optdict)) else: parser.error("incorrect number of arguments") sys.exit(1) @@ -694,7 +694,7 @@ sys.exit(1) if options.encoding: result = result.encode(options.encoding) - print result + print(result) if __name__ == "__main__": Modified: python/branches/p3yk/Lib/cgi.py ============================================================================== --- python/branches/p3yk/Lib/cgi.py (original) +++ python/branches/p3yk/Lib/cgi.py Fri Feb 9 06:37:30 2007 @@ -901,8 +901,8 @@ the script in HTML form. """ - print "Content-type: text/html" - print + print("Content-type: text/html") + print() sys.stderr = sys.stdout try: form = FieldStorage() # Replace with other classes to test those @@ -915,12 +915,12 @@ exec("testing print_exception() -- italics?") def g(f=f): f() - print "

What follows is a test, not an actual exception:

" + print("

What follows is a test, not an actual exception:

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

Second try with a small maxlen...

" + print("

Second try with a small maxlen...

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

Traceback (most recent call last):

" + print() + print("

Traceback (most recent call last):

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

Shell Environment:

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

Shell Environment:

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

Form Contents:

" + print() + print("

Form Contents:

") if not keys: - print "

No form fields." - print "

" + print("

No form fields.") + print("

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

Current Working Directory:

" + print() + print("

Current Working Directory:

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

Command Line Arguments:

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

Command Line Arguments:

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

These environment variables could have been set:

  • AUTH_TYPE @@ -1036,7 +1036,7 @@
  • HTTP_REFERER
  • HTTP_USER_AGENT
-""" +""") # Utilities Modified: python/branches/p3yk/Lib/code.py ============================================================================== --- python/branches/p3yk/Lib/code.py (original) +++ python/branches/p3yk/Lib/code.py Fri Feb 9 06:37:30 2007 @@ -107,7 +107,7 @@ self.showtraceback() else: if softspace(sys.stdout, 0): - print + print() def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. Modified: python/branches/p3yk/Lib/compileall.py ============================================================================== --- python/branches/p3yk/Lib/compileall.py (original) +++ python/branches/p3yk/Lib/compileall.py Fri Feb 9 06:37:30 2007 @@ -33,11 +33,11 @@ """ if not quiet: - print 'Listing', dir, '...' + print('Listing', dir, '...') try: names = os.listdir(dir) except os.error: - print "Can't list", dir + print("Can't list", dir) names = [] names.sort() success = 1 @@ -60,18 +60,18 @@ except os.error: ctime = 0 if (ctime > ftime) and not force: continue if not quiet: - print 'Compiling', fullname, '...' + print('Compiling', fullname, '...') try: ok = py_compile.compile(fullname, None, dfile, True) except KeyboardInterrupt: raise KeyboardInterrupt except py_compile.PyCompileError as err: if quiet: - print 'Compiling', fullname, '...' - print err.msg + print('Compiling', fullname, '...') + print(err.msg) success = 0 except IOError as e: - print "Sorry", e + print("Sorry", e) success = 0 else: if ok == 0: @@ -98,7 +98,7 @@ success = 1 for dir in sys.path: if (not dir or dir == os.curdir) and skip_curdir: - print 'Skipping current directory' + print('Skipping current directory') else: success = success and compile_dir(dir, maxlevels, None, force, quiet=quiet) @@ -110,16 +110,16 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:') except getopt.error as msg: - print msg - print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ - "[-x regexp] [directory ...]" - print "-l: don't recurse down" - print "-f: force rebuild even if timestamps are up-to-date" - print "-q: quiet operation" - print "-d destdir: purported directory name for error messages" - print " if no directory arguments, -l sys.path is assumed" - print "-x regexp: skip files matching the regular expression regexp" - print " the regexp is search for in the full path of the file" + print(msg) + print("usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ + "[-x regexp] [directory ...]") + print("-l: don't recurse down") + print("-f: force rebuild even if timestamps are up-to-date") + print("-q: quiet operation") + print("-d destdir: purported directory name for error messages") + print(" if no directory arguments, -l sys.path is assumed") + print("-x regexp: skip files matching the regular expression regexp") + print(" the regexp is search for in the full path of the file") sys.exit(2) maxlevels = 10 ddir = None @@ -136,7 +136,7 @@ rx = re.compile(a) if ddir: if len(args) != 1: - print "-d destdir require exactly one directory argument" + print("-d destdir require exactly one directory argument") sys.exit(2) success = 1 try: @@ -148,7 +148,7 @@ else: success = compile_path() except KeyboardInterrupt: - print "\n[interrupt]" + print("\n[interrupt]") success = 0 return success Modified: python/branches/p3yk/Lib/compiler/future.py ============================================================================== --- python/branches/p3yk/Lib/compiler/future.py (original) +++ python/branches/p3yk/Lib/compiler/future.py Fri Feb 9 06:37:30 2007 @@ -65,9 +65,9 @@ from compiler import parseFile, walk for file in sys.argv[1:]: - print file + print(file) tree = parseFile(file) v = FutureParser() walk(tree, v) - print v.found - print + print(v.found) + print() Modified: python/branches/p3yk/Lib/compiler/pyassem.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pyassem.py (original) +++ python/branches/p3yk/Lib/compiler/pyassem.py Fri Feb 9 06:37:30 2007 @@ -19,10 +19,10 @@ def startBlock(self, block): if self._debug: if self.current: - print "end", repr(self.current) - print " next", self.current.next - print " ", self.current.get_children() - print repr(block) + print("end", repr(self.current)) + print(" next", self.current.next) + print(" ", self.current.get_children()) + print(repr(block)) self.current = block def nextBlock(self, block=None): @@ -68,7 +68,7 @@ def emit(self, *inst): if self._debug: - print "\t", inst + print("\t", inst) if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']: self.current.addOutEdge(self.exit) if len(inst) == 2 and isinstance(inst[1], Block): @@ -400,12 +400,12 @@ for t in self.insts: opname = t[0] if opname == "SET_LINENO": - print + print() if len(t) == 1: - print "\t", "%3d" % pc, opname + print("\t", "%3d" % pc, opname) pc = pc + 1 else: - print "\t", "%3d" % pc, opname, t[1] + print("\t", "%3d" % pc, opname, t[1]) pc = pc + 3 if io: sys.stdout = save @@ -601,8 +601,8 @@ try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: - print opname, oparg - print self.opnum[opname], lo, hi + print(opname, oparg) + print(self.opnum[opname], lo, hi) raise self.stage = DONE @@ -744,7 +744,7 @@ for i in insts: opname = i[0] if debug: - print i, + print(i, end=' ') delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta @@ -763,7 +763,7 @@ if depth > maxDepth: maxDepth = depth if debug: - print depth, maxDepth + print(depth, maxDepth) return maxDepth effect = { Modified: python/branches/p3yk/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk/Lib/compiler/pycodegen.py Fri Feb 9 06:37:30 2007 @@ -112,7 +112,7 @@ gen = ModuleCodeGenerator(tree) if display: import pprint - print pprint.pprint(tree) + print(pprint.pprint(tree)) self.code = gen.getCode() def dump(self, f): @@ -1018,7 +1018,7 @@ self.set_lineno(node) self.delName(node.name) else: - print "oops", node.flags + print("oops", node.flags) def visitAssAttr(self, node): self.visit(node.expr) @@ -1027,8 +1027,8 @@ elif node.flags == 'OP_DELETE': self.emit('DELETE_ATTR', self.mangle(node.attrname)) else: - print "warning: unexpected flags:", node.flags - print node + print("warning: unexpected flags:", node.flags) + print(node) def _visitAssSequence(self, node, op='UNPACK_SEQUENCE'): if findOp(node) != 'OP_DELETE': @@ -1189,7 +1189,7 @@ elif node.flags == 'OP_DELETE': self.emit('DELETE_SLICE+%d' % slice) else: - print "weird slice", node.flags + print("weird slice", node.flags) raise def visitSubscript(self, node, aug_flag=None): Modified: python/branches/p3yk/Lib/compiler/symbols.py ============================================================================== --- python/branches/p3yk/Lib/compiler/symbols.py (original) +++ python/branches/p3yk/Lib/compiler/symbols.py Fri Feb 9 06:37:30 2007 @@ -76,12 +76,12 @@ return self.children def DEBUG(self): - print >> sys.stderr, self.name, self.nested and "nested" or "" - print >> sys.stderr, "\tglobals: ", self.globals - print >> sys.stderr, "\tcells: ", self.cells - print >> sys.stderr, "\tdefs: ", self.defs - print >> sys.stderr, "\tuses: ", self.uses - print >> sys.stderr, "\tfrees:", self.frees + print(self.name, self.nested and "nested" or "", file=sys.stderr) + print("\tglobals: ", self.globals, file=sys.stderr) + print("\tcells: ", self.cells, file=sys.stderr) + print("\tdefs: ", self.defs, file=sys.stderr) + print("\tuses: ", self.uses, file=sys.stderr) + print("\tfrees:", self.frees, file=sys.stderr) def check_name(self, name): """Return scope of name. @@ -429,7 +429,7 @@ if not (s.startswith('_[') or s.startswith('.'))] for file in sys.argv[1:]: - print file + print(file) f = open(file) buf = f.read() f.close() @@ -443,10 +443,10 @@ names2 = s.scopes[tree].get_names() if not list_eq(mod_names, names2): - print - print "oops", file - print sorted(mod_names) - print sorted(names2) + print() + print("oops", file) + print(sorted(mod_names)) + print(sorted(names2)) sys.exit(-1) d = {} @@ -460,11 +460,11 @@ l = [sc for sc in scopes if sc.name == s.get_name()] if len(l) > 1: - print "skipping", s.get_name() + print("skipping", s.get_name()) else: if not list_eq(get_names(s.get_namespace()), l[0].get_names()): - print s.get_name() - print sorted(get_names(s.get_namespace())) - print sorted(l[0].get_names()) + print(s.get_name()) + print(sorted(get_names(s.get_namespace()))) + print(sorted(l[0].get_names())) sys.exit(-1) Modified: python/branches/p3yk/Lib/compiler/syntax.py ============================================================================== --- python/branches/p3yk/Lib/compiler/syntax.py (original) +++ python/branches/p3yk/Lib/compiler/syntax.py Fri Feb 9 06:37:30 2007 @@ -32,7 +32,7 @@ def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: - print "%s:%s: %s" % (node.filename, node.lineno, msg) + print("%s:%s: %s" % (node.filename, node.lineno, msg)) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Fri Feb 9 06:37:30 2007 @@ -86,7 +86,7 @@ try: return nodes[kind](*args[1:]) except TypeError: - print nodes[kind], len(args), args + print(nodes[kind], len(args), args) raise else: raise WalkerError, "Can't find appropriate Node type: %s" % str(args) Modified: python/branches/p3yk/Lib/compiler/visitor.py ============================================================================== --- python/branches/p3yk/Lib/compiler/visitor.py (original) +++ python/branches/p3yk/Lib/compiler/visitor.py Fri Feb 9 06:37:30 2007 @@ -79,20 +79,20 @@ meth = getattr(self.visitor, 'visit' + className, 0) self._cache[node.__class__] = meth if self.VERBOSE > 1: - print "dispatch", className, (meth and meth.__name__ or '') + print("dispatch", className, (meth and meth.__name__ or '')) if meth: meth(node, *args) elif self.VERBOSE > 0: klass = node.__class__ if klass not in self.examples: self.examples[klass] = klass - print - print self.visitor - print klass + print() + print(self.visitor) + print(klass) for attr in dir(node): if attr[0] != '_': - print "\t", "%-12.12s" % attr, getattr(node, attr) - print + print("\t", "%-12.12s" % attr, getattr(node, attr)) + print() return self.default(node, *args) # XXX this is an API change @@ -107,7 +107,7 @@ return walker.visitor def dumpNode(node): - print node.__class__ + print(node.__class__) for attr in dir(node): if attr[0] != '_': - print "\t", "%-10.10s" % attr, getattr(node, attr) + print("\t", "%-10.10s" % attr, getattr(node, attr)) Modified: python/branches/p3yk/Lib/copy.py ============================================================================== --- python/branches/p3yk/Lib/copy.py (original) +++ python/branches/p3yk/Lib/copy.py Fri Feb 9 06:37:30 2007 @@ -318,11 +318,11 @@ l = [None, 1, 2, 3.14, 'xyzzy', (1, 2), [3.14, 'abc'], {'abc': 'ABC'}, (), [], {}] l1 = copy(l) - print l1==l + print(l1==l) l1 = map(copy, l) - print l1==l + print(l1==l) l1 = deepcopy(l) - print l1==l + print(l1==l) class C: def __init__(self, arg=None): self.a = 1 @@ -346,26 +346,26 @@ c = C('argument sketch') l.append(c) l2 = copy(l) - print l == l2 - print l - print l2 + print(l == l2) + print(l) + print(l2) l2 = deepcopy(l) - print l == l2 - print l - print l2 + print(l == l2) + print(l) + print(l2) l.append({l[1]: l, 'xyz': l[2]}) l3 = copy(l) import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) + print(map(repr.repr, l)) + print(map(repr.repr, l1)) + print(map(repr.repr, l2)) + print(map(repr.repr, l3)) l3 = deepcopy(l) import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) + print(map(repr.repr, l)) + print(map(repr.repr, l1)) + print(map(repr.repr, l2)) + print(map(repr.repr, l3)) if __name__ == '__main__': _test() Modified: python/branches/p3yk/Lib/ctypes/test/__init__.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/__init__.py (original) +++ python/branches/p3yk/Lib/ctypes/test/__init__.py Fri Feb 9 06:37:30 2007 @@ -60,10 +60,10 @@ except ResourceDenied as detail: skipped.append(modname) if verbosity > 1: - print >> sys.stderr, "Skipped %s: %s" % (modname, detail) + print("Skipped %s: %s" % (modname, detail), file=sys.stderr) continue except Exception as detail: - print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail) + print("Warning: could not import %s: %s" % (modname, detail), file=sys.stderr) continue for name in dir(mod): if name.startswith("_"): @@ -74,7 +74,7 @@ return skipped, tests def usage(): - print __doc__ + print(__doc__) return 1 def test_with_refcounts(runner, verbosity, testcase): @@ -106,9 +106,9 @@ cleanup() refcounts[i] = sys.gettotalrefcount() - rc if filter(None, refcounts): - print "%s leaks:\n\t" % testcase, refcounts + print("%s leaks:\n\t" % testcase, refcounts) elif verbosity: - print "%s: ok." % testcase + print("%s: ok." % testcase) class TestRunner(unittest.TextTestRunner): def run(self, test, skipped): @@ -166,7 +166,7 @@ try: sys.gettotalrefcount except AttributeError: - print >> sys.stderr, "-r flag requires Python debug build" + print("-r flag requires Python debug build", file=sys.stderr) return -1 search_leaks = True elif flag == "-u": Modified: python/branches/p3yk/Lib/ctypes/test/test_byteswap.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_byteswap.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_byteswap.py Fri Feb 9 06:37:30 2007 @@ -15,7 +15,7 @@ class Test(unittest.TestCase): def X_test(self): - print >> sys.stderr, sys.byteorder + print(sys.byteorder, file=sys.stderr) for i in range(32): bits = BITS() setattr(bits, "i%s" % i, 1) Modified: python/branches/p3yk/Lib/ctypes/test/test_find.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_find.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_find.py Fri Feb 9 06:37:30 2007 @@ -22,12 +22,12 @@ ## print, for debugging if is_resource_enabled("printing"): if lib_gl or lib_glu or lib_glut or lib_gle: - print "OpenGL libraries:" + print("OpenGL libraries:") for item in (("GL", lib_gl), ("GLU", lib_glu), ("glut", lib_glut), ("gle", lib_gle)): - print "\t", item + print("\t", item) # On some systems, loading the OpenGL libraries needs the RTLD_GLOBAL mode. Modified: python/branches/p3yk/Lib/ctypes/test/test_keeprefs.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_keeprefs.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_keeprefs.py Fri Feb 9 06:37:30 2007 @@ -100,13 +100,13 @@ x = X() i = c_char_p("abc def") from sys import getrefcount as grc - print "2?", grc(i) + print("2?", grc(i)) x.p = pointer(i) - print "3?", grc(i) + print("3?", grc(i)) for i in range(320): c_int(99) x.p[0] - print x.p[0] + print(x.p[0]) ## del x ## print "2?", grc(i) ## del i @@ -115,14 +115,14 @@ for i in range(320): c_int(99) x.p[0] - print x.p[0] - print x.p.contents + print(x.p[0]) + print(x.p.contents) ## print x._objects x.p[0] = "spam spam" ## print x.p[0] - print "+" * 42 - print x._objects + print("+" * 42) + print(x._objects) class PointerToStructure(unittest.TestCase): def test(self): Modified: python/branches/p3yk/Lib/ctypes/test/test_loading.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_loading.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_loading.py Fri Feb 9 06:37:30 2007 @@ -15,7 +15,7 @@ libc_name = find_library("c") if is_resource_enabled("printing"): - print "libc_name is", libc_name + print("libc_name is", libc_name) class LoaderTest(unittest.TestCase): @@ -44,8 +44,8 @@ if os.name in ("nt", "ce"): def test_load_library(self): if is_resource_enabled("printing"): - print find_library("kernel32") - print find_library("user32") + print(find_library("kernel32")) + print(find_library("user32")) if os.name == "nt": windll.kernel32.GetModuleHandleW Modified: python/branches/p3yk/Lib/ctypes/test/test_numbers.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_numbers.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_numbers.py Fri Feb 9 06:37:30 2007 @@ -192,7 +192,7 @@ for i in items: func(); func(); func(); func(); func() stop = clock() - print "%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)) + print("%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))) def check_perf(): # Construct 5 objects Modified: python/branches/p3yk/Lib/ctypes/test/test_strings.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_strings.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_strings.py Fri Feb 9 06:37:30 2007 @@ -189,7 +189,7 @@ for i in items: func(arg); func(arg); func(arg); func(arg); func(arg) stop = clock() - print "%20s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)) + print("%20s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))) def check_perf(): # Construct 5 objects Modified: python/branches/p3yk/Lib/ctypes/util.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/util.py (original) +++ python/branches/p3yk/Lib/ctypes/util.py Fri Feb 9 06:37:30 2007 @@ -125,15 +125,15 @@ def test(): from ctypes import cdll if os.name == "nt": - print cdll.msvcrt - print cdll.load("msvcrt") - print find_library("msvcrt") + print(cdll.msvcrt) + print(cdll.load("msvcrt")) + print(find_library("msvcrt")) if os.name == "posix": # find and load_version - print find_library("m") - print find_library("c") - print find_library("bz2") + print(find_library("m")) + print(find_library("c")) + print(find_library("bz2")) # getattr ## print cdll.m @@ -141,14 +141,14 @@ # load if sys.platform == "darwin": - print cdll.LoadLibrary("libm.dylib") - print cdll.LoadLibrary("libcrypto.dylib") - print cdll.LoadLibrary("libSystem.dylib") - print cdll.LoadLibrary("System.framework/System") + print(cdll.LoadLibrary("libm.dylib")) + print(cdll.LoadLibrary("libcrypto.dylib")) + print(cdll.LoadLibrary("libSystem.dylib")) + print(cdll.LoadLibrary("System.framework/System")) else: - print cdll.LoadLibrary("libm.so") - print cdll.LoadLibrary("libcrypt.so") - print find_library("crypt") + print(cdll.LoadLibrary("libm.so")) + print(cdll.LoadLibrary("libcrypt.so")) + print(find_library("crypt")) if __name__ == "__main__": test() Modified: python/branches/p3yk/Lib/curses/has_key.py ============================================================================== --- python/branches/p3yk/Lib/curses/has_key.py (original) +++ python/branches/p3yk/Lib/curses/has_key.py Fri Feb 9 06:37:30 2007 @@ -189,4 +189,4 @@ % (_curses.keyname( key ), system, python) ) finally: _curses.endwin() - for i in L: print i + for i in L: print(i) Modified: python/branches/p3yk/Lib/curses/textpad.py ============================================================================== --- python/branches/p3yk/Lib/curses/textpad.py (original) +++ python/branches/p3yk/Lib/curses/textpad.py Fri Feb 9 06:37:30 2007 @@ -170,4 +170,4 @@ return Textbox(win).edit() str = curses.wrapper(test_editbox) - print 'Contents of text box:', repr(str) + print('Contents of text box:', repr(str)) Modified: python/branches/p3yk/Lib/difflib.py ============================================================================== --- python/branches/p3yk/Lib/difflib.py (original) +++ python/branches/p3yk/Lib/difflib.py Fri Feb 9 06:37:30 2007 @@ -76,7 +76,7 @@ sequences. As a rule of thumb, a .ratio() value over 0.6 means the sequences are close matches: - >>> print round(s.ratio(), 3) + >>> print(round(s.ratio(), 3)) 0.866 >>> @@ -84,7 +84,7 @@ .get_matching_blocks() is handy: >>> for block in s.get_matching_blocks(): - ... print "a[%d] and b[%d] match for %d elements" % block + ... print("a[%d] and b[%d] match for %d elements" % block) a[0] and b[0] match for 8 elements a[8] and b[17] match for 21 elements a[29] and b[38] match for 0 elements @@ -97,7 +97,7 @@ use .get_opcodes(): >>> for opcode in s.get_opcodes(): - ... print "%6s a[%d:%d] b[%d:%d]" % opcode + ... print("%6s a[%d:%d] b[%d:%d]" % opcode) equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:29] b[17:38] @@ -545,8 +545,8 @@ >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): - ... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % - ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])) + ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % + ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) @@ -832,7 +832,7 @@ As a single multi-line string it looks like this: - >>> print ''.join(result), + >>> print(''.join(result), end="") 1. Beautiful is better than ugly. - 2. Explicit is better than implicit. - 3. Simple is better than complex. @@ -889,8 +889,9 @@ Example: - >>> print ''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1), + >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1))), + ... end="") - one ? ^ + ore @@ -950,7 +951,7 @@ >>> d = Differ() >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1, ... ['abcdefGhijkl\n'], 0, 1) - >>> print ''.join(results), + >>> print(''.join(results), end="") - abcDefghiJkl ? ^ ^ ^ + abcdefGhijkl @@ -1058,7 +1059,7 @@ >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n', ... ' ^ ^ ^ ', '+ ^ ^ ^ ') - >>> for line in results: print repr(line) + >>> for line in results: print(repr(line)) ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' @@ -1164,7 +1165,7 @@ ... 'zero one tree four'.split(), 'Original', 'Current', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003', ... lineterm=''): - ... print line + ... print(line) --- Original Sat Jan 26 23:30:50 1991 +++ Current Fri Jun 06 10:20:52 2003 @@ -1,4 +1,4 @@ @@ -1223,9 +1224,10 @@ Example: - >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1), + >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1), ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')), + ... end="") *** Original Sat Jan 26 23:30:50 1991 --- Current Fri Jun 06 10:22:46 2003 *************** @@ -1295,7 +1297,7 @@ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) - >>> print ''.join(diff), + >>> print(''.join(diff), end="") - one ? ^ + ore @@ -1992,11 +1994,11 @@ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> diff = list(diff) - >>> print ''.join(restore(diff, 1)), + >>> print(''.join(restore(diff, 1)), end="") one two three - >>> print ''.join(restore(diff, 2)), + >>> print(''.join(restore(diff, 2)), end="") ore tree emu Modified: python/branches/p3yk/Lib/dis.py ============================================================================== --- python/branches/p3yk/Lib/dis.py (original) +++ python/branches/p3yk/Lib/dis.py Fri Feb 9 06:37:30 2007 @@ -30,12 +30,12 @@ types.FunctionType, types.CodeType, types.ClassType): - print "Disassembly of %s:" % name + print("Disassembly of %s:" % name) try: dis(x1) except TypeError as msg: - print "Sorry:", msg - print + print("Sorry:", msg) + print() elif hasattr(x, 'co_code'): disassemble(x) elif isinstance(x, str): @@ -69,17 +69,17 @@ op = ord(c) if i in linestarts: if i > 0: - print - print "%3d" % linestarts[i], + print() + print("%3d" % linestarts[i], end=' ') else: - print ' ', + print(' ', end=' ') - if i == lasti: print '-->', - else: print ' ', - if i in labels: print '>>', - else: print ' ', - print repr(i).rjust(4), - print opname[op].ljust(20), + if i == lasti: print('-->', end=' ') + else: print(' ', end=' ') + if i in labels: print('>>', end=' ') + else: print(' ', end=' ') + print(repr(i).rjust(4), end=' ') + print(opname[op].ljust(20), end=' ') i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg @@ -87,22 +87,22 @@ i = i+2 if op == EXTENDED_ARG: extended_arg = oparg*65536 - print repr(oparg).rjust(5), + print(repr(oparg).rjust(5), end=' ') if op in hasconst: - print '(' + repr(co.co_consts[oparg]) + ')', + print('(' + repr(co.co_consts[oparg]) + ')', end=' ') elif op in hasname: - print '(' + co.co_names[oparg] + ')', + print('(' + co.co_names[oparg] + ')', end=' ') elif op in hasjrel: - print '(to ' + repr(i + oparg) + ')', + print('(to ' + repr(i + oparg) + ')', end=' ') elif op in haslocal: - print '(' + co.co_varnames[oparg] + ')', + print('(' + co.co_varnames[oparg] + ')', end=' ') elif op in hascompare: - print '(' + cmp_op[oparg] + ')', + print('(' + cmp_op[oparg] + ')', end=' ') elif op in hasfree: if free is None: free = co.co_cellvars + co.co_freevars - print '(' + free[oparg] + ')', - print + print('(' + free[oparg] + ')', end=' ') + print() def disassemble_string(code, lasti=-1, varnames=None, names=None, constants=None): @@ -112,37 +112,37 @@ while i < n: c = code[i] op = ord(c) - if i == lasti: print '-->', - else: print ' ', - if i in labels: print '>>', - else: print ' ', - print repr(i).rjust(4), - print opname[op].ljust(15), + if i == lasti: print('-->', end=' ') + else: print(' ', end=' ') + if i in labels: print('>>', end=' ') + else: print(' ', end=' ') + print(repr(i).rjust(4), end=' ') + print(opname[op].ljust(15), end=' ') i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 - print repr(oparg).rjust(5), + print(repr(oparg).rjust(5), end=' ') if op in hasconst: if constants: - print '(' + repr(constants[oparg]) + ')', + print('(' + repr(constants[oparg]) + ')', end=' ') else: - print '(%d)'%oparg, + print('(%d)'%oparg, end=' ') elif op in hasname: if names is not None: - print '(' + names[oparg] + ')', + print('(' + names[oparg] + ')', end=' ') else: - print '(%d)'%oparg, + print('(%d)'%oparg, end=' ') elif op in hasjrel: - print '(to ' + repr(i + oparg) + ')', + print('(to ' + repr(i + oparg) + ')', end=' ') elif op in haslocal: if varnames: - print '(' + varnames[oparg] + ')', + print('(' + varnames[oparg] + ')', end=' ') else: - print '(%d)' % oparg, + print('(%d)' % oparg, end=' ') elif op in hascompare: - print '(' + cmp_op[oparg] + ')', - print + print('(' + cmp_op[oparg] + ')', end=' ') + print() disco = disassemble # XXX For backwards compatibility Modified: python/branches/p3yk/Lib/distutils/bcppcompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/bcppcompiler.py (original) +++ python/branches/p3yk/Lib/distutils/bcppcompiler.py Fri Feb 9 06:37:30 2007 @@ -392,7 +392,7 @@ try: self.spawn(pp_args) except DistutilsExecError as msg: - print msg + print(msg) raise CompileError, msg # preprocess() Modified: python/branches/p3yk/Lib/distutils/ccompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/ccompiler.py (original) +++ python/branches/p3yk/Lib/distutils/ccompiler.py Fri Feb 9 06:37:30 2007 @@ -1026,7 +1026,7 @@ def debug_print (self, msg): from distutils.debug import DEBUG if DEBUG: - print msg + print(msg) def warn (self, msg): sys.stderr.write ("warning: %s\n" % msg) Modified: python/branches/p3yk/Lib/distutils/cmd.py ============================================================================== --- python/branches/p3yk/Lib/distutils/cmd.py (original) +++ python/branches/p3yk/Lib/distutils/cmd.py Fri Feb 9 06:37:30 2007 @@ -163,14 +163,14 @@ from distutils.fancy_getopt import longopt_xlate if header is None: header = "command options for '%s':" % self.get_command_name() - print indent + header + print(indent + header) indent = indent + " " for (option, _, _) in self.user_options: option = string.translate(option, longopt_xlate) if option[-1] == "=": option = option[:-1] value = getattr(self, option) - print indent + "%s = %s" % (option, value) + print(indent + "%s = %s" % (option, value)) def run (self): @@ -199,7 +199,7 @@ """ from distutils.debug import DEBUG if DEBUG: - print msg + print(msg) sys.stdout.flush() @@ -475,4 +475,4 @@ if __name__ == "__main__": - print "ok" + print("ok") Modified: python/branches/p3yk/Lib/distutils/command/bdist_rpm.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/bdist_rpm.py (original) +++ python/branches/p3yk/Lib/distutils/command/bdist_rpm.py Fri Feb 9 06:37:30 2007 @@ -267,11 +267,11 @@ def run (self): if DEBUG: - print "before _get_package_data():" - print "vendor =", self.vendor - print "packager =", self.packager - print "doc_files =", self.doc_files - print "changelog =", self.changelog + print("before _get_package_data():") + print("vendor =", self.vendor) + print("packager =", self.packager) + print("doc_files =", self.doc_files) + print("changelog =", self.changelog) # make directories if self.spec_only: Modified: python/branches/p3yk/Lib/distutils/command/config.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/config.py (original) +++ python/branches/p3yk/Lib/distutils/command/config.py Fri Feb 9 06:37:30 2007 @@ -359,9 +359,9 @@ def dump_file (filename, head=None): if head is None: - print filename + ":" + print(filename + ":") else: - print head + print(head) file = open(filename) sys.stdout.write(file.read()) Modified: python/branches/p3yk/Lib/distutils/command/install.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/install.py (original) +++ python/branches/p3yk/Lib/distutils/command/install.py Fri Feb 9 06:37:30 2007 @@ -292,7 +292,7 @@ if DEBUG: from pprint import pprint - print "config vars:" + print("config vars:") pprint(self.config_vars) # Expand "~" and configuration variables in the installation @@ -347,7 +347,7 @@ def dump_dirs (self, msg): if DEBUG: from distutils.fancy_getopt import longopt_xlate - print msg + ":" + print(msg + ":") for opt in self.user_options: opt_name = opt[0] if opt_name[-1] == "=": @@ -359,7 +359,7 @@ else: opt_name = string.translate(opt_name, longopt_xlate) val = getattr(self, opt_name) - print " %s: %s" % (opt_name, val) + print(" %s: %s" % (opt_name, val)) def finalize_unix (self): Modified: python/branches/p3yk/Lib/distutils/command/register.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/register.py (original) +++ python/branches/p3yk/Lib/distutils/command/register.py Fri Feb 9 06:37:30 2007 @@ -86,14 +86,14 @@ ''' Fetch the list of classifiers from the server. ''' response = urllib2.urlopen(self.repository+'?:action=list_classifiers') - print response.read() + print(response.read()) def verify_metadata(self): ''' Send the metadata to the package index server to be checked. ''' # send the info to the server and report the result (code, result) = self.post_to_server(self.build_post_data('verify')) - print 'Server response (%s): %s'%(code, result) + print('Server response (%s): %s'%(code, result)) def send_metadata(self): ''' Send the metadata to the package index server. @@ -128,7 +128,7 @@ if os.environ.has_key('HOME'): rc = os.path.join(os.environ['HOME'], '.pypirc') if os.path.exists(rc): - print 'Using PyPI login from %s'%rc + print('Using PyPI login from %s'%rc) config = ConfigParser.ConfigParser() config.read(rc) username = config.get('server-login', 'username') @@ -138,17 +138,17 @@ # get the user's login info choices = '1 2 3 4'.split() while choice not in choices: - print '''We need to know who you are, so please choose either: + print('''We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit -Your selection [default 1]: ''', +Your selection [default 1]: ''', end=' ') choice = raw_input() if not choice: choice = '1' elif choice not in choices: - print 'Please choose one of the four options!' + print('Please choose one of the four options!') if choice == '1': # get the username and password @@ -165,13 +165,13 @@ # send the info to the server and report the result code, result = self.post_to_server(self.build_post_data('submit'), auth) - print 'Server response (%s): %s'%(code, result) + print('Server response (%s): %s'%(code, result)) # possibly save the login if os.environ.has_key('HOME') and config is None and code == 200: rc = os.path.join(os.environ['HOME'], '.pypirc') - print 'I can store your PyPI login so future submissions will be faster.' - print '(the login will be stored in %s)'%rc + print('I can store your PyPI login so future submissions will be faster.') + print('(the login will be stored in %s)'%rc) choice = 'X' while choice.lower() not in 'yn': choice = raw_input('Save your login (y/N)?') @@ -200,22 +200,22 @@ if data['password'] != data['confirm']: data['password'] = '' data['confirm'] = None - print "Password and confirm don't match!" + print("Password and confirm don't match!") while not data['email']: data['email'] = raw_input(' EMail: ') code, result = self.post_to_server(data) if code != 200: - print 'Server response (%s): %s'%(code, result) + print('Server response (%s): %s'%(code, result)) else: - print 'You will receive an email shortly.' - print 'Follow the instructions in it to complete registration.' + print('You will receive an email shortly.') + print('Follow the instructions in it to complete registration.') elif choice == '3': data = {':action': 'password_reset'} data['email'] = '' while not data['email']: data['email'] = raw_input('Your email address: ') code, result = self.post_to_server(data) - print 'Server response (%s): %s'%(code, result) + print('Server response (%s): %s'%(code, result)) def build_post_data(self, action): # figure the data to send - the metadata plus some additional @@ -295,5 +295,5 @@ data = result.read() result = 200, 'OK' if self.show_response: - print '-'*75, data, '-'*75 + print('-'*75, data, '-'*75) return result Modified: python/branches/p3yk/Lib/distutils/command/upload.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/upload.py (original) +++ python/branches/p3yk/Lib/distutils/command/upload.py Fri Feb 9 06:37:30 2007 @@ -196,4 +196,4 @@ self.announce('Upload failed (%s): %s' % (r.status, r.reason), log.ERROR) if self.show_response: - print '-'*75, r.read(), '-'*75 + print('-'*75, r.read(), '-'*75) Modified: python/branches/p3yk/Lib/distutils/core.py ============================================================================== --- python/branches/p3yk/Lib/distutils/core.py (original) +++ python/branches/p3yk/Lib/distutils/core.py Fri Feb 9 06:37:30 2007 @@ -125,7 +125,7 @@ dist.parse_config_files() if DEBUG: - print "options (after parsing config files):" + print("options (after parsing config files):") dist.dump_option_dicts() if _setup_stop_after == "config": @@ -139,7 +139,7 @@ raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg if DEBUG: - print "options (after parsing command line):" + print("options (after parsing command line):") dist.dump_option_dicts() if _setup_stop_after == "commandline": Modified: python/branches/p3yk/Lib/distutils/dist.py ============================================================================== --- python/branches/p3yk/Lib/distutils/dist.py (original) +++ python/branches/p3yk/Lib/distutils/dist.py Fri Feb 9 06:37:30 2007 @@ -290,22 +290,22 @@ commands.sort() if header is not None: - print indent + header + print(indent + header) indent = indent + " " if not commands: - print indent + "no commands known yet" + print(indent + "no commands known yet") return for cmd_name in commands: opt_dict = self.command_options.get(cmd_name) if opt_dict is None: - print indent + "no option dict for '%s' command" % cmd_name + print(indent + "no option dict for '%s' command" % cmd_name) else: - print indent + "option dict for '%s' command:" % cmd_name + print(indent + "option dict for '%s' command:" % cmd_name) out = pformat(opt_dict) for line in string.split(out, "\n"): - print indent + " " + line + print(indent + " " + line) # dump_option_dicts () @@ -365,11 +365,11 @@ if filenames is None: filenames = self.find_config_files() - if DEBUG: print "Distribution.parse_config_files():" + if DEBUG: print("Distribution.parse_config_files():") parser = ConfigParser() for filename in filenames: - if DEBUG: print " reading", filename + if DEBUG: print(" reading", filename) parser.read(filename) for section in parser.sections(): options = parser.options(section) @@ -636,14 +636,14 @@ options = self.global_options parser.set_option_table(options) parser.print_help(self.common_usage + "\nGlobal options:") - print + print() if display_options: parser.set_option_table(self.display_options) parser.print_help( "Information display options (just display " + "information, ignore any commands)") - print + print() for command in self.commands: if type(command) is ClassType and issubclass(command, Command): @@ -657,9 +657,9 @@ else: parser.set_option_table(klass.user_options) parser.print_help("Options for '%s' command:" % klass.__name__) - print + print() - print gen_usage(self.script_name) + print(gen_usage(self.script_name)) return # _show_help () @@ -678,8 +678,8 @@ # we ignore "foo bar"). if self.help_commands: self.print_commands() - print - print gen_usage(self.script_name) + print() + print(gen_usage(self.script_name)) return 1 # If user supplied any of the "display metadata" options, then @@ -695,12 +695,12 @@ opt = translate_longopt(opt) value = getattr(self.metadata, "get_"+opt)() if opt in ['keywords', 'platforms']: - print string.join(value, ',') + print(string.join(value, ',')) elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'): - print string.join(value, '\n') + print(string.join(value, '\n')) else: - print value + print(value) any_display_options = 1 return any_display_options @@ -712,7 +712,7 @@ 'print_commands()'. """ - print header + ":" + print(header + ":") for cmd in commands: klass = self.cmdclass.get(cmd) @@ -723,7 +723,7 @@ except AttributeError: description = "(no description available)" - print " %-*s %s" % (max_length, cmd, description) + print(" %-*s %s" % (max_length, cmd, description)) # print_command_list () @@ -757,7 +757,7 @@ "Standard commands", max_length) if extra_commands: - print + print() self.print_command_list(extra_commands, "Extra commands", max_length) @@ -862,8 +862,8 @@ cmd_obj = self.command_obj.get(command) if not cmd_obj and create: if DEBUG: - print "Distribution.get_command_obj(): " \ - "creating '%s' command object" % command + print("Distribution.get_command_obj(): " \ + "creating '%s' command object" % command) klass = self.get_command_class(command) cmd_obj = self.command_obj[command] = klass(self) @@ -893,9 +893,9 @@ if option_dict is None: option_dict = self.get_option_dict(command_name) - if DEBUG: print " setting options for '%s' command:" % command_name + if DEBUG: print(" setting options for '%s' command:" % command_name) for (option, (source, value)) in option_dict.items(): - if DEBUG: print " %s = %s (from %s)" % (option, value, source) + if DEBUG: print(" %s = %s (from %s)" % (option, value, source)) try: bool_opts = map(translate_longopt, command_obj.boolean_options) except AttributeError: @@ -1219,4 +1219,4 @@ if __name__ == "__main__": dist = Distribution() - print "ok" + print("ok") Modified: python/branches/p3yk/Lib/distutils/fancy_getopt.py ============================================================================== --- python/branches/p3yk/Lib/distutils/fancy_getopt.py (original) +++ python/branches/p3yk/Lib/distutils/fancy_getopt.py Fri Feb 9 06:37:30 2007 @@ -497,6 +497,6 @@ say, "How should I know?"].)""" for w in (10, 20, 30, 40): - print "width: %d" % w - print string.join(wrap_text(text, w), "\n") - print + print("width: %d" % w) + print(string.join(wrap_text(text, w), "\n")) + print() Modified: python/branches/p3yk/Lib/distutils/filelist.py ============================================================================== --- python/branches/p3yk/Lib/distutils/filelist.py (original) +++ python/branches/p3yk/Lib/distutils/filelist.py Fri Feb 9 06:37:30 2007 @@ -53,7 +53,7 @@ """ from distutils.debug import DEBUG if DEBUG: - print msg + print(msg) # -- List-like methods --------------------------------------------- Modified: python/branches/p3yk/Lib/distutils/log.py ============================================================================== --- python/branches/p3yk/Lib/distutils/log.py (original) +++ python/branches/p3yk/Lib/distutils/log.py Fri Feb 9 06:37:30 2007 @@ -23,9 +23,9 @@ if not args: # msg may contain a '%'. If args is empty, # don't even try to string-format - print msg + print(msg) else: - print msg % args + print(msg % args) sys.stdout.flush() def log(self, level, msg, *args): Modified: python/branches/p3yk/Lib/distutils/mwerkscompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/mwerkscompiler.py (original) +++ python/branches/p3yk/Lib/distutils/mwerkscompiler.py Fri Feb 9 06:37:30 2007 @@ -160,9 +160,9 @@ settings['libraries'] = libraries settings['extrasearchdirs'] = sourcefiledirs + include_dirs + library_dirs if self.dry_run: - print 'CALLING LINKER IN', os.getcwd() + print('CALLING LINKER IN', os.getcwd()) for key, value in settings.items(): - print '%20.20s %s'%(key, value) + print('%20.20s %s'%(key, value)) return # Build the export file exportfilename = os.path.join(build_temp, exportname) Modified: python/branches/p3yk/Lib/distutils/spawn.py ============================================================================== --- python/branches/p3yk/Lib/distutils/spawn.py (original) +++ python/branches/p3yk/Lib/distutils/spawn.py Fri Feb 9 06:37:30 2007 @@ -109,7 +109,7 @@ "command '%s' failed: %s" % (cmd[0], exc[-1]) if rc != 0: # and this reflects the command running but failing - print "command '%s' failed with exit status %d" % (cmd[0], rc) + print("command '%s' failed with exit status %d" % (cmd[0], rc)) raise DistutilsExecError, \ "command '%s' failed with exit status %d" % (cmd[0], rc) Modified: python/branches/p3yk/Lib/distutils/tests/test_dist.py ============================================================================== --- python/branches/p3yk/Lib/distutils/tests/test_dist.py (original) +++ python/branches/p3yk/Lib/distutils/tests/test_dist.py Fri Feb 9 06:37:30 2007 @@ -74,8 +74,8 @@ sys.argv.append("build") f = open(TESTFN, "w") try: - print >>f, "[global]" - print >>f, "command_packages = foo.bar, splat" + print("[global]", file=f) + print("command_packages = foo.bar, splat", file=f) f.close() d = self.create_distribution([TESTFN]) self.assertEqual(d.get_command_packages(), Modified: python/branches/p3yk/Lib/distutils/text_file.py ============================================================================== --- python/branches/p3yk/Lib/distutils/text_file.py (original) +++ python/branches/p3yk/Lib/distutils/text_file.py Fri Feb 9 06:37:30 2007 @@ -342,13 +342,13 @@ result = file.readlines () # result = string.join (result, '') if result == expected_result: - print "ok %d (%s)" % (count, description) + print("ok %d (%s)" % (count, description)) else: - print "not ok %d (%s):" % (count, description) - print "** expected:" - print expected_result - print "** received:" - print result + print("not ok %d (%s):" % (count, description)) + print("** expected:") + print(expected_result) + print("** received:") + print(result) filename = "test.txt" Modified: python/branches/p3yk/Lib/doctest.py ============================================================================== --- python/branches/p3yk/Lib/doctest.py (original) +++ python/branches/p3yk/Lib/doctest.py Fri Feb 9 06:37:30 2007 @@ -855,7 +855,7 @@ add them to `tests`. """ if self._verbose: - print 'Finding tests in %s' % name + print('Finding tests in %s' % name) # If we've already processed this object, then ignore it. if id(obj) in seen: @@ -1384,28 +1384,28 @@ failed.append(x) if verbose: if notests: - print len(notests), "items had no tests:" + print(len(notests), "items had no tests:") notests.sort() for thing in notests: - print " ", thing + print(" ", thing) if passed: - print len(passed), "items passed all tests:" + print(len(passed), "items passed all tests:") passed.sort() for thing, count in passed: - print " %3d tests in %s" % (count, thing) + print(" %3d tests in %s" % (count, thing)) if failed: - print self.DIVIDER - print len(failed), "items had failures:" + print(self.DIVIDER) + print(len(failed), "items had failures:") failed.sort() for thing, (f, t) in failed: - print " %3d of %3d in %s" % (f, t, thing) + print(" %3d of %3d in %s" % (f, t, thing)) if verbose: - print totalt, "tests in", len(self._name2ft), "items." - print totalt - totalf, "passed and", totalf, "failed." + print(totalt, "tests in", len(self._name2ft), "items.") + print(totalt - totalf, "passed and", totalf, "failed.") if totalf: - print "***Test Failed***", totalf, "failures." + print("***Test Failed***", totalf, "failures.") elif verbose: - print "Test passed." + print("Test passed.") return totalf, totalt #///////////////////////////////////////////////////////////////// @@ -1415,8 +1415,8 @@ d = self._name2ft for name, (f, t) in other._name2ft.items(): if name in d: - print "*** DocTestRunner.merge: '" + name + "' in both" \ - " testers; summing outcomes." + print("*** DocTestRunner.merge: '" + name + "' in both" \ + " testers; summing outcomes.") f2, t2 = d[name] f = f + f2 t = t + t2 @@ -1985,10 +1985,10 @@ def runstring(self, s, name): test = DocTestParser().get_doctest(s, self.globs, name, None, None) if self.verbose: - print "Running string", name + print("Running string", name) (f,t) = self.testrunner.run(test) if self.verbose: - print f, "of", t, "examples failed in string", name + print(f, "of", t, "examples failed in string", name) return (f,t) def rundoc(self, object, name=None, module=None): @@ -2512,7 +2512,7 @@ try: execfile(srcfilename, globs, globs) except: - print sys.exc_info()[1] + print(sys.exc_info()[1]) pdb.post_mortem(sys.exc_info()[2]) else: # Note that %r is vital here. '%s' instead can, e.g., cause Modified: python/branches/p3yk/Lib/email/generator.py ============================================================================== --- python/branches/p3yk/Lib/email/generator.py (original) +++ python/branches/p3yk/Lib/email/generator.py Fri Feb 9 06:37:30 2007 @@ -80,7 +80,7 @@ ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) - print >> self._fp, ufrom + print(ufrom, file=self._fp) self._write(msg) def clone(self, fp): @@ -140,13 +140,13 @@ def _write_headers(self, msg): for h, v in msg.items(): - print >> self._fp, '%s:' % h, + print('%s:' % h, end=' ', file=self._fp) if self._maxheaderlen == 0: # Explicit no-wrapping - print >> self._fp, v + print(v, file=self._fp) elif isinstance(v, Header): # Header instances know what to do - print >> self._fp, v.encode() + print(v.encode(), file=self._fp) elif _is8bitstring(v): # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this @@ -154,14 +154,14 @@ # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. - print >> self._fp, v + print(v, file=self._fp) else: # Header's got lots of smarts, so use it. - print >> self._fp, Header( + print(Header( v, maxlinelen=self._maxheaderlen, - header_name=h, continuation_ws='\t').encode() + header_name=h, continuation_ws='\t').encode(), file=self._fp) # A blank line always separates headers from body - print >> self._fp + print(file=self._fp) # # Handlers for writing types and subtypes @@ -215,9 +215,9 @@ msg.set_boundary(boundary) # If there's a preamble, write it out, with a trailing CRLF if msg.preamble is not None: - print >> self._fp, msg.preamble + print(msg.preamble, file=self._fp) # dash-boundary transport-padding CRLF - print >> self._fp, '--' + boundary + print('--' + boundary, file=self._fp) # body-part if msgtexts: self._fp.write(msgtexts.pop(0)) @@ -226,13 +226,13 @@ # --> CRLF body-part for body_part in msgtexts: # delimiter transport-padding CRLF - print >> self._fp, '\n--' + boundary + print('\n--' + boundary, file=self._fp) # body-part self._fp.write(body_part) # close-delimiter transport-padding self._fp.write('\n--' + boundary + '--') if msg.epilogue is not None: - print >> self._fp + print(file=self._fp) self._fp.write(msg.epilogue) def _handle_message_delivery_status(self, msg): @@ -308,12 +308,12 @@ for part in msg.walk(): maintype = part.get_content_maintype() if maintype == 'text': - print >> self, part.get_payload(decode=True) + print(part.get_payload(decode=True), file=self) elif maintype == 'multipart': # Just skip this pass else: - print >> self, self._fmt % { + print(self._fmt % { 'type' : part.get_content_type(), 'maintype' : part.get_content_maintype(), 'subtype' : part.get_content_subtype(), @@ -322,7 +322,7 @@ '[no description]'), 'encoding' : part.get('Content-Transfer-Encoding', '[no encoding]'), - } + }, file=self) Modified: python/branches/p3yk/Lib/email/iterators.py ============================================================================== --- python/branches/p3yk/Lib/email/iterators.py (original) +++ python/branches/p3yk/Lib/email/iterators.py Fri Feb 9 06:37:30 2007 @@ -63,11 +63,11 @@ if fp is None: fp = sys.stdout tab = ' ' * (level * 4) - print >> fp, tab + msg.get_content_type(), + print(tab + msg.get_content_type(), end=' ', file=fp) if include_default: - print >> fp, '[%s]' % msg.get_default_type() + print('[%s]' % msg.get_default_type(), file=fp) else: - print >> fp + print(file=fp) if msg.is_multipart(): for subpart in msg.get_payload(): _structure(subpart, fp, level+1, include_default) Modified: python/branches/p3yk/Lib/email/test/test_email.py ============================================================================== --- python/branches/p3yk/Lib/email/test/test_email.py (original) +++ python/branches/p3yk/Lib/email/test/test_email.py Fri Feb 9 06:37:30 2007 @@ -56,7 +56,7 @@ ssecond = str(second) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) fp = StringIO() - print >> fp, NL, NL.join(diff) + print(NL, NL.join(diff), file=fp) raise self.failureException, fp.getvalue() def _msgobj(self, filename): Modified: python/branches/p3yk/Lib/email/test/test_email_renamed.py ============================================================================== --- python/branches/p3yk/Lib/email/test/test_email_renamed.py (original) +++ python/branches/p3yk/Lib/email/test/test_email_renamed.py Fri Feb 9 06:37:30 2007 @@ -57,7 +57,7 @@ ssecond = str(second) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) fp = StringIO() - print >> fp, NL, NL.join(diff) + print(NL, NL.join(diff), file=fp) raise self.failureException, fp.getvalue() def _msgobj(self, filename): Modified: python/branches/p3yk/Lib/filecmp.py ============================================================================== --- python/branches/p3yk/Lib/filecmp.py (original) +++ python/branches/p3yk/Lib/filecmp.py Fri Feb 9 06:37:30 2007 @@ -192,39 +192,39 @@ def report(self): # Print a report on the differences between a and b # Output format is purposely lousy - print 'diff', self.left, self.right + print('diff', self.left, self.right) if self.left_only: self.left_only.sort() - print 'Only in', self.left, ':', self.left_only + print('Only in', self.left, ':', self.left_only) if self.right_only: self.right_only.sort() - print 'Only in', self.right, ':', self.right_only + print('Only in', self.right, ':', self.right_only) if self.same_files: self.same_files.sort() - print 'Identical files :', self.same_files + print('Identical files :', self.same_files) if self.diff_files: self.diff_files.sort() - print 'Differing files :', self.diff_files + print('Differing files :', self.diff_files) if self.funny_files: self.funny_files.sort() - print 'Trouble with common files :', self.funny_files + print('Trouble with common files :', self.funny_files) if self.common_dirs: self.common_dirs.sort() - print 'Common subdirectories :', self.common_dirs + print('Common subdirectories :', self.common_dirs) if self.common_funny: self.common_funny.sort() - print 'Common funny cases :', self.common_funny + print('Common funny cases :', self.common_funny) def report_partial_closure(self): # Print reports on self and on subdirs self.report() for sd in self.subdirs.itervalues(): - print + print() sd.report() def report_full_closure(self): # Report on self and subdirs recursively self.report() for sd in self.subdirs.itervalues(): - print + print() sd.report_full_closure() methodmap = dict(subdirs=phase4, Modified: python/branches/p3yk/Lib/fileinput.py ============================================================================== --- python/branches/p3yk/Lib/fileinput.py (original) +++ python/branches/p3yk/Lib/fileinput.py Fri Feb 9 06:37:30 2007 @@ -405,9 +405,9 @@ for line in input(args, inplace=inplace, backup=backup): if line[-1:] == '\n': line = line[:-1] if line[-1:] == '\r': line = line[:-1] - print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(), - isfirstline() and "*" or "", line) - print "%d: %s[%d]" % (lineno(), filename(), filelineno()) + print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(), + isfirstline() and "*" or "", line)) + print("%d: %s[%d]" % (lineno(), filename(), filelineno())) if __name__ == '__main__': _test() Modified: python/branches/p3yk/Lib/formatter.py ============================================================================== --- python/branches/p3yk/Lib/formatter.py (original) +++ python/branches/p3yk/Lib/formatter.py Fri Feb 9 06:37:30 2007 @@ -323,37 +323,37 @@ """ def new_alignment(self, align): - print "new_alignment(%r)" % (align,) + print("new_alignment(%r)" % (align,)) def new_font(self, font): - print "new_font(%r)" % (font,) + print("new_font(%r)" % (font,)) def new_margin(self, margin, level): - print "new_margin(%r, %d)" % (margin, level) + print("new_margin(%r, %d)" % (margin, level)) def new_spacing(self, spacing): - print "new_spacing(%r)" % (spacing,) + print("new_spacing(%r)" % (spacing,)) def new_styles(self, styles): - print "new_styles(%r)" % (styles,) + print("new_styles(%r)" % (styles,)) def send_paragraph(self, blankline): - print "send_paragraph(%r)" % (blankline,) + print("send_paragraph(%r)" % (blankline,)) def send_line_break(self): - print "send_line_break()" + print("send_line_break()") def send_hor_rule(self, *args, **kw): - print "send_hor_rule()" + print("send_hor_rule()") def send_label_data(self, data): - print "send_label_data(%r)" % (data,) + print("send_label_data(%r)" % (data,)) def send_flowing_data(self, data): - print "send_flowing_data(%r)" % (data,) + print("send_flowing_data(%r)" % (data,)) def send_literal_data(self, data): - print "send_literal_data(%r)" % (data,) + print("send_literal_data(%r)" % (data,)) class DumbWriter(NullWriter): Modified: python/branches/p3yk/Lib/fpformat.py ============================================================================== --- python/branches/p3yk/Lib/fpformat.py (original) +++ python/branches/p3yk/Lib/fpformat.py Fri Feb 9 06:37:30 2007 @@ -137,6 +137,6 @@ try: while 1: x, digs = input('Enter (x, digs): ') - print x, fix(x, digs), sci(x, digs) + print(x, fix(x, digs), sci(x, digs)) except (EOFError, KeyboardInterrupt): pass Modified: python/branches/p3yk/Lib/ftplib.py ============================================================================== --- python/branches/p3yk/Lib/ftplib.py (original) +++ python/branches/p3yk/Lib/ftplib.py Fri Feb 9 06:37:30 2007 @@ -137,7 +137,7 @@ '''Get the welcome message from the server. (this is read and squirreled away by connect())''' if self.debugging: - print '*welcome*', self.sanitize(self.welcome) + print('*welcome*', self.sanitize(self.welcome)) return self.welcome def set_debuglevel(self, level): @@ -167,12 +167,12 @@ # Internal: send one line to the server, appending CRLF def putline(self, line): line = line + CRLF - if self.debugging > 1: print '*put*', self.sanitize(line) + if self.debugging > 1: print('*put*', self.sanitize(line)) self.sock.sendall(line) # Internal: send one command to the server (through putline()) def putcmd(self, line): - if self.debugging: print '*cmd*', self.sanitize(line) + if self.debugging: print('*cmd*', self.sanitize(line)) self.putline(line) # Internal: return one line from the server, stripping CRLF. @@ -180,7 +180,7 @@ def getline(self): line = self.file.readline() if self.debugging > 1: - print '*get*', self.sanitize(line) + print('*get*', self.sanitize(line)) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] @@ -206,7 +206,7 @@ # Raise various errors if the response indicates an error def getresp(self): resp = self.getmultiline() - if self.debugging: print '*resp*', self.sanitize(resp) + if self.debugging: print('*resp*', self.sanitize(resp)) self.lastresp = resp[:3] c = resp[:1] if c in ('1', '2', '3'): @@ -230,7 +230,7 @@ IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.''' line = 'ABOR' + CRLF - if self.debugging > 1: print '*put urgent*', self.sanitize(line) + if self.debugging > 1: print('*put urgent*', self.sanitize(line)) self.sock.sendall(line, MSG_OOB) resp = self.getmultiline() if resp[:3] not in ('426', '226'): @@ -409,7 +409,7 @@ fp = conn.makefile('rb') while 1: line = fp.readline() - if self.debugging > 2: print '*retr*', repr(line) + if self.debugging > 2: print('*retr*', repr(line)) if not line: break if line[-2:] == CRLF: @@ -636,7 +636,7 @@ def print_line(line): '''Default retrlines callback to print a line.''' - print line + print(line) def ftpcp(source, sourcename, target, targetname = '', type = 'I'): @@ -775,7 +775,7 @@ ''' if len(sys.argv) < 2: - print test.__doc__ + print(test.__doc__) sys.exit(0) debugging = 0 Modified: python/branches/p3yk/Lib/getopt.py ============================================================================== --- python/branches/p3yk/Lib/getopt.py (original) +++ python/branches/p3yk/Lib/getopt.py Fri Feb 9 06:37:30 2007 @@ -208,4 +208,4 @@ if __name__ == '__main__': import sys - print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) + print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])) Modified: python/branches/p3yk/Lib/getpass.py ============================================================================== --- python/branches/p3yk/Lib/getpass.py (original) +++ python/branches/p3yk/Lib/getpass.py Fri Feb 9 06:37:30 2007 @@ -67,7 +67,7 @@ def default_getpass(prompt='Password: ', stream=None): - print >>sys.stderr, "Warning: Problem with getpass. Passwords may be echoed." + print("Warning: Problem with getpass. Passwords may be echoed.", file=sys.stderr) return _raw_input(prompt, stream) Modified: python/branches/p3yk/Lib/gopherlib.py ============================================================================== --- python/branches/p3yk/Lib/gopherlib.py (original) +++ python/branches/p3yk/Lib/gopherlib.py Fri Feb 9 06:37:30 2007 @@ -103,7 +103,7 @@ while 1: line = f.readline() if not line: - print '(Unexpected EOF from server)' + print('(Unexpected EOF from server)') break if line[-2:] == CRLF: line = line[:-2] @@ -112,17 +112,17 @@ if line == '.': break if not line: - print '(Empty line from server)' + print('(Empty line from server)') continue gtype = line[0] parts = line[1:].split(TAB) if len(parts) < 4: - print '(Bad line from server: %r)' % (line,) + print('(Bad line from server: %r)' % (line,)) continue if len(parts) > 4: if parts[4:] != ['+']: - print '(Extra info from server:', - print parts[4:], ')' + print('(Extra info from server:', end=' ') + print(parts[4:], ')') else: parts.append('') parts.insert(0, gtype) @@ -140,7 +140,7 @@ while 1: line = f.readline() if not line: - print '(Unexpected EOF from server)' + print('(Unexpected EOF from server)') break if line[-2:] == CRLF: line = line[:-2] @@ -196,13 +196,13 @@ f = send_selector(selector, host) if type == A_TEXT: lines = get_textfile(f) - for item in lines: print item + for item in lines: print(item) elif type in (A_MENU, A_INDEX): entries = get_directory(f) - for item in entries: print item + for item in entries: print(item) else: data = get_binary(f) - print 'binary data:', len(data), 'bytes:', repr(data[:100])[:40] + print('binary data:', len(data), 'bytes:', repr(data[:100])[:40]) # Run the test when run as script if __name__ == '__main__': Modified: python/branches/p3yk/Lib/gzip.py ============================================================================== --- python/branches/p3yk/Lib/gzip.py (original) +++ python/branches/p3yk/Lib/gzip.py Fri Feb 9 06:37:30 2007 @@ -470,7 +470,7 @@ g = sys.stdout else: if arg[-3:] != ".gz": - print "filename doesn't end in .gz:", repr(arg) + print("filename doesn't end in .gz:", repr(arg)) continue f = open(arg, "rb") g = __builtin__.open(arg[:-3], "wb") Modified: python/branches/p3yk/Lib/heapq.py ============================================================================== --- python/branches/p3yk/Lib/heapq.py (original) +++ python/branches/p3yk/Lib/heapq.py Fri Feb 9 06:37:30 2007 @@ -340,4 +340,4 @@ sort = [] while heap: sort.append(heappop(heap)) - print sort + print(sort) Modified: python/branches/p3yk/Lib/hotshot/log.py ============================================================================== --- python/branches/p3yk/Lib/hotshot/log.py (original) +++ python/branches/p3yk/Lib/hotshot/log.py Fri Feb 9 06:37:30 2007 @@ -159,7 +159,7 @@ try: filename = self._filemap[fileno] except KeyError: - print "Could not identify fileId", fileno + print("Could not identify fileId", fileno) return 1 if filename is None: return 1 Modified: python/branches/p3yk/Lib/hotshot/stones.py ============================================================================== --- python/branches/p3yk/Lib/hotshot/stones.py (original) +++ python/branches/p3yk/Lib/hotshot/stones.py Fri Feb 9 06:37:30 2007 @@ -10,9 +10,9 @@ benchtime, stones = p.runcall(test.pystone.pystones) p.close() - print "Pystone(%s) time for %d passes = %g" % \ - (test.pystone.__version__, test.pystone.LOOPS, benchtime) - print "This machine benchmarks at %g pystones/second" % stones + print("Pystone(%s) time for %d passes = %g" % \ + (test.pystone.__version__, test.pystone.LOOPS, benchtime)) + print("This machine benchmarks at %g pystones/second" % stones) stats = hotshot.stats.load(logfile) stats.strip_dirs() Modified: python/branches/p3yk/Lib/htmllib.py ============================================================================== --- python/branches/p3yk/Lib/htmllib.py (original) +++ python/branches/p3yk/Lib/htmllib.py Fri Feb 9 06:37:30 2007 @@ -464,7 +464,7 @@ try: f = open(file, 'r') except IOError as msg: - print file, ":", msg + print(file, ":", msg) sys.exit(1) data = f.read() Modified: python/branches/p3yk/Lib/httplib.py ============================================================================== --- python/branches/p3yk/Lib/httplib.py (original) +++ python/branches/p3yk/Lib/httplib.py Fri Feb 9 06:37:30 2007 @@ -342,7 +342,7 @@ # Initialize with Simple-Response defaults line = self.fp.readline() if self.debuglevel > 0: - print "reply:", repr(line) + print("reply:", repr(line)) if not line: # Presumably, the server closed the connection before # sending a valid response. @@ -391,7 +391,7 @@ if not skip: break if self.debuglevel > 0: - print "header:", skip + print("header:", skip) self.status = status self.reason = reason.strip() @@ -414,7 +414,7 @@ self.msg = HTTPMessage(self.fp, 0) if self.debuglevel > 0: for hdr in self.msg.headers: - print "header:", hdr, + print("header:", hdr, end=' ') # don't let the msg keep an fp self.msg.fp = None @@ -665,11 +665,11 @@ try: self.sock = socket.socket(af, socktype, proto) if self.debuglevel > 0: - print "connect: (%s, %s)" % (self.host, self.port) + print("connect: (%s, %s)" % (self.host, self.port)) self.sock.connect(sa) except socket.error as msg: if self.debuglevel > 0: - print 'connect fail:', (self.host, self.port) + print('connect fail:', (self.host, self.port)) if self.sock: self.sock.close() self.sock = None @@ -702,11 +702,11 @@ # NOTE: we DO propagate the error, though, because we cannot simply # ignore the error... the caller will know if they can retry. if self.debuglevel > 0: - print "send:", repr(str) + print("send:", repr(str)) try: blocksize=8192 if hasattr(str,'read') : - if self.debuglevel > 0: print "sendIng a read()able" + if self.debuglevel > 0: print("sendIng a read()able") data=str.read(blocksize) while data: self.sock.sendall(data) @@ -898,7 +898,7 @@ thelen = str(os.fstat(body.fileno()).st_size) except (AttributeError, OSError): # Don't send a length if this failed - if self.debuglevel > 0: print "Cannot stat!!" + if self.debuglevel > 0: print("Cannot stat!!") if thelen is not None: self.putheader('Content-Length',thelen) @@ -1408,13 +1408,13 @@ h.putrequest('GET', selector) h.endheaders() status, reason, headers = h.getreply() - print 'status =', status - print 'reason =', reason - print "read", len(h.getfile().read()) - print + print('status =', status) + print('reason =', reason) + print("read", len(h.getfile().read())) + print() if headers: - for header in headers.headers: print header.strip() - print + for header in headers.headers: print(header.strip()) + print() # minimal test that code to extract host from url works class HTTP11(HTTP): @@ -1431,20 +1431,20 @@ for host, selector in (('sourceforge.net', '/projects/python'), ): - print "https://%s%s" % (host, selector) + print("https://%s%s" % (host, selector)) hs = HTTPS() hs.set_debuglevel(dl) hs.connect(host) hs.putrequest('GET', selector) hs.endheaders() status, reason, headers = hs.getreply() - print 'status =', status - print 'reason =', reason - print "read", len(hs.getfile().read()) - print + print('status =', status) + print('reason =', reason) + print("read", len(hs.getfile().read())) + print() if headers: - for header in headers.headers: print header.strip() - print + for header in headers.headers: print(header.strip()) + print() if __name__ == '__main__': test() Modified: python/branches/p3yk/Lib/idlelib/CallTips.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/CallTips.py (original) +++ python/branches/p3yk/Lib/idlelib/CallTips.py Fri Feb 9 06:37:30 2007 @@ -201,9 +201,9 @@ arg_text = ct.fetch_tip(name) if arg_text != expected: failed.append(t) - print "%s - expected %s, but got %s" % (t, expected, - get_arg_text(entity)) - print "%d of %d tests failed" % (len(failed), len(tests)) + print("%s - expected %s, but got %s" % (t, expected, + get_arg_text(entity))) + print("%d of %d tests failed" % (len(failed), len(tests))) tc = TC() tests = (t1, t2, t3, t4, t5, t6, Modified: python/branches/p3yk/Lib/idlelib/ColorDelegator.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/ColorDelegator.py (original) +++ python/branches/p3yk/Lib/idlelib/ColorDelegator.py Fri Feb 9 06:37:30 2007 @@ -72,7 +72,7 @@ "hit": idleConf.GetHighlight(theme, "hit"), } - if DEBUG: print 'tagdefs',self.tagdefs + if DEBUG: print('tagdefs',self.tagdefs) def insert(self, index, chars, tags=None): index = self.index(index) @@ -91,13 +91,13 @@ def notify_range(self, index1, index2=None): self.tag_add("TODO", index1, index2) if self.after_id: - if DEBUG: print "colorizing already scheduled" + if DEBUG: print("colorizing already scheduled") return if self.colorizing: self.stop_colorizing = True - if DEBUG: print "stop colorizing" + if DEBUG: print("stop colorizing") if self.allow_colorizing: - if DEBUG: print "schedule colorizing" + if DEBUG: print("schedule colorizing") self.after_id = self.after(1, self.recolorize) close_when_done = None # Window to be closed when done colorizing @@ -106,7 +106,7 @@ if self.after_id: after_id = self.after_id self.after_id = None - if DEBUG: print "cancel scheduled recolorizer" + if DEBUG: print("cancel scheduled recolorizer") self.after_cancel(after_id) self.allow_colorizing = False self.stop_colorizing = True @@ -120,42 +120,42 @@ if self.after_id: after_id = self.after_id self.after_id = None - if DEBUG: print "cancel scheduled recolorizer" + if DEBUG: print("cancel scheduled recolorizer") self.after_cancel(after_id) if self.allow_colorizing and self.colorizing: - if DEBUG: print "stop colorizing" + if DEBUG: print("stop colorizing") self.stop_colorizing = True self.allow_colorizing = not self.allow_colorizing if self.allow_colorizing and not self.colorizing: self.after_id = self.after(1, self.recolorize) if DEBUG: - print "auto colorizing turned",\ - self.allow_colorizing and "on" or "off" + print("auto colorizing turned",\ + self.allow_colorizing and "on" or "off") return "break" def recolorize(self): self.after_id = None if not self.delegate: - if DEBUG: print "no delegate" + if DEBUG: print("no delegate") return if not self.allow_colorizing: - if DEBUG: print "auto colorizing is off" + if DEBUG: print("auto colorizing is off") return if self.colorizing: - if DEBUG: print "already colorizing" + if DEBUG: print("already colorizing") return try: self.stop_colorizing = False self.colorizing = True - if DEBUG: print "colorizing..." + if DEBUG: print("colorizing...") t0 = time.clock() self.recolorize_main() t1 = time.clock() - if DEBUG: print "%.3f seconds" % (t1-t0) + if DEBUG: print("%.3f seconds" % (t1-t0)) finally: self.colorizing = False if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): - if DEBUG: print "reschedule colorizing" + if DEBUG: print("reschedule colorizing") self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done @@ -240,7 +240,7 @@ self.tag_add("TODO", next) self.update() if self.stop_colorizing: - if DEBUG: print "colorizing stopped" + if DEBUG: print("colorizing stopped") return def removecolors(self): Modified: python/branches/p3yk/Lib/idlelib/Delegator.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/Delegator.py (original) +++ python/branches/p3yk/Lib/idlelib/Delegator.py Fri Feb 9 06:37:30 2007 @@ -23,7 +23,7 @@ def cachereport(self): keys = self.__cache.keys() keys.sort() - print keys + print(keys) def setdelegate(self, delegate): self.resetcache() Modified: python/branches/p3yk/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/EditorWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/EditorWindow.py Fri Feb 9 06:37:30 2007 @@ -859,7 +859,7 @@ try: self.load_extension(name) except: - print "Failed to load extension", repr(name) + print("Failed to load extension", repr(name)) import traceback traceback.print_exc() @@ -870,7 +870,7 @@ try: mod = __import__(name, globals(), locals(), []) except ImportError: - print "\nFailed to import extension: ", name + print("\nFailed to import extension: ", name) return cls = getattr(mod, name) keydefs = idleConf.GetExtensionBindings(name) Modified: python/branches/p3yk/Lib/idlelib/FileList.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/FileList.py (original) +++ python/branches/p3yk/Lib/idlelib/FileList.py Fri Feb 9 06:37:30 2007 @@ -54,7 +54,7 @@ try: key = self.inversedict[edit] except KeyError: - print "Don't know this EditorWindow object. (close)" + print("Don't know this EditorWindow object. (close)") return if key: del self.dict[key] @@ -67,7 +67,7 @@ try: key = self.inversedict[edit] except KeyError: - print "Don't know this EditorWindow object. (rename)" + print("Don't know this EditorWindow object. (rename)") return filename = edit.io.filename if not filename: Modified: python/branches/p3yk/Lib/idlelib/GrepDialog.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/GrepDialog.py (original) +++ python/branches/p3yk/Lib/idlelib/GrepDialog.py Fri Feb 9 06:37:30 2007 @@ -77,13 +77,13 @@ list.sort() self.close() pat = self.engine.getpat() - print "Searching %r in %s ..." % (pat, path) + print("Searching %r in %s ..." % (pat, path)) hits = 0 for fn in list: try: f = open(fn) except IOError as msg: - print msg + print(msg) continue lineno = 0 while 1: @@ -102,16 +102,16 @@ s = "" else: s = "s" - print "Found", hits, "hit%s." % s - print "(Hint: right-click to open locations.)" + print("Found", hits, "hit%s." % s) + print("(Hint: right-click to open locations.)") else: - print "No hits." + print("No hits.") def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) except os.error as msg: - print msg + print(msg) return [] list = [] subdirs = [] Modified: python/branches/p3yk/Lib/idlelib/MultiCall.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/MultiCall.py (original) +++ python/branches/p3yk/Lib/idlelib/MultiCall.py Fri Feb 9 06:37:30 2007 @@ -388,7 +388,7 @@ text.pack() def bindseq(seq, n=[0]): def handler(event): - print seq + print(seq) text.bind("<>"%n[0], handler) text.event_add("<>"%n[0], seq) n[0] += 1 Modified: python/branches/p3yk/Lib/idlelib/Percolator.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/Percolator.py (original) +++ python/branches/p3yk/Lib/idlelib/Percolator.py Fri Feb 9 06:37:30 2007 @@ -58,10 +58,10 @@ self.name = name Delegator.__init__(self, None) def insert(self, *args): - print self.name, ": insert", args + print(self.name, ": insert", args) self.delegate.insert(*args) def delete(self, *args): - print self.name, ": delete", args + print(self.name, ": delete", args) self.delegate.delete(*args) root = Tk() root.wm_protocol("WM_DELETE_WINDOW", root.quit) Modified: python/branches/p3yk/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/PyShell.py (original) +++ python/branches/p3yk/Lib/idlelib/PyShell.py Fri Feb 9 06:37:30 2007 @@ -19,8 +19,8 @@ try: from Tkinter import * except ImportError: - print>>sys.__stderr__, "** IDLE can't import Tkinter. " \ - "Your Python may not be configured for Tk. **" + print("** IDLE can't import Tkinter. " \ + "Your Python may not be configured for Tk. **", file=sys.__stderr__) sys.exit(1) import tkMessageBox @@ -504,14 +504,14 @@ console = self.tkconsole.console if how == "OK": if what is not None: - print >>console, repr(what) + print(repr(what), file=console) elif how == "EXCEPTION": if self.tkconsole.getvar("<>"): self.remote_stack_viewer() elif how == "ERROR": errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n" - print >>sys.__stderr__, errmsg, what - print >>console, errmsg, what + print(errmsg, what, file=sys.__stderr__) + print(errmsg, what, file=console) # we received a response to the currently active seq number: try: self.tkconsole.endexecuting() @@ -576,8 +576,8 @@ except (OverflowError, SyntaxError): self.tkconsole.resetoutput() tkerr = self.tkconsole.stderr - print>>tkerr, '*** Error in script or command!\n' - print>>tkerr, 'Traceback (most recent call last):' + print('*** Error in script or command!\n', file=tkerr) + print('Traceback (most recent call last):', file=tkerr) InteractiveInterpreter.showsyntaxerror(self, filename) self.tkconsole.showprompt() else: @@ -730,8 +730,7 @@ 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()" + print("IDLE internal error in runcode()", file=self.tkconsole.stderr) self.showtraceback() if use_subprocess: self.tkconsole.endexecuting() @@ -1349,7 +1348,7 @@ if os.path.isfile(script): pass else: - print "No script file: ", script + print("No script file: ", script) sys.exit() enable_shell = True if o == '-s': Modified: python/branches/p3yk/Lib/idlelib/ScrolledList.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/ScrolledList.py (original) +++ python/branches/p3yk/Lib/idlelib/ScrolledList.py Fri Feb 9 06:37:30 2007 @@ -124,8 +124,8 @@ root.protocol("WM_DELETE_WINDOW", root.destroy) class MyScrolledList(ScrolledList): def fill_menu(self): self.menu.add_command(label="pass") - def on_select(self, index): print "select", self.get(index) - def on_double(self, index): print "double", self.get(index) + def on_select(self, index): print("select", self.get(index)) + def on_double(self, index): print("double", self.get(index)) s = MyScrolledList(root) for i in range(30): s.append("item %02d" % i) Modified: python/branches/p3yk/Lib/idlelib/UndoDelegator.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/UndoDelegator.py (original) +++ python/branches/p3yk/Lib/idlelib/UndoDelegator.py Fri Feb 9 06:37:30 2007 @@ -38,10 +38,10 @@ def dump_event(self, event): from pprint import pprint pprint(self.undolist[:self.pointer]) - print "pointer:", self.pointer, - print "saved:", self.saved, - print "can_merge:", self.can_merge, - print "get_saved():", self.get_saved() + print("pointer:", self.pointer, end=' ') + print("saved:", self.saved, end=' ') + print("can_merge:", self.can_merge, end=' ') + print("get_saved():", self.get_saved()) pprint(self.undolist[self.pointer:]) return "break" Modified: python/branches/p3yk/Lib/idlelib/WidgetRedirector.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/WidgetRedirector.py (original) +++ python/branches/p3yk/Lib/idlelib/WidgetRedirector.py Fri Feb 9 06:37:30 2007 @@ -83,7 +83,7 @@ redir = WidgetRedirector(text) global orig_insert def my_insert(*args): - print "insert", args + print("insert", args) orig_insert(*args) orig_insert = redir.register("insert", my_insert) root.mainloop() Modified: python/branches/p3yk/Lib/idlelib/WindowList.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/WindowList.py (original) +++ python/branches/p3yk/Lib/idlelib/WindowList.py Fri Feb 9 06:37:30 2007 @@ -46,7 +46,7 @@ callback() except: t, v, tb = sys.exc_info() - print "warning: callback failed in WindowList", t, ":", v + print("warning: callback failed in WindowList", t, ":", v) registry = WindowList() Modified: python/branches/p3yk/Lib/idlelib/configHandler.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/configHandler.py (original) +++ python/branches/p3yk/Lib/idlelib/configHandler.py Fri Feb 9 06:37:30 2007 @@ -679,18 +679,18 @@ ### module test if __name__ == '__main__': def dumpCfg(cfg): - print '\n',cfg,'\n' + print('\n',cfg,'\n') for key in cfg.keys(): sections=cfg[key].sections() - print key - print sections + print(key) + print(sections) for section in sections: options=cfg[key].options(section) - print section - print options + print(section) + print(options) for option in options: - print option, '=', cfg[key].Get(section,option) + print(option, '=', cfg[key].Get(section,option)) dumpCfg(idleConf.defaultCfg) dumpCfg(idleConf.userCfg) - print idleConf.userCfg['main'].Get('Theme','name') + print(idleConf.userCfg['main'].Get('Theme','name')) #print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal') Modified: python/branches/p3yk/Lib/idlelib/configHelpSourceEdit.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/configHelpSourceEdit.py (original) +++ python/branches/p3yk/Lib/idlelib/configHelpSourceEdit.py Fri Feb 9 06:37:30 2007 @@ -164,6 +164,6 @@ def run(): keySeq = '' dlg = GetHelpSourceDialog(root, 'Get Help Source') - print dlg.result + print(dlg.result) Button(root,text='Dialog', command=run).pack() root.mainloop() Modified: python/branches/p3yk/Lib/idlelib/configSectionNameDialog.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/configSectionNameDialog.py (original) +++ python/branches/p3yk/Lib/idlelib/configSectionNameDialog.py Fri Feb 9 06:37:30 2007 @@ -92,6 +92,6 @@ keySeq='' dlg=GetCfgSectionNameDialog(root,'Get Name', 'The information here should need to be word wrapped. Test.') - print dlg.result + print(dlg.result) Button(root,text='Dialog',command=run).pack() root.mainloop() Modified: python/branches/p3yk/Lib/idlelib/keybindingDialog.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/keybindingDialog.py (original) +++ python/branches/p3yk/Lib/idlelib/keybindingDialog.py Fri Feb 9 06:37:30 2007 @@ -263,6 +263,6 @@ def run(): keySeq='' dlg=GetKeysDialog(root,'Get Keys','find-again',[]) - print dlg.result + print(dlg.result) Button(root,text='Dialog',command=run).pack() root.mainloop() Modified: python/branches/p3yk/Lib/idlelib/rpc.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/rpc.py (original) +++ python/branches/p3yk/Lib/idlelib/rpc.py Fri Feb 9 06:37:30 2007 @@ -104,14 +104,14 @@ raise except: erf = sys.__stderr__ - print>>erf, '\n' + '-'*40 - print>>erf, 'Unhandled server exception!' - print>>erf, 'Thread: %s' % threading.currentThread().getName() - print>>erf, 'Client Address: ', client_address - print>>erf, 'Request: ', repr(request) + print('\n' + '-'*40, file=erf) + print('Unhandled server exception!', file=erf) + print('Thread: %s' % threading.currentThread().getName(), file=erf) + print('Client Address: ', client_address, file=erf) + print('Request: ', repr(request), file=erf) traceback.print_exc(file=erf) - print>>erf, '\n*** Unrecoverable, server exiting!' - print>>erf, '-'*40 + print('\n*** Unrecoverable, server exiting!', file=erf) + print('-'*40, file=erf) os._exit(0) #----------------- end class RPCServer -------------------- @@ -152,7 +152,7 @@ s = self.location + " " + str(threading.currentThread().getName()) for a in args: s = s + " " + str(a) - print>>sys.__stderr__, s + print(s, file=sys.__stderr__) def register(self, oid, object): self.objtable[oid] = object @@ -201,7 +201,7 @@ except: msg = "*** Internal Error: rpc.py:SocketIO.localcall()\n\n"\ " Object: %s \n Method: %s \n Args: %s\n" - print>>sys.__stderr__, msg % (oid, method, args) + print(msg % (oid, method, args), file=sys.__stderr__) traceback.print_exc(file=sys.__stderr__) return ("EXCEPTION", None) @@ -323,7 +323,7 @@ try: s = pickle.dumps(message) except pickle.PicklingError: - print >>sys.__stderr__, "Cannot pickle:", repr(message) + print("Cannot pickle:", repr(message), file=sys.__stderr__) raise s = struct.pack(" 0: @@ -379,10 +379,10 @@ try: message = pickle.loads(packet) except pickle.UnpicklingError: - print >>sys.__stderr__, "-----------------------" - print >>sys.__stderr__, "cannot unpickle packet:", repr(packet) + print("-----------------------", file=sys.__stderr__) + print("cannot unpickle packet:", repr(packet), file=sys.__stderr__) traceback.print_stack(file=sys.__stderr__) - print >>sys.__stderr__, "-----------------------" + print("-----------------------", file=sys.__stderr__) raise return message @@ -526,11 +526,11 @@ def accept(self): working_sock, address = self.listening_sock.accept() if self.debugging: - print>>sys.__stderr__, "****** Connection request from ", address + print("****** Connection request from ", address, file=sys.__stderr__) if address[0] == LOCALHOST: SocketIO.__init__(self, working_sock) else: - print>>sys.__stderr__, "** Invalid host: ", address + print("** Invalid host: ", address, file=sys.__stderr__) raise socket.error def get_remote_proxy(self, oid): Modified: python/branches/p3yk/Lib/idlelib/run.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/run.py (original) +++ python/branches/p3yk/Lib/idlelib/run.py Fri Feb 9 06:37:30 2007 @@ -115,11 +115,11 @@ server = MyRPCServer(address, MyHandler) break except socket.error as err: - print>>sys.__stderr__,"IDLE Subprocess: socket error: "\ - + err[1] + ", retrying...." + print("IDLE Subprocess: socket error: "\ + + err[1] + ", retrying....", file=sys.__stderr__) else: - print>>sys.__stderr__, "IDLE Subprocess: Connection to "\ - "IDLE GUI failed, exiting." + print("IDLE Subprocess: Connection to "\ + "IDLE GUI failed, exiting.", file=sys.__stderr__) show_socket_error(err, address) global exit_now exit_now = True @@ -149,14 +149,14 @@ typ, val, tb = excinfo = sys.exc_info() sys.last_type, sys.last_value, sys.last_traceback = excinfo tbe = traceback.extract_tb(tb) - print>>efile, '\nTraceback (most recent call last):' + print('\nTraceback (most recent call last):', file=efile) exclude = ("run.py", "rpc.py", "threading.py", "Queue.py", "RemoteDebugger.py", "bdb.py") cleanup_traceback(tbe, exclude) traceback.print_list(tbe, file=efile) lines = traceback.format_exception_only(typ, val) for line in lines: - print>>efile, line, + print(line, end=' ', file=efile) def cleanup_traceback(tb, exclude): "Remove excluded traces from beginning/end of tb; get cached lines" @@ -178,7 +178,7 @@ if len(tb) == 0: # exception was in IDLE internals, don't prune! tb[:] = orig_tb[:] - print>>sys.stderr, "** IDLE Internal Exception: " + print("** IDLE Internal Exception: ", file=sys.stderr) rpchandler = rpc.objecttable['exec'].rpchandler for i in range(len(tb)): fn, ln, nm, line = tb[i] @@ -227,14 +227,14 @@ thread.interrupt_main() except: erf = sys.__stderr__ - print>>erf, '\n' + '-'*40 - print>>erf, 'Unhandled server exception!' - print>>erf, 'Thread: %s' % threading.currentThread().getName() - print>>erf, 'Client Address: ', client_address - print>>erf, 'Request: ', repr(request) + print('\n' + '-'*40, file=erf) + print('Unhandled server exception!', file=erf) + print('Thread: %s' % threading.currentThread().getName(), file=erf) + print('Client Address: ', client_address, file=erf) + print('Request: ', repr(request), file=erf) traceback.print_exc(file=erf) - print>>erf, '\n*** Unrecoverable, server exiting!' - print>>erf, '-'*40 + print('\n*** Unrecoverable, server exiting!', file=erf) + print('-'*40, file=erf) quitting = True thread.interrupt_main() Modified: python/branches/p3yk/Lib/ihooks.py ============================================================================== --- python/branches/p3yk/Lib/ihooks.py (original) +++ python/branches/p3yk/Lib/ihooks.py Fri Feb 9 06:37:30 2007 @@ -87,9 +87,9 @@ def message(self, format, *args): if args: - print format%args + print(format%args) else: - print format + print(format) class BasicModuleLoader(_Verbose): Modified: python/branches/p3yk/Lib/imaplib.py ============================================================================== --- python/branches/p3yk/Lib/imaplib.py (original) +++ python/branches/p3yk/Lib/imaplib.py Fri Feb 9 06:37:30 2007 @@ -1485,15 +1485,15 @@ run('uid', ('FETCH', '%s' % uid[-1], '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)')) - print '\nAll tests OK.' + print('\nAll tests OK.') except: - print '\nTests failed.' + print('\nTests failed.') if not Debug: - print ''' + print(''' If you would like to see debugging output, try: %s -d5 -''' % sys.argv[0] +''' % sys.argv[0]) raise Modified: python/branches/p3yk/Lib/imghdr.py ============================================================================== --- python/branches/p3yk/Lib/imghdr.py (original) +++ python/branches/p3yk/Lib/imghdr.py Fri Feb 9 06:37:30 2007 @@ -144,18 +144,18 @@ import os for filename in list: if os.path.isdir(filename): - print filename + '/:', + print(filename + '/:', end=' ') if recursive or toplevel: - print 'recursing down:' + print('recursing down:') import glob names = glob.glob(os.path.join(filename, '*')) testall(names, recursive, 0) else: - print '*** directory (use -r) ***' + print('*** directory (use -r) ***') else: - print filename + ':', + print(filename + ':', end=' ') sys.stdout.flush() try: - print what(filename) + print(what(filename)) except IOError: - print '*** not found ***' + print('*** not found ***') Modified: python/branches/p3yk/Lib/imputil.py ============================================================================== --- python/branches/p3yk/Lib/imputil.py (original) +++ python/branches/p3yk/Lib/imputil.py Fri Feb 9 06:37:30 2007 @@ -618,9 +618,9 @@ items.sort() for name, module in items: if module: - print name, module.__dict__.get('__importer__', '-- no importer') + print(name, module.__dict__.get('__importer__', '-- no importer')) else: - print name, '-- non-existent module' + print(name, '-- non-existent module') def _test_revamp(): ImportManager().install() Modified: python/branches/p3yk/Lib/lib-tk/Dialog.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/Dialog.py (original) +++ python/branches/p3yk/Lib/lib-tk/Dialog.py Fri Feb 9 06:37:30 2007 @@ -36,7 +36,7 @@ 'strings': ('Save File', 'Discard Changes', 'Return to Editor')}) - print d.num + print(d.num) if __name__ == '__main__': Modified: python/branches/p3yk/Lib/lib-tk/FileDialog.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/FileDialog.py (original) +++ python/branches/p3yk/Lib/lib-tk/FileDialog.py Fri Feb 9 06:37:30 2007 @@ -267,7 +267,7 @@ loadfile = fd.go(key="test") fd = SaveFileDialog(root) savefile = fd.go(key="test") - print loadfile, savefile + print(loadfile, savefile) if __name__ == '__main__': Modified: python/branches/p3yk/Lib/lib-tk/SimpleDialog.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/SimpleDialog.py (original) +++ python/branches/p3yk/Lib/lib-tk/SimpleDialog.py Fri Feb 9 06:37:30 2007 @@ -102,7 +102,7 @@ default=0, cancel=2, title="Test Dialog") - print d.go() + print(d.go()) t = Button(root, text='Test', command=doit) t.pack() q = Button(root, text='Quit', command=t.quit) Modified: python/branches/p3yk/Lib/lib-tk/Tkinter.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/Tkinter.py (original) +++ python/branches/p3yk/Lib/lib-tk/Tkinter.py Fri Feb 9 06:37:30 2007 @@ -86,7 +86,7 @@ try: cnf.update(c) except (AttributeError, TypeError) as msg: - print "_cnfmerge: fallback due to:", msg + print("_cnfmerge: fallback due to:", msg) for k, v in c.items(): cnf[k] = v return cnf Modified: python/branches/p3yk/Lib/lib-tk/tkColorChooser.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/tkColorChooser.py (original) +++ python/branches/p3yk/Lib/lib-tk/tkColorChooser.py Fri Feb 9 06:37:30 2007 @@ -67,4 +67,4 @@ if __name__ == "__main__": - print "color", askcolor() + print("color", askcolor()) Modified: python/branches/p3yk/Lib/lib-tk/tkFileDialog.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/tkFileDialog.py (original) +++ python/branches/p3yk/Lib/lib-tk/tkFileDialog.py Fri Feb 9 06:37:30 2007 @@ -204,12 +204,12 @@ fp=open(openfilename,"r") fp.close() except: - print "Could not open File: " - print sys.exc_info()[1] + print("Could not open File: ") + print(sys.exc_info()[1]) - print "open", openfilename.encode(enc) + print("open", openfilename.encode(enc)) # dialog for saving files saveasfilename=asksaveasfilename() - print "saveas", saveasfilename.encode(enc) + print("saveas", saveasfilename.encode(enc)) Modified: python/branches/p3yk/Lib/lib-tk/tkFont.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/tkFont.py (original) +++ python/branches/p3yk/Lib/lib-tk/tkFont.py Fri Feb 9 06:37:30 2007 @@ -185,22 +185,22 @@ # create a font f = Font(family="times", size=30, weight=NORMAL) - print f.actual() - print f.actual("family") - print f.actual("weight") + print(f.actual()) + print(f.actual("family")) + print(f.actual("weight")) - print f.config() - print f.cget("family") - print f.cget("weight") + print(f.config()) + print(f.cget("family")) + print(f.cget("weight")) - print names() + print(names()) - print f.measure("hello"), f.metrics("linespace") + print(f.measure("hello"), f.metrics("linespace")) - print f.metrics() + print(f.metrics()) f = Font(font=("Courier", 20, "bold")) - print f.measure("hello"), f.metrics("linespace") + print(f.measure("hello"), f.metrics("linespace")) w = Tkinter.Label(root, text="Hello, world", font=f) w.pack() Modified: python/branches/p3yk/Lib/lib-tk/tkMessageBox.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/tkMessageBox.py (original) +++ python/branches/p3yk/Lib/lib-tk/tkMessageBox.py Fri Feb 9 06:37:30 2007 @@ -122,11 +122,11 @@ if __name__ == "__main__": - print "info", showinfo("Spam", "Egg Information") - print "warning", showwarning("Spam", "Egg Warning") - print "error", showerror("Spam", "Egg Alert") - print "question", askquestion("Spam", "Question?") - print "proceed", askokcancel("Spam", "Proceed?") - print "yes/no", askyesno("Spam", "Got it?") - print "yes/no/cancel", askyesnocancel("Spam", "Want it?") - print "try again", askretrycancel("Spam", "Try again?") + print("info", showinfo("Spam", "Egg Information")) + print("warning", showwarning("Spam", "Egg Warning")) + print("error", showerror("Spam", "Egg Alert")) + print("question", askquestion("Spam", "Question?")) + print("proceed", askokcancel("Spam", "Proceed?")) + print("yes/no", askyesno("Spam", "Got it?")) + print("yes/no/cancel", askyesnocancel("Spam", "Want it?")) + print("try again", askretrycancel("Spam", "Try again?")) Modified: python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py (original) +++ python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py Fri Feb 9 06:37:30 2007 @@ -315,6 +315,6 @@ root = Tk() root.update() - print askinteger("Spam", "Egg count", initialvalue=12*12) - print askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100) - print askstring("Spam", "Egg label") + print(askinteger("Spam", "Egg count", initialvalue=12*12)) + print(askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100)) + print(askstring("Spam", "Egg label")) Modified: python/branches/p3yk/Lib/locale.py ============================================================================== --- python/branches/p3yk/Lib/locale.py (original) +++ python/branches/p3yk/Lib/locale.py Fri Feb 9 06:37:30 2007 @@ -262,10 +262,10 @@ setlocale(LC_ALL, "") #do grouping s1 = format("%d", 123456789,1) - print s1, "is", atoi(s1) + print(s1, "is", atoi(s1)) #standard formatting s1 = str(3.14) - print s1, "is", atof(s1) + print(s1, "is", atof(s1)) ### Locale name aliasing engine @@ -1499,49 +1499,49 @@ _init_categories() del categories['LC_ALL'] - print 'Locale defaults as determined by getdefaultlocale():' - print '-'*72 + print('Locale defaults as determined by getdefaultlocale():') + print('-'*72) lang, enc = getdefaultlocale() - print 'Language: ', lang or '(undefined)' - print 'Encoding: ', enc or '(undefined)' - print + print('Language: ', lang or '(undefined)') + print('Encoding: ', enc or '(undefined)') + print() - print 'Locale settings on startup:' - print '-'*72 + print('Locale settings on startup:') + print('-'*72) for name,category in categories.items(): - print name, '...' + print(name, '...') lang, enc = getlocale(category) - print ' Language: ', lang or '(undefined)' - print ' Encoding: ', enc or '(undefined)' - print - - print - print 'Locale settings after calling resetlocale():' - print '-'*72 + print(' Language: ', lang or '(undefined)') + print(' Encoding: ', enc or '(undefined)') + print() + + print() + print('Locale settings after calling resetlocale():') + print('-'*72) resetlocale() for name,category in categories.items(): - print name, '...' + print(name, '...') lang, enc = getlocale(category) - print ' Language: ', lang or '(undefined)' - print ' Encoding: ', enc or '(undefined)' - print + print(' Language: ', lang or '(undefined)') + print(' Encoding: ', enc or '(undefined)') + print() try: setlocale(LC_ALL, "") except: - print 'NOTE:' - print 'setlocale(LC_ALL, "") does not support the default locale' - print 'given in the OS environment variables.' + print('NOTE:') + print('setlocale(LC_ALL, "") does not support the default locale') + print('given in the OS environment variables.') else: - print - print 'Locale settings after calling setlocale(LC_ALL, ""):' - print '-'*72 + print() + print('Locale settings after calling setlocale(LC_ALL, ""):') + print('-'*72) for name,category in categories.items(): - print name, '...' + print(name, '...') lang, enc = getlocale(category) - print ' Language: ', lang or '(undefined)' - print ' Encoding: ', enc or '(undefined)' - print + print(' Language: ', lang or '(undefined)') + print(' Encoding: ', enc or '(undefined)') + print() ### @@ -1553,10 +1553,10 @@ __all__.append("LC_MESSAGES") if __name__=='__main__': - print 'Locale aliasing:' - print + print('Locale aliasing:') + print() _print_locale() - print - print 'Number formatting:' - print + print() + print('Number formatting:') + print() _test() Modified: python/branches/p3yk/Lib/logging/handlers.py ============================================================================== --- python/branches/p3yk/Lib/logging/handlers.py (original) +++ python/branches/p3yk/Lib/logging/handlers.py Fri Feb 9 06:37:30 2007 @@ -834,8 +834,8 @@ logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, } except ImportError: - print "The Python Win32 extensions for NT (service, event "\ - "logging) appear not to be available." + print("The Python Win32 extensions for NT (service, event "\ + "logging) appear not to be available.") self._welu = None def getMessageID(self, record): Modified: python/branches/p3yk/Lib/macurl2path.py ============================================================================== --- python/branches/p3yk/Lib/macurl2path.py (original) +++ python/branches/p3yk/Lib/macurl2path.py Fri Feb 9 06:37:30 2007 @@ -82,7 +82,7 @@ "/foo/bar/index.html", "/foo/bar/", "/"]: - print '%r -> %r' % (url, url2pathname(url)) + print('%r -> %r' % (url, url2pathname(url))) for path in ["drive:", "drive:dir:", "drive:dir:file", @@ -91,7 +91,7 @@ ":file", ":dir:", ":dir:file"]: - print '%r -> %r' % (path, pathname2url(path)) + print('%r -> %r' % (path, pathname2url(path))) if __name__ == '__main__': test() Modified: python/branches/p3yk/Lib/mailcap.py ============================================================================== --- python/branches/p3yk/Lib/mailcap.py (original) +++ python/branches/p3yk/Lib/mailcap.py Fri Feb 9 06:37:30 2007 @@ -219,37 +219,37 @@ for i in range(1, len(sys.argv), 2): args = sys.argv[i:i+2] if len(args) < 2: - print "usage: mailcap [MIMEtype file] ..." + print("usage: mailcap [MIMEtype file] ...") return MIMEtype = args[0] file = args[1] command, e = findmatch(caps, MIMEtype, 'view', file) if not command: - print "No viewer found for", type + print("No viewer found for", type) else: - print "Executing:", command + print("Executing:", command) sts = os.system(command) if sts: - print "Exit status:", sts + print("Exit status:", sts) def show(caps): - print "Mailcap files:" - for fn in listmailcapfiles(): print "\t" + fn - print + print("Mailcap files:") + for fn in listmailcapfiles(): print("\t" + fn) + print() if not caps: caps = getcaps() - print "Mailcap entries:" - print + print("Mailcap entries:") + print() ckeys = caps.keys() ckeys.sort() for type in ckeys: - print type + print(type) entries = caps[type] for e in entries: keys = e.keys() keys.sort() for k in keys: - print " %-15s" % k, e[k] - print + print(" %-15s" % k, e[k]) + print() if __name__ == '__main__': test() Modified: python/branches/p3yk/Lib/mhlib.py ============================================================================== --- python/branches/p3yk/Lib/mhlib.py (original) +++ python/branches/p3yk/Lib/mhlib.py Fri Feb 9 06:37:30 2007 @@ -959,7 +959,7 @@ global mh, f os.system('rm -rf $HOME/Mail/@test') mh = MH() - def do(s): print s; print eval(s) + def do(s): print(s); print(eval(s)) do('mh.listfolders()') do('mh.listallfolders()') testfolders = ['@test', '@test/test1', '@test/test2', @@ -974,7 +974,7 @@ do('f.getsequences()') seqs = f.getsequences() seqs['foo'] = IntSet('1-10 12-20', ' ').tolist() - print seqs + print(seqs) f.putsequences(seqs) do('f.getsequences()') for t in reversed(testfolders): do('mh.deletefolder(%r)' % (t,)) @@ -990,10 +990,10 @@ try: do('f.parsesequence(%r)' % (seq,)) except Error as msg: - print "Error:", msg + print("Error:", msg) stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read() list = map(int, stuff.split()) - print list, "<-- pick" + print(list, "<-- pick") do('f.listmessages()') Modified: python/branches/p3yk/Lib/mimetypes.py ============================================================================== --- python/branches/p3yk/Lib/mimetypes.py (original) +++ python/branches/p3yk/Lib/mimetypes.py Fri Feb 9 06:37:30 2007 @@ -503,8 +503,8 @@ """ def usage(code, msg=''): - print USAGE - if msg: print msg + print(USAGE) + if msg: print(msg) sys.exit(code) try: @@ -525,9 +525,9 @@ for gtype in args: if extension: guess = guess_extension(gtype, strict) - if not guess: print "I don't know anything about type", gtype - else: print guess + if not guess: print("I don't know anything about type", gtype) + else: print(guess) else: guess, encoding = guess_type(gtype, strict) - if not guess: print "I don't know anything about type", gtype - else: print 'type:', guess, 'encoding:', encoding + if not guess: print("I don't know anything about type", gtype) + else: print('type:', guess, 'encoding:', encoding) Modified: python/branches/p3yk/Lib/mimify.py ============================================================================== --- python/branches/p3yk/Lib/mimify.py (original) +++ python/branches/p3yk/Lib/mimify.py Fri Feb 9 06:37:30 2007 @@ -434,11 +434,11 @@ decode_base64 = 0 opts, args = getopt.getopt(sys.argv[1:], 'l:edb') if len(args) not in (0, 1, 2): - print usage + print(usage) sys.exit(1) if (('-e', '') in opts) == (('-d', '') in opts) or \ ((('-b', '') in opts) and (('-d', '') not in opts)): - print usage + print(usage) sys.exit(1) for o, a in opts: if o == '-e': @@ -449,7 +449,7 @@ try: MAXLEN = int(a) except (ValueError, OverflowError): - print usage + print(usage) sys.exit(1) elif o == '-b': decode_base64 = 1 Modified: python/branches/p3yk/Lib/modulefinder.py ============================================================================== --- python/branches/p3yk/Lib/modulefinder.py (original) +++ python/branches/p3yk/Lib/modulefinder.py Fri Feb 9 06:37:30 2007 @@ -89,11 +89,11 @@ def msg(self, level, str, *args): if level <= self.debug: for i in range(self.indent): - print " ", - print str, + print(" ", end=' ') + print(str, end=' ') for arg in args: - print repr(arg), - print + print(repr(arg), end=' ') + print() def msgin(self, *args): level = args[0] @@ -482,38 +482,38 @@ """Print a report to stdout, listing the found modules with their paths, as well as modules that are missing, or seem to be missing. """ - print - print " %-25s %s" % ("Name", "File") - print " %-25s %s" % ("----", "----") + print() + print(" %-25s %s" % ("Name", "File")) + print(" %-25s %s" % ("----", "----")) # Print modules found keys = self.modules.keys() keys.sort() for key in keys: m = self.modules[key] if m.__path__: - print "P", + print("P", end=' ') else: - print "m", - print "%-25s" % key, m.__file__ or "" + print("m", end=' ') + print("%-25s" % key, m.__file__ or "") # Print missing modules missing, maybe = self.any_missing_maybe() if missing: - print - print "Missing modules:" + print() + print("Missing modules:") for name in missing: mods = self.badmodules[name].keys() mods.sort() - print "?", name, "imported from", ', '.join(mods) + print("?", name, "imported from", ', '.join(mods)) # Print modules that may be missing, but then again, maybe not... if maybe: - print - print "Submodules thay appear to be missing, but could also be", - print "global names in the parent package:" + print() + print("Submodules thay appear to be missing, but could also be", end=' ') + print("global names in the parent package:") for name in maybe: mods = self.badmodules[name].keys() mods.sort() - print "?", name, "imported from", ', '.join(mods) + print("?", name, "imported from", ', '.join(mods)) def any_missing(self): """Return a list of modules that appear to be missing. Use @@ -603,7 +603,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") except getopt.error as msg: - print msg + print(msg) return # Process options @@ -634,9 +634,9 @@ path[0] = os.path.dirname(script) path = addpath + path if debug > 1: - print "path:" + print("path:") for item in path: - print " ", repr(item) + print(" ", repr(item)) # Create the module finder and turn its crank mf = ModuleFinder(path, debug, exclude) @@ -660,4 +660,4 @@ try: mf = test() except KeyboardInterrupt: - print "\n[interrupt]" + print("\n[interrupt]") Modified: python/branches/p3yk/Lib/msilib/__init__.py ============================================================================== --- python/branches/p3yk/Lib/msilib/__init__.py (original) +++ python/branches/p3yk/Lib/msilib/__init__.py Fri Feb 9 06:37:30 2007 @@ -40,7 +40,7 @@ index -= 1 unk = type & ~knownbits if unk: - print "%s.%s unknown bits %x" % (self.name, name, unk) + print("%s.%s unknown bits %x" % (self.name, name, unk)) size = type & datasizemask dtype = type & typemask if dtype == type_string: @@ -59,7 +59,7 @@ tname="OBJECT" else: tname="unknown" - print "%s.%sunknown integer type %d" % (self.name, name, size) + print("%s.%sunknown integer type %d" % (self.name, name, size)) if type & type_nullable: flags = "" else: Modified: python/branches/p3yk/Lib/netrc.py ============================================================================== --- python/branches/p3yk/Lib/netrc.py (original) +++ python/branches/p3yk/Lib/netrc.py Fri Feb 9 06:37:30 2007 @@ -108,4 +108,4 @@ return rep if __name__ == '__main__': - print netrc() + print(netrc()) Modified: python/branches/p3yk/Lib/nntplib.py ============================================================================== --- python/branches/p3yk/Lib/nntplib.py (original) +++ python/branches/p3yk/Lib/nntplib.py Fri Feb 9 06:37:30 2007 @@ -175,7 +175,7 @@ If the response code is 200, posting is allowed; if it 201, posting is not allowed.""" - if self.debugging: print '*welcome*', repr(self.welcome) + if self.debugging: print('*welcome*', repr(self.welcome)) return self.welcome def set_debuglevel(self, level): @@ -190,12 +190,12 @@ def putline(self, line): """Internal: send one line to the server, appending CRLF.""" line = line + CRLF - if self.debugging > 1: print '*put*', repr(line) + if self.debugging > 1: print('*put*', repr(line)) self.sock.sendall(line) def putcmd(self, line): """Internal: send one command to the server (through putline()).""" - if self.debugging: print '*cmd*', repr(line) + if self.debugging: print('*cmd*', repr(line)) self.putline(line) def getline(self): @@ -203,7 +203,7 @@ Raise EOFError if the connection is closed.""" line = self.file.readline() if self.debugging > 1: - print '*get*', repr(line) + print('*get*', repr(line)) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] @@ -213,7 +213,7 @@ """Internal: get a response from the server. Raise various errors if the response indicates an error.""" resp = self.getline() - if self.debugging: print '*resp*', repr(resp) + if self.debugging: print('*resp*', repr(resp)) c = resp[:1] if c == '4': raise NNTPTemporaryError(resp) @@ -618,11 +618,11 @@ mode = None s = NNTP(newshost, readermode=mode) resp, count, first, last, name = s.group('comp.lang.python') - print resp - print 'Group', name, 'has', count, 'articles, range', first, 'to', last + print(resp) + print('Group', name, 'has', count, 'articles, range', first, 'to', last) resp, subs = s.xhdr('subject', first + '-' + last) - print resp + print(resp) for item in subs: - print "%7s %s" % item + print("%7s %s" % item) resp = s.quit() - print resp + print(resp) Modified: python/branches/p3yk/Lib/optparse.py ============================================================================== --- python/branches/p3yk/Lib/optparse.py (original) +++ python/branches/p3yk/Lib/optparse.py Fri Feb 9 06:37:30 2007 @@ -1578,7 +1578,7 @@ or not defined. """ if self.usage: - print >>file, self.get_usage() + print(self.get_usage(), file=file) def get_version(self): if self.version: @@ -1595,7 +1595,7 @@ name. Does nothing if self.version is empty or undefined. """ if self.version: - print >>file, self.get_version() + print(self.get_version(), file=file) def format_option_help(self, formatter=None): if formatter is None: Modified: python/branches/p3yk/Lib/pdb.py ============================================================================== --- python/branches/p3yk/Lib/pdb.py (original) +++ python/branches/p3yk/Lib/pdb.py Fri Feb 9 06:37:30 2007 @@ -135,7 +135,7 @@ if self._wait_for_mainpyfile: return if self.stop_here(frame): - print >>self.stdout, '--Call--' + print('--Call--', file=self.stdout) self.interaction(frame, None) def user_line(self, frame): @@ -171,7 +171,7 @@ def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" frame.f_locals['__return__'] = return_value - print >>self.stdout, '--Return--' + print('--Return--', file=self.stdout) self.interaction(frame, None) def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): @@ -181,7 +181,7 @@ if type(exc_type) == type(''): exc_type_name = exc_type else: exc_type_name = exc_type.__name__ - print >>self.stdout, exc_type_name + ':', _saferepr(exc_value) + print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout) self.interaction(frame, exc_traceback) # General interaction function @@ -204,7 +204,7 @@ if type(t) == type(''): exc_type_name = t else: exc_type_name = t.__name__ - print >>self.stdout, '***', exc_type_name + ':', v + print('***', exc_type_name + ':', v, file=self.stdout) def precmd(self, line): """Handle alias expansion and ';;' separator.""" @@ -283,7 +283,7 @@ try: bnum = int(arg) except: - print >>self.stdout, "Usage : commands [bnum]\n ...\n end" + print("Usage : commands [bnum]\n ...\n end", file=self.stdout) return self.commands_bnum = bnum self.commands[bnum] = [] @@ -300,7 +300,7 @@ # break [ ([filename:]lineno | function) [, "condition"] ] if not arg: if self.breaks: # There's at least one - print >>self.stdout, "Num Type Disp Enb Where" + print("Num Type Disp Enb Where", file=self.stdout) for bp in bdb.Breakpoint.bpbynumber: if bp: bp.bpprint(self.stdout) @@ -322,8 +322,8 @@ filename = arg[:colon].rstrip() f = self.lookupmodule(filename) if not f: - print >>self.stdout, '*** ', repr(filename), - print >>self.stdout, 'not found from sys.path' + print('*** ', repr(filename), end=' ', file=self.stdout) + print('not found from sys.path', file=self.stdout) return else: filename = f @@ -331,7 +331,7 @@ try: lineno = int(arg) except ValueError as msg: - print >>self.stdout, '*** Bad lineno:', arg + print('*** Bad lineno:', arg, file=self.stdout) return else: # no colon; can be lineno or function @@ -357,10 +357,10 @@ # last thing to try (ok, filename, ln) = self.lineinfo(arg) if not ok: - print >>self.stdout, '*** The specified object', - print >>self.stdout, repr(arg), - print >>self.stdout, 'is not a function' - print >>self.stdout, 'or was not found along sys.path.' + print('*** The specified object', end=' ', file=self.stdout) + print(repr(arg), end=' ', file=self.stdout) + print('is not a function', file=self.stdout) + print('or was not found along sys.path.', file=self.stdout) return funcname = ok # ok contains a function name lineno = int(ln) @@ -371,12 +371,12 @@ if line: # now set the break point err = self.set_break(filename, line, temporary, cond, funcname) - if err: print >>self.stdout, '***', err + if err: print('***', err, file=self.stdout) else: bp = self.get_breaks(filename, line)[-1] - print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number, + print("Breakpoint %d at %s:%d" % (bp.number, bp.file, - bp.line) + bp.line), file=self.stdout) # To be overridden in derived debuggers def defaultFile(self): @@ -432,13 +432,13 @@ """ line = linecache.getline(filename, lineno) if not line: - print >>self.stdout, 'End of file' + print('End of file', file=self.stdout) return 0 line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): - print >>self.stdout, '*** Blank or comment' + print('*** Blank or comment', file=self.stdout) return 0 return lineno @@ -448,11 +448,11 @@ try: i = int(i) except ValueError: - print >>self.stdout, 'Breakpoint index %r is not a number' % i + print('Breakpoint index %r is not a number' % i, file=self.stdout) continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): - print >>self.stdout, 'No breakpoint numbered', i + print('No breakpoint numbered', i, file=self.stdout) continue bp = bdb.Breakpoint.bpbynumber[i] @@ -465,11 +465,11 @@ try: i = int(i) except ValueError: - print >>self.stdout, 'Breakpoint index %r is not a number' % i + print('Breakpoint index %r is not a number' % i, file=self.stdout) continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): - print >>self.stdout, 'No breakpoint numbered', i + print('No breakpoint numbered', i, file=self.stdout) continue bp = bdb.Breakpoint.bpbynumber[i] @@ -483,8 +483,7 @@ bpnum = int(args[0].strip()) except ValueError: # something went wrong - print >>self.stdout, \ - 'Breakpoint index %r is not a number' % args[0] + print('Breakpoint index %r is not a number' % args[0], file=self.stdout) try: cond = args[1] except: @@ -493,8 +492,8 @@ if bp: bp.cond = cond if not cond: - print >>self.stdout, 'Breakpoint', bpnum, - print >>self.stdout, 'is now unconditional.' + print('Breakpoint', bpnum, end=' ', file=self.stdout) + print('is now unconditional.', file=self.stdout) def do_ignore(self,arg): """arg is bp number followed by ignore count.""" @@ -503,8 +502,7 @@ bpnum = int(args[0].strip()) except ValueError: # something went wrong - print >>self.stdout, \ - 'Breakpoint index %r is not a number' % args[0] + print('Breakpoint index %r is not a number' % args[0], file=self.stdout) try: count = int(args[1].strip()) except: @@ -518,10 +516,10 @@ reply = reply + '%d crossings' % count else: reply = reply + '1 crossing' - print >>self.stdout, reply + ' of breakpoint %d.' % bpnum + print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout) else: - print >>self.stdout, 'Will stop next time breakpoint', - print >>self.stdout, bpnum, 'is reached.' + print('Will stop next time breakpoint', end=' ', file=self.stdout) + print(bpnum, 'is reached.', file=self.stdout) def do_clear(self, arg): """Three possibilities, tried in this order: @@ -548,24 +546,24 @@ err = "Invalid line number (%s)" % arg else: err = self.clear_break(filename, lineno) - if err: print >>self.stdout, '***', err + if err: print('***', err, file=self.stdout) return numberlist = arg.split() for i in numberlist: try: i = int(i) except ValueError: - print >>self.stdout, 'Breakpoint index %r is not a number' % i + print('Breakpoint index %r is not a number' % i, file=self.stdout) continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): - print >>self.stdout, 'No breakpoint numbered', i + print('No breakpoint numbered', i, file=self.stdout) continue err = self.clear_bpbynumber(i) if err: - print >>self.stdout, '***', err + print('***', err, file=self.stdout) else: - print >>self.stdout, 'Deleted breakpoint', i + print('Deleted breakpoint', i, file=self.stdout) do_cl = do_clear # 'c' is already an abbreviation for 'continue' def do_where(self, arg): @@ -575,7 +573,7 @@ def do_up(self, arg): if self.curindex == 0: - print >>self.stdout, '*** Oldest frame' + print('*** Oldest frame', file=self.stdout) else: self.curindex = self.curindex - 1 self.curframe = self.stack[self.curindex][0] @@ -585,7 +583,7 @@ def do_down(self, arg): if self.curindex + 1 == len(self.stack): - print >>self.stdout, '*** Newest frame' + print('*** Newest frame', file=self.stdout) else: self.curindex = self.curindex + 1 self.curframe = self.stack[self.curindex][0] @@ -615,12 +613,12 @@ def do_jump(self, arg): if self.curindex + 1 != len(self.stack): - print >>self.stdout, "*** You can only jump within the bottom frame" + print("*** You can only jump within the bottom frame", file=self.stdout) return try: arg = int(arg) except ValueError: - print >>self.stdout, "*** The 'jump' command requires a line number." + print("*** The 'jump' command requires a line number.", file=self.stdout) else: try: # Do the jump, fix up our copy of the stack, and display the @@ -629,7 +627,7 @@ self.stack[self.curindex] = self.stack[self.curindex][0], arg self.print_stack_entry(self.stack[self.curindex]) except ValueError as e: - print >>self.stdout, '*** Jump failed:', e + print('*** Jump failed:', e, file=self.stdout) do_j = do_jump def do_debug(self, arg): @@ -638,9 +636,9 @@ locals = self.curframe.f_locals p = Pdb() p.prompt = "(%s) " % self.prompt.strip() - print >>self.stdout, "ENTERING RECURSIVE DEBUGGER" + print("ENTERING RECURSIVE DEBUGGER", file=self.stdout) sys.call_tracing(p.run, (arg, globals, locals)) - print >>self.stdout, "LEAVING RECURSIVE DEBUGGER" + print("LEAVING RECURSIVE DEBUGGER", file=self.stdout) sys.settrace(self.trace_dispatch) self.lastcmd = p.lastcmd @@ -653,7 +651,7 @@ do_exit = do_quit def do_EOF(self, arg): - print >>self.stdout + print(file=self.stdout) self._user_requested_quit = 1 self.set_quit() return 1 @@ -667,16 +665,16 @@ if co.co_flags & 8: n = n+1 for i in range(n): name = co.co_varnames[i] - print >>self.stdout, name, '=', - if name in dict: print >>self.stdout, dict[name] - else: print >>self.stdout, "*** undefined ***" + print(name, '=', end=' ', file=self.stdout) + if name in dict: print(dict[name], file=self.stdout) + else: print("*** undefined ***", file=self.stdout) do_a = do_args def do_retval(self, arg): if '__return__' in self.curframe.f_locals: - print >>self.stdout, self.curframe.f_locals['__return__'] + print(self.curframe.f_locals['__return__'], file=self.stdout) else: - print >>self.stdout, '*** Not yet returned!' + print('*** Not yet returned!', file=self.stdout) do_rv = do_retval def _getval(self, arg): @@ -688,12 +686,12 @@ if isinstance(t, str): exc_type_name = t else: exc_type_name = t.__name__ - print >>self.stdout, '***', exc_type_name + ':', repr(v) + print('***', exc_type_name + ':', repr(v), file=self.stdout) raise def do_p(self, arg): try: - print >>self.stdout, repr(self._getval(arg)) + print(repr(self._getval(arg)), file=self.stdout) except: pass @@ -719,7 +717,7 @@ else: first = max(1, int(x) - 5) except: - print >>self.stdout, '*** Error in argument:', repr(arg) + print('*** Error in argument:', repr(arg), file=self.stdout) return elif self.lineno is None: first = max(1, self.curframe.f_lineno - 5) @@ -733,7 +731,7 @@ for lineno in range(first, last+1): line = linecache.getline(filename, lineno) if not line: - print >>self.stdout, '[EOF]' + print('[EOF]', file=self.stdout) break else: s = repr(lineno).rjust(3) @@ -742,7 +740,7 @@ else: s = s + ' ' if lineno == self.curframe.f_lineno: s = s + '->' - print >>self.stdout, s + '\t' + line, + print(s + '\t' + line, end=' ', file=self.stdout) self.lineno = lineno except KeyboardInterrupt: pass @@ -757,23 +755,23 @@ if type(t) == type(''): exc_type_name = t else: exc_type_name = t.__name__ - print >>self.stdout, '***', exc_type_name + ':', repr(v) + print('***', exc_type_name + ':', repr(v), file=self.stdout) return code = None # Is it a function? try: code = value.func_code except: pass if code: - print >>self.stdout, 'Function', code.co_name + print('Function', code.co_name, file=self.stdout) return # Is it an instance method? try: code = value.im_func.func_code except: pass if code: - print >>self.stdout, 'Method', code.co_name + print('Method', code.co_name, file=self.stdout) return # None of the above... - print >>self.stdout, type(value) + print(type(value), file=self.stdout) def do_alias(self, arg): args = arg.split() @@ -781,10 +779,10 @@ keys = self.aliases.keys() keys.sort() for alias in keys: - print >>self.stdout, "%s = %s" % (alias, self.aliases[alias]) + print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout) return if args[0] in self.aliases and len(args) == 1: - print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]]) + print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout) else: self.aliases[args[0]] = ' '.join(args[1:]) @@ -816,11 +814,11 @@ def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix): frame, lineno = frame_lineno if frame is self.curframe: - print >>self.stdout, '>', + print('>', end=' ', file=self.stdout) else: - print >>self.stdout, ' ', - print >>self.stdout, self.format_stack_entry(frame_lineno, - prompt_prefix) + print(' ', end=' ', file=self.stdout) + print(self.format_stack_entry(frame_lineno, + prompt_prefix), file=self.stdout) # Help methods (derived from pdb.doc) @@ -829,20 +827,20 @@ self.help_h() def help_h(self): - print >>self.stdout, """h(elp) + print("""h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command "help pdb" pipes the full documentation file to the $PAGER -"help exec" gives help on the ! command""" +"help exec" gives help on the ! command""", file=self.stdout) def help_where(self): self.help_w() def help_w(self): - print >>self.stdout, """w(here) + print("""w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the "current frame", which determines the -context of most commands. 'bt' is an alias for this command.""" +context of most commands. 'bt' is an alias for this command.""", file=self.stdout) help_bt = help_w @@ -850,23 +848,23 @@ self.help_d() def help_d(self): - print >>self.stdout, """d(own) + print("""d(own) Move the current frame one level down in the stack trace -(to a newer frame).""" +(to a newer frame).""", file=self.stdout) def help_up(self): self.help_u() def help_u(self): - print >>self.stdout, """u(p) + print("""u(p) Move the current frame one level up in the stack trace -(to an older frame).""" +(to an older frame).""", file=self.stdout) def help_break(self): self.help_b() def help_b(self): - print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition] + print("""b(reak) ([file:]lineno | function) [, condition] With a line number argument, set a break there in the current file. With a function name, set a break at first executable line of that function. Without argument, list all breaks. If a second @@ -876,14 +874,14 @@ The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet). The file is searched for on sys.path; -the .py suffix may be omitted.""" +the .py suffix may be omitted.""", file=self.stdout) def help_clear(self): self.help_cl() def help_cl(self): - print >>self.stdout, "cl(ear) filename:lineno" - print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]] + print("cl(ear) filename:lineno", file=self.stdout) + print("""cl(ear) [bpnumber [bpnumber...]] With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, @@ -892,59 +890,59 @@ Note that the argument is different from previous versions of the debugger (in python distributions 1.5.1 and before) where a linenumber was used instead of either filename:lineno or -breakpoint numbers.""" +breakpoint numbers.""", file=self.stdout) def help_tbreak(self): - print >>self.stdout, """tbreak same arguments as break, but breakpoint is -removed when first hit.""" + print("""tbreak same arguments as break, but breakpoint is +removed when first hit.""", file=self.stdout) def help_enable(self): - print >>self.stdout, """enable bpnumber [bpnumber ...] + print("""enable bpnumber [bpnumber ...] Enables the breakpoints given as a space separated list of -bp numbers.""" +bp numbers.""", file=self.stdout) def help_disable(self): - print >>self.stdout, """disable bpnumber [bpnumber ...] + print("""disable bpnumber [bpnumber ...] Disables the breakpoints given as a space separated list of -bp numbers.""" +bp numbers.""", file=self.stdout) def help_ignore(self): - print >>self.stdout, """ignore bpnumber count + print("""ignore bpnumber count Sets the ignore count for the given breakpoint number. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates -to true.""" +to true.""", file=self.stdout) def help_condition(self): - print >>self.stdout, """condition bpnumber str_condition + print("""condition bpnumber str_condition str_condition is a string specifying an expression which must evaluate to true before the breakpoint is honored. If str_condition is absent, any existing condition is removed; -i.e., the breakpoint is made unconditional.""" +i.e., the breakpoint is made unconditional.""", file=self.stdout) def help_step(self): self.help_s() def help_s(self): - print >>self.stdout, """s(tep) + print("""s(tep) Execute the current line, stop at the first possible occasion -(either in a function that is called or in the current function).""" +(either in a function that is called or in the current function).""", file=self.stdout) def help_next(self): self.help_n() def help_n(self): - print >>self.stdout, """n(ext) + print("""n(ext) Continue execution until the next line in the current function -is reached or it returns.""" +is reached or it returns.""", file=self.stdout) def help_return(self): self.help_r() def help_r(self): - print >>self.stdout, """r(eturn) -Continue execution until the current function returns.""" + print("""r(eturn) +Continue execution until the current function returns.""", file=self.stdout) def help_continue(self): self.help_c() @@ -953,51 +951,51 @@ self.help_c() def help_c(self): - print >>self.stdout, """c(ont(inue)) -Continue execution, only stop when a breakpoint is encountered.""" + print("""c(ont(inue)) +Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout) def help_jump(self): self.help_j() def help_j(self): - print >>self.stdout, """j(ump) lineno -Set the next line that will be executed.""" + print("""j(ump) lineno +Set the next line that will be executed.""", file=self.stdout) def help_debug(self): - print >>self.stdout, """debug code + print("""debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed -in the current environment).""" +in the current environment).""", file=self.stdout) def help_list(self): self.help_l() def help_l(self): - print >>self.stdout, """l(ist) [first [,last]] + print("""l(ist) [first [,last]] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With one argument, list 11 lines starting at that line. With two arguments, list the given range; -if the second argument is less than the first, it is a count.""" +if the second argument is less than the first, it is a count.""", file=self.stdout) def help_args(self): self.help_a() def help_a(self): - print >>self.stdout, """a(rgs) -Print the arguments of the current function.""" + print("""a(rgs) +Print the arguments of the current function.""", file=self.stdout) def help_p(self): - print >>self.stdout, """p expression -Print the value of the expression.""" + print("""p expression +Print the value of the expression.""", file=self.stdout) def help_pp(self): - print >>self.stdout, """pp expression -Pretty-print the value of the expression.""" + print("""pp expression +Pretty-print the value of the expression.""", file=self.stdout) def help_exec(self): - print >>self.stdout, """(!) statement + print("""(!) statement Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word @@ -1005,27 +1003,27 @@ To assign to a global variable you must always prefix the command with a 'global' command, e.g.: (Pdb) global list_options; list_options = ['-l'] -(Pdb)""" +(Pdb)""", file=self.stdout) def help_quit(self): self.help_q() def help_q(self): - print >>self.stdout, """q(uit) or exit - Quit from the debugger. -The program being executed is aborted.""" + print("""q(uit) or exit - Quit from the debugger. +The program being executed is aborted.""", file=self.stdout) help_exit = help_q def help_whatis(self): - print >>self.stdout, """whatis arg -Prints the type of the argument.""" + print("""whatis arg +Prints the type of the argument.""", file=self.stdout) def help_EOF(self): - print >>self.stdout, """EOF -Handles the receipt of EOF as a command.""" + print("""EOF +Handles the receipt of EOF as a command.""", file=self.stdout) def help_alias(self): - print >>self.stdout, """alias [name [command [parameter parameter ...] ]] + print("""alias [name [command [parameter parameter ...] ]] Creates an alias called 'name' the executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters are indicated by %1, %2, and so on, while %* is replaced by all the @@ -1046,14 +1044,14 @@ #Print instance variables in self alias ps pi self -""" +""", file=self.stdout) def help_unalias(self): - print >>self.stdout, """unalias name -Deletes the specified alias.""" + print("""unalias name +Deletes the specified alias.""", file=self.stdout) def help_commands(self): - print >>self.stdout, """commands [bpnumber] + print("""commands [bpnumber] (com) ... (com) end (Pdb) @@ -1085,7 +1083,7 @@ be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you see no sign that the breakpoint was reached. -""" +""", file=self.stdout) def help_pdb(self): help() @@ -1176,20 +1174,20 @@ fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) - if sts: print '*** Pager exit status:', sts + if sts: print('*** Pager exit status:', sts) break else: - print 'Sorry, can\'t find the help file "pdb.doc"', - print 'along the Python search path' + print('Sorry, can\'t find the help file "pdb.doc"', end=' ') + print('along the Python search path') def main(): if not sys.argv[1:]: - print "usage: pdb.py scriptfile [arg] ..." + print("usage: pdb.py scriptfile [arg] ...") sys.exit(2) mainpyfile = sys.argv[1] # Get script filename if not os.path.exists(mainpyfile): - print 'Error:', mainpyfile, 'does not exist' + print('Error:', mainpyfile, 'does not exist') sys.exit(1) del sys.argv[0] # Hide "pdb.py" from argument list @@ -1208,20 +1206,20 @@ pdb._runscript(mainpyfile) if pdb._user_requested_quit: break - print "The program finished and will be restarted" + print("The program finished and will be restarted") except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. - print "The program exited via sys.exit(). Exit status: ", - print sys.exc_info()[1] + print("The program exited via sys.exit(). Exit status: ", end=' ') + print(sys.exc_info()[1]) except: traceback.print_exc() - print "Uncaught exception. Entering post mortem debugging" - print "Running 'cont' or 'step' will restart the program" + print("Uncaught exception. Entering post mortem debugging") + print("Running 'cont' or 'step' will restart the program") t = sys.exc_info()[2] while t.tb_next is not None: t = t.tb_next pdb.interaction(t.tb_frame,t) - print "Post mortem debugger finished. The "+mainpyfile+" will be restarted" + print("Post mortem debugger finished. The "+mainpyfile+" will be restarted") # When invoked as main program, invoke the debugger on a script Modified: python/branches/p3yk/Lib/pickletools.py ============================================================================== --- python/branches/p3yk/Lib/pickletools.py (original) +++ python/branches/p3yk/Lib/pickletools.py Fri Feb 9 06:37:30 2007 @@ -1757,18 +1757,18 @@ for name in pickle.__all__: if not re.match("[A-Z][A-Z0-9_]+$", name): if verbose: - print "skipping %r: it doesn't look like an opcode name" % name + print("skipping %r: it doesn't look like an opcode name" % name) continue picklecode = getattr(pickle, name) if not isinstance(picklecode, str) or len(picklecode) != 1: if verbose: - print ("skipping %r: value %r doesn't look like a pickle " - "code" % (name, picklecode)) + print(("skipping %r: value %r doesn't look like a pickle " + "code" % (name, picklecode))) continue if picklecode in copy: if verbose: - print "checking name %r w/ code %r for consistency" % ( - name, picklecode) + print("checking name %r w/ code %r for consistency" % ( + name, picklecode)) d = copy[picklecode] if d.name != name: raise ValueError("for pickle code %r, pickle.py uses name %r " @@ -1899,7 +1899,7 @@ errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: - print >> out, "%5d:" % pos, + print("%5d:" % pos, end=' ', file=out) line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), @@ -1964,7 +1964,7 @@ line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg - print >> out, line + print(line, file=out) if errormsg: # Note that we delayed complaining until the offending opcode @@ -1983,7 +1983,7 @@ stack.extend(after) - print >> out, "highest protocol among opcodes =", maxproto + print("highest protocol among opcodes =", maxproto, file=out) if stack: raise ValueError("stack not empty after STOP: %r" % stack) Modified: python/branches/p3yk/Lib/pipes.py ============================================================================== --- python/branches/p3yk/Lib/pipes.py (original) +++ python/branches/p3yk/Lib/pipes.py Fri Feb 9 06:37:30 2007 @@ -188,7 +188,7 @@ def makepipeline(self, infile, outfile): cmd = makepipeline(infile, self.steps, outfile) if self.debugging: - print cmd + print(cmd) cmd = 'set -x; ' + cmd return cmd @@ -286,7 +286,7 @@ # Small test program and example def test(): - print 'Testing...' + print('Testing...') t = Template() t.append('togif $IN $OUT', 'ff') t.append('giftoppm', '--') @@ -295,4 +295,4 @@ t.debug(1) FILE = '/usr/local/images/rgb/rogues/guido.rgb' t.copy(FILE, '@temp') - print 'Done.' + print('Done.') Modified: python/branches/p3yk/Lib/plat-irix5/cddb.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix5/cddb.py (original) +++ python/branches/p3yk/Lib/plat-irix5/cddb.py Fri Feb 9 06:37:30 2007 @@ -89,7 +89,7 @@ break match = reg.match(line) if not match: - print 'syntax error in ' + file + print('syntax error in ' + file) continue name1, name2, value = match.group(1, 2, 3) if name1 == 'album': @@ -101,17 +101,17 @@ if not self.toc: self.toc = value if self.toc != value: - print 'toc\'s don\'t match' + print('toc\'s don\'t match') elif name2 == 'notes': self.notes.append(value) elif name1[:5] == 'track': try: trackno = int(name1[5:]) except strings.atoi_error: - print 'syntax error in ' + file + print('syntax error in ' + file) continue if trackno > ntracks: - print 'track number %r in file %r out of range' % (trackno, file) + print('track number %r in file %r out of range' % (trackno, file)) continue if name2 == 'title': self.track[trackno] = value Modified: python/branches/p3yk/Lib/plat-irix5/cdplayer.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix5/cdplayer.py (original) +++ python/branches/p3yk/Lib/plat-irix5/cdplayer.py Fri Feb 9 06:37:30 2007 @@ -51,7 +51,7 @@ line = line[l:] match = reg.match(line) if not match: - print 'syntax error in ~/' + cdplayerrc + print('syntax error in ~/' + cdplayerrc) continue name, value = match.group(1, 2) if name == 'title': Modified: python/branches/p3yk/Lib/plat-irix5/flp.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix5/flp.py (original) +++ python/branches/p3yk/Lib/plat-irix5/flp.py Fri Feb 9 06:37:30 2007 @@ -66,7 +66,7 @@ return None try: if fp.read(4) != MAGIC: - print 'flp: bad magic word in cache file', cachename + print('flp: bad magic word in cache file', cachename) return None cache_mtime = rdlong(fp) file_mtime = getmtime(filename) @@ -122,7 +122,7 @@ try: fp = open(cachename, 'w') except IOError: - print 'flp: can\'t create cache file', cachename + print('flp: can\'t create cache file', cachename) return # Never mind fp.write('\0\0\0\0') # Seek back and write MAGIC when done wrlong(fp, getmtime(filename)) @@ -145,8 +145,8 @@ def freeze(filename): forms = parse_forms(filename) altforms = _pack_cache(forms) - print 'import flp' - print 'flp._internal_cache[', repr(filename), '] =', altforms + print('import flp') + print('flp._internal_cache[', repr(filename), '] =', altforms) # # Internal: create the data structure to be placed in the cache @@ -426,7 +426,7 @@ if len(sys.argv) == 2: forms = parse_forms(sys.argv[1]) t1 = time.time() - print 'parse time:', 0.001*(t1-t0), 'sec.' + print('parse time:', 0.001*(t1-t0), 'sec.') keys = forms.keys() keys.sort() for i in keys: @@ -434,18 +434,18 @@ elif len(sys.argv) == 3: form = parse_form(sys.argv[1], sys.argv[2]) t1 = time.time() - print 'parse time:', round(t1-t0, 3), 'sec.' + print('parse time:', round(t1-t0, 3), 'sec.') _printform(form) else: - print 'Usage: test fdfile [form]' + print('Usage: test fdfile [form]') def _printform(form): f = form[0] objs = form[1] - print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects + print('Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects) for i in objs: - print ' Obj ', i.Name, ' type ', i.Class, i.Type - print ' Box ', i.Box, ' btype ', i.Boxtype - print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment - print ' cols ', i.Colors - print ' cback ', i.Callback, i.Argument + print(' Obj ', i.Name, ' type ', i.Class, i.Type) + print(' Box ', i.Box, ' btype ', i.Boxtype) + print(' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment) + print(' cols ', i.Colors) + print(' cback ', i.Callback, i.Argument) Modified: python/branches/p3yk/Lib/plat-irix5/panel.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix5/panel.py (original) +++ python/branches/p3yk/Lib/plat-irix5/panel.py Fri Feb 9 06:37:30 2007 @@ -62,18 +62,18 @@ def show_actuator(prefix, a): for item in a: if not is_list(item): - print prefix, item + print(prefix, item) elif item and item[0] == 'al': - print prefix, 'Subactuator list:' + print(prefix, 'Subactuator list:') for a in item[1:]: show_actuator(prefix + ' ', a) elif len(item) == 2: - print prefix, item[0], '=>', item[1] + print(prefix, item[0], '=>', item[1]) elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] + print(prefix, 'Prop', item[1], '=>', end=' ') + print(item[2]) else: - print prefix, '?', item + print(prefix, '?', item) # Neatly display a panel. @@ -81,18 +81,18 @@ def show_panel(prefix, p): for item in p: if not is_list(item): - print prefix, item + print(prefix, item) elif item and item[0] == 'al': - print prefix, 'Actuator list:' + print(prefix, 'Actuator list:') for a in item[1:]: show_actuator(prefix + ' ', a) elif len(item) == 2: - print prefix, item[0], '=>', item[1] + print(prefix, item[0], '=>', item[1]) elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] + print(prefix, 'Prop', item[1], '=>', end=' ') + print(item[2]) else: - print prefix, '?', item + print(prefix, '?', item) # Exception raised by build_actuator or build_panel. @@ -123,18 +123,18 @@ # Strange default set by Panel Editor... ok = 0 else: - print 'unknown value', value, 'for', name + print('unknown value', value, 'for', name) ok = 0 if ok: lhs = 'target.' + prefix + name stmt = lhs + '=' + repr(value) - if debug: print 'exec', stmt + if debug: print('exec', stmt) try: exec(stmt + '\n') except KeyboardInterrupt: # Don't catch this! raise KeyboardInterrupt except: - print 'assign failed:', stmt + print('assign failed:', stmt) # Build a real actuator from an actuator description. @@ -185,7 +185,7 @@ act.addsubact(super_act) if name: stmt = 'panel.' + name + ' = act' - if debug: print 'exec', stmt + if debug: print('exec', stmt) exec(stmt + '\n') if is_endgroup(a): panel.endgroup() Modified: python/branches/p3yk/Lib/plat-irix6/cddb.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix6/cddb.py (original) +++ python/branches/p3yk/Lib/plat-irix6/cddb.py Fri Feb 9 06:37:30 2007 @@ -89,7 +89,7 @@ break match = reg.match(line) if not match: - print 'syntax error in ' + file + print('syntax error in ' + file) continue name1, name2, value = match.group(1, 2, 3) if name1 == 'album': @@ -101,17 +101,17 @@ if not self.toc: self.toc = value if self.toc != value: - print 'toc\'s don\'t match' + print('toc\'s don\'t match') elif name2 == 'notes': self.notes.append(value) elif name1[:5] == 'track': try: trackno = int(name1[5:]) except ValueError: - print 'syntax error in ' + file + print('syntax error in ' + file) continue if trackno > ntracks: - print 'track number %r in file %s out of range' % (trackno, file) + print('track number %r in file %s out of range' % (trackno, file)) continue if name2 == 'title': self.track[trackno] = value Modified: python/branches/p3yk/Lib/plat-irix6/cdplayer.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix6/cdplayer.py (original) +++ python/branches/p3yk/Lib/plat-irix6/cdplayer.py Fri Feb 9 06:37:30 2007 @@ -51,7 +51,7 @@ line = line[l:] match = reg.match(line) if not match: - print 'syntax error in ~/' + cdplayerrc + print('syntax error in ~/' + cdplayerrc) continue name, value = match.group(1, 2) if name == 'title': Modified: python/branches/p3yk/Lib/plat-irix6/flp.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix6/flp.py (original) +++ python/branches/p3yk/Lib/plat-irix6/flp.py Fri Feb 9 06:37:30 2007 @@ -65,7 +65,7 @@ return None try: if fp.read(4) != MAGIC: - print 'flp: bad magic word in cache file', cachename + print('flp: bad magic word in cache file', cachename) return None cache_mtime = rdlong(fp) file_mtime = getmtime(filename) @@ -121,7 +121,7 @@ try: fp = open(cachename, 'w') except IOError: - print 'flp: can\'t create cache file', cachename + print('flp: can\'t create cache file', cachename) return # Never mind fp.write('\0\0\0\0') # Seek back and write MAGIC when done wrlong(fp, getmtime(filename)) @@ -144,8 +144,8 @@ def freeze(filename): forms = parse_forms(filename) altforms = _pack_cache(forms) - print 'import flp' - print 'flp._internal_cache[', repr(filename), '] =', altforms + print('import flp') + print('flp._internal_cache[', repr(filename), '] =', altforms) # # Internal: create the data structure to be placed in the cache @@ -425,7 +425,7 @@ if len(sys.argv) == 2: forms = parse_forms(sys.argv[1]) t1 = time.time() - print 'parse time:', 0.001*(t1-t0), 'sec.' + print('parse time:', 0.001*(t1-t0), 'sec.') keys = forms.keys() keys.sort() for i in keys: @@ -433,18 +433,18 @@ elif len(sys.argv) == 3: form = parse_form(sys.argv[1], sys.argv[2]) t1 = time.time() - print 'parse time:', round(t1-t0, 3), 'sec.' + print('parse time:', round(t1-t0, 3), 'sec.') _printform(form) else: - print 'Usage: test fdfile [form]' + print('Usage: test fdfile [form]') def _printform(form): f = form[0] objs = form[1] - print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects + print('Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects) for i in objs: - print ' Obj ', i.Name, ' type ', i.Class, i.Type - print ' Box ', i.Box, ' btype ', i.Boxtype - print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment - print ' cols ', i.Colors - print ' cback ', i.Callback, i.Argument + print(' Obj ', i.Name, ' type ', i.Class, i.Type) + print(' Box ', i.Box, ' btype ', i.Boxtype) + print(' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment) + print(' cols ', i.Colors) + print(' cback ', i.Callback, i.Argument) Modified: python/branches/p3yk/Lib/plat-irix6/panel.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix6/panel.py (original) +++ python/branches/p3yk/Lib/plat-irix6/panel.py Fri Feb 9 06:37:30 2007 @@ -62,18 +62,18 @@ def show_actuator(prefix, a): for item in a: if not is_list(item): - print prefix, item + print(prefix, item) elif item and item[0] == 'al': - print prefix, 'Subactuator list:' + print(prefix, 'Subactuator list:') for a in item[1:]: show_actuator(prefix + ' ', a) elif len(item) == 2: - print prefix, item[0], '=>', item[1] + print(prefix, item[0], '=>', item[1]) elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] + print(prefix, 'Prop', item[1], '=>', end=' ') + print(item[2]) else: - print prefix, '?', item + print(prefix, '?', item) # Neatly display a panel. @@ -81,18 +81,18 @@ def show_panel(prefix, p): for item in p: if not is_list(item): - print prefix, item + print(prefix, item) elif item and item[0] == 'al': - print prefix, 'Actuator list:' + print(prefix, 'Actuator list:') for a in item[1:]: show_actuator(prefix + ' ', a) elif len(item) == 2: - print prefix, item[0], '=>', item[1] + print(prefix, item[0], '=>', item[1]) elif len(item) == 3 and item[0] == 'prop': - print prefix, 'Prop', item[1], '=>', - print item[2] + print(prefix, 'Prop', item[1], '=>', end=' ') + print(item[2]) else: - print prefix, '?', item + print(prefix, '?', item) # Exception raised by build_actuator or build_panel. @@ -123,18 +123,18 @@ # Strange default set by Panel Editor... ok = 0 else: - print 'unknown value', value, 'for', name + print('unknown value', value, 'for', name) ok = 0 if ok: lhs = 'target.' + prefix + name stmt = lhs + '=' + repr(value) - if debug: print 'exec', stmt + if debug: print('exec', stmt) try: exec(stmt + '\n') except KeyboardInterrupt: # Don't catch this! raise KeyboardInterrupt except: - print 'assign failed:', stmt + print('assign failed:', stmt) # Build a real actuator from an actuator description. @@ -185,7 +185,7 @@ act.addsubact(super_act) if name: stmt = 'panel.' + name + ' = act' - if debug: print 'exec', stmt + if debug: print('exec', stmt) exec(stmt + '\n') if is_endgroup(a): panel.endgroup() Modified: python/branches/p3yk/Lib/plat-mac/Audio_mac.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Audio_mac.py (original) +++ python/branches/p3yk/Lib/plat-mac/Audio_mac.py Fri Feb 9 06:37:30 2007 @@ -104,7 +104,7 @@ fn = EasyDialogs.AskFileForOpen(message="Select an AIFF soundfile", typeList=("AIFF",)) if not fn: return af = aifc.open(fn, 'r') - print af.getparams() + print(af.getparams()) p = Play_Audio_mac() p.setoutrate(af.getframerate()) p.setsampwidth(af.getsampwidth()) @@ -114,7 +114,7 @@ data = af.readframes(BUFSIZ) if not data: break p.writeframes(data) - print 'wrote', len(data), 'space', p.getfillable() + print('wrote', len(data), 'space', p.getfillable()) p.wait() if __name__ == '__main__': Modified: python/branches/p3yk/Lib/plat-mac/EasyDialogs.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/EasyDialogs.py (original) +++ python/branches/p3yk/Lib/plat-mac/EasyDialogs.py Fri Feb 9 06:37:30 2007 @@ -75,7 +75,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return h = d.GetDialogItemAsControl(2) SetDialogItemText(h, lf2cr(msg)) @@ -108,7 +108,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return h = d.GetDialogItemAsControl(3) SetDialogItemText(h, lf2cr(prompt)) @@ -150,7 +150,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return h = d.GetDialogItemAsControl(3) SetDialogItemText(h, lf2cr(prompt)) @@ -194,7 +194,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return # Button assignments: # 1 = default (invisible) @@ -429,7 +429,7 @@ _interact() d = GetNewDialog(id, -1) if not d: - print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)" + print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)") return # h = d.GetDialogItemAsControl(3) # SetDialogItemText(h, lf2cr(prompt)) @@ -791,7 +791,7 @@ argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0) Message("Command line: %s"%' '.join(argv)) for i in range(len(argv)): - print 'arg[%d] = %r' % (i, argv[i]) + print('arg[%d] = %r' % (i, argv[i])) ok = AskYesNoCancel("Do you want to proceed?") ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No") if ok > 0: Modified: python/branches/p3yk/Lib/plat-mac/FrameWork.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/FrameWork.py (original) +++ python/branches/p3yk/Lib/plat-mac/FrameWork.py Fri Feb 9 06:37:30 2007 @@ -250,7 +250,7 @@ if window in self._windows: self._windows[window].do_itemhit(item, event) else: - print 'Dialog event for unknown dialog' + print('Dialog event for unknown dialog') return 1 return 0 @@ -323,14 +323,14 @@ def do_unknownpartcode(self, partcode, window, event): (what, message, when, where, modifiers) = event - if DEBUG: print "Mouse down at global:", where - if DEBUG: print "\tUnknown part code:", partcode - if DEBUG: print "\tEvent:", self.printevent(event) + if DEBUG: print("Mouse down at global:", where) + if DEBUG: print("\tUnknown part code:", partcode) + if DEBUG: print("\tEvent:", self.printevent(event)) if hasattr(MacOS, 'HandleEvent'): MacOS.HandleEvent(event) def do_unknownwindow(self, partcode, window, event): - if DEBUG: print 'Unknown window:', window + if DEBUG: print('Unknown window:', window) if hasattr(MacOS, 'HandleEvent'): MacOS.HandleEvent(event) @@ -373,7 +373,7 @@ # else it wasn't for us, sigh... def do_char(self, c, event): - if DEBUG: print "Character", repr(c) + if DEBUG: print("Character", repr(c)) def do_updateEvt(self, event): (what, message, when, where, modifiers) = event @@ -402,7 +402,7 @@ self.do_suspendresume(event) else: if DEBUG: - print 'unknown osEvt:', + print('unknown osEvt:', end=' ') self.printevent(event) def do_suspendresume(self, event): @@ -415,7 +415,7 @@ def do_kHighLevelEvent(self, event): (what, message, when, where, modifiers) = event if DEBUG: - print "High Level Event:", + print("High Level Event:", end=' ') self.printevent(event) try: AEProcessAppleEvent(event) @@ -426,7 +426,7 @@ def do_unknownevent(self, event): if DEBUG: - print "Unhandled event:", + print("Unhandled event:", end=' ') self.printevent(event) def printevent(self, event): @@ -434,13 +434,13 @@ nicewhat = repr(what) if what in eventname: nicewhat = eventname[what] - print nicewhat, + print(nicewhat, end=' ') if what == kHighLevelEvent: h, v = where - print repr(ostypecode(message)), hex(when), repr(ostypecode(h | (v<<16))), + print(repr(ostypecode(message)), hex(when), repr(ostypecode(h | (v<<16))), end=' ') else: - print hex(message), hex(when), where, - print hex(modifiers) + print(hex(message), hex(when), where, end=' ') + print(hex(modifiers)) class MenuBar: @@ -477,7 +477,7 @@ def addmenu(self, title, after = 0, id=None): if id == None: id = self.getnextid() - if DEBUG: print 'Newmenu', title, id # XXXX + if DEBUG: print('Newmenu', title, id) # XXXX m = NewMenu(id, title) m.InsertMenu(after) if after >= 0: @@ -488,7 +488,7 @@ return id, m def delmenu(self, id): - if DEBUG: print 'Delmenu', id # XXXX + if DEBUG: print('Delmenu', id) # XXXX DeleteMenu(id) def addpopup(self, title = ''): @@ -531,8 +531,8 @@ if id in self.menus: self.menus[id].dispatch(id, item, window, event) else: - if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ - (id, item, window, event) + if DEBUG: print("MenuBar.dispatch(%d, %d, %s, %s)" % \ + (id, item, window, event)) # XXX Need a way to get menus as resources and bind them to callbacks @@ -837,10 +837,10 @@ def do_contentclick(self, local, modifiers, event): if DEBUG: - print 'Click in contents at %s, modifiers %s'%(local, modifiers) + print('Click in contents at %s, modifiers %s'%(local, modifiers)) def do_rawupdate(self, window, event): - if DEBUG: print "raw update for", window + if DEBUG: print("raw update for", window) SetPort(window) window.BeginUpdate() self.do_update(window, event) @@ -857,12 +857,12 @@ EraseRgn(window.GetWindowPort().visRgn) def do_activate(self, activate, event): - if DEBUG: print 'Activate %d for %s'%(activate, self.wid) + if DEBUG: print('Activate %d for %s'%(activate, self.wid)) class ControlsWindow(Window): def do_rawupdate(self, window, event): - if DEBUG: print "raw update for", window + if DEBUG: print("raw update for", window) SetPort(window) window.BeginUpdate() self.do_update(window, event) @@ -872,7 +872,7 @@ window.EndUpdate() def do_controlhit(self, window, control, pcode, event): - if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode + if DEBUG: print("control hit in", window, "on", control, "; pcode =", pcode) def do_inContent(self, partcode, window, event): if MyFrontWindow() != window: @@ -885,8 +885,8 @@ if pcode and control: self.do_rawcontrolhit(window, control, pcode, local, event) else: - if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \ - (local, window, pcode, control) + if DEBUG: print("FindControl(%s, %s) -> (%s, %s)" % \ + (local, window, pcode, control)) self.do_contentclick(local, modifiers, event) def do_rawcontrolhit(self, window, control, pcode, local, event): @@ -975,11 +975,11 @@ pcode = control.TrackControl(local) if pcode == inThumb: value = control.GetControlValue() - print 'setbars', which, value #DBG + print('setbars', which, value) #DBG self.scrollbar_callback(which, 'set', value) self.updatescrollbars() else: - print 'funny part', pcode #DBG + print('funny part', pcode) #DBG return 1 def do_controltrack(self, control, pcode): @@ -1045,7 +1045,7 @@ return 0, 0 def scrollbar_callback(self, which, what, value): - print 'scroll', which, what, value + print('scroll', which, what, value) class DialogWindow(Window): """A modeless dialog window""" @@ -1063,7 +1063,7 @@ Window.do_postclose(self) def do_itemhit(self, item, event): - print 'Dialog %s, item %d hit'%(self.dlg, item) + print('Dialog %s, item %d hit'%(self.dlg, item)) def do_rawupdate(self, window, event): pass @@ -1096,7 +1096,7 @@ self.quititem = MenuItem(m, "Quit", "Q", self.quit) def save(self, *args): - print "Save" + print("Save") def quit(self, *args): raise self @@ -1106,7 +1106,7 @@ self.nohelpitem = MenuItem(hm, "There isn't any", None, self.nohelp) def nohelp(self, *args): - print "I told you there isn't any!" + print("I told you there isn't any!") def debug(self, *args): import pdb Modified: python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py (original) +++ python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py Fri Feb 9 06:37:30 2007 @@ -71,8 +71,8 @@ try: AE.AEProcessAppleEvent(event) except AE.Error as err: - print 'AE error: ', err - print 'in', msg + print('AE error: ', err) + print('in', msg) traceback.print_exc() return elif what == keyDown: @@ -107,7 +107,7 @@ if hasattr(MacOS, 'HandleEvent'): MacOS.HandleEvent(event) else: - print "Unhandled event:", event + print("Unhandled event:", event) def getabouttext(self): return self.__class__.__name__ @@ -191,7 +191,7 @@ pass def other(self, _object=None, _class=None, _type=None, **args): - print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args + print('AppleEvent', (_class, _type), 'for', _object, 'Other args:', args) if __name__ == '__main__': Modified: python/branches/p3yk/Lib/plat-mac/aetools.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/aetools.py (original) +++ python/branches/p3yk/Lib/plat-mac/aetools.py Fri Feb 9 06:37:30 2007 @@ -349,15 +349,15 @@ target = AE.AECreateDesc('sign', 'quil') ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0) - print unpackevent(ae) + print(unpackevent(ae)) raw_input(":") ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0) obj = Character(2, Word(1, Document(1))) - print obj - print repr(obj) + print(obj) + print(repr(obj)) packevent(ae, {'----': obj}) params, attrs = unpackevent(ae) - print params['----'] + print(params['----']) raw_input(":") if __name__ == '__main__': Modified: python/branches/p3yk/Lib/plat-mac/applesingle.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/applesingle.py (original) +++ python/branches/p3yk/Lib/plat-mac/applesingle.py Fri Feb 9 06:37:30 2007 @@ -51,9 +51,9 @@ except ValueError as arg: raise Error, "Unpack header error: %s" % (arg,) if verbose: - print 'Magic: 0x%8.8x' % (magic,) - print 'Version: 0x%8.8x' % (version,) - print 'Entries: %d' % (nentry,) + print('Magic: 0x%8.8x' % (magic,)) + print('Version: 0x%8.8x' % (version,)) + print('Entries: %d' % (nentry,)) if magic != AS_MAGIC: raise Error, "Unknown AppleSingle magic number 0x%8.8x" % (magic,) if version != AS_VERSION: @@ -68,7 +68,7 @@ except ValueError as arg: raise Error, "Unpack entry error: %s" % (arg,) if verbose: - print "Fork %d, offset %d, length %d" % (restype, offset, length) + print("Fork %d, offset %d, length %d" % (restype, offset, length)) fileobj.seek(offset) data = fileobj.read(length) if len(data) != length: @@ -124,7 +124,7 @@ def _test(): if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4: - print 'Usage: applesingle.py [-r] applesinglefile decodedfile' + print('Usage: applesingle.py [-r] applesinglefile decodedfile') sys.exit(1) if sys.argv[1] == '-r': resonly = True Modified: python/branches/p3yk/Lib/plat-mac/argvemulator.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/argvemulator.py (original) +++ python/branches/p3yk/Lib/plat-mac/argvemulator.py Fri Feb 9 06:37:30 2007 @@ -37,7 +37,7 @@ self._dooneevent(mask, timeout) if not self.quitting: - print "argvemulator: timeout waiting for arguments" + print("argvemulator: timeout waiting for arguments") self.close() @@ -54,12 +54,12 @@ AE.AEProcessAppleEvent(event) except AE.Error as err: msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16))) - print 'AE error: ', err - print 'in', msg + print('AE error: ', err) + print('in', msg) traceback.print_exc() return else: - print "Unhandled event:", event + print("Unhandled event:", event) def _quit(self): @@ -78,7 +78,7 @@ pathname = fsref.as_pathname() sys.argv.append(pathname) except Exception as e: - print "argvemulator.py warning: can't unpack an open document event" + print("argvemulator.py warning: can't unpack an open document event") import traceback traceback.print_exc() @@ -86,4 +86,4 @@ if __name__ == '__main__': ArgvCollector().mainloop() - print "sys.argv=", sys.argv + print("sys.argv=", sys.argv) Modified: python/branches/p3yk/Lib/plat-mac/bundlebuilder.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/bundlebuilder.py (original) +++ python/branches/p3yk/Lib/plat-mac/bundlebuilder.py Fri Feb 9 06:37:30 2007 @@ -831,8 +831,8 @@ def usage(msg=None): if msg: - print msg - print cmdline_doc + print(msg) + print(cmdline_doc) sys.exit(1) def main(builder=None): Modified: python/branches/p3yk/Lib/plat-mac/findertools.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/findertools.py (original) +++ python/branches/p3yk/Lib/plat-mac/findertools.py Fri Feb 9 06:37:30 2007 @@ -695,76 +695,76 @@ def _test(): import EasyDialogs - print 'Original findertools functionality test...' - print 'Testing launch...' + print('Original findertools functionality test...') + print('Testing launch...') pathname = EasyDialogs.AskFileForOpen('File to launch:') if pathname: result = launch(pathname) if result: - print 'Result: ', result - print 'Press return-', + print('Result: ', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing print...' + print('Testing print...') pathname = EasyDialogs.AskFileForOpen('File to print:') if pathname: result = Print(pathname) if result: - print 'Result: ', result - print 'Press return-', + print('Result: ', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing copy...' + print('Testing copy...') pathname = EasyDialogs.AskFileForOpen('File to copy:') if pathname: destdir = EasyDialogs.AskFolder('Destination:') if destdir: result = copy(pathname, destdir) if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing move...' + print('Testing move...') pathname = EasyDialogs.AskFileForOpen('File to move:') if pathname: destdir = EasyDialogs.AskFolder('Destination:') if destdir: result = move(pathname, destdir) if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing sleep...' + print('Testing sleep...') if EasyDialogs.AskYesNoCancel('Sleep?') > 0: result = sleep() if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing shutdown...' + print('Testing shutdown...') if EasyDialogs.AskYesNoCancel('Shut down?') > 0: result = shutdown() if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() - print 'Testing restart...' + print('Testing restart...') if EasyDialogs.AskYesNoCancel('Restart?') > 0: result = restart() if result: - print 'Result:', result - print 'Press return-', + print('Result:', result) + print('Press return-', end=' ') sys.stdin.readline() def _test2(): - print '\nmorefindertools version %s\nTests coming up...' %__version__ + print('\nmorefindertools version %s\nTests coming up...' %__version__) import os import random # miscellaneous - print '\tfilesharing on?', filesharing() # is file sharing on, off, starting up? - print '\tOS version', OSversion() # the version of the system software + print('\tfilesharing on?', filesharing()) # is file sharing on, off, starting up? + print('\tOS version', OSversion()) # the version of the system software # set the soundvolume in a simple way - print '\tSystem beep volume' + print('\tSystem beep volume') for i in range(0, 7): volumelevel(i) MacOS.SysBeep() @@ -781,10 +781,10 @@ windowview(base, 1) # set the view by list label(f, 2) # set the label of this file to something orange - print '\tlabel', label(f) # get the label of this file + print('\tlabel', label(f)) # get the label of this file # the file location only works in a window with icon view! - print 'Random locations for an icon' + print('Random locations for an icon') windowview(base, 0) # set the view by icon windowsize(base, (600, 600)) for i in range(50): @@ -794,36 +794,36 @@ windowview(base, 1) # set the view by icon orgpos = windowposition(base) - print 'Animated window location' + print('Animated window location') for i in range(10): pos = (100+i*10, 100+i*10) windowposition(base, pos) - print '\twindow position', pos + print('\twindow position', pos) windowposition(base, orgpos) # park it where it was before - print 'Put a comment in file', f, ':' - print '\t', comment(f) # print the Finder comment this file has + print('Put a comment in file', f, ':') + print('\t', comment(f)) # print the Finder comment this file has s = 'This is a comment no one reads!' comment(f, s) # set the Finder comment def _test3(): - print 'MacOS9 or better specific functions' + print('MacOS9 or better specific functions') # processes pr = processes() # return a list of tuples with (active_processname, creatorcode) - print 'Return a list of current active processes:' + print('Return a list of current active processes:') for p in pr: - print '\t', p + print('\t', p) # get attributes of the first process in the list - print 'Attributes of the first process in the list:' + print('Attributes of the first process in the list:') pinfo = processinfo(pr[0][0]) - print '\t', pr[0][0] - print '\t\tmemory partition', pinfo.partition # the memory allocated to this process - print '\t\tmemory used', pinfo.used # the memory actuall used by this process - print '\t\tis visible', pinfo.visible # is the process visible to the user - print '\t\tis frontmost', pinfo.frontmost # is the process the front most one? - print '\t\thas scripting', pinfo.hasscripting # is the process scriptable? - print '\t\taccepts high level events', pinfo.accepthighlevel # does the process accept high level appleevents? + print('\t', pr[0][0]) + print('\t\tmemory partition', pinfo.partition) # the memory allocated to this process + print('\t\tmemory used', pinfo.used) # the memory actuall used by this process + print('\t\tis visible', pinfo.visible) # is the process visible to the user + print('\t\tis frontmost', pinfo.frontmost) # is the process the front most one? + print('\t\thas scripting', pinfo.hasscripting) # is the process scriptable? + print('\t\taccepts high level events', pinfo.accepthighlevel) # does the process accept high level appleevents? if __name__ == '__main__': _test() Modified: python/branches/p3yk/Lib/plat-mac/gensuitemodule.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/gensuitemodule.py (original) +++ python/branches/p3yk/Lib/plat-mac/gensuitemodule.py Fri Feb 9 06:37:30 2007 @@ -115,8 +115,8 @@ processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) except MacOS.Error as arg: - print "Error getting terminology:", arg - print "Retry, manually parsing resources" + print("Error getting terminology:", arg) + print("Retry, manually parsing resources") processfile_fromresource(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) @@ -145,10 +145,10 @@ edit_modnames=None, creatorsignature=None, dump=None, verbose=None): """Process all resources in a single file""" if not is_scriptable(fullname) and verbose: - print >>verbose, "Warning: app does not seem scriptable: %s" % fullname + print("Warning: app does not seem scriptable: %s" % fullname, file=verbose) cur = CurResFile() if verbose: - print >>verbose, "Processing", fullname + print("Processing", fullname, file=verbose) rf = macresource.open_pathname(fullname) try: UseResFile(rf) @@ -160,11 +160,11 @@ res = Get1IndResource('aeut', 1+i) resources.append(res) if verbose: - print >>verbose, "\nLISTING aete+aeut RESOURCES IN", repr(fullname) + print("\nLISTING aete+aeut RESOURCES IN", repr(fullname), file=verbose) aetelist = [] for res in resources: if verbose: - print >>verbose, "decoding", res.GetResInfo(), "..." + print("decoding", res.GetResInfo(), "...", file=verbose) data = res.data aete = decode(data, verbose) aetelist.append((aete, res.GetResInfo())) @@ -185,15 +185,15 @@ verbose=None): """Ask an application for its terminology and process that""" if not is_scriptable(fullname) and verbose: - print >>verbose, "Warning: app does not seem scriptable: %s" % fullname + print("Warning: app does not seem scriptable: %s" % fullname, file=verbose) if verbose: - print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname) + print("\nASKING FOR aete DICTIONARY IN", repr(fullname), file=verbose) try: aedescobj, launched = OSATerminology.GetAppTerminology(fullname) except MacOS.Error as arg: if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound if verbose: - print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually" + print("GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually", file=verbose) aedata, sig = getappterminology(fullname, verbose=verbose) if not creatorsignature: creatorsignature = sig @@ -202,15 +202,15 @@ else: if launched: if verbose: - print >>verbose, "Launched", fullname + print("Launched", fullname, file=verbose) raw = aetools.unpack(aedescobj) if not raw: if verbose: - print >>verbose, 'Unpack returned empty value:', raw + print('Unpack returned empty value:', raw, file=verbose) return if not raw[0].data: if verbose: - print >>verbose, 'Unpack returned value without data:', raw + print('Unpack returned value without data:', raw, file=verbose) return aedata = raw[0] aete = decode(aedata.data, verbose) @@ -246,7 +246,7 @@ talker._start() except (MacOS.Error, aetools.Error) as arg: if verbose: - print >>verbose, 'Warning: start() failed, continuing anyway:', arg + print('Warning: start() failed, continuing anyway:', arg, file=verbose) reply = talker.send("ascr", "gdte") #reply2 = talker.send("ascr", "gdut") # Now pick the bits out of the return that we need. @@ -344,9 +344,9 @@ return list def alt_generic(what, f, *args): - print "generic", repr(what), args + print("generic", repr(what), args) res = vageneric(what, f, args) - print '->', repr(res) + print('->', repr(res)) return res def generic(what, f, *args): @@ -940,14 +940,14 @@ for mapper in self.othernamemappers: if mapper.hasname(name) and mapper.modulename != self.modulename: if self.verbose: - print >>self.verbose, "Duplicate Python identifier:", name, self.modulename, mapper.modulename + print("Duplicate Python identifier:", name, self.modulename, mapper.modulename, file=self.verbose) return True return False def askdefinitionmodule(self, type, code): if not self.can_interact: if self.verbose: - print >>self.verbose, "** No definition for %s '%s' found" % (type, code) + print("** No definition for %s '%s' found" % (type, code), file=self.verbose) return None path = EasyDialogs.AskFileForSave(message='Where is %s %s declared?'%(type, code)) if not path: return @@ -1018,7 +1018,7 @@ if self.fp and (elements or len(properties) > 1 or (len(properties) == 1 and properties[0][1] != 'c@#!')): if self.verbose: - print >>self.verbose, '** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code) + print('** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code), file=self.verbose) raise RuntimeError, "About to skip non-empty class" return plist = [] Modified: python/branches/p3yk/Lib/plat-mac/ic.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/ic.py (original) +++ python/branches/p3yk/Lib/plat-mac/ic.py Fri Feb 9 06:37:30 2007 @@ -94,7 +94,7 @@ chr(0) + _code_default(name) def _code_boolean(data, key): - print 'XXXX boolean:', repr(data) + print('XXXX boolean:', repr(data)) return chr(data) def _code_text(data, key): @@ -258,7 +258,7 @@ v = ic[k] except error: v = '????' - print k, '\t', v + print(k, '\t', v) sys.exit(1) if __name__ == '__main__': Modified: python/branches/p3yk/Lib/plat-mac/macresource.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/macresource.py (original) +++ python/branches/p3yk/Lib/plat-mac/macresource.py Fri Feb 9 06:37:30 2007 @@ -140,7 +140,7 @@ import tempfile fd, newpathname = tempfile.mkstemp(".rsrc") if verbose: - print 'Decoding', pathname, 'to', newpathname + print('Decoding', pathname, 'to', newpathname) import applesingle applesingle.decode(pathname, newpathname, resonly=1) return newpathname Modified: python/branches/p3yk/Lib/plat-mac/pimp.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/pimp.py (original) +++ python/branches/p3yk/Lib/plat-mac/pimp.py Fri Feb 9 06:37:30 2007 @@ -229,7 +229,7 @@ #print 'SKIP', member.name else: member.name = newprefix + member.name[len(oldprefix):] - print ' ', member.name + print(' ', member.name) break elif oldprefix2 and member.name[:len(oldprefix2)] == oldprefix2: if newprefix is None: @@ -1020,8 +1020,8 @@ elif mode =='list': if not args: args = db.listnames() - print "%-20.20s\t%s" % ("Package", "Description") - print + print("%-20.20s\t%s" % ("Package", "Description")) + print() for pkgname in args: pkg = db.find(pkgname) if pkg: @@ -1029,21 +1029,21 @@ pkgname = pkg.fullname() else: description = 'Error: no such package' - print "%-20.20s\t%s" % (pkgname, description) + print("%-20.20s\t%s" % (pkgname, description)) if verbose: - print "\tHome page:\t", pkg.homepage() + print("\tHome page:\t", pkg.homepage()) try: - print "\tDownload URL:\t", pkg.downloadURL() + print("\tDownload URL:\t", pkg.downloadURL()) except KeyError: pass description = pkg.description() description = '\n\t\t\t\t\t'.join(description.splitlines()) - print "\tDescription:\t%s" % description + print("\tDescription:\t%s" % description) elif mode =='status': if not args: args = db.listnames() - print "%-20.20s\t%s\t%s" % ("Package", "Installed", "Message") - print + print("%-20.20s\t%s\t%s" % ("Package", "Installed", "Message")) + print() for pkgname in args: pkg = db.find(pkgname) if pkg: @@ -1052,7 +1052,7 @@ else: status = 'error' msg = 'No such package' - print "%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg) + print("%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg)) if verbose and status == "no": prereq = pkg.prerequisites() for pkg, msg in prereq: @@ -1060,22 +1060,22 @@ pkg = '' else: pkg = pkg.fullname() - print "%-20.20s\tRequirement: %s %s" % ("", pkg, msg) + print("%-20.20s\tRequirement: %s %s" % ("", pkg, msg)) elif mode == 'install': if not args: - print 'Please specify packages to install' + print('Please specify packages to install') sys.exit(1) inst = PimpInstaller(db) for pkgname in args: pkg = db.find(pkgname) if not pkg: - print '%s: No such package' % pkgname + print('%s: No such package' % pkgname) continue list, messages = inst.prepareInstall(pkg, force) if messages and not force: - print "%s: Not installed:" % pkgname + print("%s: Not installed:" % pkgname) for m in messages: - print "\t", m + print("\t", m) else: if verbose: output = sys.stdout @@ -1083,26 +1083,26 @@ output = None messages = inst.install(list, output) if messages: - print "%s: Not installed:" % pkgname + print("%s: Not installed:" % pkgname) for m in messages: - print "\t", m + print("\t", m) def main(): """Minimal commandline tool to drive pimp.""" import getopt def _help(): - print "Usage: pimp [options] -s [package ...] List installed status" - print " pimp [options] -l [package ...] Show package information" - print " pimp [options] -i package ... Install packages" - print " pimp -d Dump database to stdout" - print " pimp -V Print version number" - print "Options:" - print " -v Verbose" - print " -f Force installation" - print " -D dir Set destination directory" - print " (default: %s)" % DEFAULT_INSTALLDIR - print " -u url URL for database" + print("Usage: pimp [options] -s [package ...] List installed status") + print(" pimp [options] -l [package ...] Show package information") + print(" pimp [options] -i package ... Install packages") + print(" pimp -d Dump database to stdout") + print(" pimp -V Print version number") + print("Options:") + print(" -v Verbose") + print(" -f Force installation") + print(" -D dir Set destination directory") + print(" (default: %s)" % DEFAULT_INSTALLDIR) + print(" -u url URL for database") sys.exit(1) class _Watcher: @@ -1152,7 +1152,7 @@ if not mode: _help() if mode == 'version': - print 'Pimp version %s; module name is %s' % (PIMP_VERSION, __name__) + print('Pimp version %s; module name is %s' % (PIMP_VERSION, __name__)) else: _run(mode, verbose, force, args, prefargs, watcher) Modified: python/branches/p3yk/Lib/plat-mac/videoreader.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/videoreader.py (original) +++ python/branches/p3yk/Lib/plat-mac/videoreader.py Fri Feb 9 06:37:30 2007 @@ -272,8 +272,8 @@ fname = 'frame%04.4d.jpg'%num num = num+1 pname = os.path.join(dstdir, fname) - if not img: print 'Not', - print 'Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data)) + if not img: print('Not', end=' ') + print('Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data))) if img: wrt = img.writer(imgfmt, pname) wrt.width = imgw @@ -282,9 +282,9 @@ timestamp, data = rdr.ReadVideo() MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG') if num > 20: - print 'stopping at 20 frames so your disk does not fill up:-)' + print('stopping at 20 frames so your disk does not fill up:-)') break - print 'Total frames:', num + print('Total frames:', num) if __name__ == '__main__': _test() Modified: python/branches/p3yk/Lib/plat-os2emx/_emx_link.py ============================================================================== --- python/branches/p3yk/Lib/plat-os2emx/_emx_link.py (original) +++ python/branches/p3yk/Lib/plat-os2emx/_emx_link.py Fri Feb 9 06:37:30 2007 @@ -74,6 +74,6 @@ try: link(sys.argv[1], sys.argv[2]) except IndexError: - print 'Usage: emx_link ' + print('Usage: emx_link ') except OSError: - print 'emx_link: %s' % str(sys.exc_info()[1]) + print('emx_link: %s' % str(sys.exc_info()[1])) Modified: python/branches/p3yk/Lib/plat-riscos/rourl2path.py ============================================================================== --- python/branches/p3yk/Lib/plat-riscos/rourl2path.py (original) +++ python/branches/p3yk/Lib/plat-riscos/rourl2path.py Fri Feb 9 06:37:30 2007 @@ -60,12 +60,12 @@ "/foo/bar/index.html", "/foo/bar/", "/"]: - print '%r -> %r' % (url, url2pathname(url)) - print "*******************************************************" + print('%r -> %r' % (url, url2pathname(url))) + print("*******************************************************") for path in ["SCSI::SCSI4.$.Anwendung", "PythonApp:Lib", "PythonApp:Lib.rourl2path/py"]: - print '%r -> %r' % (path, pathname2url(path)) + print('%r -> %r' % (path, pathname2url(path))) if __name__ == '__main__': test() Modified: python/branches/p3yk/Lib/platform.py ============================================================================== --- python/branches/p3yk/Lib/platform.py (original) +++ python/branches/p3yk/Lib/platform.py Fri Feb 9 06:37:30 2007 @@ -283,7 +283,7 @@ ): parsed = _parse_release_file(input) if parsed != output: - print (input, parsed) + print((input, parsed)) def linux_distribution(distname='', version='', id='', @@ -1308,7 +1308,7 @@ ): parsed = _sys_version(input) if parsed != output: - print (input, parsed) + print((input, parsed)) def python_implementation(): @@ -1480,5 +1480,5 @@ # Default is to print the aliased verbose platform string terse = ('terse' in sys.argv or '--terse' in sys.argv) aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv) - print platform(aliased,terse) + print(platform(aliased,terse)) sys.exit(0) Modified: python/branches/p3yk/Lib/popen2.py ============================================================================== --- python/branches/p3yk/Lib/popen2.py (original) +++ python/branches/p3yk/Lib/popen2.py Fri Feb 9 06:37:30 2007 @@ -213,14 +213,14 @@ # sometimes adding an extra newline at the start or the # end. So we strip whitespace off both ends for comparison. expected = teststr.strip() - print "testing popen2..." + print("testing popen2...") r, w = popen2(cmd) w.write(teststr) w.close() got = r.read() if got.strip() != expected: raise ValueError("wrote %r read %r" % (teststr, got)) - print "testing popen3..." + print("testing popen3...") try: r, w, e = popen3([cmd]) except: @@ -238,7 +238,7 @@ _cleanup() if _active: raise ValueError("_active not empty") - print "All OK" + print("All OK") if __name__ == '__main__': _test() Modified: python/branches/p3yk/Lib/poplib.py ============================================================================== --- python/branches/p3yk/Lib/poplib.py (original) +++ python/branches/p3yk/Lib/poplib.py Fri Feb 9 06:37:30 2007 @@ -100,14 +100,14 @@ def _putline(self, line): - if self._debugging > 1: print '*put*', repr(line) + if self._debugging > 1: print('*put*', repr(line)) self.sock.sendall('%s%s' % (line, CRLF)) # Internal: send one command to the server (through _putline()) def _putcmd(self, line): - if self._debugging: print '*cmd*', repr(line) + if self._debugging: print('*cmd*', repr(line)) self._putline(line) @@ -117,7 +117,7 @@ def _getline(self): line = self.file.readline() - if self._debugging > 1: print '*get*', repr(line) + if self._debugging > 1: print('*get*', repr(line)) if not line: raise error_proto('-ERR EOF') octets = len(line) # server can send any combination of CR & LF @@ -135,7 +135,7 @@ def _getresp(self): resp, o = self._getline() - if self._debugging > 1: print '*resp*', repr(resp) + if self._debugging > 1: print('*resp*', repr(resp)) c = resp[:1] if c != '+': raise error_proto(resp) @@ -209,7 +209,7 @@ """ retval = self._shortcmd('STAT') rets = retval.split() - if self._debugging: print '*stat*', repr(rets) + if self._debugging: print('*stat*', repr(rets)) numMessages = int(rets[1]) sizeMessages = int(rets[2]) return (numMessages, sizeMessages) @@ -375,7 +375,7 @@ match = renewline.match(self.buffer) line = match.group(0) self.buffer = renewline.sub('' ,self.buffer, 1) - if self._debugging > 1: print '*get*', repr(line) + if self._debugging > 1: print('*get*', repr(line)) octets = len(line) if line[-2:] == CRLF: @@ -385,7 +385,7 @@ return line[:-1], octets def _putline(self, line): - if self._debugging > 1: print '*put*', repr(line) + if self._debugging > 1: print('*put*', repr(line)) line += CRLF bytes = len(line) while bytes > 0: @@ -409,15 +409,15 @@ if __name__ == "__main__": import sys a = POP3(sys.argv[1]) - print a.getwelcome() + print(a.getwelcome()) a.user(sys.argv[2]) a.pass_(sys.argv[3]) a.list() (numMsgs, totalSize) = a.stat() for i in range(1, numMsgs + 1): (header, msg, octets) = a.retr(i) - print "Message %d:" % i + print("Message %d:" % i) for line in msg: - print ' ' + line - print '-----------------------' + print(' ' + line) + print('-----------------------') a.quit() Modified: python/branches/p3yk/Lib/pprint.py ============================================================================== --- python/branches/p3yk/Lib/pprint.py (original) +++ python/branches/p3yk/Lib/pprint.py Fri Feb 9 06:37:30 2007 @@ -313,8 +313,8 @@ t2 = time.time() p.pformat(object) t3 = time.time() - print "_safe_repr:", t2 - t1 - print "pformat:", t3 - t2 + print("_safe_repr:", t2 - t1) + print("pformat:", t3 - t2) if __name__ == "__main__": _perfcheck() Modified: python/branches/p3yk/Lib/profile.py ============================================================================== --- python/branches/p3yk/Lib/profile.py (original) +++ python/branches/p3yk/Lib/profile.py Fri Feb 9 06:37:30 2007 @@ -94,8 +94,8 @@ # Backwards compatibility. def help(): - print "Documentation for the profile module can be found " - print "in the Python Library Reference, section 'The Python Profiler'." + print("Documentation for the profile module can be found ") + print("in the Python Library Reference, section 'The Python Profiler'.") if os.name == "mac": import MacOS @@ -550,7 +550,7 @@ t1 = get_time() elapsed_noprofile = t1 - t0 if verbose: - print "elapsed time without profiling =", elapsed_noprofile + print("elapsed time without profiling =", elapsed_noprofile) # elapsed_profile <- time f(m) takes with profiling. The difference # is profiling overhead, only some of which the profiler subtracts @@ -561,7 +561,7 @@ t1 = get_time() elapsed_profile = t1 - t0 if verbose: - print "elapsed time with profiling =", elapsed_profile + print("elapsed time with profiling =", elapsed_profile) # reported_time <- "CPU seconds" the profiler charged to f and f1. total_calls = 0.0 @@ -573,8 +573,8 @@ reported_time += tt if verbose: - print "'CPU seconds' profiler reported =", reported_time - print "total # calls =", total_calls + print("'CPU seconds' profiler reported =", reported_time) + print("total # calls =", total_calls) if total_calls != m + 1: raise ValueError("internal error: total calls = %d" % total_calls) @@ -584,12 +584,12 @@ # overhead per event. mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls if verbose: - print "mean stopwatch overhead per profile event =", mean + print("mean stopwatch overhead per profile event =", mean) return mean #**************************************************************************** def Stats(*args): - print 'Report generating functions are in the "pstats" module\a' + print('Report generating functions are in the "pstats" module\a') def main(): usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..." Modified: python/branches/p3yk/Lib/pstats.py ============================================================================== --- python/branches/p3yk/Lib/pstats.py (original) +++ python/branches/p3yk/Lib/pstats.py Fri Feb 9 06:37:30 2007 @@ -110,9 +110,9 @@ trouble = 0 finally: if trouble: - print >> self.stream, "Invalid timing data", - if self.files: print >> self.stream, self.files[-1], - print >> self.stream + print("Invalid timing data", end=' ', file=self.stream) + if self.files: print(self.files[-1], end=' ', file=self.stream) + print(file=self.stream) def load_stats(self, arg): if not arg: self.stats = {} @@ -334,7 +334,7 @@ if not list: return 0, list - print >> self.stream, msg + print(msg, file=self.stream) if count < len(self.stats): width = 0 for func in list: @@ -344,24 +344,24 @@ def print_stats(self, *amount): for filename in self.files: - print >> self.stream, filename - if self.files: print >> self.stream + print(filename, file=self.stream) + if self.files: print(file=self.stream) indent = ' ' * 8 for func in self.top_level: - print >> self.stream, indent, func_get_function_name(func) + print(indent, func_get_function_name(func), file=self.stream) - print >> self.stream, indent, self.total_calls, "function calls", + print(indent, self.total_calls, "function calls", end=' ', file=self.stream) if self.total_calls != self.prim_calls: - print >> self.stream, "(%d primitive calls)" % self.prim_calls, - print >> self.stream, "in %.3f CPU seconds" % self.total_tt - print >> self.stream + print("(%d primitive calls)" % self.prim_calls, end=' ', file=self.stream) + print("in %.3f CPU seconds" % self.total_tt, file=self.stream) + print(file=self.stream) width, list = self.get_print_list(amount) if list: self.print_title() for func in list: self.print_line(func) - print >> self.stream - print >> self.stream + print(file=self.stream) + print(file=self.stream) return self def print_callees(self, *amount): @@ -375,8 +375,8 @@ self.print_call_line(width, func, self.all_callees[func]) else: self.print_call_line(width, func, {}) - print >> self.stream - print >> self.stream + print(file=self.stream) + print(file=self.stream) return self def print_callers(self, *amount): @@ -386,12 +386,12 @@ for func in list: cc, nc, tt, ct, callers = self.stats[func] self.print_call_line(width, func, callers, "<-") - print >> self.stream - print >> self.stream + print(file=self.stream) + print(file=self.stream) return self def print_call_heading(self, name_size, column_title): - print >> self.stream, "Function ".ljust(name_size) + column_title + print("Function ".ljust(name_size) + column_title, file=self.stream) # print sub-header only if we have new-style callers subheader = False for cc, nc, tt, ct, callers in self.stats.itervalues(): @@ -400,12 +400,12 @@ subheader = isinstance(value, tuple) break if subheader: - print >> self.stream, " "*name_size + " ncalls tottime cumtime" + print(" "*name_size + " ncalls tottime cumtime", file=self.stream) def print_call_line(self, name_size, source, call_dict, arrow="->"): - print >> self.stream, func_std_string(source).ljust(name_size) + arrow, + print(func_std_string(source).ljust(name_size) + arrow, end=' ', file=self.stream) if not call_dict: - print >> self.stream + print(file=self.stream) return clist = call_dict.keys() clist.sort() @@ -425,30 +425,30 @@ else: substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3])) left_width = name_size + 3 - print >> self.stream, indent*left_width + substats + print(indent*left_width + substats, file=self.stream) indent = " " def print_title(self): - print >> self.stream, ' ncalls tottime percall cumtime percall', - print >> self.stream, 'filename:lineno(function)' + print(' ncalls tottime percall cumtime percall', end=' ', file=self.stream) + print('filename:lineno(function)', file=self.stream) def print_line(self, func): # hack : should print percentages cc, nc, tt, ct, callers = self.stats[func] c = str(nc) if nc != cc: c = c + '/' + str(cc) - print >> self.stream, c.rjust(9), - print >> self.stream, f8(tt), + print(c.rjust(9), end=' ', file=self.stream) + print(f8(tt), end=' ', file=self.stream) if nc == 0: - print >> self.stream, ' '*8, + print(' '*8, end=' ', file=self.stream) else: - print >> self.stream, f8(tt/nc), - print >> self.stream, f8(ct), + print(f8(tt/nc), end=' ', file=self.stream) + print(f8(ct), end=' ', file=self.stream) if cc == 0: - print >> self.stream, ' '*8, + print(' '*8, end=' ', file=self.stream) else: - print >> self.stream, f8(ct/cc), - print >> self.stream, func_std_string(func) + print(f8(ct/cc), end=' ', file=self.stream) + print(func_std_string(func), file=self.stream) class TupleComp: """This class provides a generic function for comparing any two tuples. @@ -565,7 +565,7 @@ try: frac = float(term) if frac > 1 or frac < 0: - print >> self.stream, "Fraction argument must be in [0, 1]" + print("Fraction argument must be in [0, 1]", file=self.stream) continue processed.append(frac) continue @@ -575,93 +575,93 @@ if self.stats: getattr(self.stats, fn)(*processed) else: - print >> self.stream, "No statistics object is loaded." + print("No statistics object is loaded.", file=self.stream) return 0 def generic_help(self): - print >> self.stream, "Arguments may be:" - print >> self.stream, "* An integer maximum number of entries to print." - print >> self.stream, "* A decimal fractional number between 0 and 1, controlling" - print >> self.stream, " what fraction of selected entries to print." - print >> self.stream, "* A regular expression; only entries with function names" - print >> self.stream, " that match it are printed." + print("Arguments may be:", file=self.stream) + print("* An integer maximum number of entries to print.", file=self.stream) + print("* A decimal fractional number between 0 and 1, controlling", file=self.stream) + print(" what fraction of selected entries to print.", file=self.stream) + print("* A regular expression; only entries with function names", file=self.stream) + print(" that match it are printed.", file=self.stream) def do_add(self, line): self.stats.add(line) return 0 def help_add(self): - print >> self.stream, "Add profile info from given file to current statistics object." + print("Add profile info from given file to current statistics object.", file=self.stream) def do_callees(self, line): return self.generic('print_callees', line) def help_callees(self): - print >> self.stream, "Print callees statistics from the current stat object." + print("Print callees statistics from the current stat object.", file=self.stream) self.generic_help() def do_callers(self, line): return self.generic('print_callers', line) def help_callers(self): - print >> self.stream, "Print callers statistics from the current stat object." + print("Print callers statistics from the current stat object.", file=self.stream) self.generic_help() def do_EOF(self, line): - print >> self.stream, "" + print("", file=self.stream) return 1 def help_EOF(self): - print >> self.stream, "Leave the profile brower." + print("Leave the profile brower.", file=self.stream) def do_quit(self, line): return 1 def help_quit(self): - print >> self.stream, "Leave the profile brower." + print("Leave the profile brower.", file=self.stream) def do_read(self, line): if line: try: self.stats = Stats(line) except IOError as args: - print >> self.stream, args[1] + print(args[1], file=self.stream) return self.prompt = line + "% " elif len(self.prompt) > 2: line = self.prompt[-2:] else: - print >> self.stream, "No statistics object is current -- cannot reload." + print("No statistics object is current -- cannot reload.", file=self.stream) return 0 def help_read(self): - print >> self.stream, "Read in profile data from a specified file." + print("Read in profile data from a specified file.", file=self.stream) def do_reverse(self, line): self.stats.reverse_order() return 0 def help_reverse(self): - print >> self.stream, "Reverse the sort order of the profiling report." + print("Reverse the sort order of the profiling report.", file=self.stream) def do_sort(self, line): abbrevs = self.stats.get_sort_arg_defs() if line and not filter(lambda x,a=abbrevs: x not in a,line.split()): self.stats.sort_stats(*line.split()) else: - print >> self.stream, "Valid sort keys (unique prefixes are accepted):" + print("Valid sort keys (unique prefixes are accepted):", file=self.stream) for (key, value) in Stats.sort_arg_dict_default.iteritems(): - print >> self.stream, "%s -- %s" % (key, value[1]) + print("%s -- %s" % (key, value[1]), file=self.stream) return 0 def help_sort(self): - print >> self.stream, "Sort profile data according to specified keys." - print >> self.stream, "(Typing `sort' without arguments lists valid keys.)" + print("Sort profile data according to specified keys.", file=self.stream) + print("(Typing `sort' without arguments lists valid keys.)", file=self.stream) def complete_sort(self, text, *args): return [a for a in Stats.sort_arg_dict_default if a.startswith(text)] def do_stats(self, line): return self.generic('print_stats', line) def help_stats(self): - print >> self.stream, "Print statistics from the current stat object." + print("Print statistics from the current stat object.", file=self.stream) self.generic_help() def do_strip(self, line): self.stats.strip_dirs() return 0 def help_strip(self): - print >> self.stream, "Strip leading path information from filenames in the report." + print("Strip leading path information from filenames in the report.", file=self.stream) def postcmd(self, stop, line): if stop: @@ -675,9 +675,9 @@ initprofile = None try: browser = ProfileBrowser(initprofile) - print >> browser.stream, "Welcome to the profile statistics browser." + print("Welcome to the profile statistics browser.", file=browser.stream) browser.cmdloop() - print >> browser.stream, "Goodbye." + print("Goodbye.", file=browser.stream) except KeyboardInterrupt: pass Modified: python/branches/p3yk/Lib/pyclbr.py ============================================================================== --- python/branches/p3yk/Lib/pyclbr.py (original) +++ python/branches/p3yk/Lib/pyclbr.py Fri Feb 9 06:37:30 2007 @@ -328,13 +328,13 @@ getattr(b, 'lineno', 0))) for obj in objs: if isinstance(obj, Class): - print "class", obj.name, obj.super, obj.lineno + print("class", obj.name, obj.super, obj.lineno) methods = sorted(obj.methods.iteritems(), key=itemgetter(1)) for name, lineno in methods: if name != "__path__": - print " def", name, lineno + print(" def", name, lineno) elif isinstance(obj, Function): - print "def", obj.name, obj.lineno + print("def", obj.name, obj.lineno) if __name__ == "__main__": _main() Modified: python/branches/p3yk/Lib/pydoc.py ============================================================================== --- python/branches/p3yk/Lib/pydoc.py (original) +++ python/branches/p3yk/Lib/pydoc.py Fri Feb 9 06:37:30 2007 @@ -1480,7 +1480,7 @@ desc += ' object' pager(title % desc + '\n\n' + text.document(object, name)) except (ImportError, ErrorDuringImport) as value: - print value + print(value) def writedoc(thing, forceload=0): """Write HTML documentation to a file in the current directory.""" @@ -1490,9 +1490,9 @@ file = open(name + '.html', 'w') file.write(page) file.close() - print 'wrote', name + '.html' + print('wrote', name + '.html') except (ImportError, ErrorDuringImport) as value: - print value + print(value) def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" @@ -1883,7 +1883,7 @@ def callback(path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' - print modname, desc and '- ' + desc + print(modname, desc and '- ' + desc) try: import warnings except ImportError: pass else: warnings.filterwarnings('ignore') # ignore problems during import @@ -2200,9 +2200,9 @@ except ValueError: raise BadUsage def ready(server): - print 'pydoc server ready at %s' % server.url + print('pydoc server ready at %s' % server.url) def stopped(): - print 'pydoc server stopped' + print('pydoc server stopped') serve(port, ready, stopped) return if opt == '-w': @@ -2211,7 +2211,7 @@ if not args: raise BadUsage for arg in args: if ispath(arg) and not os.path.exists(arg): - print 'file %r does not exist' % arg + print('file %r does not exist' % arg) break try: if ispath(arg) and os.path.isfile(arg): @@ -2224,11 +2224,11 @@ else: help.help(arg) except ErrorDuringImport as value: - print value + print(value) except (getopt.error, BadUsage): cmd = os.path.basename(sys.argv[0]) - print """pydoc - the Python documentation tool + print("""pydoc - the Python documentation tool %s ... Show text documentation on something. may be the name of a @@ -2251,6 +2251,6 @@ Write out the HTML documentation for a module to a file in the current directory. If contains a '%s', it is treated as a filename; if it names a directory, documentation is written for all the contents. -""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep) +""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)) if __name__ == '__main__': cli() Modified: python/branches/p3yk/Lib/quopri.py ============================================================================== --- python/branches/p3yk/Lib/quopri.py (original) +++ python/branches/p3yk/Lib/quopri.py Fri Feb 9 06:37:30 2007 @@ -196,10 +196,10 @@ opts, args = getopt.getopt(sys.argv[1:], 'td') except getopt.error as msg: sys.stdout = sys.stderr - print msg - print "usage: quopri [-t | -d] [file] ..." - print "-t: quote tabs" - print "-d: decode; default encode" + print(msg) + print("usage: quopri [-t | -d] [file] ...") + print("-t: quote tabs") + print("-d: decode; default encode") sys.exit(2) deco = 0 tabs = 0 @@ -208,7 +208,7 @@ if o == '-d': deco = 1 if tabs and deco: sys.stdout = sys.stderr - print "-t and -d are mutually exclusive" + print("-t and -d are mutually exclusive") sys.exit(2) if not args: args = ['-'] sts = 0 Modified: python/branches/p3yk/Lib/random.py ============================================================================== --- python/branches/p3yk/Lib/random.py (original) +++ python/branches/p3yk/Lib/random.py Fri Feb 9 06:37:30 2007 @@ -792,7 +792,7 @@ def _test_generator(n, func, args): import time - print n, 'times', func.__name__ + print(n, 'times', func.__name__) total = 0.0 sqsum = 0.0 smallest = 1e10 @@ -805,11 +805,11 @@ smallest = min(x, smallest) largest = max(x, largest) t1 = time.time() - print round(t1-t0, 3), 'sec,', + print(round(t1-t0, 3), 'sec,', end=' ') avg = total/n stddev = _sqrt(sqsum/n - avg*avg) - print 'avg %g, stddev %g, min %g, max %g' % \ - (avg, stddev, smallest, largest) + print('avg %g, stddev %g, min %g, max %g' % \ + (avg, stddev, smallest, largest)) def _test(N=2000): Modified: python/branches/p3yk/Lib/rexec.py ============================================================================== --- python/branches/p3yk/Lib/rexec.py (original) +++ python/branches/p3yk/Lib/rexec.py Fri Feb 9 06:37:30 2007 @@ -552,7 +552,7 @@ try: fp = open(args[0]) except IOError as msg: - print "%s: can't open file %r" % (sys.argv[0], args[0]) + print("%s: can't open file %r" % (sys.argv[0], args[0])) return 1 if fp.isatty(): try: Modified: python/branches/p3yk/Lib/rfc822.py ============================================================================== --- python/branches/p3yk/Lib/rfc822.py (original) +++ python/branches/p3yk/Lib/rfc822.py Fri Feb 9 06:37:30 2007 @@ -972,32 +972,32 @@ if sys.argv[1:]: file = sys.argv[1] f = open(file, 'r') m = Message(f) - print 'From:', m.getaddr('from') - print 'To:', m.getaddrlist('to') - print 'Subject:', m.getheader('subject') - print 'Date:', m.getheader('date') + print('From:', m.getaddr('from')) + print('To:', m.getaddrlist('to')) + print('Subject:', m.getheader('subject')) + print('Date:', m.getheader('date')) date = m.getdate_tz('date') tz = date[-1] date = time.localtime(mktime_tz(date)) if date: - print 'ParsedDate:', time.asctime(date), + print('ParsedDate:', time.asctime(date), end=' ') hhmmss = tz hhmm, ss = divmod(hhmmss, 60) hh, mm = divmod(hhmm, 60) - print "%+03d%02d" % (hh, mm), - if ss: print ".%02d" % ss, - print + print("%+03d%02d" % (hh, mm), end=' ') + if ss: print(".%02d" % ss, end=' ') + print() else: - print 'ParsedDate:', None + print('ParsedDate:', None) m.rewindbody() n = 0 while f.readline(): n += 1 - print 'Lines:', n - print '-'*70 - print 'len =', len(m) - if 'Date' in m: print 'Date =', m['Date'] + print('Lines:', n) + print('-'*70) + print('len =', len(m)) + if 'Date' in m: print('Date =', m['Date']) if 'X-Nonsense' in m: pass - print 'keys =', m.keys() - print 'values =', m.values() - print 'items =', m.items() + print('keys =', m.keys()) + print('values =', m.values()) + print('items =', m.items()) Modified: python/branches/p3yk/Lib/robotparser.py ============================================================================== --- python/branches/p3yk/Lib/robotparser.py (original) +++ python/branches/p3yk/Lib/robotparser.py Fri Feb 9 06:37:30 2007 @@ -16,7 +16,7 @@ debug = 0 def _debug(msg): - if debug: print msg + if debug: print(msg) class RobotFileParser: @@ -244,10 +244,10 @@ else: ac = "access allowed" if a!=b: - print "failed" + print("failed") else: - print "ok (%s)" % ac - print + print("ok (%s)" % ac) + print() def _test(): global debug Modified: python/branches/p3yk/Lib/runpy.py ============================================================================== --- python/branches/p3yk/Lib/runpy.py (original) +++ python/branches/p3yk/Lib/runpy.py Fri Feb 9 06:37:30 2007 @@ -98,7 +98,7 @@ if __name__ == "__main__": # Run the module specified as the next command line argument if len(sys.argv) < 2: - print >> sys.stderr, "No module specified for execution" + print("No module specified for execution", file=sys.stderr) else: del sys.argv[0] # Make the requested module sys.argv[0] run_module(sys.argv[0], run_name="__main__", alter_sys=True) Modified: python/branches/p3yk/Lib/sgmllib.py ============================================================================== --- python/branches/p3yk/Lib/sgmllib.py (original) +++ python/branches/p3yk/Lib/sgmllib.py Fri Feb 9 06:37:30 2007 @@ -382,8 +382,8 @@ # Example -- report an unbalanced tag. def report_unbalanced(self, tag): if self.verbose: - print '*** Unbalanced ' - print '*** Stack:', self.stack + print('*** Unbalanced ') + print('*** Stack:', self.stack) def convert_charref(self, name): """Convert character reference, may be overridden.""" @@ -468,40 +468,40 @@ data = self.testdata if data: self.testdata = "" - print 'data:', repr(data) + print('data:', repr(data)) def handle_comment(self, data): self.flush() r = repr(data) if len(r) > 68: r = r[:32] + '...' + r[-32:] - print 'comment:', r + print('comment:', r) def unknown_starttag(self, tag, attrs): self.flush() if not attrs: - print 'start tag: <' + tag + '>' + print('start tag: <' + tag + '>') else: - print 'start tag: <' + tag, + print('start tag: <' + tag, end=' ') for name, value in attrs: - print name + '=' + '"' + value + '"', - print '>' + print(name + '=' + '"' + value + '"', end=' ') + print('>') def unknown_endtag(self, tag): self.flush() - print 'end tag: ' + print('end tag: ') def unknown_entityref(self, ref): self.flush() - print '*** unknown entity ref: &' + ref + ';' + print('*** unknown entity ref: &' + ref + ';') def unknown_charref(self, ref): self.flush() - print '*** unknown char ref: &#' + ref + ';' + print('*** unknown char ref: &#' + ref + ';') def unknown_decl(self, data): self.flush() - print '*** unknown decl: [' + data + ']' + print('*** unknown decl: [' + data + ']') def close(self): SGMLParser.close(self) @@ -531,7 +531,7 @@ try: f = open(file, 'r') except IOError as msg: - print file, ":", msg + print(file, ":", msg) sys.exit(1) data = f.read() Modified: python/branches/p3yk/Lib/shlex.py ============================================================================== --- python/branches/p3yk/Lib/shlex.py (original) +++ python/branches/p3yk/Lib/shlex.py Fri Feb 9 06:37:30 2007 @@ -53,13 +53,13 @@ self.filestack = deque() self.source = None if self.debug: - print 'shlex: reading from %s, line %d' \ - % (self.instream, self.lineno) + print('shlex: reading from %s, line %d' \ + % (self.instream, self.lineno)) def push_token(self, tok): "Push a token onto the stack popped by the get_token method" if self.debug >= 1: - print "shlex: pushing token " + repr(tok) + print("shlex: pushing token " + repr(tok)) self.pushback.appendleft(tok) def push_source(self, newstream, newfile=None): @@ -72,17 +72,17 @@ self.lineno = 1 if self.debug: if newfile is not None: - print 'shlex: pushing to file %s' % (self.infile,) + print('shlex: pushing to file %s' % (self.infile,)) else: - print 'shlex: pushing to stream %s' % (self.instream,) + print('shlex: pushing to stream %s' % (self.instream,)) def pop_source(self): "Pop the input source stack." self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() if self.debug: - print 'shlex: popping to %s, line %d' \ - % (self.instream, self.lineno) + print('shlex: popping to %s, line %d' \ + % (self.instream, self.lineno)) self.state = ' ' def get_token(self): @@ -90,7 +90,7 @@ if self.pushback: tok = self.pushback.popleft() if self.debug >= 1: - print "shlex: popping token " + repr(tok) + print("shlex: popping token " + repr(tok)) return tok # No pushback. Get a token. raw = self.read_token() @@ -112,9 +112,9 @@ # Neither inclusion nor EOF if self.debug >= 1: if raw != self.eof: - print "shlex: token=" + repr(raw) + print("shlex: token=" + repr(raw)) else: - print "shlex: token=EOF" + print("shlex: token=EOF") return raw def read_token(self): @@ -125,8 +125,8 @@ if nextchar == '\n': self.lineno = self.lineno + 1 if self.debug >= 3: - print "shlex: in state", repr(self.state), \ - "I see character:", repr(nextchar) + print("shlex: in state", repr(self.state), \ + "I see character:", repr(nextchar)) if self.state is None: self.token = '' # past end of file break @@ -136,7 +136,7 @@ break elif nextchar in self.whitespace: if self.debug >= 2: - print "shlex: I see whitespace in whitespace state" + print("shlex: I see whitespace in whitespace state") if self.token or (self.posix and quoted): break # emit current token else: @@ -167,7 +167,7 @@ quoted = True if not nextchar: # end of file if self.debug >= 2: - print "shlex: I see EOF in quotes state" + print("shlex: I see EOF in quotes state") # XXX what error should be raised here? raise ValueError, "No closing quotation" if nextchar == self.state: @@ -186,7 +186,7 @@ elif self.state in self.escape: if not nextchar: # end of file if self.debug >= 2: - print "shlex: I see EOF in escape state" + print("shlex: I see EOF in escape state") # XXX what error should be raised here? raise ValueError, "No escaped character" # In posix shells, only the quote itself or the escape @@ -202,7 +202,7 @@ break elif nextchar in self.whitespace: if self.debug >= 2: - print "shlex: I see whitespace in word state" + print("shlex: I see whitespace in word state") self.state = ' ' if self.token or (self.posix and quoted): break # emit current token @@ -228,7 +228,7 @@ else: self.pushback.appendleft(nextchar) if self.debug >= 2: - print "shlex: I see punctuation in word state" + print("shlex: I see punctuation in word state") self.state = ' ' if self.token: break # emit current token @@ -240,9 +240,9 @@ result = None if self.debug > 1: if result: - print "shlex: raw token=" + repr(result) + print("shlex: raw token=" + repr(result)) else: - print "shlex: raw token=EOF" + print("shlex: raw token=EOF") return result def sourcehook(self, newfile): @@ -287,6 +287,6 @@ while 1: tt = lexer.get_token() if tt: - print "Token: " + repr(tt) + print("Token: " + repr(tt)) else: break Modified: python/branches/p3yk/Lib/site.py ============================================================================== --- python/branches/p3yk/Lib/site.py (original) +++ python/branches/p3yk/Lib/site.py Fri Feb 9 06:37:30 2007 @@ -301,7 +301,7 @@ while 1: try: for i in range(lineno, lineno + self.MAXLINES): - print self.__lines[i] + print(self.__lines[i]) except IndexError: break else: @@ -424,10 +424,10 @@ main() def _test(): - print "sys.path = [" + print("sys.path = [") for dir in sys.path: - print " %r," % (dir,) - print "]" + print(" %r," % (dir,)) + print("]") if __name__ == '__main__': _test() Modified: python/branches/p3yk/Lib/smtpd.py ============================================================================== --- python/branches/p3yk/Lib/smtpd.py (original) +++ python/branches/p3yk/Lib/smtpd.py Fri Feb 9 06:37:30 2007 @@ -98,9 +98,9 @@ def usage(code, msg=''): - print >> sys.stderr, __doc__ % globals() + print(__doc__ % globals(), file=sys.stderr) if msg: - print >> sys.stderr, msg + print(msg, file=sys.stderr) sys.exit(code) @@ -122,7 +122,7 @@ self.__data = '' self.__fqdn = socket.getfqdn() self.__peer = conn.getpeername() - print >> DEBUGSTREAM, 'Peer:', repr(self.__peer) + print('Peer:', repr(self.__peer), file=DEBUGSTREAM) self.push('220 %s %s' % (self.__fqdn, __version__)) self.set_terminator('\r\n') @@ -137,7 +137,7 @@ # Implementation of base class abstract method def found_terminator(self): line = EMPTYSTRING.join(self.__line) - print >> DEBUGSTREAM, 'Data:', repr(line) + print('Data:', repr(line), file=DEBUGSTREAM) self.__line = [] if self.__state == self.COMMAND: if not line: @@ -220,7 +220,7 @@ return address def smtp_MAIL(self, arg): - print >> DEBUGSTREAM, '===> MAIL', arg + print('===> MAIL', arg, file=DEBUGSTREAM) address = self.__getaddr('FROM:', arg) if not address: self.push('501 Syntax: MAIL FROM:
') @@ -229,11 +229,11 @@ self.push('503 Error: nested MAIL command') return self.__mailfrom = address - print >> DEBUGSTREAM, 'sender:', self.__mailfrom + print('sender:', self.__mailfrom, file=DEBUGSTREAM) self.push('250 Ok') def smtp_RCPT(self, arg): - print >> DEBUGSTREAM, '===> RCPT', arg + print('===> RCPT', arg, file=DEBUGSTREAM) if not self.__mailfrom: self.push('503 Error: need MAIL command') return @@ -242,7 +242,7 @@ self.push('501 Syntax: RCPT TO:
') return self.__rcpttos.append(address) - print >> DEBUGSTREAM, 'recips:', self.__rcpttos + print('recips:', self.__rcpttos, file=DEBUGSTREAM) self.push('250 Ok') def smtp_RSET(self, arg): @@ -279,14 +279,13 @@ self.set_reuse_addr() self.bind(localaddr) self.listen(5) - print >> DEBUGSTREAM, \ - '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( + print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( self.__class__.__name__, time.ctime(time.time()), - localaddr, remoteaddr) + localaddr, remoteaddr), file=DEBUGSTREAM) def handle_accept(self): conn, addr = self.accept() - print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr) + print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM) channel = SMTPChannel(self, conn, addr) # API for "doing something useful with the message" @@ -321,14 +320,14 @@ def process_message(self, peer, mailfrom, rcpttos, data): inheaders = 1 lines = data.split('\n') - print '---------- MESSAGE FOLLOWS ----------' + print('---------- MESSAGE FOLLOWS ----------') for line in lines: # headers first if inheaders and not line: - print 'X-Peer:', peer[0] + print('X-Peer:', peer[0]) inheaders = 0 - print line - print '------------ END MESSAGE ------------' + print(line) + print('------------ END MESSAGE ------------') @@ -345,7 +344,7 @@ data = NEWLINE.join(lines) refused = self._deliver(mailfrom, rcpttos, data) # TBD: what to do with refused addresses? - print >> DEBUGSTREAM, 'we got some refusals:', refused + print('we got some refusals:', refused, file=DEBUGSTREAM) def _deliver(self, mailfrom, rcpttos, data): import smtplib @@ -358,10 +357,10 @@ finally: s.quit() except smtplib.SMTPRecipientsRefused as e: - print >> DEBUGSTREAM, 'got SMTPRecipientsRefused' + print('got SMTPRecipientsRefused', file=DEBUGSTREAM) refused = e.recipients except (socket.error, smtplib.SMTPException) as e: - print >> DEBUGSTREAM, 'got', e.__class__ + print('got', e.__class__, file=DEBUGSTREAM) # All recipients were refused. If the exception had an associated # error code, use it. Otherwise,fake it with a non-triggering # exception code. @@ -410,11 +409,11 @@ for rcpt, listname, command in listnames: rcpttos.remove(rcpt) # If there's any non-list destined recipients left, - print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos) + print('forwarding recips:', ' '.join(rcpttos), file=DEBUGSTREAM) if rcpttos: refused = self._deliver(mailfrom, rcpttos, data) # TBD: what to do with refused addresses? - print >> DEBUGSTREAM, 'we got refusals:', refused + print('we got refusals:', refused, file=DEBUGSTREAM) # Now deliver directly to the list commands mlists = {} s = StringIO(data) @@ -427,7 +426,7 @@ if not msg.getheader('date'): msg['Date'] = time.ctime(time.time()) for rcpt, listname, command in listnames: - print >> DEBUGSTREAM, 'sending message to', rcpt + print('sending message to', rcpt, file=DEBUGSTREAM) mlist = mlists.get(listname) if not mlist: mlist = MailList.MailList(listname, lock=0) @@ -472,7 +471,7 @@ if opt in ('-h', '--help'): usage(0) elif opt in ('-V', '--version'): - print >> sys.stderr, __version__ + print(__version__, file=sys.stderr) sys.exit(0) elif opt in ('-n', '--nosetuid'): options.setuid = 0 @@ -522,16 +521,14 @@ try: import pwd except ImportError: - print >> sys.stderr, \ - 'Cannot import module "pwd"; try running with -n option.' + print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr) sys.exit(1) nobody = pwd.getpwnam('nobody')[2] try: os.setuid(nobody) except OSError as e: if e.errno != errno.EPERM: raise - print >> sys.stderr, \ - 'Cannot setuid "nobody"; try running with -n option.' + print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr) sys.exit(1) classname = options.classname if "." in classname: Modified: python/branches/p3yk/Lib/smtplib.py ============================================================================== --- python/branches/p3yk/Lib/smtplib.py (original) +++ python/branches/p3yk/Lib/smtplib.py Fri Feb 9 06:37:30 2007 @@ -277,7 +277,7 @@ # This makes it simpler for SMTP_SSL to use the SMTP connect code # and just alter the socket connection bit. self.sock = socket.socket(af, socktype, proto) - if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) + if self.debuglevel > 0: print('connect:', (host, port), file=stderr) self.sock.connect(sa) def connect(self, host='localhost', port = 0): @@ -299,7 +299,7 @@ except ValueError: raise socket.error, "nonnumeric port" if not port: port = self.default_port - if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) + if self.debuglevel > 0: print('connect:', (host, port), file=stderr) msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): @@ -307,7 +307,7 @@ try: self._get_socket(af,socktype,proto,sa) except socket.error as msg: - if self.debuglevel > 0: print>>stderr, 'connect fail:', msg + if self.debuglevel > 0: print('connect fail:', msg, file=stderr) if self.sock: self.sock.close() self.sock = None @@ -316,12 +316,12 @@ if not self.sock: raise socket.error, msg (code, msg) = self.getreply() - if self.debuglevel > 0: print>>stderr, "connect:", msg + if self.debuglevel > 0: print("connect:", msg, file=stderr) return (code, msg) def send(self, str): """Send `str' to the server.""" - if self.debuglevel > 0: print>>stderr, 'send:', repr(str) + if self.debuglevel > 0: print('send:', repr(str), file=stderr) if self.sock: try: self.sock.sendall(str) @@ -360,7 +360,7 @@ if line == '': self.close() raise SMTPServerDisconnected("Connection unexpectedly closed") - if self.debuglevel > 0: print>>stderr, 'reply:', repr(line) + if self.debuglevel > 0: print('reply:', repr(line), file=stderr) resp.append(line[4:].strip()) code=line[:3] # Check that the error code is syntactically correct. @@ -376,7 +376,7 @@ errmsg = "\n".join(resp) if self.debuglevel > 0: - print>>stderr, 'reply: retcode (%s); Msg: %s' % (errcode,errmsg) + print('reply: retcode (%s); Msg: %s' % (errcode,errmsg), file=stderr) return errcode, errmsg def docmd(self, cmd, args=""): @@ -489,7 +489,7 @@ """ self.putcmd("data") (code,repl)=self.getreply() - if self.debuglevel >0 : print>>stderr, "data:", (code,repl) + if self.debuglevel >0 : print("data:", (code,repl), file=stderr) if code != 354: raise SMTPDataError(code,repl) else: @@ -499,7 +499,7 @@ q = q + "." + CRLF self.send(q) (code,msg)=self.getreply() - if self.debuglevel >0 : print>>stderr, "data:", (code,msg) + if self.debuglevel >0 : print("data:", (code,msg), file=stderr) return (code,msg) def verify(self, address): @@ -740,7 +740,7 @@ def _get_socket(self,af, socktype, proto,sa): self.sock = socket.socket(af, socktype, proto) - if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) + if self.debuglevel > 0: print('connect:', (host, port), file=stderr) self.sock.connect(sa) sslobj = socket.ssl(self.sock, self.keyfile, self.certfile) self.sock = SSLFakeSocket(self.sock, sslobj) @@ -757,14 +757,14 @@ fromaddr = prompt("From") toaddrs = prompt("To").split(',') - print "Enter message, end with ^D:" + print("Enter message, end with ^D:") msg = '' while 1: line = sys.stdin.readline() if not line: break msg = msg + line - print "Message length is %d" % len(msg) + print("Message length is %d" % len(msg)) server = SMTP('localhost') server.set_debuglevel(1) Modified: python/branches/p3yk/Lib/sndhdr.py ============================================================================== --- python/branches/p3yk/Lib/sndhdr.py (original) +++ python/branches/p3yk/Lib/sndhdr.py Fri Feb 9 06:37:30 2007 @@ -208,21 +208,21 @@ import os for filename in list: if os.path.isdir(filename): - print filename + '/:', + print(filename + '/:', end=' ') if recursive or toplevel: - print 'recursing down:' + print('recursing down:') import glob names = glob.glob(os.path.join(filename, '*')) testall(names, recursive, 0) else: - print '*** directory (use -r) ***' + print('*** directory (use -r) ***') else: - print filename + ':', + print(filename + ':', end=' ') sys.stdout.flush() try: - print what(filename) + print(what(filename)) except IOError: - print '*** not found ***' + print('*** not found ***') if __name__ == '__main__': test() Modified: python/branches/p3yk/Lib/sqlite3/test/dbapi.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/test/dbapi.py (original) +++ python/branches/p3yk/Lib/sqlite3/test/dbapi.py Fri Feb 9 06:37:30 2007 @@ -327,7 +327,7 @@ except TypeError: return except Exception as e: - print "raised", e.__class__ + print("raised", e.__class__) self.fail("raised wrong exception.") def CheckFetchIter(self): Modified: python/branches/p3yk/Lib/sre_constants.py ============================================================================== --- python/branches/p3yk/Lib/sre_constants.py (original) +++ python/branches/p3yk/Lib/sre_constants.py Fri Feb 9 06:37:30 2007 @@ -258,4 +258,4 @@ f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET) f.close() - print "done" + print("done") Modified: python/branches/p3yk/Lib/sre_parse.py ============================================================================== --- python/branches/p3yk/Lib/sre_parse.py (original) +++ python/branches/p3yk/Lib/sre_parse.py Fri Feb 9 06:37:30 2007 @@ -103,30 +103,30 @@ nl = 1 seqtypes = type(()), type([]) for op, av in self.data: - print level*" " + op,; nl = 0 + print(level*" " + op, end=' '); nl = 0 if op == "in": # member sublanguage - print; nl = 1 + print(); nl = 1 for op, a in av: - print (level+1)*" " + op, a + print((level+1)*" " + op, a) elif op == "branch": - print; nl = 1 + print(); nl = 1 i = 0 for a in av[1]: if i > 0: - print level*" " + "or" + print(level*" " + "or") a.dump(level+1); nl = 1 i = i + 1 elif type(av) in seqtypes: for a in av: if isinstance(a, SubPattern): - if not nl: print + if not nl: print() a.dump(level+1); nl = 1 else: - print a, ; nl = 0 + print(a, end=' ') ; nl = 0 else: - print av, ; nl = 0 - if not nl: print + print(av, end=' ') ; nl = 0 + if not nl: print() def __repr__(self): return repr(self.data) def __len__(self): Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Fri Feb 9 06:37:30 2007 @@ -1165,8 +1165,8 @@ # Example 1: Simple redirection: Get process list # plist = Popen(["ps"], stdout=PIPE).communicate()[0] - print "Process list:" - print plist + print("Process list:") + print(plist) # # Example 2: Change uid before executing child @@ -1178,42 +1178,42 @@ # # Example 3: Connecting several subprocesses # - print "Looking for 'hda'..." + print("Looking for 'hda'...") p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) - print repr(p2.communicate()[0]) + print(repr(p2.communicate()[0])) # # Example 4: Catch execution error # - print - print "Trying a weird file..." + print() + print("Trying a weird file...") try: - print Popen(["/this/path/does/not/exist"]).communicate() + print(Popen(["/this/path/does/not/exist"]).communicate()) except OSError as e: if e.errno == errno.ENOENT: - print "The file didn't exist. I thought so..." - print "Child traceback:" - print e.child_traceback + print("The file didn't exist. I thought so...") + print("Child traceback:") + print(e.child_traceback) else: - print "Error", e.errno + print("Error", e.errno) else: - print >>sys.stderr, "Gosh. No error." + print("Gosh. No error.", file=sys.stderr) def _demo_windows(): # # Example 1: Connecting several subprocesses # - print "Looking for 'PROMPT' in set output..." + print("Looking for 'PROMPT' in set output...") p1 = Popen("set", stdout=PIPE, shell=True) p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) - print repr(p2.communicate()[0]) + print(repr(p2.communicate()[0])) # # Example 2: Simple execution of program # - print "Executing calc..." + print("Executing calc...") p = Popen("calc") p.wait() Modified: python/branches/p3yk/Lib/sunaudio.py ============================================================================== --- python/branches/p3yk/Lib/sunaudio.py (original) +++ python/branches/p3yk/Lib/sunaudio.py Fri Feb 9 06:37:30 2007 @@ -36,9 +36,9 @@ data_size, encoding, sample_rate, channels, info = hdr while info[-1:] == '\0': info = info[:-1] - print 'File name: ', file - print 'Data size: ', data_size - print 'Encoding: ', encoding - print 'Sample rate:', sample_rate - print 'Channels: ', channels - print 'Info: ', repr(info) + print('File name: ', file) + print('Data size: ', data_size) + print('Encoding: ', encoding) + print('Sample rate:', sample_rate) + print('Channels: ', channels) + print('Info: ', repr(info)) Modified: python/branches/p3yk/Lib/symtable.py ============================================================================== --- python/branches/p3yk/Lib/symtable.py (original) +++ python/branches/p3yk/Lib/symtable.py Fri Feb 9 06:37:30 2007 @@ -249,4 +249,4 @@ mod = symtable(src, os.path.split(sys.argv[0])[1], "exec") for ident in mod.get_identifiers(): info = mod.lookup(ident) - print info, info.is_local(), info.is_namespace() + print(info, info.is_local(), info.is_namespace()) Modified: python/branches/p3yk/Lib/tabnanny.py ============================================================================== --- python/branches/p3yk/Lib/tabnanny.py (original) +++ python/branches/p3yk/Lib/tabnanny.py Fri Feb 9 06:37:30 2007 @@ -83,7 +83,7 @@ if os.path.isdir(file) and not os.path.islink(file): if verbose: - print "%r: listing directory" % (file,) + print("%r: listing directory" % (file,)) names = os.listdir(file) for name in names: fullname = os.path.join(file, name) @@ -100,7 +100,7 @@ return if verbose > 1: - print "checking %r ..." % file + print("checking %r ..." % file) try: process_tokens(tokenize.generate_tokens(f.readline)) @@ -117,17 +117,17 @@ badline = nag.get_lineno() line = nag.get_line() if verbose: - print "%r: *** Line %d: trouble in tab city! ***" % (file, badline) - print "offending line: %r" % (line,) - print nag.get_msg() + print("%r: *** Line %d: trouble in tab city! ***" % (file, badline)) + print("offending line: %r" % (line,)) + print(nag.get_msg()) else: if ' ' in file: file = '"' + file + '"' - if filename_only: print file - else: print file, badline, repr(line) + if filename_only: print(file) + else: print(file, badline, repr(line)) return if verbose: - print "%r: Clean bill of health." % (file,) + print("%r: Clean bill of health." % (file,)) class Whitespace: # the characters used for space and tab Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Fri Feb 9 06:37:30 2007 @@ -1408,25 +1408,25 @@ for tarinfo in self: if verbose: - print filemode(tarinfo.mode), - print "%s/%s" % (tarinfo.uname or tarinfo.uid, - tarinfo.gname or tarinfo.gid), + print(filemode(tarinfo.mode), end=' ') + print("%s/%s" % (tarinfo.uname or tarinfo.uid, + tarinfo.gname or tarinfo.gid), end=' ') if tarinfo.ischr() or tarinfo.isblk(): - print "%10s" % ("%d,%d" \ - % (tarinfo.devmajor, tarinfo.devminor)), + print("%10s" % ("%d,%d" \ + % (tarinfo.devmajor, tarinfo.devminor)), end=' ') else: - print "%10d" % tarinfo.size, - print "%d-%02d-%02d %02d:%02d:%02d" \ - % time.localtime(tarinfo.mtime)[:6], + print("%10d" % tarinfo.size, end=' ') + print("%d-%02d-%02d %02d:%02d:%02d" \ + % time.localtime(tarinfo.mtime)[:6], end=' ') - print tarinfo.name, + print(tarinfo.name, end=' ') if verbose: if tarinfo.issym(): - print "->", tarinfo.linkname, + print("->", tarinfo.linkname, end=' ') if tarinfo.islnk(): - print "link to", tarinfo.linkname, - print + print("link to", tarinfo.linkname, end=' ') + print() def add(self, name, arcname=None, recursive=True): """Add the file `name' to the archive. `name' may be any type of file @@ -2022,7 +2022,7 @@ """Write debugging output to sys.stderr. """ if level <= self.debug: - print >> sys.stderr, msg + print(msg, file=sys.stderr) # class TarFile class TarIter: Modified: python/branches/p3yk/Lib/telnetlib.py ============================================================================== --- python/branches/p3yk/Lib/telnetlib.py (original) +++ python/branches/p3yk/Lib/telnetlib.py Fri Feb 9 06:37:30 2007 @@ -248,11 +248,11 @@ """ if self.debuglevel > 0: - print 'Telnet(%s,%d):' % (self.host, self.port), + print('Telnet(%s,%d):' % (self.host, self.port), end=' ') if args: - print msg % args + print(msg % args) else: - print msg + print(msg) def set_debuglevel(self, debuglevel): """Set the debug level. @@ -545,7 +545,7 @@ try: text = self.read_eager() except EOFError: - print '*** Connection closed by remote host ***' + print('*** Connection closed by remote host ***') break if text: sys.stdout.write(text) @@ -572,7 +572,7 @@ try: data = self.read_eager() except EOFError: - print '*** Connection closed by remote host ***' + print('*** Connection closed by remote host ***') return if data: sys.stdout.write(data) Modified: python/branches/p3yk/Lib/test/badsyntax_future8.py ============================================================================== --- python/branches/p3yk/Lib/test/badsyntax_future8.py (original) +++ python/branches/p3yk/Lib/test/badsyntax_future8.py Fri Feb 9 06:37:30 2007 @@ -7,4 +7,4 @@ return x + y return g -print f(2)(4) +print(f(2)(4)) Modified: python/branches/p3yk/Lib/test/badsyntax_future9.py ============================================================================== --- python/branches/p3yk/Lib/test/badsyntax_future9.py (original) +++ python/branches/p3yk/Lib/test/badsyntax_future9.py Fri Feb 9 06:37:30 2007 @@ -7,4 +7,4 @@ return x + y return g -print f(2)(4) +print(f(2)(4)) Modified: python/branches/p3yk/Lib/test/crashers/bogus_sre_bytecode.py ============================================================================== --- python/branches/p3yk/Lib/test/crashers/bogus_sre_bytecode.py (original) +++ python/branches/p3yk/Lib/test/crashers/bogus_sre_bytecode.py Fri Feb 9 06:37:30 2007 @@ -38,7 +38,7 @@ while 1: code = [pick() for i in range(random.randrange(5, 25))] - print code + print(code) pat = _sre.compile(None, 0, code) for s in ss: try: Modified: python/branches/p3yk/Lib/test/crashers/borrowed_ref_1.py ============================================================================== --- python/branches/p3yk/Lib/test/crashers/borrowed_ref_1.py (original) +++ python/branches/p3yk/Lib/test/crashers/borrowed_ref_1.py Fri Feb 9 06:37:30 2007 @@ -8,7 +8,7 @@ class B(object): def __del__(self): - print 'hi' + print('hi') del D.__missing__ class D(dict): Modified: python/branches/p3yk/Lib/test/crashers/borrowed_ref_2.py ============================================================================== --- python/branches/p3yk/Lib/test/crashers/borrowed_ref_2.py (original) +++ python/branches/p3yk/Lib/test/crashers/borrowed_ref_2.py Fri Feb 9 06:37:30 2007 @@ -10,7 +10,7 @@ class B(object): def __del__(self): - print "hi" + print("hi") del C.d class D(object): Modified: python/branches/p3yk/Lib/test/crashers/gc_inspection.py ============================================================================== --- python/branches/p3yk/Lib/test/crashers/gc_inspection.py (original) +++ python/branches/p3yk/Lib/test/crashers/gc_inspection.py Fri Feb 9 06:37:30 2007 @@ -25,8 +25,8 @@ yield marker # now the marker is in the tuple being constructed [tup] = [x for x in gc.get_referrers(marker) if type(x) is tuple] - print tup - print tup[1] + print(tup) + print(tup[1]) tuple(g()) Modified: python/branches/p3yk/Lib/test/crashers/loosing_mro_ref.py ============================================================================== --- python/branches/p3yk/Lib/test/crashers/loosing_mro_ref.py (original) +++ python/branches/p3yk/Lib/test/crashers/loosing_mro_ref.py Fri Feb 9 06:37:30 2007 @@ -32,5 +32,5 @@ # there from the beginning :-) locals()[MyKey()] = 5 -print X.mykey +print(X.mykey) # I get a segfault, or a slightly wrong assertion error in a debug build. Modified: python/branches/p3yk/Lib/test/crashers/modify_dict_attr.py ============================================================================== --- python/branches/p3yk/Lib/test/crashers/modify_dict_attr.py (original) +++ python/branches/p3yk/Lib/test/crashers/modify_dict_attr.py Fri Feb 9 06:37:30 2007 @@ -16,4 +16,4 @@ if __name__ == '__main__': del MyClass.__dict__ # if we set tp_dict to NULL, - print MyClass # doing anything with MyClass segfaults + print(MyClass) # doing anything with MyClass segfaults Modified: python/branches/p3yk/Lib/test/crashers/nasty_eq_vs_dict.py ============================================================================== --- python/branches/p3yk/Lib/test/crashers/nasty_eq_vs_dict.py (original) +++ python/branches/p3yk/Lib/test/crashers/nasty_eq_vs_dict.py Fri Feb 9 06:37:30 2007 @@ -44,4 +44,4 @@ z = Yuck() y.make_dangerous() -print dict[z] +print(dict[z]) Modified: python/branches/p3yk/Lib/test/inspect_fodder2.py ============================================================================== --- python/branches/p3yk/Lib/test/inspect_fodder2.py (original) +++ python/branches/p3yk/Lib/test/inspect_fodder2.py Fri Feb 9 06:37:30 2007 @@ -7,7 +7,7 @@ # line 7 def replace(func): def insteadfunc(): - print 'hello' + print('hello') return insteadfunc # line 13 Modified: python/branches/p3yk/Lib/test/list_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/list_tests.py (original) +++ python/branches/p3yk/Lib/test/list_tests.py Fri Feb 9 06:37:30 2007 @@ -54,7 +54,7 @@ d.append(400) try: fo = open(test_support.TESTFN, "wb") - print >> fo, d, + print(d, end=' ', file=fo) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(d)) Modified: python/branches/p3yk/Lib/test/pydocfodder.py ============================================================================== --- python/branches/p3yk/Lib/test/pydocfodder.py (original) +++ python/branches/p3yk/Lib/test/pydocfodder.py Fri Feb 9 06:37:30 2007 @@ -192,19 +192,19 @@ def __init__(self, attr): self.attr = attr def __call__(self, inst): - print 'Get called', self, inst + print('Get called', self, inst) return inst.desc[self.attr] class set_desc: def __init__(self, attr): self.attr = attr def __call__(self, inst, val): - print 'Set called', self, inst, val + print('Set called', self, inst, val) inst.desc[self.attr] = val class del_desc: def __init__(self, attr): self.attr = attr def __call__(self, inst): - print 'Del called', self, inst + print('Del called', self, inst) del inst.desc[self.attr] x = property(get_desc('x'), set_desc('x'), del_desc('x'), 'prop x') Modified: python/branches/p3yk/Lib/test/pystone.py ============================================================================== --- python/branches/p3yk/Lib/test/pystone.py (original) +++ python/branches/p3yk/Lib/test/pystone.py Fri Feb 9 06:37:30 2007 @@ -59,9 +59,9 @@ def main(loops=LOOPS): benchtime, stones = pystones(loops) - print "Pystone(%s) time for %d passes = %g" % \ - (__version__, loops, benchtime) - print "This machine benchmarks at %g pystones/second" % stones + print("Pystone(%s) time for %d passes = %g" % \ + (__version__, loops, benchtime)) + print("This machine benchmarks at %g pystones/second" % stones) def pystones(loops=LOOPS): @@ -251,8 +251,8 @@ if __name__ == '__main__': import sys def error(msg): - print >>sys.stderr, msg, - print >>sys.stderr, "usage: %s [number_of_loops]" % sys.argv[0] + print(msg, end=' ', file=sys.stderr) + print("usage: %s [number_of_loops]" % sys.argv[0], file=sys.stderr) sys.exit(100) nargs = len(sys.argv) - 1 if nargs > 1: Modified: python/branches/p3yk/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk/Lib/test/regrtest.py (original) +++ python/branches/p3yk/Lib/test/regrtest.py Fri Feb 9 06:37:30 2007 @@ -171,8 +171,8 @@ def usage(code, msg=''): - print __doc__ - if msg: print msg + print(__doc__) + if msg: print(msg) sys.exit(code) @@ -253,7 +253,7 @@ elif o in ('-R', '--huntrleaks'): huntrleaks = a.split(':') if len(huntrleaks) != 3: - print a, huntrleaks + print(a, huntrleaks) usage(2, '-R takes three colon-separated arguments') if len(huntrleaks[0]) == 0: huntrleaks[0] = 5 @@ -298,7 +298,7 @@ try: import gc except ImportError: - print 'No GC available, disabling findleaks.' + print('No GC available, disabling findleaks.') findleaks = False else: # Uncomment the line below to report garbage that is not @@ -355,7 +355,7 @@ save_modules = sys.modules.keys() for test in tests: if not quiet: - print test + print(test) sys.stdout.flush() if trace: # If we're tracing code coverage, then we don't exit with status @@ -368,7 +368,7 @@ huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C - print + print() break except: raise @@ -383,8 +383,8 @@ if findleaks: gc.collect() if gc.garbage: - print "Warning: test created", len(gc.garbage), - print "uncollectable object(s)." + print("Warning: test created", len(gc.garbage), end=' ') + print("uncollectable object(s).") # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) @@ -401,16 +401,16 @@ if good and not quiet: if not bad and not skipped and len(good) > 1: - print "All", - print count(len(good), "test"), "OK." + print("All", end=' ') + print(count(len(good), "test"), "OK.") if verbose: - print "CAUTION: stdout isn't compared in verbose mode:" - print "a test that passes in verbose mode may fail without it." + print("CAUTION: stdout isn't compared in verbose mode:") + print("a test that passes in verbose mode may fail without it.") if bad: - print count(len(bad), "test"), "failed:" + print(count(len(bad), "test"), "failed:") printlist(bad) if skipped and not quiet: - print count(len(skipped), "test"), "skipped:" + print(count(len(skipped), "test"), "skipped:") printlist(skipped) e = _ExpectedSkips() @@ -418,19 +418,19 @@ if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: - print count(len(surprise), "skip"), \ - "unexpected on", plat + ":" + print(count(len(surprise), "skip"), \ + "unexpected on", plat + ":") printlist(surprise) else: - print "Those skips are all expected on", plat + "." + print("Those skips are all expected on", plat + ".") else: - print "Ask someone to teach regrtest.py about which tests are" - print "expected to get skipped on", plat + "." + print("Ask someone to teach regrtest.py about which tests are") + print("expected to get skipped on", plat + ".") if verbose2 and bad: - print "Re-running failed tests in verbose mode" + print("Re-running failed tests in verbose mode") for test in bad: - print "Re-running test %r in verbose mode" % test + print("Re-running test %r in verbose mode" % test) sys.stdout.flush() try: test_support.verbose = 1 @@ -438,7 +438,7 @@ huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C - print + print() break except: raise @@ -537,7 +537,7 @@ try: if cfp: sys.stdout = cfp - print test # Output file starts with test name + print(test) # Output file starts with test name if test.startswith('test.'): abstest = test else: @@ -558,23 +558,23 @@ sys.stdout = save_stdout except test_support.ResourceDenied as msg: if not quiet: - print test, "skipped --", msg + print(test, "skipped --", msg) sys.stdout.flush() return -2 except (ImportError, test_support.TestSkipped) as msg: if not quiet: - print test, "skipped --", msg + print(test, "skipped --", msg) sys.stdout.flush() return -1 except KeyboardInterrupt: raise except test_support.TestFailed as msg: - print "test", test, "failed --", msg + print("test", test, "failed --", msg) sys.stdout.flush() return 0 except: type, value = sys.exc_info()[:2] - print "test", test, "crashed --", str(type) + ":", value + print("test", test, "crashed --", str(type) + ":", value) sys.stdout.flush() if verbose: traceback.print_exc(file=sys.stdout) @@ -590,8 +590,8 @@ # Write it since it already exists (and the contents # may have changed), but let the user know it isn't # needed: - print "output file", outputfile, \ - "is no longer needed; consider removing it" + print("output file", outputfile, \ + "is no longer needed; consider removing it") else: # We don't need it, so don't create it. return 1 @@ -607,7 +607,7 @@ expected = test + "\n" if output == expected or huntrleaks: return 1 - print "test", test, "produced unexpected output:" + print("test", test, "produced unexpected output:") sys.stdout.flush() reportdiff(expected, output) sys.stdout.flush() @@ -637,12 +637,12 @@ "directory nor file" % name) if verbose: - print "%r left behind %s %r" % (testname, kind, name) + print("%r left behind %s %r" % (testname, kind, name)) try: nuker(name) except Exception as msg: - print >> sys.stderr, ("%r left behind %s %r and it couldn't be " - "removed: %s" % (testname, kind, name, msg)) + print(("%r left behind %s %r and it couldn't be " + "removed: %s" % (testname, kind, name, msg)), file=sys.stderr) def dash_R(the_module, test, indirect_test, huntrleaks): # This code is hackish and inelegant, but it seems to do the job. @@ -667,8 +667,8 @@ deltas = [] nwarmup, ntracked, fname = huntrleaks repcount = nwarmup + ntracked - print >> sys.stderr, "beginning", repcount, "repetitions" - print >> sys.stderr, ("1234567890"*(repcount//10 + 1))[:repcount] + print("beginning", repcount, "repetitions", file=sys.stderr) + print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr) dash_R_cleanup(fs, ps, pic) for i in range(repcount): rc = sys.gettotalrefcount() @@ -677,11 +677,11 @@ dash_R_cleanup(fs, ps, pic) if i >= nwarmup: deltas.append(sys.gettotalrefcount() - rc - 2) - print >> sys.stderr + print(file=sys.stderr) if any(deltas): - print >> sys.stderr, test, 'leaked', deltas, 'references' + print(test, 'leaked', deltas, 'references', file=sys.stderr) refrep = open(fname, "a") - print >> refrep, test, 'leaked', deltas, 'references' + print(test, 'leaked', deltas, 'references', file=refrep) refrep.close() def dash_R_cleanup(fs, ps, pic): @@ -717,7 +717,7 @@ def reportdiff(expected, output): import difflib - print "*" * 70 + print("*" * 70) a = expected.splitlines(1) b = output.splitlines(1) sm = difflib.SequenceMatcher(a=a, b=b) @@ -736,26 +736,26 @@ pass elif op == 'delete': - print "***", pair(a0, a1), "of expected output missing:" + print("***", pair(a0, a1), "of expected output missing:") for line in a[a0:a1]: - print "-", line, + print("-", line, end=' ') elif op == 'replace': - print "*** mismatch between", pair(a0, a1), "of expected", \ - "output and", pair(b0, b1), "of actual output:" + print("*** mismatch between", pair(a0, a1), "of expected", \ + "output and", pair(b0, b1), "of actual output:") for line in difflib.ndiff(a[a0:a1], b[b0:b1]): - print line, + print(line, end=' ') elif op == 'insert': - print "***", pair(b0, b1), "of actual output doesn't appear", \ - "in expected output after line", str(a1)+":" + print("***", pair(b0, b1), "of actual output doesn't appear", \ + "in expected output after line", str(a1)+":") for line in b[b0:b1]: - print "+", line, + print("+", line, end=' ') else: - print "get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1) + print("get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1)) - print "*" * 70 + print("*" * 70) def findtestdir(): if __name__ == '__main__': @@ -786,8 +786,8 @@ from textwrap import fill blanks = ' ' * indent - print fill(' '.join(map(str, x)), width, - initial_indent=blanks, subsequent_indent=blanks) + print(fill(' '.join(map(str, x)), width, + initial_indent=blanks, subsequent_indent=blanks)) # Map sys.platform to a string containing the basenames of tests # expected to be skipped on that platform. @@ -1369,5 +1369,5 @@ if os.path.abspath(os.path.normpath(sys.path[i])) == mydir: del sys.path[i] if len(sys.path) == pathlen: - print 'Could not find %r in sys.path to remove it' % mydir + print('Could not find %r in sys.path to remove it' % mydir) main() Modified: python/branches/p3yk/Lib/test/reperf.py ============================================================================== --- python/branches/p3yk/Lib/test/reperf.py (original) +++ python/branches/p3yk/Lib/test/reperf.py Fri Feb 9 06:37:30 2007 @@ -17,7 +17,7 @@ finally: t1 = time.clock() if n > 1: - print n, "times", - print func.__name__, "%.3f" % (t1-t0), "CPU seconds" + print(n, "times", end=' ') + print(func.__name__, "%.3f" % (t1-t0), "CPU seconds") main() Modified: python/branches/p3yk/Lib/test/sortperf.py ============================================================================== --- python/branches/p3yk/Lib/test/sortperf.py (original) +++ python/branches/p3yk/Lib/test/sortperf.py Fri Feb 9 06:37:30 2007 @@ -38,7 +38,7 @@ except os.error: pass except IOError as msg: - print "can't write", fn, ":", msg + print("can't write", fn, ":", msg) else: result = marshal.load(fp) fp.close() @@ -60,7 +60,7 @@ t0 = time.clock() L.sort() t1 = time.clock() - print "%6.2f" % (t1-t0), + print("%6.2f" % (t1-t0), end=' ') flush() def tabulate(r): @@ -84,11 +84,11 @@ """ cases = tuple([ch + "sort" for ch in r"*\/3+%~=!"]) fmt = ("%2s %7s" + " %6s"*len(cases)) - print fmt % (("i", "2**i") + cases) + print(fmt % (("i", "2**i") + cases)) for i in r: n = 1 << i L = randfloats(n) - print "%2d %7d" % (i, n), + print("%2d %7d" % (i, n), end=' ') flush() doit(L) # *sort L.reverse() @@ -137,7 +137,7 @@ # significantly faster if we leave tham as ints. L = map(float, L) doit(L) # !sort - print + print() def main(): """Main program when invoked as a script. Modified: python/branches/p3yk/Lib/test/test_al.py ============================================================================== --- python/branches/p3yk/Lib/test/test_al.py (original) +++ python/branches/p3yk/Lib/test/test_al.py Fri Feb 9 06:37:30 2007 @@ -14,10 +14,10 @@ def main(): # touch all the attributes of al without doing anything if verbose: - print 'Touching al module attributes...' + print('Touching al module attributes...') for attr in alattrs: if verbose: - print 'touching: ', attr + print('touching: ', attr) getattr(al, attr) main() Modified: python/branches/p3yk/Lib/test/test_array.py ============================================================================== --- python/branches/p3yk/Lib/test/test_array.py (original) +++ python/branches/p3yk/Lib/test/test_array.py Fri Feb 9 06:37:30 2007 @@ -975,7 +975,7 @@ test_support.run_unittest(*tests) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_ast.py ============================================================================== --- python/branches/p3yk/Lib/test/test_ast.py (original) +++ python/branches/p3yk/Lib/test/test_ast.py Fri Feb 9 06:37:30 2007 @@ -117,11 +117,11 @@ if __name__=='__main__' and sys.argv[1:] == ['-g']: for statements, kind in ((exec_tests, "exec"), (single_tests, "single"), (eval_tests, "eval")): - print kind+"_results = [" + print(kind+"_results = [") for s in statements: - print repr(to_tuple(compile(s, "?", kind, 0x400)))+"," - print "]" - print "run_tests()" + print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",") + print("]") + print("run_tests()") raise SystemExit def test_order(ast_node, parent_pos): Modified: python/branches/p3yk/Lib/test/test_atexit.py ============================================================================== --- python/branches/p3yk/Lib/test/test_atexit.py (original) +++ python/branches/p3yk/Lib/test/test_atexit.py Fri Feb 9 06:37:30 2007 @@ -75,16 +75,16 @@ ### helpers def h1(self): - print "h1" + print("h1") def h2(self): - print "h2" + print("h2") def h3(self): - print "h3" + print("h3") def h4(self, *args, **kwargs): - print "h4", args, kwargs + print("h4", args, kwargs) def raise1(self): raise TypeError Modified: python/branches/p3yk/Lib/test/test_audioop.py ============================================================================== --- python/branches/p3yk/Lib/test/test_audioop.py (original) +++ python/branches/p3yk/Lib/test/test_audioop.py Fri Feb 9 06:37:30 2007 @@ -7,7 +7,7 @@ def gendata2(): if verbose: - print 'getsample' + print('getsample') if audioop.getsample('\0\1', 2, 0) == 1: return '\0\0\0\1\0\2' else: @@ -15,7 +15,7 @@ def gendata4(): if verbose: - print 'getsample' + print('getsample') if audioop.getsample('\0\0\0\1', 4, 0) == 1: return '\0\0\0\0\0\0\0\1\0\0\0\2' else: @@ -23,7 +23,7 @@ def testmax(data): if verbose: - print 'max' + print('max') if audioop.max(data[0], 1) != 2 or \ audioop.max(data[1], 2) != 2 or \ audioop.max(data[2], 4) != 2: @@ -32,7 +32,7 @@ def testminmax(data): if verbose: - print 'minmax' + print('minmax') if audioop.minmax(data[0], 1) != (0, 2) or \ audioop.minmax(data[1], 2) != (0, 2) or \ audioop.minmax(data[2], 4) != (0, 2): @@ -41,7 +41,7 @@ def testmaxpp(data): if verbose: - print 'maxpp' + print('maxpp') if audioop.maxpp(data[0], 1) != 0 or \ audioop.maxpp(data[1], 2) != 0 or \ audioop.maxpp(data[2], 4) != 0: @@ -50,7 +50,7 @@ def testavg(data): if verbose: - print 'avg' + print('avg') if audioop.avg(data[0], 1) != 1 or \ audioop.avg(data[1], 2) != 1 or \ audioop.avg(data[2], 4) != 1: @@ -59,7 +59,7 @@ def testavgpp(data): if verbose: - print 'avgpp' + print('avgpp') if audioop.avgpp(data[0], 1) != 0 or \ audioop.avgpp(data[1], 2) != 0 or \ audioop.avgpp(data[2], 4) != 0: @@ -75,7 +75,7 @@ def testcross(data): if verbose: - print 'cross' + print('cross') if audioop.cross(data[0], 1) != 0 or \ audioop.cross(data[1], 2) != 0 or \ audioop.cross(data[2], 4) != 0: @@ -84,7 +84,7 @@ def testadd(data): if verbose: - print 'add' + print('add') data2 = [] for d in data: str = '' @@ -99,7 +99,7 @@ def testbias(data): if verbose: - print 'bias' + print('bias') # Note: this test assumes that avg() works d1 = audioop.bias(data[0], 1, 100) d2 = audioop.bias(data[1], 2, 100) @@ -112,7 +112,7 @@ def testlin2lin(data): if verbose: - print 'lin2lin' + print('lin2lin') # too simple: we test only the size for d1 in data: for d2 in data: @@ -130,7 +130,7 @@ def testlin2adpcm(data): if verbose: - print 'lin2adpcm' + print('lin2adpcm') # Very cursory test if audioop.lin2adpcm('\0\0\0\0', 1, None) != ('\0\0', (0,0)): return 0 @@ -138,7 +138,7 @@ def testlin2alaw(data): if verbose: - print 'lin2alaw' + print('lin2alaw') if audioop.lin2alaw(data[0], 1) != '\xd5\xc5\xf5' or \ audioop.lin2alaw(data[1], 2) != '\xd5\xd5\xd5' or \ audioop.lin2alaw(data[2], 4) != '\xd5\xd5\xd5': @@ -147,7 +147,7 @@ def testalaw2lin(data): if verbose: - print 'alaw2lin' + print('alaw2lin') # Cursory d = audioop.lin2alaw(data[0], 1) if audioop.alaw2lin(d, 1) != data[0]: @@ -156,7 +156,7 @@ def testlin2ulaw(data): if verbose: - print 'lin2ulaw' + print('lin2ulaw') if audioop.lin2ulaw(data[0], 1) != '\xff\xe7\xdb' or \ audioop.lin2ulaw(data[1], 2) != '\xff\xff\xff' or \ audioop.lin2ulaw(data[2], 4) != '\xff\xff\xff': @@ -165,7 +165,7 @@ def testulaw2lin(data): if verbose: - print 'ulaw2lin' + print('ulaw2lin') # Cursory d = audioop.lin2ulaw(data[0], 1) if audioop.ulaw2lin(d, 1) != data[0]: @@ -174,7 +174,7 @@ def testmul(data): if verbose: - print 'mul' + print('mul') data2 = [] for d in data: str = '' @@ -189,7 +189,7 @@ def testratecv(data): if verbose: - print 'ratecv' + print('ratecv') state = None d1, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state) d2, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state) @@ -199,14 +199,14 @@ def testreverse(data): if verbose: - print 'reverse' + print('reverse') if audioop.reverse(data[0], 1) != '\2\1\0': return 0 return 1 def testtomono(data): if verbose: - print 'tomono' + print('tomono') data2 = '' for d in data[0]: data2 = data2 + d + d @@ -216,7 +216,7 @@ def testtostereo(data): if verbose: - print 'tostereo' + print('tostereo') data2 = '' for d in data[0]: data2 = data2 + d + d @@ -226,28 +226,28 @@ def testfindfactor(data): if verbose: - print 'findfactor' + print('findfactor') if audioop.findfactor(data[1], data[1]) != 1.0: return 0 return 1 def testfindfit(data): if verbose: - print 'findfit' + print('findfit') if audioop.findfit(data[1], data[1]) != (0, 1.0): return 0 return 1 def testfindmax(data): if verbose: - print 'findmax' + print('findmax') if audioop.findmax(data[1], 1) != 2: return 0 return 1 def testgetsample(data): if verbose: - print 'getsample' + print('getsample') for i in range(3): if audioop.getsample(data[0], 1, i) != i or \ audioop.getsample(data[1], 2, i) != i or \ @@ -259,15 +259,15 @@ try: func = eval('test'+name) except NameError: - print 'No test found for audioop.'+name+'()' + print('No test found for audioop.'+name+'()') return try: rv = func(data) except 'xx': - print 'Test FAILED for audioop.'+name+'() (with an exception)' + print('Test FAILED for audioop.'+name+'() (with an exception)') return if not rv: - print 'Test FAILED for audioop.'+name+'()' + print('Test FAILED for audioop.'+name+'()') def testall(): data = [gendata1(), gendata2(), gendata4()] Modified: python/branches/p3yk/Lib/test/test_bisect.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bisect.py (original) +++ python/branches/p3yk/Lib/test/test_bisect.py Fri Feb 9 06:37:30 2007 @@ -252,7 +252,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_bool.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bool.py (original) +++ python/branches/p3yk/Lib/test/test_bool.py Fri Feb 9 06:37:30 2007 @@ -27,7 +27,7 @@ def test_print(self): try: fo = open(test_support.TESTFN, "wb") - print >> fo, False, True + print(False, True, file=fo) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), 'False True\n') Modified: python/branches/p3yk/Lib/test/test_bsddb.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bsddb.py (original) +++ python/branches/p3yk/Lib/test/test_bsddb.py Fri Feb 9 06:37:30 2007 @@ -147,42 +147,42 @@ # in pybsddb's _DBWithCursor this causes an internal DBCursor # object is created. Other test_ methods in this class could # inadvertently cause the deadlock but an explicit test is needed. - if debug: print "A" + if debug: print("A") k,v = self.f.first() - if debug: print "B", k + if debug: print("B", k) self.f[k] = "deadlock. do not pass go. do not collect $200." - if debug: print "C" + if debug: print("C") # if the bsddb implementation leaves the DBCursor open during # the database write and locking+threading support is enabled # the cursor's read lock will deadlock the write lock request.. # test the iterator interface (if present) if hasattr(self.f, 'iteritems'): - if debug: print "D" + if debug: print("D") i = self.f.iteritems() k,v = i.next() - if debug: print "E" + if debug: print("E") self.f[k] = "please don't deadlock" - if debug: print "F" + if debug: print("F") while 1: try: k,v = i.next() except StopIteration: break - if debug: print "F2" + if debug: print("F2") i = iter(self.f) - if debug: print "G" + if debug: print("G") while i: try: - if debug: print "H" + if debug: print("H") k = i.next() - if debug: print "I" + if debug: print("I") self.f[k] = "deadlocks-r-us" - if debug: print "J" + if debug: print("J") except StopIteration: i = None - if debug: print "K" + if debug: print("K") # test the legacy cursor interface mixed with writes self.assert_(self.f.first()[0] in self.d) Modified: python/branches/p3yk/Lib/test/test_bsddb3.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bsddb3.py (original) +++ python/branches/p3yk/Lib/test/test_bsddb3.py Fri Feb 9 06:37:30 2007 @@ -65,12 +65,12 @@ # For invocation as a script if __name__ == '__main__': from bsddb import db - print '-=' * 38 - print db.DB_VERSION_STRING - print 'bsddb.db.version(): %s' % (db.version(),) - print 'bsddb.db.__version__: %s' % db.__version__ - print 'bsddb.db.cvsid: %s' % db.cvsid - print 'python version: %s' % sys.version - print '-=' * 38 + print('-=' * 38) + print(db.DB_VERSION_STRING) + print('bsddb.db.version(): %s' % (db.version(),)) + print('bsddb.db.__version__: %s' % db.__version__) + print('bsddb.db.cvsid: %s' % db.cvsid) + print('python version: %s' % sys.version) + print('-=' * 38) unittest.main(defaultTest='suite') Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Fri Feb 9 06:37:30 2007 @@ -204,15 +204,15 @@ self.assertRaises(TypeError, cmp) def test_compile(self): - compile('print 1\n', '', 'exec') + compile('print(1)\n', '', 'exec') bom = '\xef\xbb\xbf' - compile(bom + 'print 1\n', '', 'exec') + compile(bom + 'print(1)\n', '', 'exec') self.assertRaises(TypeError, compile) - self.assertRaises(ValueError, compile, 'print 42\n', '', 'badmode') - self.assertRaises(ValueError, compile, 'print 42\n', '', 'single', 0xff) + self.assertRaises(ValueError, compile, 'print(42)\n', '', 'badmode') + self.assertRaises(ValueError, compile, 'print(42)\n', '', 'single', 0xff) self.assertRaises(TypeError, compile, chr(0), 'f', 'exec') if have_unicode: - compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec') + compile(unicode('print(u"\xc3\xa5")\n', 'utf8'), '', 'exec') self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec') self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad') @@ -1659,7 +1659,7 @@ run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": Modified: python/branches/p3yk/Lib/test/test_capi.py ============================================================================== --- python/branches/p3yk/Lib/test/test_capi.py (original) +++ python/branches/p3yk/Lib/test/test_capi.py Fri Feb 9 06:37:30 2007 @@ -11,7 +11,7 @@ if name.startswith('test_'): test = getattr(_testcapi, name) if test_support.verbose: - print "internal", name + print("internal", name) try: test() except _testcapi.error: @@ -23,7 +23,7 @@ import time if test_support.verbose: - print "auto-thread-state" + print("auto-thread-state") idents = [] Modified: python/branches/p3yk/Lib/test/test_cd.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cd.py (original) +++ python/branches/p3yk/Lib/test/test_cd.py Fri Feb 9 06:37:30 2007 @@ -17,10 +17,10 @@ def main(): # touch all the attributes of cd without doing anything if verbose: - print 'Touching cd module attributes...' + print('Touching cd module attributes...') for attr in cdattrs: if verbose: - print 'touching: ', attr + print('touching: ', attr) getattr(cd, attr) main() Modified: python/branches/p3yk/Lib/test/test_cl.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cl.py (original) +++ python/branches/p3yk/Lib/test/test_cl.py Fri Feb 9 06:37:30 2007 @@ -69,10 +69,10 @@ def main(): # touch all the attributes of al without doing anything if verbose: - print 'Touching cl module attributes...' + print('Touching cl module attributes...') for attr in clattrs: if verbose: - print 'touching: ', attr + print('touching: ', attr) getattr(cl, attr) main() Modified: python/branches/p3yk/Lib/test/test_class.py ============================================================================== --- python/branches/p3yk/Lib/test/test_class.py (original) +++ python/branches/p3yk/Lib/test/test_class.py Fri Feb 9 06:37:30 2007 @@ -65,63 +65,63 @@ class AllTests: def __hash__(self, *args): - print "__hash__:", args + print("__hash__:", args) return hash(id(self)) def __str__(self, *args): - print "__str__:", args + print("__str__:", args) return "AllTests" def __repr__(self, *args): - print "__repr__:", args + print("__repr__:", args) return "AllTests" def __int__(self, *args): - print "__int__:", args + print("__int__:", args) return 1 def __float__(self, *args): - print "__float__:", args + print("__float__:", args) return 1.0 def __oct__(self, *args): - print "__oct__:", args + print("__oct__:", args) return '01' def __hex__(self, *args): - print "__hex__:", args + print("__hex__:", args) return '0x1' def __cmp__(self, *args): - print "__cmp__:", args + print("__cmp__:", args) return 0 def __eq__(self, *args): - print "__eq__:", args + print("__eq__:", args) return True def __ne__(self, *args): - print "__ne__:", args + print("__ne__:", args) return False def __lt__(self, *args): - print "__lt__:", args + print("__lt__:", args) return False def __le__(self, *args): - print "__le__:", args + print("__le__:", args) return True def __gt__(self, *args): - print "__gt__:", args + print("__gt__:", args) return False def __ge__(self, *args): - print "__ge__:", args + print("__ge__:", args) return True def __del__(self, *args): - print "__del__:", args + print("__del__:", args) # Synthesize AllTests methods from the names in testmeths. @@ -186,7 +186,7 @@ try: 1 in Empty() - print 'failed, should have raised TypeError' + print('failed, should have raised TypeError') except TypeError: pass @@ -224,9 +224,9 @@ else: # This works under Jython, but the actual slice values are # different. - print "__getitem__: (slice(0, 42, None),)" - print "__setitem__: (slice(0, 42, None), 'The Answer')" - print "__delitem__: (slice(0, 42, None),)" + print("__getitem__: (slice(0, 42, None),)") + print("__setitem__: (slice(0, 42, None), 'The Answer')") + print("__delitem__: (slice(0, 42, None),)") # Unary operations @@ -265,14 +265,14 @@ class ExtraTests: def __getattr__(self, *args): - print "__getattr__:", args + print("__getattr__:", args) return "SomeVal" def __setattr__(self, *args): - print "__setattr__:", args + print("__setattr__:", args) def __delattr__(self, *args): - print "__delattr__:", args + print("__delattr__:", args) testme = ExtraTests() testme.spam @@ -349,7 +349,7 @@ A().a # Raised AttributeError: A instance has no attribute 'a' except AttributeError as x: if str(x) != "booh": - print "attribute error for A().a got masked:", str(x) + print("attribute error for A().a got masked:", str(x)) class E: __eq__ = property(booh) @@ -362,7 +362,7 @@ except AttributeError as x: pass else: - print "attribute error for I.__init__ got masked" + print("attribute error for I.__init__ got masked") # Test comparison and hash of methods Modified: python/branches/p3yk/Lib/test/test_cmath.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cmath.py (original) +++ python/branches/p3yk/Lib/test/test_cmath.py Fri Feb 9 06:37:30 2007 @@ -43,10 +43,10 @@ f = getattr(cmath, func) r = f(testdict[func]) if verbose: - print 'Calling %s(%f) = %f' % (func, testdict[func], abs(r)) + print('Calling %s(%f) = %f' % (func, testdict[func], abs(r))) p = cmath.pi e = cmath.e if verbose: - print 'PI = ', abs(p) - print 'E = ', abs(e) + print('PI = ', abs(p)) + print('E = ', abs(e)) Modified: python/branches/p3yk/Lib/test/test_code.py ============================================================================== --- python/branches/p3yk/Lib/test/test_code.py (original) +++ python/branches/p3yk/Lib/test/test_code.py Fri Feb 9 06:37:30 2007 @@ -115,8 +115,8 @@ """Print out a text representation of a code object.""" for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames", "cellvars", "freevars", "nlocals", "flags"]: - print "%s: %s" % (attr, getattr(co, "co_" + attr)) - print "consts:", tuple(consts(co.co_consts)) + print("%s: %s" % (attr, getattr(co, "co_" + attr))) + print("consts:", tuple(consts(co.co_consts))) def test_main(verbose=None): from test.test_support import run_doctest Modified: python/branches/p3yk/Lib/test/test_codecs.py ============================================================================== --- python/branches/p3yk/Lib/test/test_codecs.py (original) +++ python/branches/p3yk/Lib/test/test_codecs.py Fri Feb 9 06:37:30 2007 @@ -548,7 +548,7 @@ for i in punycode_testcases: if len(i)!=2: - print repr(i) + print(repr(i)) class PunycodeTest(unittest.TestCase): def test_encode(self): Modified: python/branches/p3yk/Lib/test/test_compiler.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compiler.py (original) +++ python/branches/p3yk/Lib/test/test_compiler.py Fri Feb 9 06:37:30 2007 @@ -30,8 +30,7 @@ # Print still working message since this test can be really slow if next_time <= time.time(): next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - print >>sys.__stdout__, \ - ' testCompileLibrary still working, be patient...' + print(' testCompileLibrary still working, be patient...', file=sys.__stdout__) sys.__stdout__.flush() if not basename.endswith(".py"): @@ -40,7 +39,7 @@ continue path = os.path.join(dir, basename) if test.test_support.verbose: - print "compiling", path + print("compiling", path) f = open(path, "U") buf = f.read() f.close() @@ -94,7 +93,7 @@ try: self._check_lineno(node) except AssertionError: - print node.__class__, node.lineno + print(node.__class__, node.lineno) raise def _check_lineno(self, node): @@ -217,7 +216,7 @@ a, b = b, a try: - print yo + print(yo) except: yo = 3 else: Modified: python/branches/p3yk/Lib/test/test_complex.py ============================================================================== --- python/branches/p3yk/Lib/test/test_complex.py (original) +++ python/branches/p3yk/Lib/test/test_complex.py Fri Feb 9 06:37:30 2007 @@ -315,7 +315,7 @@ fo = None try: fo = open(test_support.TESTFN, "wb") - print >>fo, a, b + print(a, b, file=fo) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), "%s %s\n" % (a, b)) Modified: python/branches/p3yk/Lib/test/test_crypt.py ============================================================================== --- python/branches/p3yk/Lib/test/test_crypt.py (original) +++ python/branches/p3yk/Lib/test/test_crypt.py Fri Feb 9 06:37:30 2007 @@ -8,4 +8,4 @@ c = crypt.crypt('mypassword', 'ab') if verbose: - print 'Test encryption: ', c + print('Test encryption: ', c) Modified: python/branches/p3yk/Lib/test/test_csv.py ============================================================================== --- python/branches/p3yk/Lib/test/test_csv.py (original) +++ python/branches/p3yk/Lib/test/test_csv.py Fri Feb 9 06:37:30 2007 @@ -894,7 +894,7 @@ self.assertEqual(dialect.quotechar, "'") if not hasattr(sys, "gettotalrefcount"): - if test_support.verbose: print "*** skipping leakage tests ***" + if test_support.verbose: print("*** skipping leakage tests ***") else: class NUL: def write(s, *args): Modified: python/branches/p3yk/Lib/test/test_curses.py ============================================================================== --- python/branches/p3yk/Lib/test/test_curses.py (original) +++ python/branches/p3yk/Lib/test/test_curses.py Fri Feb 9 06:37:30 2007 @@ -228,7 +228,7 @@ ('\x8a', '!^J'), ('\xc1', '!A'), ]: if ascii.unctrl(ch) != expected: - print 'curses.unctrl fails on character', repr(ch) + print('curses.unctrl fails on character', repr(ch)) def test_userptr_without_set(stdscr): Modified: python/branches/p3yk/Lib/test/test_datetime.py ============================================================================== --- python/branches/p3yk/Lib/test/test_datetime.py (original) +++ python/branches/p3yk/Lib/test/test_datetime.py Fri Feb 9 06:37:30 2007 @@ -3287,11 +3287,11 @@ gc.garbage) if hasattr(sys, 'gettotalrefcount'): thisrc = sys.gettotalrefcount() - print >> sys.stderr, '*' * 10, 'total refs:', thisrc, + print('*' * 10, 'total refs:', thisrc, end=' ', file=sys.stderr) if lastrc: - print >> sys.stderr, 'delta:', thisrc - lastrc + print('delta:', thisrc - lastrc, file=sys.stderr) else: - print >> sys.stderr + print(file=sys.stderr) lastrc = thisrc if __name__ == "__main__": Modified: python/branches/p3yk/Lib/test/test_dbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dbm.py (original) +++ python/branches/p3yk/Lib/test/test_dbm.py Fri Feb 9 06:37:30 2007 @@ -31,7 +31,7 @@ d.keys() if 'a' in d: if verbose: - print 'Test dbm keys: ', d.keys() + print('Test dbm keys: ', d.keys()) d.close() Modified: python/branches/p3yk/Lib/test/test_decimal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_decimal.py (original) +++ python/branches/p3yk/Lib/test/test_decimal.py Fri Feb 9 06:37:30 2007 @@ -143,8 +143,8 @@ try: t = self.eval_line(line) except InvalidOperation: - print 'Error in test cases:' - print line + print('Error in test cases:') + print(line) continue except DecimalException as exception: #Exception raised where there shoudn't have been one. @@ -271,7 +271,7 @@ except Signals as error: self.fail("Raised %s in %s" % (error, s)) except: #Catch any error long enough to state the test case. - print "ERROR:", s + print("ERROR:", s) raise myexceptions = self.getexceptions() Modified: python/branches/p3yk/Lib/test/test_defaultdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_defaultdict.py (original) +++ python/branches/p3yk/Lib/test/test_defaultdict.py Fri Feb 9 06:37:30 2007 @@ -81,8 +81,8 @@ try: f = open(tfn, "w+") try: - print >>f, d1 - print >>f, d2 + print(d1, file=f) + print(d2, file=f) f.seek(0) self.assertEqual(f.readline(), repr(d1) + "\n") self.assertEqual(f.readline(), repr(d2) + "\n") Modified: python/branches/p3yk/Lib/test/test_deque.py ============================================================================== --- python/branches/p3yk/Lib/test/test_deque.py (original) +++ python/branches/p3yk/Lib/test/test_deque.py Fri Feb 9 06:37:30 2007 @@ -245,7 +245,7 @@ d.append(d) try: fo = open(test_support.TESTFN, "wb") - print >> fo, d, + print(d, end=' ', file=fo) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(d)) @@ -622,7 +622,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) # doctests from test import test_deque Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Fri Feb 9 06:37:30 2007 @@ -13,7 +13,7 @@ raise TestFailed, "%r is %r" % (a, b) def testunop(a, res, expr="len(a)", meth="__len__"): - if verbose: print "checking", expr + if verbose: print("checking", expr) dict = {'a': a} vereq(eval(expr, dict), res) t = type(a) @@ -26,7 +26,7 @@ vereq(bm(), res) def testbinop(a, b, res, expr="a+b", meth="__add__"): - if verbose: print "checking", expr + if verbose: print("checking", expr) dict = {'a': a, 'b': b} vereq(eval(expr, dict), res) @@ -40,7 +40,7 @@ vereq(bm(b), res) def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"): - if verbose: print "checking", expr + if verbose: print("checking", expr) dict = {'a': a, 'b': b, 'c': c} vereq(eval(expr, dict), res) t = type(a) @@ -53,7 +53,7 @@ vereq(bm(b, c), res) def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"): - if verbose: print "checking", stmt + if verbose: print("checking", stmt) dict = {'a': deepcopy(a), 'b': b} exec(stmt, dict) vereq(dict['a'], res) @@ -71,7 +71,7 @@ vereq(dict['a'], res) def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"): - if verbose: print "checking", stmt + if verbose: print("checking", stmt) dict = {'a': deepcopy(a), 'b': b, 'c': c} exec(stmt, dict) vereq(dict['a'], res) @@ -89,7 +89,7 @@ vereq(dict['a'], res) def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"): - if verbose: print "checking", stmt + if verbose: print("checking", stmt) dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d} exec(stmt, dict) vereq(dict['a'], res) @@ -135,7 +135,7 @@ verify(NewDynamic2.__doc__ is None) def lists(): - if verbose: print "Testing list operations..." + if verbose: print("Testing list operations...") testbinop([1], [2], [1,2], "a+b", "__add__") testbinop([1,2,3], 2, 1, "b in a", "__contains__") testbinop([1,2,3], 4, 0, "b in a", "__contains__") @@ -150,7 +150,7 @@ testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__") def dicts(): - if verbose: print "Testing dict operations..." + if verbose: print("Testing dict operations...") ##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__") testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__") @@ -175,7 +175,7 @@ def dict_constructor(): if verbose: - print "Testing dict constructor ..." + print("Testing dict constructor ...") d = dict() vereq(d, {}) d = dict({}) @@ -258,7 +258,7 @@ def test_dir(): if verbose: - print "Testing dir() ..." + print("Testing dir() ...") junk = 12 vereq(dir(), ['junk']) del junk @@ -413,7 +413,7 @@ testunop(a, res, expr, name) def ints(): - if verbose: print "Testing int operations..." + if verbose: print("Testing int operations...") numops(100, 3) # The following crashes in Python 2.2 vereq((1).__bool__(), True) @@ -431,15 +431,15 @@ raise TestFailed, "NotImplemented should have caused TypeError" def longs(): - if verbose: print "Testing long operations..." + if verbose: print("Testing long operations...") numops(100, 3) def floats(): - if verbose: print "Testing float operations..." + if verbose: print("Testing float operations...") numops(100.0, 3.0) def complexes(): - if verbose: print "Testing complex operations..." + if verbose: print("Testing complex operations...") numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float']) class Number(complex): __slots__ = ['prec'] @@ -469,7 +469,7 @@ vereq(a.prec, 12) def spamlists(): - if verbose: print "Testing spamlist operations..." + if verbose: print("Testing spamlist operations...") import copy, xxsubtype as spam def spamlist(l, memo=None): import xxsubtype as spam @@ -505,7 +505,7 @@ vereq(a.getstate(), 42) def spamdicts(): - if verbose: print "Testing spamdict operations..." + if verbose: print("Testing spamdict operations...") import copy, xxsubtype as spam def spamdict(d, memo=None): import xxsubtype as spam @@ -550,7 +550,7 @@ vereq(a.getstate(), 100) def pydicts(): - if verbose: print "Testing Python subclass of dict..." + if verbose: print("Testing Python subclass of dict...") verify(issubclass(dict, dict)) verify(isinstance({}, dict)) d = dict() @@ -591,7 +591,7 @@ vereq(a[42], 0) a[42] = 24 vereq(a[42], 24) - if verbose: print "pydict stress test ..." + if verbose: print("pydict stress test ...") N = 50 for i in range(N): a[i] = C() @@ -602,7 +602,7 @@ vereq(a[i][j], i*j) def pylists(): - if verbose: print "Testing Python subclass of list..." + if verbose: print("Testing Python subclass of list...") class C(list): def __getitem__(self, i): return list.__getitem__(self, i) + 100 @@ -616,7 +616,7 @@ vereq(a[100:200], (100,200)) def metaclass(): - if verbose: print "Testing __metaclass__..." + if verbose: print("Testing __metaclass__...") class C: __metaclass__ = type def __init__(self): @@ -778,7 +778,7 @@ else: raise TestFailed, "calling object w/o call method should raise TypeError" def pymods(): - if verbose: print "Testing Python subclass of module..." + if verbose: print("Testing Python subclass of module...") log = [] import sys MT = type(sys) @@ -803,7 +803,7 @@ ("delattr", "foo")]) def multi(): - if verbose: print "Testing multiple inheritance..." + if verbose: print("Testing multiple inheritance...") class C(object): def __init__(self): self.__state = 0 @@ -844,7 +844,7 @@ vereq(int(Frag()), 42) def diamond(): - if verbose: print "Testing multiple inheritance special cases..." + if verbose: print("Testing multiple inheritance special cases...") class A(object): def spam(self): return "A" vereq(A().spam(), "A") @@ -882,7 +882,7 @@ # see thread python-dev/2002-October/029035.html def ex5(): - if verbose: print "Testing ex5 from C3 switch discussion..." + if verbose: print("Testing ex5 from C3 switch discussion...") class A(object): pass class B(object): pass class C(object): pass @@ -894,7 +894,7 @@ # see "A Monotonic Superclass Linearization for Dylan", # by Kim Barrett et al. (OOPSLA 1996) def monotonicity(): - if verbose: print "Testing MRO monotonicity..." + if verbose: print("Testing MRO monotonicity...") class Boat(object): pass class DayBoat(Boat): pass class WheelBoat(Boat): pass @@ -917,7 +917,7 @@ # see "A Monotonic Superclass Linearization for Dylan", # by Kim Barrett et al. (OOPSLA 1996) def consistency_with_epg(): - if verbose: print "Testing consistentcy with EPG..." + if verbose: print("Testing consistentcy with EPG...") class Pane(object): pass class ScrollingMixin(object): pass class EditingMixin(object): pass @@ -933,7 +933,7 @@ order (MRO) for bases """ def mro_disagreement(): - if verbose: print "Testing error messages for MRO disagreement..." + if verbose: print("Testing error messages for MRO disagreement...") def raises(exc, expected, callable, *args): try: callable(*args) @@ -963,7 +963,7 @@ type, "ConfusedGrid", (HVGrid, VHGrid), {}) def objects(): - if verbose: print "Testing object class..." + if verbose: print("Testing object class...") a = object() vereq(a.__class__, object) vereq(type(a), object) @@ -987,7 +987,7 @@ vereq(x.__dict__, {'foo': 1}) def slots(): - if verbose: print "Testing __slots__..." + if verbose: print("Testing __slots__...") class C0(object): __slots__ = [] x = C0() @@ -1152,7 +1152,7 @@ sys.stderr = save_stderr def slotspecials(): - if verbose: print "Testing __dict__ and __weakref__ in __slots__..." + if verbose: print("Testing __dict__ and __weakref__ in __slots__...") class D(object): __slots__ = ["__dict__"] @@ -1199,7 +1199,7 @@ # __slots__ = [] def dynamics(): - if verbose: print "Testing class attribute propagation..." + if verbose: print("Testing class attribute propagation...") class D(object): pass class E(D): @@ -1278,7 +1278,7 @@ verify(someclass != object) def errors(): - if verbose: print "Testing errors..." + if verbose: print("Testing errors...") try: class C(list, dict): @@ -1323,7 +1323,7 @@ verify(0, "__slots__ = [1] should be illegal") def classmethods(): - if verbose: print "Testing class methods..." + if verbose: print("Testing class methods...") class C(object): def foo(*a): return a goo = classmethod(foo) @@ -1369,7 +1369,7 @@ raise TestFailed, "classmethod shouldn't accept keyword args" def classmethods_in_c(): - if verbose: print "Testing C-based class methods..." + if verbose: print("Testing C-based class methods...") import xxsubtype as spam a = (1, 2, 3) d = {'abc': 123} @@ -1383,7 +1383,7 @@ vereq(d, d1) def staticmethods(): - if verbose: print "Testing static methods..." + if verbose: print("Testing static methods...") class C(object): def foo(*a): return a goo = staticmethod(foo) @@ -1400,7 +1400,7 @@ vereq(D.foo(d, 1), (d, 1)) def staticmethods_in_c(): - if verbose: print "Testing C-based static methods..." + if verbose: print("Testing C-based static methods...") import xxsubtype as spam a = (1, 2, 3) d = {"abc": 123} @@ -1414,7 +1414,7 @@ vereq(d, d1) def classic(): - if verbose: print "Testing classic classes..." + if verbose: print("Testing classic classes...") class C: def foo(*a): return a goo = classmethod(foo) @@ -1435,7 +1435,7 @@ verify(repr(C.foo.__get__(C())).startswith("> capture, o - print >> capture, str(o) + print(o, file=capture) + print(str(o), file=capture) vereq(capture.getvalue(), '41\n41\n') capture.close() def kwdargs(): - if verbose: print "Testing keyword arguments to __init__, __call__..." + if verbose: print("Testing keyword arguments to __init__, __call__...") def f(a): return a vereq(f.__call__(a=42), 42) a = [] @@ -3066,8 +3066,8 @@ vereq(a, [0, 1, 2]) def recursive__call__(): - if verbose: print ("Testing recursive __call__() by setting to instance of " - "class ...") + if verbose: print(("Testing recursive __call__() by setting to instance of " + "class ...")) class A(object): pass @@ -3081,7 +3081,7 @@ "__call__()") def delhook(): - if verbose: print "Testing __del__ hook..." + if verbose: print("Testing __del__ hook...") log = [] class C(object): def __del__(self): @@ -3098,7 +3098,7 @@ else: raise TestFailed, "invalid del() didn't raise TypeError" def hashinherit(): - if verbose: print "Testing hash of mutable subclasses..." + if verbose: print("Testing hash of mutable subclasses...") class mydict(dict): pass @@ -3167,7 +3167,7 @@ vereq('%c' % '5', '5') def deepcopyrecursive(): - if verbose: print "Testing deepcopy of recursive objects..." + if verbose: print("Testing deepcopy of recursive objects...") class Node: pass a = Node() @@ -3177,7 +3177,7 @@ z = deepcopy(a) # This blew up before def modules(): - if verbose: print "Testing uninitialized module objects..." + if verbose: print("Testing uninitialized module objects...") from types import ModuleType as M m = M.__new__(M) str(m) @@ -3192,7 +3192,7 @@ class C(object): def meth(self): pass - if verbose: print "Testing dict-proxy iterkeys..." + if verbose: print("Testing dict-proxy iterkeys...") keys = [ key for key in C.__dict__.iterkeys() ] keys.sort() vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) @@ -3201,7 +3201,7 @@ class C(object): def meth(self): pass - if verbose: print "Testing dict-proxy itervalues..." + if verbose: print("Testing dict-proxy itervalues...") values = [ values for values in C.__dict__.itervalues() ] vereq(len(values), 5) @@ -3209,13 +3209,13 @@ class C(object): def meth(self): pass - if verbose: print "Testing dict-proxy iteritems..." + if verbose: print("Testing dict-proxy iteritems...") keys = [ key for (key, value) in C.__dict__.iteritems() ] keys.sort() vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) def funnynew(): - if verbose: print "Testing __new__ returning something unexpected..." + if verbose: print("Testing __new__ returning something unexpected...") class C(object): def __new__(cls, arg): if isinstance(arg, str): return [1, 2, 3] @@ -3237,7 +3237,7 @@ def imulbug(): # SF bug 544647 - if verbose: print "Testing for __imul__ problems..." + if verbose: print("Testing for __imul__ problems...") class C(object): def __imul__(self, other): return (self, other) @@ -3263,7 +3263,7 @@ def docdescriptor(): # SF bug 542984 - if verbose: print "Testing __doc__ descriptor..." + if verbose: print("Testing __doc__ descriptor...") class DocDescr(object): def __get__(self, object, otype): if object: @@ -3282,7 +3282,7 @@ def copy_setstate(): if verbose: - print "Testing that copy.*copy() correctly uses __setstate__..." + print("Testing that copy.*copy() correctly uses __setstate__...") import copy class C(object): def __init__(self, foo=None): @@ -3310,7 +3310,7 @@ def slices(): if verbose: - print "Testing cases with slices and overridden __getitem__ ..." + print("Testing cases with slices and overridden __getitem__ ...") # Strings vereq("hello"[:4], "hell") vereq("hello"[slice(4)], "hell") @@ -3354,7 +3354,7 @@ def subtype_resurrection(): if verbose: - print "Testing resurrection of new-style instance..." + print("Testing resurrection of new-style instance...") class C(object): container = [] @@ -3384,7 +3384,7 @@ def slottrash(): # Deallocating deeply nested slotted trash caused stack overflows if verbose: - print "Testing slot trash..." + print("Testing slot trash...") class trash(object): __slots__ = ['x'] def __init__(self, x): @@ -3410,7 +3410,7 @@ def testrmul(): # SF patch 592646 if verbose: - print "Testing correct invocation of __rmul__..." + print("Testing correct invocation of __rmul__...") class C(object): def __mul__(self, other): return "mul" @@ -3425,7 +3425,7 @@ def testipow(): # [SF bug 620179] if verbose: - print "Testing correct invocation of __ipow__..." + print("Testing correct invocation of __ipow__...") class C(object): def __ipow__(self, other): pass @@ -3434,7 +3434,7 @@ def do_this_first(): if verbose: - print "Testing SF bug 551412 ..." + print("Testing SF bug 551412 ...") # This dumps core when SF bug 551412 isn't fixed -- # but only when test_descr.py is run separately. # (That can't be helped -- as soon as PyType_Ready() @@ -3448,14 +3448,14 @@ pass if verbose: - print "Testing SF bug 570483..." + print("Testing SF bug 570483...") # Another segfault only when run early # (before PyType_Ready(tuple) is called) type.mro(tuple) def test_mutable_bases(): if verbose: - print "Testing mutable bases..." + print("Testing mutable bases...") # stuff that should work: class C(object): pass @@ -3545,7 +3545,7 @@ def test_mutable_bases_with_failing_mro(): if verbose: - print "Testing mutable bases with failing mro..." + print("Testing mutable bases with failing mro...") class WorkOnce(type): def __new__(self, name, bases, ns): self.flag = 0 @@ -3600,7 +3600,7 @@ def test_mutable_bases_catch_mro_conflict(): if verbose: - print "Testing mutable bases catch mro conflict..." + print("Testing mutable bases catch mro conflict...") class A(object): pass @@ -3625,7 +3625,7 @@ def mutable_names(): if verbose: - print "Testing mutable names..." + print("Testing mutable names...") class C(object): pass @@ -3640,7 +3640,7 @@ def subclass_right_op(): if verbose: - print "Testing correct dispatch of subclass overloading __r__..." + print("Testing correct dispatch of subclass overloading __r__...") # This code tests various cases where right-dispatch of a subclass # should be preferred over left-dispatch of a base class. @@ -3692,7 +3692,7 @@ def dict_type_with_metaclass(): if verbose: - print "Testing type of __dict__ when __metaclass__ set..." + print("Testing type of __dict__ when __metaclass__ set...") class B(object): pass @@ -3706,7 +3706,7 @@ def meth_class_get(): # Full coverage of descrobject.c::classmethod_get() if verbose: - print "Testing __get__ method of METH_CLASS C methods..." + print("Testing __get__ method of METH_CLASS C methods...") # Baseline arg = [1, 2, 3] res = {1: None, 2: None, 3: None} @@ -3745,7 +3745,7 @@ def isinst_isclass(): if verbose: - print "Testing proxy isinstance() and isclass()..." + print("Testing proxy isinstance() and isclass()...") class Proxy(object): def __init__(self, obj): self.__obj = obj @@ -3785,7 +3785,7 @@ def proxysuper(): if verbose: - print "Testing super() for a proxy object..." + print("Testing super() for a proxy object...") class Proxy(object): def __init__(self, obj): self.__obj = obj @@ -3809,7 +3809,7 @@ def carloverre(): if verbose: - print "Testing prohibition of Carlo Verre's hack..." + print("Testing prohibition of Carlo Verre's hack...") try: object.__setattr__(str, "foo", 42) except TypeError: @@ -3826,7 +3826,7 @@ def weakref_segfault(): # SF 742911 if verbose: - print "Testing weakref segfault..." + print("Testing weakref segfault...") import weakref @@ -3854,7 +3854,7 @@ # Fix SF #762455, segfault when sys.stdout is changed in getattr def filefault(): if verbose: - print "Testing sys.stdout is changed in getattr..." + print("Testing sys.stdout is changed in getattr...") import sys class StdoutGuard: def __getattr__(self, attr): @@ -3862,7 +3862,7 @@ raise RuntimeError("Premature access to sys.stdout.%s" % attr) sys.stdout = StdoutGuard() try: - print "Oops!" + print("Oops!") except RuntimeError: pass @@ -3871,7 +3871,7 @@ # python-dev 2003-04-17, turned into an example & fixed by Michael # Hudson just less than four months later... if verbose: - print "Testing vicious_descriptor_nonsense..." + print("Testing vicious_descriptor_nonsense...") class Evil(object): def __hash__(self): @@ -3910,7 +3910,7 @@ def methodwrapper(): # did not support any reflection before 2.5 if verbose: - print "Testing method-wrapper objects..." + print("Testing method-wrapper objects...") return # XXX should methods really support __eq__? @@ -3938,7 +3938,7 @@ def notimplemented(): # all binary methods should be able to return a NotImplemented if verbose: - print "Testing NotImplemented..." + print("Testing NotImplemented...") import sys import types @@ -4098,7 +4098,7 @@ methodwrapper() notimplemented() - if verbose: print "All OK" + if verbose: print("All OK") if __name__ == "__main__": test_main() Modified: python/branches/p3yk/Lib/test/test_dis.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dis.py (original) +++ python/branches/p3yk/Lib/test/test_dis.py Fri Feb 9 06:37:30 2007 @@ -8,7 +8,7 @@ import unittest def _f(a): - print a + print(a) return 1 dis_f = """\ Modified: python/branches/p3yk/Lib/test/test_dl.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dl.py (original) +++ python/branches/p3yk/Lib/test/test_dl.py Fri Feb 9 06:37:30 2007 @@ -16,19 +16,19 @@ for s, func in sharedlibs: try: if verbose: - print 'trying to open:', s, + print('trying to open:', s, end=' ') l = dl.open(s) except dl.error as err: if verbose: - print 'failed', repr(str(err)) + print('failed', repr(str(err))) pass else: if verbose: - print 'succeeded...', + print('succeeded...', end=' ') l.call(func) l.close() if verbose: - print 'worked!' + print('worked!') break else: raise TestSkipped, 'Could not open any shared libraries' Modified: python/branches/p3yk/Lib/test/test_doctest.py ============================================================================== --- python/branches/p3yk/Lib/test/test_doctest.py (original) +++ python/branches/p3yk/Lib/test/test_doctest.py Fri Feb 9 06:37:30 2007 @@ -143,7 +143,7 @@ def readline(self): line = self.lines.pop(0) - print line + print(line) return line+'\n' ###################################################################### @@ -2407,7 +2407,7 @@ trace=0, count=1) tracer.run('reload(doctest); test_main()') r = tracer.results() - print 'Writing coverage results...' + print('Writing coverage results...') r.write_results(show_missing=True, summary=True, coverdir=coverdir) Modified: python/branches/p3yk/Lib/test/test_dummy_thread.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dummy_thread.py (original) +++ python/branches/p3yk/Lib/test/test_dummy_thread.py Fri Feb 9 06:37:30 2007 @@ -72,13 +72,13 @@ start_time = int(time.time()) _thread.start_new_thread(delay_unlock,(self.lock, DELAY)) if test_support.verbose: - print - print "*** Waiting for thread to release the lock "\ - "(approx. %s sec.) ***" % DELAY + print() + print("*** Waiting for thread to release the lock "\ + "(approx. %s sec.) ***" % DELAY) self.lock.acquire() end_time = int(time.time()) if test_support.verbose: - print "done" + print("done") self.failUnless((end_time - start_time) >= DELAY, "Blocking by unconditional acquiring failed.") @@ -150,9 +150,9 @@ thread_count = 5 testing_queue = Queue.Queue(thread_count) if test_support.verbose: - print - print "*** Testing multiple thread creation "\ - "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count) + print() + print("*** Testing multiple thread creation "\ + "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)) for count in xrange(thread_count): if DELAY: local_delay = round(random.random(), 1) @@ -162,7 +162,7 @@ (testing_queue, local_delay)) time.sleep(DELAY) if test_support.verbose: - print 'done' + print('done') self.failUnless(testing_queue.qsize() == thread_count, "Not all %s threads executed properly after %s sec." % (thread_count, DELAY)) @@ -173,8 +173,8 @@ _thread = imported_module DELAY = 2 if test_support.verbose: - print - print "*** Using %s as _thread module ***" % _thread + print() + print("*** Using %s as _thread module ***" % _thread) test_support.run_unittest(LockTests, MiscTests, ThreadTests) if __name__ == '__main__': Modified: python/branches/p3yk/Lib/test/test_dummy_threading.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dummy_threading.py (original) +++ python/branches/p3yk/Lib/test/test_dummy_threading.py Fri Feb 9 06:37:30 2007 @@ -17,20 +17,20 @@ #delay = random.random() * 2 delay = 0 if verbose: - print 'task', self.getName(), 'will run for', delay, 'sec' + print('task', self.getName(), 'will run for', delay, 'sec') sema.acquire() mutex.acquire() running = running + 1 if verbose: - print running, 'tasks are running' + print(running, 'tasks are running') mutex.release() time.sleep(delay) if verbose: - print 'task', self.getName(), 'done' + print('task', self.getName(), 'done') mutex.acquire() running = running - 1 if verbose: - print self.getName(), 'is finished.', running, 'tasks are running' + print(self.getName(), 'is finished.', running, 'tasks are running') mutex.release() sema.release() @@ -61,11 +61,11 @@ starttasks() if verbose: - print 'waiting for all tasks to complete' + print('waiting for all tasks to complete') for t in threads: t.join() if verbose: - print 'all tasks done' + print('all tasks done') Modified: python/branches/p3yk/Lib/test/test_enumerate.py ============================================================================== --- python/branches/p3yk/Lib/test/test_enumerate.py (original) +++ python/branches/p3yk/Lib/test/test_enumerate.py Fri Feb 9 06:37:30 2007 @@ -208,7 +208,7 @@ for i in xrange(len(counts)): test_support.run_unittest(*testclasses) counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_errno.py ============================================================================== --- python/branches/p3yk/Lib/test/test_errno.py (original) +++ python/branches/p3yk/Lib/test/test_errno.py Fri Feb 9 06:37:30 2007 @@ -43,7 +43,7 @@ a = getattr(errno, error) except AttributeError: if verbose: - print '%s: not found' % error + print('%s: not found' % error) else: if verbose: - print '%s: %d' % (error, a) + print('%s: %d' % (error, a)) Modified: python/branches/p3yk/Lib/test/test_extcall.py ============================================================================== --- python/branches/p3yk/Lib/test/test_extcall.py (original) +++ python/branches/p3yk/Lib/test/test_extcall.py Fri Feb 9 06:37:30 2007 @@ -2,16 +2,16 @@ from UserList import UserList def e(a, b): - print a, b + print(a, b) def f(*a, **k): - print a, sortdict(k) + print(a, sortdict(k)) def g(x, *y, **z): - print x, y, sortdict(z) + print(x, y, sortdict(z)) def h(j=1, a=2, h=3): - print j, a, h + print(j, a, h) f() f(1) @@ -31,28 +31,28 @@ except TypeError: pass else: - print "should raise TypeError: e() got an unexpected keyword argument 'c'" + print("should raise TypeError: e() got an unexpected keyword argument 'c'") try: g() except TypeError as err: - print "TypeError:", err + print("TypeError:", err) else: - print "should raise TypeError: not enough arguments; expected 1, got 0" + print("should raise TypeError: not enough arguments; expected 1, got 0") try: g(*()) except TypeError as err: - print "TypeError:", err + print("TypeError:", err) else: - print "should raise TypeError: not enough arguments; expected 1, got 0" + print("should raise TypeError: not enough arguments; expected 1, got 0") try: g(*(), **{}) except TypeError as err: - print "TypeError:", err + print("TypeError:", err) else: - print "should raise TypeError: not enough arguments; expected 1, got 0" + print("should raise TypeError: not enough arguments; expected 1, got 0") g(1) g(1, 2) @@ -64,7 +64,7 @@ except TypeError as attr: pass else: - print "should raise TypeError" + print("should raise TypeError") class Nothing: def __len__(self): @@ -74,7 +74,7 @@ except TypeError as attr: pass else: - print "should raise TypeError" + print("should raise TypeError") class Nothing: def __len__(self): @@ -96,7 +96,7 @@ except TypeError as attr: pass else: - print "should raise TypeError" + print("should raise TypeError") class Nothing: def __init__(self): @@ -116,8 +116,8 @@ d2 = d.copy() verify(d == d2) g(1, d=4, **d) -print sortdict(d) -print sortdict(d2) +print(sortdict(d)) +print(sortdict(d2)) verify(d == d2, "function call modified dictionary") # what about willful misconduct? @@ -133,79 +133,79 @@ try: g(1, 2, 3, **{'x':4, 'y':5}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: keyword parameter redefined" + print("should raise TypeError: keyword parameter redefined") try: g(1, 2, 3, a=4, b=5, *(6, 7), **{'a':8, 'b':9}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: keyword parameter redefined" + print("should raise TypeError: keyword parameter redefined") try: f(**{1:2}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: keywords must be strings" + print("should raise TypeError: keywords must be strings") try: h(**{'e': 2}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: unexpected keyword argument: e" + print("should raise TypeError: unexpected keyword argument: e") try: h(*h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: * argument must be a tuple" + print("should raise TypeError: * argument must be a tuple") try: dir(*h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: * argument must be a tuple" + print("should raise TypeError: * argument must be a tuple") try: None(*h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: * argument must be a tuple" + print("should raise TypeError: * argument must be a tuple") try: h(**h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: ** argument must be a dictionary" + print("should raise TypeError: ** argument must be a dictionary") try: dir(**h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: ** argument must be a dictionary" + print("should raise TypeError: ** argument must be a dictionary") try: None(**h) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: ** argument must be a dictionary" + print("should raise TypeError: ** argument must be a dictionary") try: dir(b=1,**{'b':1}) except TypeError as err: - print err + print(err) else: - print "should raise TypeError: dir() got multiple values for keyword argument 'b'" + print("should raise TypeError: dir() got multiple values for keyword argument 'b'") def f2(*a, **b): return a, b @@ -215,27 +215,27 @@ key = 'k%d' % i d[key] = i a, b = f2(1, *(2, 3), **d) -print len(a), len(b), b == d +print(len(a), len(b), b == d) class Foo: def method(self, arg1, arg2): return arg1 + arg2 x = Foo() -print Foo.method(*(x, 1, 2)) -print Foo.method(x, *(1, 2)) +print(Foo.method(*(x, 1, 2))) +print(Foo.method(x, *(1, 2))) try: - print Foo.method(*(1, 2, 3)) + print(Foo.method(*(1, 2, 3))) except TypeError as err: pass else: - print 'expected a TypeError for unbound method call' + print('expected a TypeError for unbound method call') try: - print Foo.method(1, *(2, 3)) + print(Foo.method(1, *(2, 3))) except TypeError as err: pass else: - print 'expected a TypeError for unbound method call' + print('expected a TypeError for unbound method call') # A PyCFunction that takes only positional parameters should allow an # empty keyword dictionary to pass without a complaint, but raise a @@ -274,6 +274,6 @@ for kwargs in ['', 'a', 'd', 'ad', 'abde']: kwdict = {} for k in kwargs: kwdict[k] = k + k - print func.func_name, args, sortdict(kwdict), '->', + print(func.func_name, args, sortdict(kwdict), '->', end=' ') try: func(*args, **kwdict) - except TypeError as err: print err + except TypeError as err: print(err) Modified: python/branches/p3yk/Lib/test/test_fcntl.py ============================================================================== --- python/branches/p3yk/Lib/test/test_fcntl.py (original) +++ python/branches/p3yk/Lib/test/test_fcntl.py Fri Feb 9 06:37:30 2007 @@ -41,18 +41,18 @@ lockdata = struct.pack('hh'+start_len+'hh', fcntl.F_WRLCK, 0, 0, 0, 0, 0) if lockdata: if verbose: - print 'struct.pack: ', repr(lockdata) + print('struct.pack: ', repr(lockdata)) # the example from the library docs f = open(filename, 'w') rv = fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) if verbose: - print 'Status from fcntl with O_NONBLOCK: ', rv + print('Status from fcntl with O_NONBLOCK: ', rv) if sys.platform not in ['os2emx']: rv = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, lockdata) if verbose: - print 'String from fcntl with F_SETLKW: ', repr(rv) + print('String from fcntl with F_SETLKW: ', repr(rv)) f.close() os.unlink(filename) Modified: python/branches/p3yk/Lib/test/test_file.py ============================================================================== --- python/branches/p3yk/Lib/test/test_file.py (original) +++ python/branches/p3yk/Lib/test/test_file.py Fri Feb 9 06:37:30 2007 @@ -142,9 +142,9 @@ if sys.platform != 'osf1V5': self.assertRaises(IOError, sys.stdin.seek, -1) else: - print >>sys.__stdout__, ( + print(( ' Skipping sys.stdin.seek(-1), it may crash the interpreter.' - ' Test manually.') + ' Test manually.'), file=sys.__stdout__) self.assertRaises(IOError, sys.stdin.truncate) def testUnicodeOpen(self): Modified: python/branches/p3yk/Lib/test/test_fileinput.py ============================================================================== --- python/branches/p3yk/Lib/test/test_fileinput.py (original) +++ python/branches/p3yk/Lib/test/test_fileinput.py Fri Feb 9 06:37:30 2007 @@ -34,7 +34,7 @@ def runTests(t1, t2, t3, t4, bs=0, round=0): start = 1 + round*6 if verbose: - print '%s. Simple iteration (bs=%s)' % (start+0, bs) + print('%s. Simple iteration (bs=%s)' % (start+0, bs)) fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) lines = list(fi) fi.close() @@ -45,7 +45,7 @@ verify(fi.filename() == t4) if verbose: - print '%s. Status variables (bs=%s)' % (start+1, bs) + print('%s. Status variables (bs=%s)' % (start+1, bs)) fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) s = "x" while s and s != 'Line 6 of file 2\n': @@ -57,14 +57,14 @@ verify(not fi.isstdin()) if verbose: - print '%s. Nextfile (bs=%s)' % (start+2, bs) + print('%s. Nextfile (bs=%s)' % (start+2, bs)) fi.nextfile() verify(fi.readline() == 'Line 1 of file 3\n') verify(fi.lineno() == 22) fi.close() if verbose: - print '%s. Stdin (bs=%s)' % (start+3, bs) + print('%s. Stdin (bs=%s)' % (start+3, bs)) fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs) savestdin = sys.stdin try: @@ -78,7 +78,7 @@ sys.stdin = savestdin if verbose: - print '%s. Boundary conditions (bs=%s)' % (start+4, bs) + print('%s. Boundary conditions (bs=%s)' % (start+4, bs)) fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) verify(fi.lineno() == 0) verify(fi.filename() == None) @@ -87,13 +87,13 @@ verify(fi.filename() == None) if verbose: - print '%s. Inplace (bs=%s)' % (start+5, bs) + print('%s. Inplace (bs=%s)' % (start+5, bs)) savestdout = sys.stdout try: fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs) for line in fi: line = line[:-1].upper() - print line + print(line) fi.close() finally: sys.stdout = savestdout @@ -124,7 +124,7 @@ # Next, check for proper behavior with 0-byte files. if verbose: - print "13. 0-byte files" + print("13. 0-byte files") try: t1 = writeTmp(1, [""]) t2 = writeTmp(2, [""]) @@ -146,7 +146,7 @@ remove_tempfiles(t1, t2, t3, t4) if verbose: - print "14. Files that don't end with newline" + print("14. Files that don't end with newline") try: t1 = writeTmp(1, ["A\nB\nC"]) t2 = writeTmp(2, ["D\nE\nF"]) @@ -159,7 +159,7 @@ remove_tempfiles(t1, t2) if verbose: - print "15. Unicode filenames" + print("15. Unicode filenames") try: t1 = writeTmp(1, ["A\nB"]) encoding = sys.getfilesystemencoding() @@ -172,7 +172,7 @@ remove_tempfiles(t1) if verbose: - print "16. fileno()" + print("16. fileno()") try: t1 = writeTmp(1, ["A\nB"]) t2 = writeTmp(2, ["C\nD"]) @@ -188,7 +188,7 @@ remove_tempfiles(t1, t2) if verbose: - print "17. Specify opening mode" + print("17. Specify opening mode") try: # invalid mode, should raise ValueError fi = FileInput(mode="w") @@ -205,7 +205,7 @@ remove_tempfiles(t1) if verbose: - print "18. Test file opening hook" + print("18. Test file opening hook") try: # cannot use openhook and inplace mode fi = FileInput(inplace=1, openhook=lambda f,m: None) Modified: python/branches/p3yk/Lib/test/test_format.py ============================================================================== --- python/branches/p3yk/Lib/test/test_format.py (original) +++ python/branches/p3yk/Lib/test/test_format.py Fri Feb 9 06:37:30 2007 @@ -11,26 +11,26 @@ def testformat(formatstr, args, output=None): if verbose: if output: - print "%s %% %s =? %s ..." %\ - (repr(formatstr), repr(args), repr(output)), + print("%s %% %s =? %s ..." %\ + (repr(formatstr), repr(args), repr(output)), end=' ') else: - print "%s %% %s works? ..." % (repr(formatstr), repr(args)), + print("%s %% %s works? ..." % (repr(formatstr), repr(args)), end=' ') try: result = formatstr % args except OverflowError: if not overflowok: raise if verbose: - print 'overflow (this is fine)' + print('overflow (this is fine)') else: if output and result != output: if verbose: - print 'no' - print "%s %% %s == %s != %s" %\ - (repr(formatstr), repr(args), repr(result), repr(output)) + print('no') + print("%s %% %s == %s != %s" %\ + (repr(formatstr), repr(args), repr(result), repr(output))) else: if verbose: - print 'yes' + print('yes') def testboth(formatstr, *args): testformat(formatstr, *args) @@ -194,7 +194,7 @@ # Test exception for unknown format characters if verbose: - print 'Testing exceptions' + print('Testing exceptions') def test_exc(formatstr, args, exception, excmsg): try: @@ -202,13 +202,13 @@ except exception as exc: if str(exc) == excmsg: if verbose: - print "yes" + print("yes") else: - if verbose: print 'no' - print 'Unexpected ', exception, ':', repr(str(exc)) + if verbose: print('no') + print('Unexpected ', exception, ':', repr(str(exc))) except: - if verbose: print 'no' - print 'Unexpected exception' + if verbose: print('no') + print('Unexpected exception') raise else: raise TestFailed, 'did not get expected exception: %s' % excmsg Modified: python/branches/p3yk/Lib/test/test_funcattrs.py ============================================================================== --- python/branches/p3yk/Lib/test/test_funcattrs.py (original) +++ python/branches/p3yk/Lib/test/test_funcattrs.py Fri Feb 9 06:37:30 2007 @@ -204,7 +204,7 @@ pass def temp(): - print 1 + print(1) if foo==bar: raise TestFailed @@ -235,7 +235,7 @@ def test_func_closure(): a = 12 - def f(): print a + def f(): print(a) c = f.func_closure verify(isinstance(c, tuple)) verify(len(c) == 1) @@ -284,10 +284,10 @@ def test_func_code(): a = b = 24 def f(): pass - def g(): print 12 - def f1(): print a - def g1(): print b - def f2(): print a, b + def g(): print(12) + def f1(): print(a) + def g1(): print(b) + def f2(): print(a, b) verify(type(f.func_code) is types.CodeType) f.func_code = g.func_code cantset(f, "func_code", None) Modified: python/branches/p3yk/Lib/test/test_functools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_functools.py (original) +++ python/branches/p3yk/Lib/test/test_functools.py Fri Feb 9 06:37:30 2007 @@ -356,7 +356,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == '__main__': test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_gc.py ============================================================================== --- python/branches/p3yk/Lib/test/test_gc.py (original) +++ python/branches/p3yk/Lib/test/test_gc.py Fri Feb 9 06:37:30 2007 @@ -14,10 +14,10 @@ def run_test(name, thunk): if verbose: - print "testing %s..." % name, + print("testing %s..." % name, end=' ') thunk() if verbose: - print "ok" + print("ok") def test_list(): l = [] @@ -612,7 +612,7 @@ def test(): if verbose: - print "disabling automatic collection" + print("disabling automatic collection") enabled = gc.isenabled() gc.disable() verify(not gc.isenabled()) @@ -625,7 +625,7 @@ gc.set_debug(debug) # test gc.enable() even if GC is disabled by default if verbose: - print "restoring automatic collection" + print("restoring automatic collection") # make sure to always test gc.enable() gc.enable() verify(gc.isenabled()) Modified: python/branches/p3yk/Lib/test/test_gdbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_gdbm.py (original) +++ python/branches/p3yk/Lib/test/test_gdbm.py Fri Feb 9 06:37:30 2007 @@ -15,7 +15,7 @@ g['12345678910'] = '019237410982340912840198242' a = g.keys() if verbose: - print 'Test gdbm file keys: ', a + print('Test gdbm file keys: ', a) 'a' in g g.close() Modified: python/branches/p3yk/Lib/test/test_generators.py ============================================================================== --- python/branches/p3yk/Lib/test/test_generators.py (original) +++ python/branches/p3yk/Lib/test/test_generators.py Fri Feb 9 06:37:30 2007 @@ -1082,12 +1082,12 @@ n = self.n assert n == len(row2col) sep = "+" + "-+" * n - print sep + print(sep) for i in range(n): squares = [" " for j in range(n)] squares[row2col[i]] = "Q" - print "|" + "|".join(squares) + "|" - print sep + print("|" + "|".join(squares) + "|") + print(sep) # A conjoin-based Knight's Tour solver. This is pretty sophisticated # (e.g., when used with flat_conjoin above, and passing hard=1 to the @@ -1279,11 +1279,11 @@ k += 1 sep = "+" + ("-" * w + "+") * n - print sep + print(sep) for i in range(m): row = squares[i] - print "|" + "|".join(row) + "|" - print sep + print("|" + "|".join(row) + "|") + print(sep) conjoin_tests = """ Modified: python/branches/p3yk/Lib/test/test_genexps.py ============================================================================== --- python/branches/p3yk/Lib/test/test_genexps.py (original) +++ python/branches/p3yk/Lib/test/test_genexps.py Fri Feb 9 06:37:30 2007 @@ -274,7 +274,7 @@ test_support.run_doctest(test_genexps, verbose) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_getopt.py ============================================================================== --- python/branches/p3yk/Lib/test/test_getopt.py (original) +++ python/branches/p3yk/Lib/test/test_getopt.py Fri Feb 9 06:37:30 2007 @@ -21,14 +21,14 @@ del os.environ["POSIXLY_CORRECT"] if verbose: - print 'Running tests on getopt.short_has_arg' + print('Running tests on getopt.short_has_arg') verify(getopt.short_has_arg('a', 'a:')) verify(not getopt.short_has_arg('a', 'a')) expectException("tmp = getopt.short_has_arg('a', 'b')", GetoptError) expectException("tmp = getopt.short_has_arg('a', '')", GetoptError) if verbose: - print 'Running tests on getopt.long_has_args' + print('Running tests on getopt.long_has_args') has_arg, option = getopt.long_has_args('abc', ['abc=']) verify(has_arg) verify(option == 'abc') @@ -47,7 +47,7 @@ GetoptError) if verbose: - print 'Running tests on getopt.do_shorts' + print('Running tests on getopt.do_shorts') opts, args = getopt.do_shorts([], 'a', 'a', []) verify(opts == [('-a', '')]) verify(args == []) @@ -69,7 +69,7 @@ GetoptError) if verbose: - print 'Running tests on getopt.do_longs' + print('Running tests on getopt.do_longs') opts, args = getopt.do_longs([], 'abc', ['abc'], []) verify(opts == [('--abc', '')]) verify(args == []) @@ -99,7 +99,7 @@ '--beta', 'arg1', 'arg2'] if verbose: - print 'Running tests on getopt.getopt' + print('Running tests on getopt.getopt') opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta']) verify(opts == [('-a', '1'), ('-b', ''), ('--alpha', '2'), ('--beta', ''), ('-a', '3'), ('-a', ''), ('--beta', '')] ) @@ -113,7 +113,7 @@ # Test handling of GNU style scanning mode. if verbose: - print 'Running tests on getopt.gnu_getopt' + print('Running tests on getopt.gnu_getopt') cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2'] # GNU style opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta=']) @@ -177,4 +177,4 @@ #------------------------------------------------------------------------------ if verbose: - print "Module getopt: tests completed successfully." + print("Module getopt: tests completed successfully.") Modified: python/branches/p3yk/Lib/test/test_gl.py ============================================================================== --- python/branches/p3yk/Lib/test/test_gl.py (original) +++ python/branches/p3yk/Lib/test/test_gl.py Fri Feb 9 06:37:30 2007 @@ -91,60 +91,60 @@ # touch all the attributes of gl without doing anything if verbose: - print 'Touching gl module attributes...' + print('Touching gl module attributes...') for attr in glattrs: if verbose: - print 'touching: ', attr + print('touching: ', attr) getattr(gl, attr) # create a small 'Crisscross' window if verbose: - print 'Creating a small "CrissCross" window...' - print 'foreground' + print('Creating a small "CrissCross" window...') + print('foreground') gl.foreground() if verbose: - print 'prefposition' + print('prefposition') gl.prefposition(500, 900, 500, 900) if verbose: - print 'winopen "CrissCross"' + print('winopen "CrissCross"') w = gl.winopen('CrissCross') if verbose: - print 'clear' + print('clear') gl.clear() if verbose: - print 'ortho2' + print('ortho2') gl.ortho2(0.0, 400.0, 0.0, 400.0) if verbose: - print 'color WHITE' + print('color WHITE') gl.color(GL.WHITE) if verbose: - print 'color RED' + print('color RED') gl.color(GL.RED) if verbose: - print 'bgnline' + print('bgnline') gl.bgnline() if verbose: - print 'v2f' + print('v2f') gl.v2f(0.0, 0.0) gl.v2f(400.0, 400.0) if verbose: - print 'endline' + print('endline') gl.endline() if verbose: - print 'bgnline' + print('bgnline') gl.bgnline() if verbose: - print 'v2i' + print('v2i') gl.v2i(400, 0) gl.v2i(0, 400) if verbose: - print 'endline' + print('endline') gl.endline() if verbose: - print 'Displaying window for 2 seconds...' + print('Displaying window for 2 seconds...') time.sleep(2) if verbose: - print 'winclose' + print('winclose') gl.winclose(w) main() Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Fri Feb 9 06:37:30 2007 @@ -351,7 +351,7 @@ x = 1; pass; del x; foo() - ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt + ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt # Tested below def testExprStmt(self): @@ -367,76 +367,6 @@ check_syntax_error(self, "x + 1 = 1") check_syntax_error(self, "a + 1 = b + 2") - def testPrintStmt(self): - # 'print' (test ',')* [test] - import StringIO - - # Can't test printing to real stdout without comparing output - # which is not available in unittest. - save_stdout = sys.stdout - sys.stdout = StringIO.StringIO() - - print 1, 2, 3 - print 1, 2, 3, - print - print 0 or 1, 0 or 1, - print 0 or 1 - - # 'print' '>>' test ',' - print >> sys.stdout, 1, 2, 3 - print >> sys.stdout, 1, 2, 3, - print >> sys.stdout - print >> sys.stdout, 0 or 1, 0 or 1, - print >> sys.stdout, 0 or 1 - - # test printing to an instance - class Gulp: - def write(self, msg): pass - - gulp = Gulp() - print >> gulp, 1, 2, 3 - print >> gulp, 1, 2, 3, - print >> gulp - print >> gulp, 0 or 1, 0 or 1, - print >> gulp, 0 or 1 - - # test print >> None - def driver(): - oldstdout = sys.stdout - sys.stdout = Gulp() - try: - tellme(Gulp()) - tellme() - finally: - sys.stdout = oldstdout - - # we should see this once - def tellme(file=sys.stdout): - print >> file, 'hello world' - - driver() - - # we should not see this at all - def tellme(file=None): - print >> file, 'goodbye universe' - - driver() - - self.assertEqual(sys.stdout.getvalue(), '''\ -1 2 3 -1 2 3 -1 1 1 -1 2 3 -1 2 3 -1 1 1 -hello world -''') - sys.stdout = save_stdout - - # syntax errors - check_syntax_error(self, 'print ,') - check_syntax_error(self, 'print >> x,') - def testDelStmt(self): # 'del' exprlist abc = [1,2,3] @@ -902,7 +832,7 @@ # Test ifelse expressions in various cases def _checkeval(msg, ret): "helper to check that evaluation of expressions is done correctly" - print x + print(x) return ret self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) Modified: python/branches/p3yk/Lib/test/test_heapq.py ============================================================================== --- python/branches/p3yk/Lib/test/test_heapq.py (original) +++ python/branches/p3yk/Lib/test/test_heapq.py Fri Feb 9 06:37:30 2007 @@ -281,7 +281,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_imageop.py ============================================================================== --- python/branches/p3yk/Lib/test/test_imageop.py (original) +++ python/branches/p3yk/Lib/test/test_imageop.py Fri Feb 9 06:37:30 2007 @@ -28,7 +28,7 @@ # Return the selected part of image, which should by width by height # in size and consist of pixels of psize bytes. if verbose: - print 'crop' + print('crop') newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1) # Return image scaled to size newwidth by newheight. No interpolation @@ -36,7 +36,7 @@ # Therefore, computer-generated images or dithered images will # not look nice after scaling. if verbose: - print 'scale' + print('scale') scaleimage = imageop.scale(image, 4, width, height, 1, 1) # Run a vertical low-pass filter over an image. It does so by computing @@ -44,34 +44,34 @@ # pixels. The main use of this routine is to forestall excessive flicker # if the image two vertically-aligned source pixels, hence the name. if verbose: - print 'tovideo' + print('tovideo') videoimage = imageop.tovideo (image, 4, width, height) # Convert an rgb image to an 8 bit rgb if verbose: - print 'rgb2rgb8' + print('rgb2rgb8') greyimage = imageop.rgb2rgb8(image, width, height) # Convert an 8 bit rgb image to a 24 bit rgb image if verbose: - print 'rgb82rgb' + print('rgb82rgb') image = imageop.rgb82rgb(greyimage, width, height) # Convert an rgb image to an 8 bit greyscale image if verbose: - print 'rgb2grey' + print('rgb2grey') greyimage = imageop.rgb2grey(image, width, height) # Convert an 8 bit greyscale image to a 24 bit rgb image if verbose: - print 'grey2rgb' + print('grey2rgb') image = imageop.grey2rgb(greyimage, width, height) # Convert a 8-bit deep greyscale image to a 1-bit deep image by # thresholding all the pixels. The resulting image is tightly packed # and is probably only useful as an argument to mono2grey. if verbose: - print 'grey2mono' + print('grey2mono') monoimage = imageop.grey2mono (greyimage, width, height, 0) # monoimage, width, height = getimage('monotest.rgb') @@ -81,42 +81,42 @@ # monochrome black-and-white image to greyscale pass the values 0 and # 255 respectively. if verbose: - print 'mono2grey' + print('mono2grey') greyimage = imageop.mono2grey (monoimage, width, height, 0, 255) # Convert an 8-bit greyscale image to a 1-bit monochrome image using a # (simple-minded) dithering algorithm. if verbose: - print 'dither2mono' + print('dither2mono') monoimage = imageop.dither2mono (greyimage, width, height) # Convert an 8-bit greyscale image to a 4-bit greyscale image without # dithering. if verbose: - print 'grey2grey4' + print('grey2grey4') grey4image = imageop.grey2grey4 (greyimage, width, height) # Convert an 8-bit greyscale image to a 2-bit greyscale image without # dithering. if verbose: - print 'grey2grey2' + print('grey2grey2') grey2image = imageop.grey2grey2 (greyimage, width, height) # Convert an 8-bit greyscale image to a 2-bit greyscale image with # dithering. As for dither2mono, the dithering algorithm is currently # very simple. if verbose: - print 'dither2grey2' + print('dither2grey2') grey2image = imageop.dither2grey2 (greyimage, width, height) # Convert a 4-bit greyscale image to an 8-bit greyscale image. if verbose: - print 'grey42grey' + print('grey42grey') greyimage = imageop.grey42grey (grey4image, width, height) # Convert a 2-bit greyscale image to an 8-bit greyscale image. if verbose: - print 'grey22grey' + print('grey22grey') image = imageop.grey22grey (grey2image, width, height) # Cleanup @@ -134,7 +134,7 @@ name = get_qualified_path(name) sizes = rgbimg.sizeofimage(name) if verbose: - print 'rgbimg opening test image: %s, sizes: %s' % (name, str(sizes)) + print('rgbimg opening test image: %s, sizes: %s' % (name, str(sizes))) image = rgbimg.longimagedata(name) return (image, sizes[0], sizes[1]) @@ -152,7 +152,7 @@ name = get_qualified_path(name) sizes = imgfile.getsizes(name) if verbose: - print 'imgfile opening test image: %s, sizes: %s' % (name, str(sizes)) + print('imgfile opening test image: %s, sizes: %s' % (name, str(sizes))) image = imgfile.read(name) return (image, sizes[0], sizes[1]) Modified: python/branches/p3yk/Lib/test/test_imgfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_imgfile.py (original) +++ python/branches/p3yk/Lib/test/test_imgfile.py Fri Feb 9 06:37:30 2007 @@ -51,7 +51,7 @@ name = os.sep.join(parts) sizes = imgfile.getsizes(name) if verbose: - print 'Opening test image: %s, sizes: %s' % (name, str(sizes)) + print('Opening test image: %s, sizes: %s' % (name, str(sizes))) # This function reads and decodes the image on the specified file, # and returns it as a python string. The string has either 1 byte # greyscale pixels or 4 byte RGBA pixels. The bottom left pixel @@ -65,12 +65,12 @@ # are stored as 4 byte values of which only the lower three # bytes are used). These are the formats returned by gl.lrectread. if verbose: - print 'Writing output file' + print('Writing output file') imgfile.write (outputfile, image, sizes[0], sizes[1], sizes[2]) if verbose: - print 'Opening scaled test image: %s, sizes: %s' % (name, str(sizes)) + print('Opening scaled test image: %s, sizes: %s' % (name, str(sizes))) # This function is identical to read but it returns an image that # is scaled to the given x and y sizes. If the filter and blur # parameters are omitted scaling is done by simply dropping @@ -84,7 +84,7 @@ # makes no attempt to keep the aspect ratio correct, so that # is the users' responsibility. if verbose: - print 'Filtering with "impulse"' + print('Filtering with "impulse"') simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'impulse', 2.0) # This function sets a global flag which defines whether the @@ -92,23 +92,23 @@ # top (flag is zero, compatible with SGI GL) or from top to # bottom(flag is one, compatible with X). The default is zero. if verbose: - print 'Switching to X compatibility' + print('Switching to X compatibility') imgfile.ttob (1) if verbose: - print 'Filtering with "triangle"' + print('Filtering with "triangle"') simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'triangle', 3.0) if verbose: - print 'Switching back to SGI compatibility' + print('Switching back to SGI compatibility') imgfile.ttob (0) - if verbose: print 'Filtering with "quadratic"' + if verbose: print('Filtering with "quadratic"') simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'quadratic') - if verbose: print 'Filtering with "gaussian"' + if verbose: print('Filtering with "gaussian"') simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'gaussian', 1.0) if verbose: - print 'Writing output file' + print('Writing output file') imgfile.write (outputfile, simage, sizes[0]/2, sizes[1]/2, sizes[2]) os.unlink(outputfile) Modified: python/branches/p3yk/Lib/test/test_import.py ============================================================================== --- python/branches/p3yk/Lib/test/test_import.py (original) +++ python/branches/p3yk/Lib/test/test_import.py Fri Feb 9 06:37:30 2007 @@ -45,11 +45,11 @@ pyc = TESTFN + os.extsep + "pyc" f = open(source, "w") - print >> f, "# This tests Python's ability to import a", ext, "file." + print("# This tests Python's ability to import a", ext, "file.", file=f) a = random.randrange(1000) b = random.randrange(1000) - print >> f, "a =", a - print >> f, "b =", b + print("a =", a, file=f) + print("b =", b, file=f) f.close() try: @@ -130,7 +130,7 @@ def test_failing_import_sticks(self): source = TESTFN + os.extsep + "py" f = open(source, "w") - print >> f, "a = 1/0" + print("a = 1/0", file=f) f.close() # New in 2.4, we shouldn't be able to import that no matter how often @@ -153,8 +153,8 @@ # A failing reload should leave the module object in sys.modules. source = TESTFN + os.extsep + "py" f = open(source, "w") - print >> f, "a = 1" - print >> f, "b = 2" + print("a = 1", file=f) + print("b = 2", file=f) f.close() sys.path.insert(0, os.curdir) @@ -172,8 +172,8 @@ # Now damage the module. f = open(source, "w") - print >> f, "a = 10" - print >> f, "b = 20//0" + print("a = 10", file=f) + print("b = 20//0", file=f) f.close() self.assertRaises(ZeroDivisionError, reload, mod) Modified: python/branches/p3yk/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_itertools.py (original) +++ python/branches/p3yk/Lib/test/test_itertools.py Fri Feb 9 06:37:30 2007 @@ -965,7 +965,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) # doctest the examples in the library reference test_support.run_doctest(sys.modules[__name__], verbose) Modified: python/branches/p3yk/Lib/test/test_largefile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_largefile.py (original) +++ python/branches/p3yk/Lib/test/test_largefile.py Fri Feb 9 06:37:30 2007 @@ -52,22 +52,22 @@ def expect(got_this, expect_this): if test_support.verbose: - print '%r =?= %r ...' % (got_this, expect_this), + print('%r =?= %r ...' % (got_this, expect_this), end=' ') if got_this != expect_this: if test_support.verbose: - print 'no' + print('no') raise test_support.TestFailed, 'got %r, but expected %r' %\ (got_this, expect_this) else: if test_support.verbose: - print 'yes' + print('yes') # test that each file function works as expected for a large (i.e. >2GB, do # we have to check >4GB) files if test_support.verbose: - print 'create large file via seek (may be sparse file) ...' + print('create large file via seek (may be sparse file) ...') f = open(name, 'wb') try: f.write('z') @@ -76,16 +76,16 @@ f.write('a') f.flush() if test_support.verbose: - print 'check file size with os.fstat' + print('check file size with os.fstat') expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1) finally: f.close() if test_support.verbose: - print 'check file size with os.stat' + print('check file size with os.stat') expect(os.stat(name)[stat.ST_SIZE], size+1) if test_support.verbose: - print 'play around with seek() and read() with the built largefile' + print('play around with seek() and read() with the built largefile') f = open(name, 'rb') try: expect(f.tell(), 0) @@ -119,7 +119,7 @@ f.close() if test_support.verbose: - print 'play around with os.lseek() with the built largefile' + print('play around with os.lseek() with the built largefile') f = open(name, 'rb') try: expect(os.lseek(f.fileno(), 0, 0), 0) @@ -136,7 +136,7 @@ if hasattr(f, 'truncate'): if test_support.verbose: - print 'try truncate' + print('try truncate') f = open(name, 'r+b') try: f.seek(0, 2) Modified: python/branches/p3yk/Lib/test/test_linuxaudiodev.py ============================================================================== --- python/branches/p3yk/Lib/test/test_linuxaudiodev.py (original) +++ python/branches/p3yk/Lib/test/test_linuxaudiodev.py Fri Feb 9 06:37:30 2007 @@ -22,7 +22,7 @@ fp.close() if enc != SND_FORMAT_MULAW_8: - print "Expect .au file with 8-bit mu-law samples" + print("Expect .au file with 8-bit mu-law samples") return try: @@ -63,27 +63,27 @@ try: a.setparameters(-1, size, nchannels, fmt) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, -2, nchannels, fmt) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, size, 3, fmt) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, size, nchannels, 177) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE) except ValueError as msg: - print msg + print(msg) try: a.setparameters(rate, 16, nchannels, fmt) except ValueError as msg: - print msg + print(msg) def test(): play_sound_file(findfile('audiotest.au')) Modified: python/branches/p3yk/Lib/test/test_list.py ============================================================================== --- python/branches/p3yk/Lib/test/test_list.py (original) +++ python/branches/p3yk/Lib/test/test_list.py Fri Feb 9 06:37:30 2007 @@ -30,7 +30,7 @@ test_support.run_unittest(ListTest) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": Modified: python/branches/p3yk/Lib/test/test_locale.py ============================================================================== --- python/branches/p3yk/Lib/test/test_locale.py (original) +++ python/branches/p3yk/Lib/test/test_locale.py Fri Feb 9 06:37:30 2007 @@ -23,19 +23,19 @@ def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: - print "%s %% %s =? %s ..." %\ - (repr(formatstr), repr(value), repr(output)), + print("%s %% %s =? %s ..." %\ + (repr(formatstr), repr(value), repr(output)), end=' ') else: - print "%s %% %s works? ..." % (repr(formatstr), repr(value)), + print("%s %% %s works? ..." % (repr(formatstr), repr(value)), end=' ') result = func(formatstr, value, grouping = grouping) if output and result != output: if verbose: - print 'no' - print "%s %% %s == %s != %s" %\ - (repr(formatstr), repr(value), repr(result), repr(output)) + print('no') + print("%s %% %s == %s != %s" %\ + (repr(formatstr), repr(value), repr(result), repr(output))) else: if verbose: - print "yes" + print("yes") try: # On Solaris 10, the thousands_sep is the empty string @@ -80,15 +80,15 @@ # Test BSD Rune locale's bug for isctype functions. def teststrop(s, method, output): if verbose: - print "%s.%s() =? %s ..." % (repr(s), method, repr(output)), + print("%s.%s() =? %s ..." % (repr(s), method, repr(output)), end=' ') result = getattr(s, method)() if result != output: if verbose: - print "no" - print "%s.%s() == %s != %s" % (repr(s), method, repr(result), - repr(output)) + print("no") + print("%s.%s() == %s != %s" % (repr(s), method, repr(result), + repr(output))) elif verbose: - print "yes" + print("yes") try: if sys.platform == 'sunos5': Modified: python/branches/p3yk/Lib/test/test_long_future.py ============================================================================== --- python/branches/p3yk/Lib/test/test_long_future.py (original) +++ python/branches/p3yk/Lib/test/test_long_future.py Fri Feb 9 06:37:30 2007 @@ -7,7 +7,7 @@ def test_true_division(): if verbose: - print "long true division" + print("long true division") huge = 1 << 40000 mhuge = -huge verify(huge / huge == 1.0) Modified: python/branches/p3yk/Lib/test/test_minidom.py ============================================================================== --- python/branches/p3yk/Lib/test/test_minidom.py (original) +++ python/branches/p3yk/Lib/test/test_minidom.py Fri Feb 9 06:37:30 2007 @@ -24,7 +24,7 @@ def confirm(test, testname = "Test"): if not test: - print "Failed " + testname + print("Failed " + testname) raise Exception def testParseFromFile(): @@ -140,29 +140,29 @@ try: dom.appendChild(text) except xml.dom.HierarchyRequestErr: pass else: - print "dom.appendChild didn't raise HierarchyRequestErr" + print("dom.appendChild didn't raise HierarchyRequestErr") dom.appendChild(elem) try: dom.insertBefore(text, elem) except xml.dom.HierarchyRequestErr: pass else: - print "dom.appendChild didn't raise HierarchyRequestErr" + print("dom.appendChild didn't raise HierarchyRequestErr") try: dom.replaceChild(text, elem) except xml.dom.HierarchyRequestErr: pass else: - print "dom.appendChild didn't raise HierarchyRequestErr" + print("dom.appendChild didn't raise HierarchyRequestErr") nodemap = elem.attributes try: nodemap.setNamedItem(text) except xml.dom.HierarchyRequestErr: pass else: - print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr" + print("NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr") try: nodemap.setNamedItemNS(text) except xml.dom.HierarchyRequestErr: pass else: - print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr" + print("NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr") elem.appendChild(text) dom.unlink() @@ -457,8 +457,8 @@ except xml.dom.HierarchyRequestErr: pass else: - print "Failed to catch expected exception when" \ - " adding extra document element." + print("Failed to catch expected exception when" \ + " adding extra document element.") elem.unlink() doc.unlink() @@ -896,7 +896,7 @@ except UnicodeDecodeError: pass else: - print 'parsing with bad encoding should raise a UnicodeDecodeError' + print('parsing with bad encoding should raise a UnicodeDecodeError') doc.unlink() @@ -1008,7 +1008,7 @@ except xml.dom.NamespaceErr: pass else: - print "expected NamespaceErr" + print("expected NamespaceErr") checkRenameNodeSharedConstraints(doc, attr) doc.unlink() @@ -1063,7 +1063,7 @@ except xml.dom.NamespaceErr: pass else: - print "expected NamespaceErr" + print("expected NamespaceErr") doc2 = parseString("") try: @@ -1071,7 +1071,7 @@ except xml.dom.WrongDocumentErr: pass else: - print "expected WrongDocumentErr" + print("expected WrongDocumentErr") def testRenameOther(): # We have to create a comment node explicitly since not all DOM @@ -1084,7 +1084,7 @@ except xml.dom.NotSupportedErr: pass else: - print "expected NotSupportedErr when renaming comment node" + print("expected NotSupportedErr when renaming comment node") doc.unlink() def checkWholeText(node, s): @@ -1368,13 +1368,13 @@ confirm(len(Node.allnodes) == 0, "assertion: len(Node.allnodes) == 0") if len(Node.allnodes): - print "Garbage left over:" + print("Garbage left over:") if verbose: - print Node.allnodes.items()[0:10] + print(Node.allnodes.items()[0:10]) else: # Don't print specific nodes if repeatable results # are needed - print len(Node.allnodes) + print(len(Node.allnodes)) Node.allnodes = {} for name in names: @@ -1385,13 +1385,13 @@ check_allnodes() except: failed.append(name) - print "Test Failed: ", name + print("Test Failed: ", name) sys.stdout.flush() traceback.print_exception(*sys.exc_info()) - print repr(sys.exc_info()[1]) + print(repr(sys.exc_info()[1])) Node.allnodes = {} if failed: - print "\n\n\n**** Check for failures in these tests:" + print("\n\n\n**** Check for failures in these tests:") for name in failed: - print " " + name + print(" " + name) Modified: python/branches/p3yk/Lib/test/test_module.py ============================================================================== --- python/branches/p3yk/Lib/test/test_module.py (original) +++ python/branches/p3yk/Lib/test/test_module.py Fri Feb 9 06:37:30 2007 @@ -45,4 +45,4 @@ verify(foo.__dict__ is d) if verbose: - print "All OK" + print("All OK") Modified: python/branches/p3yk/Lib/test/test_multibytecodec.py ============================================================================== --- python/branches/p3yk/Lib/test/test_multibytecodec.py (original) +++ python/branches/p3yk/Lib/test/test_multibytecodec.py Fri Feb 9 06:37:30 2007 @@ -48,7 +48,7 @@ def test_codingspec(self): try: for enc in ALL_CJKENCODINGS: - print >> open(TESTFN, 'w'), '# coding:', enc + print('# coding:', enc, file=open(TESTFN, 'w')) execfile(TESTFN) finally: os.unlink(TESTFN) Modified: python/branches/p3yk/Lib/test/test_mutants.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mutants.py (original) +++ python/branches/p3yk/Lib/test/test_mutants.py Fri Feb 9 06:37:30 2007 @@ -135,13 +135,13 @@ # same size. mutate = 1 if verbose: - print "trying w/ lengths", len(dict1), len(dict2), + print("trying w/ lengths", len(dict1), len(dict2), end=' ') while dict1 and len(dict1) == len(dict2): if verbose: - print ".", + print(".", end=' ') c = dict1 == dict2 if verbose: - print + print() # Run test_one n times. At the start (before the bugs were fixed), 20 # consecutive runs of this test each blew up on or before the sixth time @@ -186,7 +186,7 @@ # the expected-output file doesn't need to change. f = open(TESTFN, "w") -print >> f, Parent().__dict__ +print(Parent().__dict__, file=f) f.close() os.unlink(TESTFN) @@ -207,7 +207,7 @@ # Michael sez: "doesn't crash without this. don't know why." # Tim sez: "luck of the draw; crashes with or without for me." - print >> f + print(file=f) return repr("machiavelli") @@ -216,7 +216,7 @@ dict[Machiavelli()] = Machiavelli() -print >> f, str(dict) +print(str(dict), file=f) f.close() os.unlink(TESTFN) del f, dict @@ -280,7 +280,7 @@ f = open(TESTFN, "w") try: try: - print >> f, dict[Machiavelli3(2)] + print(dict[Machiavelli3(2)], file=f) except KeyError: pass finally: Modified: python/branches/p3yk/Lib/test/test_normalization.py ============================================================================== --- python/branches/p3yk/Lib/test/test_normalization.py (original) +++ python/branches/p3yk/Lib/test/test_normalization.py Fri Feb 9 06:37:30 2007 @@ -58,7 +58,7 @@ continue if verbose: - print line + print(line) # Perform tests verify(c2 == NFC(c1) == NFC(c2) == NFC(c3), line) Modified: python/branches/p3yk/Lib/test/test_ntpath.py ============================================================================== --- python/branches/p3yk/Lib/test/test_ntpath.py (original) +++ python/branches/p3yk/Lib/test/test_ntpath.py Fri Feb 9 06:37:30 2007 @@ -9,11 +9,11 @@ fn = fn.replace("\\", "\\\\") gotResult = eval(fn) if wantResult != gotResult: - print "error!" - print "evaluated: " + str(fn) - print "should be: " + str(wantResult) - print " returned: " + str(gotResult) - print "" + print("error!") + print("evaluated: " + str(fn)) + print("should be: " + str(wantResult)) + print(" returned: " + str(gotResult)) + print("") errors = errors + 1 tester('ntpath.splitext("foo.ext")', ('foo', '.ext')) @@ -152,4 +152,4 @@ if errors: raise TestFailed(str(errors) + " errors.") elif verbose: - print "No errors. Thank your lucky stars." + print("No errors. Thank your lucky stars.") Modified: python/branches/p3yk/Lib/test/test_operations.py ============================================================================== --- python/branches/p3yk/Lib/test/test_operations.py (original) +++ python/branches/p3yk/Lib/test/test_operations.py Fri Feb 9 06:37:30 2007 @@ -1,11 +1,11 @@ # Python test set -- part 3, built-in operations. -print '3. Operations' -print 'XXX Mostly not yet implemented' +print('3. Operations') +print('XXX Mostly not yet implemented') -print '3.1 Dictionary lookups fail if __cmp__() raises an exception' +print('3.1 Dictionary lookups fail if __cmp__() raises an exception') class BadDictKey: @@ -14,7 +14,7 @@ def __eq__(self, other): if isinstance(other, self.__class__): - print "raising error" + print("raising error") raise RuntimeError, "gotcha" return other @@ -32,9 +32,9 @@ try: exec(stmt) except RuntimeError: - print "%s: caught the RuntimeError outside" % (stmt,) + print("%s: caught the RuntimeError outside" % (stmt,)) else: - print "%s: No exception passed through!" % (stmt,) # old CPython behavior + print("%s: No exception passed through!" % (stmt,)) # old CPython behavior # Dict resizing bug, found by Jack Jansen in 2.2 CVS development. @@ -74,4 +74,4 @@ resizing = True d[9] = 6 -print 'resize bugs not triggered.' +print('resize bugs not triggered.') Modified: python/branches/p3yk/Lib/test/test_operator.py ============================================================================== --- python/branches/p3yk/Lib/test/test_operator.py (original) +++ python/branches/p3yk/Lib/test/test_operator.py Fri Feb 9 06:37:30 2007 @@ -468,7 +468,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_ossaudiodev.py ============================================================================== --- python/branches/p3yk/Lib/test/test_ossaudiodev.py (original) +++ python/branches/p3yk/Lib/test/test_ossaudiodev.py Fri Feb 9 06:37:30 2007 @@ -33,7 +33,7 @@ fp.close() if enc != SND_FORMAT_MULAW_8: - print "Expect .au file with 8-bit mu-law samples" + print("Expect .au file with 8-bit mu-law samples") return # Convert the data to 16-bit signed. @@ -78,8 +78,8 @@ # set parameters based on .au file headers dsp.setparameters(AFMT_S16_NE, nchannels, rate) - print ("playing test sound file (expected running time: %.2f sec)" - % expected_time) + print(("playing test sound file (expected running time: %.2f sec)" + % expected_time)) t1 = time.time() dsp.write(data) dsp.close() @@ -143,7 +143,7 @@ result = dsp.setparameters(fmt, channels, rate, True) raise AssertionError("setparameters: expected OSSAudioError") except ossaudiodev.OSSAudioError as err: - print "setparameters: got OSSAudioError as expected" + print("setparameters: got OSSAudioError as expected") def test(): (data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au')) Modified: python/branches/p3yk/Lib/test/test_peepholer.py ============================================================================== --- python/branches/p3yk/Lib/test/test_peepholer.py (original) +++ python/branches/p3yk/Lib/test/test_peepholer.py Fri Feb 9 06:37:30 2007 @@ -211,7 +211,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_pep247.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep247.py (original) +++ python/branches/p3yk/Lib/test/test_pep247.py Fri Feb 9 06:37:30 2007 @@ -41,7 +41,7 @@ hd2 += "%02x" % ord(byte) assert hd2 == hexdigest, "hexdigest doesn't appear correct" - print 'Module', module.__name__, 'seems to comply with PEP 247' + print('Module', module.__name__, 'seems to comply with PEP 247') if __name__ == '__main__': Modified: python/branches/p3yk/Lib/test/test_pep277.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep277.py (original) +++ python/branches/p3yk/Lib/test/test_pep277.py Fri Feb 9 06:37:30 2007 @@ -83,7 +83,7 @@ f2 = os.listdir(unicode(test_support.TESTFN, sys.getfilesystemencoding())) f2.sort() - print f2 + print(f2) def test_rename(self): for name in self.files: @@ -99,7 +99,7 @@ f = open(filename, 'w') f.write((filename + '\n').encode("utf-8")) f.close() - print repr(filename) + print(repr(filename)) os.access(filename,os.R_OK) os.remove(filename) os.chdir(oldwd) Modified: python/branches/p3yk/Lib/test/test_pkg.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pkg.py (original) +++ python/branches/p3yk/Lib/test/test_pkg.py Fri Feb 9 06:37:30 2007 @@ -18,7 +18,7 @@ if contents is None: mkdir(fullname) else: - if verbose: print "write", fullname + if verbose: print("write", fullname) f = open(fullname, "w") f.write(contents) if contents and contents[-1] != '\n': @@ -26,7 +26,7 @@ f.close() def mkdir(x): - if verbose: print "mkdir", x + if verbose: print("mkdir", x) os.mkdir(x) def cleanout(root): @@ -40,7 +40,7 @@ rmdir(root) def rmdir(x): - if verbose: print "rmdir", x + if verbose: print("rmdir", x) os.rmdir(x) def fixdir(lst): @@ -61,7 +61,7 @@ os.close(fd) try: sys.path.insert(0, root) - if verbose: print "sys.path =", sys.path + if verbose: print("sys.path =", sys.path) try: execfile(fname, globals(), {}) except: @@ -242,9 +242,9 @@ for name, hier, code in tests: if args and name not in args: - print "skipping test", name + print("skipping test", name) continue - print "running test", name + print("running test", name) runtest(hier, code) # Test Modified: python/branches/p3yk/Lib/test/test_popen2.py ============================================================================== --- python/branches/p3yk/Lib/test/test_popen2.py (original) +++ python/branches/p3yk/Lib/test/test_popen2.py Fri Feb 9 06:37:30 2007 @@ -13,7 +13,7 @@ # subprocess. def main(): - print "Test popen2 module:" + print("Test popen2 module:") if (sys.platform[:4] == 'beos' or sys.platform[:6] == 'atheos') \ and __name__ != '__main__': # Locks get messed up or something. Generally we're supposed @@ -33,7 +33,7 @@ def _test(): # same test as popen2._test(), but using the os.popen*() API - print "Testing os module:" + print("Testing os module:") import popen2 # When the test runs, there shouldn't be any open pipes popen2._cleanup() @@ -46,14 +46,14 @@ # sometimes adding an extra newline at the start or the # end. So we strip whitespace off both ends for comparison. expected = teststr.strip() - print "testing popen2..." + print("testing popen2...") w, r = os.popen2(cmd) w.write(teststr) w.close() got = r.read() if got.strip() != expected: raise ValueError("wrote %r read %r" % (teststr, got)) - print "testing popen3..." + print("testing popen3...") try: w, r, e = os.popen3([cmd]) except: @@ -71,7 +71,7 @@ popen2._cleanup() if popen2._active: raise ValueError("_active not empty") - print "All OK" + print("All OK") main() _test() Modified: python/branches/p3yk/Lib/test/test_pty.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pty.py (original) +++ python/branches/p3yk/Lib/test/test_pty.py Fri Feb 9 06:37:30 2007 @@ -6,7 +6,7 @@ if verbose: def debug(msg): - print msg + print(msg) else: def debug(msg): pass Modified: python/branches/p3yk/Lib/test/test_pyclbr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pyclbr.py (original) +++ python/branches/p3yk/Lib/test/test_pyclbr.py Fri Feb 9 06:37:30 2007 @@ -28,13 +28,13 @@ ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' missing = (set(l1) ^ set(l2)) - set(ignore) if missing: - print >>sys.stderr, "l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore) + print("l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore), file=sys.stderr) self.fail("%r missing" % missing.pop()) def assertHasattr(self, obj, attr, ignore): ''' succeed iff hasattr(obj,attr) or attr in ignore. ''' if attr in ignore: return - if not hasattr(obj, attr): print "???", attr + if not hasattr(obj, attr): print("???", attr) self.failUnless(hasattr(obj, attr), 'expected hasattr(%r, %r)' % (obj, attr)) @@ -43,7 +43,7 @@ ''' succeed iff key in obj or key in ignore. ''' if key in ignore: return if key not in obj: - print >>sys.stderr, "***",key + print("***",key, file=sys.stderr) self.failUnless(key in obj) def assertEqualsOrIgnored(self, a, b, ignore): @@ -110,7 +110,7 @@ try: self.assertListEq(real_bases, pyclbr_bases, ignore) except: - print >>sys.stderr, "class=%s" % py_item + print("class=%s" % py_item, file=sys.stderr) raise actualMethods = [] @@ -132,7 +132,7 @@ ignore) # can't check file or lineno except: - print >>sys.stderr, "class=%s" % py_item + print("class=%s" % py_item, file=sys.stderr) raise # Now check for missing stuff. Modified: python/branches/p3yk/Lib/test/test_pyexpat.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pyexpat.py (original) +++ python/branches/p3yk/Lib/test/test_pyexpat.py Fri Feb 9 06:37:30 2007 @@ -10,50 +10,50 @@ class Outputter: def StartElementHandler(self, name, attrs): - print 'Start element:\n\t', repr(name), sortdict(attrs) + print('Start element:\n\t', repr(name), sortdict(attrs)) def EndElementHandler(self, name): - print 'End element:\n\t', repr(name) + print('End element:\n\t', repr(name)) def CharacterDataHandler(self, data): data = data.strip() if data: - print 'Character data:' - print '\t', repr(data) + print('Character data:') + print('\t', repr(data)) def ProcessingInstructionHandler(self, target, data): - print 'PI:\n\t', repr(target), repr(data) + print('PI:\n\t', repr(target), repr(data)) def StartNamespaceDeclHandler(self, prefix, uri): - print 'NS decl:\n\t', repr(prefix), repr(uri) + print('NS decl:\n\t', repr(prefix), repr(uri)) def EndNamespaceDeclHandler(self, prefix): - print 'End of NS decl:\n\t', repr(prefix) + print('End of NS decl:\n\t', repr(prefix)) def StartCdataSectionHandler(self): - print 'Start of CDATA section' + print('Start of CDATA section') def EndCdataSectionHandler(self): - print 'End of CDATA section' + print('End of CDATA section') def CommentHandler(self, text): - print 'Comment:\n\t', repr(text) + print('Comment:\n\t', repr(text)) def NotationDeclHandler(self, *args): name, base, sysid, pubid = args - print 'Notation declared:', args + print('Notation declared:', args) def UnparsedEntityDeclHandler(self, *args): entityName, base, systemId, publicId, notationName = args - print 'Unparsed entity decl:\n\t', args + print('Unparsed entity decl:\n\t', args) def NotStandaloneHandler(self, userData): - print 'Not standalone' + print('Not standalone') return 1 def ExternalEntityRefHandler(self, *args): context, base, sysId, pubId = args - print 'External entity ref:', args[1:] + print('External entity ref:', args[1:]) return 1 def DefaultHandler(self, userData): @@ -65,9 +65,9 @@ def confirm(ok): if ok: - print "OK." + print("OK.") else: - print "Not OK." + print("Not OK.") out = Outputter() parser = expat.ParserCreate(namespace_separator='!') @@ -131,10 +131,10 @@ try: parser.Parse(data, 1) except expat.error: - print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode) - print '** Line', parser.ErrorLineNumber - print '** Column', parser.ErrorColumnNumber - print '** Byte', parser.ErrorByteIndex + print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)) + print('** Line', parser.ErrorLineNumber) + print('** Column', parser.ErrorColumnNumber) + print('** Byte', parser.ErrorByteIndex) # Try the parse again, this time producing Unicode output parser = expat.ParserCreate(namespace_separator='!') @@ -145,10 +145,10 @@ try: parser.Parse(data, 1) except expat.error: - print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode) - print '** Line', parser.ErrorLineNumber - print '** Column', parser.ErrorColumnNumber - print '** Byte', parser.ErrorByteIndex + print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)) + print('** Line', parser.ErrorLineNumber) + print('** Column', parser.ErrorColumnNumber) + print('** Byte', parser.ErrorByteIndex) # Try parsing a file parser = expat.ParserCreate(namespace_separator='!') @@ -161,35 +161,35 @@ try: parser.ParseFile(file) except expat.error: - print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode) - print '** Line', parser.ErrorLineNumber - print '** Column', parser.ErrorColumnNumber - print '** Byte', parser.ErrorByteIndex + print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)) + print('** Line', parser.ErrorLineNumber) + print('** Column', parser.ErrorColumnNumber) + print('** Byte', parser.ErrorByteIndex) # Tests that make sure we get errors when the namespace_separator value # is illegal, and that we don't for good values: -print -print "Testing constructor for proper handling of namespace_separator values:" +print() +print("Testing constructor for proper handling of namespace_separator values:") expat.ParserCreate() expat.ParserCreate(namespace_separator=None) expat.ParserCreate(namespace_separator=' ') -print "Legal values tested o.k." +print("Legal values tested o.k.") try: expat.ParserCreate(namespace_separator=42) except TypeError as e: - print "Caught expected TypeError:" - print e + print("Caught expected TypeError:") + print(e) else: - print "Failed to catch expected TypeError." + print("Failed to catch expected TypeError.") try: expat.ParserCreate(namespace_separator='too long') except ValueError as e: - print "Caught expected ValueError:" - print e + print("Caught expected ValueError:") + print(e) else: - print "Failed to catch expected ValueError." + print("Failed to catch expected ValueError.") # ParserCreate() needs to accept a namespace_separator of zero length # to satisfy the requirements of RDF applications that are required @@ -211,12 +211,12 @@ p.Parse(" ", 1) tag = L[0] if len(L) != 6: - print "L should only contain 6 entries; found", len(L) + print("L should only contain 6 entries; found", len(L)) for entry in L: if tag is not entry: - print "expected L to contain many references to the same string", - print "(it didn't)" - print "L =", repr(L) + print("expected L to contain many references to the same string", end=' ') + print("(it didn't)") + print("L =", repr(L)) break # Tests of the buffer_text attribute. @@ -323,9 +323,9 @@ parser.Parse("", 1) except RuntimeError as e: if e.args[0] != "a": - print "Expected RuntimeError for element 'a'; found %r" % e.args[0] + print("Expected RuntimeError for element 'a'; found %r" % e.args[0]) else: - print "Expected RuntimeError for 'a'" + print("Expected RuntimeError for 'a'") # Test Current* members: class PositionTest: Modified: python/branches/p3yk/Lib/test/test_queue.py ============================================================================== --- python/branches/p3yk/Lib/test/test_queue.py (original) +++ python/branches/p3yk/Lib/test/test_queue.py Fri Feb 9 06:37:30 2007 @@ -271,11 +271,11 @@ SimpleQueueTest(q) SimpleQueueTest(q) if verbose: - print "Simple Queue tests seemed to work" + print("Simple Queue tests seemed to work") q = FailingQueue(QUEUE_SIZE) FailingQueueTest(q) FailingQueueTest(q) if verbose: - print "Failing Queue tests seemed to work" + print("Failing Queue tests seemed to work") test() Modified: python/branches/p3yk/Lib/test/test_random.py ============================================================================== --- python/branches/p3yk/Lib/test/test_random.py (original) +++ python/branches/p3yk/Lib/test/test_random.py Fri Feb 9 06:37:30 2007 @@ -547,7 +547,7 @@ for i in xrange(len(counts)): test_support.run_unittest(*testclasses) counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_re.py ============================================================================== --- python/branches/p3yk/Lib/test/test_re.py (original) +++ python/branches/p3yk/Lib/test/test_re.py Fri Feb 9 06:37:30 2007 @@ -603,7 +603,7 @@ def run_re_tests(): from test.re_tests import benchmarks, tests, SUCCEED, FAIL, SYNTAX_ERROR if verbose: - print 'Running re_tests test suite' + print('Running re_tests test suite') else: # To save time, only run the first and last 10 tests #tests = tests[:10] + tests[-10:] @@ -624,23 +624,23 @@ except re.error: if outcome == SYNTAX_ERROR: pass # Expected a syntax error else: - print '=== Syntax error:', t + print('=== Syntax error:', t) except KeyboardInterrupt: raise KeyboardInterrupt except: - print '*** Unexpected error ***', t + print('*** Unexpected error ***', t) if verbose: traceback.print_exc(file=sys.stdout) else: try: result = obj.search(s) except re.error as msg: - print '=== Unexpected exception', t, repr(msg) + print('=== Unexpected exception', t, repr(msg)) if outcome == SYNTAX_ERROR: # This should have been a syntax error; forget it. pass elif outcome == FAIL: if result is None: pass # No match, as expected - else: print '=== Succeeded incorrectly', t + else: print('=== Succeeded incorrectly', t) elif outcome == SUCCEED: if result is not None: # Matched, as expected, so now we compute the @@ -668,17 +668,17 @@ vardict[i] = gi repl = eval(repl, vardict) if repl != expected: - print '=== grouping error', t, - print repr(repl) + ' should be ' + repr(expected) + print('=== grouping error', t, end=' ') + print(repr(repl) + ' should be ' + repr(expected)) else: - print '=== Failed incorrectly', t + print('=== Failed incorrectly', t) # Try the match on a unicode string, and check that it # still succeeds. try: result = obj.search(unicode(s, "latin-1")) if result is None: - print '=== Fails on unicode match', t + print('=== Fails on unicode match', t) except NameError: continue # 1.5.2 except TypeError: @@ -689,7 +689,7 @@ obj=re.compile(unicode(pattern, "latin-1")) result = obj.search(s) if result is None: - print '=== Fails on unicode pattern match', t + print('=== Fails on unicode pattern match', t) # Try the match with the search area limited to the extent # of the match and see if it still succeeds. \B will @@ -701,28 +701,28 @@ obj = re.compile(pattern) result = obj.search(s, result.start(0), result.end(0) + 1) if result is None: - print '=== Failed on range-limited match', t + print('=== Failed on range-limited match', t) # Try the match with IGNORECASE enabled, and check that it # still succeeds. obj = re.compile(pattern, re.IGNORECASE) result = obj.search(s) if result is None: - print '=== Fails on case-insensitive match', t + print('=== Fails on case-insensitive match', t) # Try the match with LOCALE enabled, and check that it # still succeeds. obj = re.compile(pattern, re.LOCALE) result = obj.search(s) if result is None: - print '=== Fails on locale-sensitive match', t + print('=== Fails on locale-sensitive match', t) # Try the match with UNICODE locale enabled, and check # that it still succeeds. obj = re.compile(pattern, re.UNICODE) result = obj.search(s) if result is None: - print '=== Fails on unicode-sensitive match', t + print('=== Fails on unicode-sensitive match', t) def test_main(): run_unittest(ReTests) Modified: python/branches/p3yk/Lib/test/test_rfc822.py ============================================================================== --- python/branches/p3yk/Lib/test/test_rfc822.py (original) +++ python/branches/p3yk/Lib/test/test_rfc822.py Fri Feb 9 06:37:30 2007 @@ -42,7 +42,7 @@ try: mn, ma = results[i][0], results[i][1] except IndexError: - print 'extra parsed address:', repr(n), repr(a) + print('extra parsed address:', repr(n), repr(a)) continue i = i + 1 self.assertEqual(mn, n, @@ -52,7 +52,7 @@ if mn == n and ma == a: pass else: - print 'not found:', repr(n), repr(a) + print('not found:', repr(n), repr(a)) out = m.getdate('date') if out: Modified: python/branches/p3yk/Lib/test/test_rgbimg.py ============================================================================== --- python/branches/p3yk/Lib/test/test_rgbimg.py (original) +++ python/branches/p3yk/Lib/test/test_rgbimg.py Fri Feb 9 06:37:30 2007 @@ -14,7 +14,7 @@ class error(Exception): pass -print 'RGBimg test suite:' +print('RGBimg test suite:') def testimg(rgb_file, raw_file): rgb_file = findfile(rgb_file) @@ -40,11 +40,11 @@ source = findfile(source) target = findfile(target) if verbose: - print "uudecoding", source, "->", target, "..." + print("uudecoding", source, "->", target, "...") uu.decode(source, target) if verbose: - print "testing..." + print("testing...") ttob = rgbimg.ttob(0) if ttob != 0: Modified: python/branches/p3yk/Lib/test/test_runpy.py ============================================================================== --- python/branches/p3yk/Lib/test/test_runpy.py (original) +++ python/branches/p3yk/Lib/test/test_runpy.py Fri Feb 9 06:37:30 2007 @@ -92,22 +92,22 @@ init_fname = "__init__"+os.extsep+"py" test_fname = "runpy_test"+os.extsep+"py" pkg_dir = sub_dir = tempfile.mkdtemp() - if verbose: print " Package tree in:", sub_dir + if verbose: print(" Package tree in:", sub_dir) sys.path.insert(0, pkg_dir) - if verbose: print " Updated sys.path:", sys.path[0] + if verbose: print(" Updated sys.path:", sys.path[0]) for i in range(depth): sub_dir = os.path.join(sub_dir, pkg_name) os.mkdir(sub_dir) - if verbose: print " Next level in:", sub_dir + if verbose: print(" Next level in:", sub_dir) pkg_fname = os.path.join(sub_dir, init_fname) pkg_file = open(pkg_fname, "w") pkg_file.close() - if verbose: print " Created:", pkg_fname + if verbose: print(" Created:", pkg_fname) mod_fname = os.path.join(sub_dir, test_fname) mod_file = open(mod_fname, "w") mod_file.write(source) mod_file.close() - if verbose: print " Created:", mod_fname + if verbose: print(" Created:", mod_fname) mod_name = (pkg_name+".")*depth + "runpy_test" return pkg_dir, mod_fname, mod_name @@ -118,49 +118,49 @@ try: del sys.modules[entry] except KeyError as ex: - if verbose: print ex # Persist with cleaning up - if verbose: print " Removed sys.modules entries" + if verbose: print(ex) # Persist with cleaning up + if verbose: print(" Removed sys.modules entries") del sys.path[0] - if verbose: print " Removed sys.path entry" + if verbose: print(" Removed sys.path entry") for root, dirs, files in os.walk(top, topdown=False): for name in files: try: os.remove(os.path.join(root, name)) except OSError as ex: - if verbose: print ex # Persist with cleaning up + if verbose: print(ex) # Persist with cleaning up for name in dirs: fullname = os.path.join(root, name) try: os.rmdir(fullname) except OSError as ex: - if verbose: print ex # Persist with cleaning up + if verbose: print(ex) # Persist with cleaning up try: os.rmdir(top) - if verbose: print " Removed package tree" + if verbose: print(" Removed package tree") except OSError as ex: - if verbose: print ex # Persist with cleaning up + if verbose: print(ex) # Persist with cleaning up def _check_module(self, depth): pkg_dir, mod_fname, mod_name = ( self._make_pkg("x=1\n", depth)) try: - if verbose: print "Running from source:", mod_name + if verbose: print("Running from source:", mod_name) d1 = run_module(mod_name) # Read from source self.failUnless(d1["x"] == 1) del d1 # Ensure __loader__ entry doesn't keep file open __import__(mod_name) os.remove(mod_fname) - if verbose: print "Running from compiled:", mod_name + if verbose: print("Running from compiled:", mod_name) d2 = run_module(mod_name) # Read from bytecode self.failUnless(d2["x"] == 1) del d2 # Ensure __loader__ entry doesn't keep file open finally: self._del_pkg(pkg_dir, depth, mod_name) - if verbose: print "Module executed successfully" + if verbose: print("Module executed successfully") def test_run_module(self): for depth in range(4): - if verbose: print "Testing package depth:", depth + if verbose: print("Testing package depth:", depth) self._check_module(depth) Modified: python/branches/p3yk/Lib/test/test_sax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sax.py (original) +++ python/branches/p3yk/Lib/test/test_sax.py Fri Feb 9 06:37:30 2007 @@ -27,7 +27,7 @@ tests = tests + 1 if outcome: if verbose: - print "Passed", name + print("Passed", name) else: failures.append(name) @@ -745,7 +745,7 @@ del items if verbose: - print "%d tests, %d failures" % (tests, len(failures)) + print("%d tests, %d failures" % (tests, len(failures))) if failures: raise TestFailed("%d of %d tests failed: %s" % (len(failures), tests, ", ".join(failures))) Modified: python/branches/p3yk/Lib/test/test_scope.py ============================================================================== --- python/branches/p3yk/Lib/test/test_scope.py (original) +++ python/branches/p3yk/Lib/test/test_scope.py Fri Feb 9 06:37:30 2007 @@ -269,7 +269,7 @@ def testUnboundLocal(self): def errorInOuter(): - print y + print(y) def inner(): return y y = 1 @@ -530,18 +530,18 @@ def testListCompLocalVars(self): try: - print bad + print(bad) except NameError: pass else: - print "bad should not be defined" + print("bad should not be defined") def x(): [bad for s in 'a b' for bad in s.split()] x() try: - print bad + print(bad) except NameError: pass Modified: python/branches/p3yk/Lib/test/test_select.py ============================================================================== --- python/branches/p3yk/Lib/test/test_select.py (original) +++ python/branches/p3yk/Lib/test/test_select.py Fri Feb 9 06:37:30 2007 @@ -9,7 +9,7 @@ except TypeError: pass else: - print 'expected TypeError exception not raised' + print('expected TypeError exception not raised') class Nope: pass @@ -23,47 +23,47 @@ except TypeError: pass else: - print 'expected TypeError exception not raised' + print('expected TypeError exception not raised') try: rfd, wfd, xfd = select.select([Almost()], [], []) except TypeError: pass else: - print 'expected TypeError exception not raised' + print('expected TypeError exception not raised') try: rfd, wfd, xfd = select.select([], [], [], 'not a number') except TypeError: pass else: - print 'expected TypeError exception not raised' + print('expected TypeError exception not raised') def test(): import sys if sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'): if verbose: - print "Can't test select easily on", sys.platform + print("Can't test select easily on", sys.platform) return cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' p = os.popen(cmd, 'r') for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: if verbose: - print 'timeout =', tout + print('timeout =', tout) rfd, wfd, xfd = select.select([p], [], [], tout) if (rfd, wfd, xfd) == ([], [], []): continue if (rfd, wfd, xfd) == ([p], [], []): line = p.readline() if verbose: - print repr(line) + print(repr(line)) if not line: if verbose: - print 'EOF' + print('EOF') break continue - print 'Unexpected return values from select():', rfd, wfd, xfd + print('Unexpected return values from select():', rfd, wfd, xfd) p.close() reap_children() Modified: python/branches/p3yk/Lib/test/test_signal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_signal.py (original) +++ python/branches/p3yk/Lib/test/test_signal.py Fri Feb 9 06:37:30 2007 @@ -15,7 +15,7 @@ pid = os.getpid() if verbose: - print "test runner's pid is", pid + print("test runner's pid is", pid) # Shell script that will send us asynchronous signals script = """ @@ -36,7 +36,7 @@ global a_called a_called = True if verbose: - print "handlerA invoked", args + print("handlerA invoked", args) class HandlerBCalled(Exception): pass @@ -45,7 +45,7 @@ global b_called b_called = True if verbose: - print "handlerB invoked", args + print("handlerB invoked", args) raise HandlerBCalled, args # Set up a child to send signals to us (the parent) after waiting long @@ -69,10 +69,10 @@ # time for the normal sequence of events to occur. This is # just a stop-gap to try to prevent the test from hanging. time.sleep(MAX_DURATION + 5) - print >> sys.__stdout__, ' child should not have to kill parent' + print(' child should not have to kill parent', file=sys.__stdout__) for signame in "SIGHUP", "SIGUSR1", "SIGUSR2", "SIGALRM": os.kill(pid, getattr(signal, signame)) - print >> sys.__stdout__, " child sent", signame, "to", pid + print(" child sent", signame, "to", pid, file=sys.__stdout__) time.sleep(1) finally: os._exit(0) @@ -126,27 +126,27 @@ # KeyboardInterrupt, finally getting us out of the loop. os.system(script) try: - print "starting pause() loop..." + print("starting pause() loop...") while 1: try: if verbose: - print "call pause()..." + print("call pause()...") signal.pause() if verbose: - print "pause() returned" + print("pause() returned") except HandlerBCalled: if verbose: - print "HandlerBCalled exception caught" + print("HandlerBCalled exception caught") except KeyboardInterrupt: if verbose: - print "KeyboardInterrupt (the alarm() went off)" + print("KeyboardInterrupt (the alarm() went off)") if not a_called: - print 'HandlerA not called' + print('HandlerA not called') if not b_called: - print 'HandlerB not called' + print('HandlerB not called') finally: # Forcibly kill the child we created to ping us if there was a test error. Modified: python/branches/p3yk/Lib/test/test_site.py ============================================================================== --- python/branches/p3yk/Lib/test/test_site.py (original) +++ python/branches/p3yk/Lib/test/test_site.py Fri Feb 9 06:37:30 2007 @@ -119,11 +119,11 @@ """ FILE = open(self.file_path, 'w') try: - print>>FILE, "#import @bad module name" - print>>FILE, "\n" - print>>FILE, "import %s" % self.imported - print>>FILE, self.good_dirname - print>>FILE, self.bad_dirname + print("#import @bad module name", file=FILE) + print("\n", file=FILE) + print("import %s" % self.imported, file=FILE) + print(self.good_dirname, file=FILE) + print(self.bad_dirname, file=FILE) finally: FILE.close() os.mkdir(self.good_dir_path) Modified: python/branches/p3yk/Lib/test/test_socket_ssl.py ============================================================================== --- python/branches/p3yk/Lib/test/test_socket_ssl.py (original) +++ python/branches/p3yk/Lib/test/test_socket_ssl.py Fri Feb 9 06:37:30 2007 @@ -16,7 +16,7 @@ import urllib if test_support.verbose: - print "test_basic ..." + print("test_basic ...") socket.RAND_status() try: @@ -24,7 +24,7 @@ except TypeError: pass else: - print "didn't raise TypeError" + print("didn't raise TypeError") socket.RAND_add("this is a random string", 75.0) f = urllib.urlopen('https://sf.net') @@ -35,14 +35,14 @@ test_support.requires('network') def error_msg(extra_msg): - print >> sys.stderr, """\ + print("""\ WARNING: an attempt to connect to %r %s, in test_timeout. That may be legitimate, but is not the outcome we hoped for. If this message is seen often, test_timeout should be changed to - use a more reliable address.""" % (ADDR, extra_msg) + use a more reliable address.""" % (ADDR, extra_msg), file=sys.stderr) if test_support.verbose: - print "test_timeout ..." + print("test_timeout ...") # A service which issues a welcome banner (without need to write # anything). @@ -73,7 +73,7 @@ def test_rude_shutdown(): if test_support.verbose: - print "test_rude_shutdown ..." + print("test_rude_shutdown ...") try: import threading Modified: python/branches/p3yk/Lib/test/test_socketserver.py ============================================================================== --- python/branches/p3yk/Lib/test/test_socketserver.py (original) +++ python/branches/p3yk/Lib/test/test_socketserver.py Fri Feb 9 06:37:30 2007 @@ -77,16 +77,16 @@ def run(self): class svrcls(MyMixinServer, self.__svrcls): pass - if verbose: print "thread: creating server" + if verbose: print("thread: creating server") svr = svrcls(self.__addr, self.__hdlrcls) # pull the address out of the server in case it changed # this can happen if another process is using the port addr = getattr(svr, 'server_address') if addr: self.__addr = addr - if verbose: print "thread: serving three times" + if verbose: print("thread: serving three times") svr.serve_a_few() - if verbose: print "thread: done" + if verbose: print("thread: done") seed = 0 def pickport(): @@ -129,19 +129,19 @@ for svrcls in servers: addr = pickaddr(proto) if verbose: - print "ADDR =", addr - print "CLASS =", svrcls + print("ADDR =", addr) + print("CLASS =", svrcls) t = ServerThread(addr, svrcls, hdlrcls) - if verbose: print "server created" + if verbose: print("server created") t.start() - if verbose: print "server running" + if verbose: print("server running") for i in range(NREQ): time.sleep(DELAY) - if verbose: print "test client", i + if verbose: print("test client", i) testfunc(proto, addr) - if verbose: print "waiting for server" + if verbose: print("waiting for server") t.join() - if verbose: print "done" + if verbose: print("done") class ForgivingTCPServer(TCPServer): # prevent errors if another process is using the port we want @@ -159,8 +159,7 @@ (err, msg) = e if err != errno.EADDRINUSE: raise - print >>sys.__stderr__, \ - ' WARNING: failed to listen on port %d, trying another' % port + print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__) tcpservers = [ForgivingTCPServer, ThreadingTCPServer] if hasattr(os, 'fork') and os.name not in ('os2',): Modified: python/branches/p3yk/Lib/test/test_softspace.py ============================================================================== --- python/branches/p3yk/Lib/test/test_softspace.py (original) +++ python/branches/p3yk/Lib/test/test_softspace.py Fri Feb 9 06:37:30 2007 @@ -5,10 +5,10 @@ f = StringIO.StringIO() class C: def __str__(self): - print >> f, 'a' + print('a', file=f) return 'b' -print >> f, C(), 'c ', 'd\t', 'e' -print >> f, 'f', 'g' +print(C(), 'c ', 'd\t', 'e', file=f) +print('f', 'g', file=f) # In 2.2 & earlier, this printed ' a\nbc d\te\nf g\n' test_support.vereq(f.getvalue(), 'a\nb c d\te\nf g\n') Modified: python/branches/p3yk/Lib/test/test_sort.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sort.py (original) +++ python/branches/p3yk/Lib/test/test_sort.py Fri Feb 9 06:37:30 2007 @@ -10,7 +10,7 @@ global nerrors if verbose: - print " checking", tag + print(" checking", tag) orig = raw[:] # save input in case of error if compare: @@ -19,22 +19,22 @@ raw.sort() if len(expected) != len(raw): - print "error in", tag - print "length mismatch;", len(expected), len(raw) - print expected - print orig - print raw + print("error in", tag) + print("length mismatch;", len(expected), len(raw)) + print(expected) + print(orig) + print(raw) nerrors += 1 return for i, good in enumerate(expected): maybe = raw[i] if good is not maybe: - print "error in", tag - print "out of order at index", i, good, maybe - print expected - print orig - print raw + print("error in", tag) + print("out of order at index", i, good, maybe) + print(expected) + print(orig) + print(raw) nerrors += 1 return @@ -56,7 +56,7 @@ def __lt__(self, other): if Complains.maybe_complain and random.random() < 0.001: if verbose: - print " complaining at", self, other + print(" complaining at", self, other) raise RuntimeError return self.i < other.i @@ -77,7 +77,7 @@ for n in sizes: x = range(n) if verbose: - print "Testing size", n + print("Testing size", n) s = x[:] check("identity", x, s) @@ -96,8 +96,8 @@ check("reversed via function", y, s, lambda a, b: cmp(b, a)) if verbose: - print " Checking against an insane comparison function." - print " If the implementation isn't careful, this may segfault." + print(" Checking against an insane comparison function.") + print(" If the implementation isn't careful, this may segfault.") s = x[:] s.sort(lambda a, b: int(random.random() * 3) - 1) check("an insane function left some permutation", x, s) @@ -285,7 +285,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) Modified: python/branches/p3yk/Lib/test/test_strftime.py ============================================================================== --- python/branches/p3yk/Lib/test/test_strftime.py (original) +++ python/branches/p3yk/Lib/test/test_strftime.py Fri Feb 9 06:37:30 2007 @@ -40,7 +40,7 @@ def strftest(now): if verbose: - print "strftime test for", time.ctime(now) + print("strftime test for", time.ctime(now)) nowsecs = str(int(now))[:-1] gmt = time.gmtime(now) now = time.localtime(now) @@ -113,42 +113,42 @@ ) if verbose: - print "Strftime test, platform: %s, Python version: %s" % \ - (sys.platform, sys.version.split()[0]) + print("Strftime test, platform: %s, Python version: %s" % \ + (sys.platform, sys.version.split()[0])) for e in expectations: try: result = time.strftime(e[0], now) except ValueError as error: - print "Standard '%s' format gave error:" % e[0], error + print("Standard '%s' format gave error:" % e[0], error) continue if re.match(escapestr(e[1], ampm), result): continue if not result or result[0] == '%': - print "Does not support standard '%s' format (%s)" % (e[0], e[2]) + print("Does not support standard '%s' format (%s)" % (e[0], e[2])) else: - print "Conflict for %s (%s):" % (e[0], e[2]) - print " Expected %s, but got %s" % (e[1], result) + print("Conflict for %s (%s):" % (e[0], e[2])) + print(" Expected %s, but got %s" % (e[1], result)) for e in nonstandard_expectations: try: result = time.strftime(e[0], now) except ValueError as result: if verbose: - print "Error for nonstandard '%s' format (%s): %s" % \ - (e[0], e[2], str(result)) + print("Error for nonstandard '%s' format (%s): %s" % \ + (e[0], e[2], str(result))) continue if re.match(escapestr(e[1], ampm), result): if verbose: - print "Supports nonstandard '%s' format (%s)" % (e[0], e[2]) + print("Supports nonstandard '%s' format (%s)" % (e[0], e[2])) elif not result or result[0] == '%': if verbose: - print "Does not appear to support '%s' format (%s)" % (e[0], - e[2]) + print("Does not appear to support '%s' format (%s)" % (e[0], + e[2])) else: if verbose: - print "Conflict for nonstandard '%s' format (%s):" % (e[0], - e[2]) - print " Expected %s, but got %s" % (e[1], result) + print("Conflict for nonstandard '%s' format (%s):" % (e[0], + e[2])) + print(" Expected %s, but got %s" % (e[1], result)) def fixasctime(s): if s[8] == ' ': Modified: python/branches/p3yk/Lib/test/test_struct.py ============================================================================== --- python/branches/p3yk/Lib/test/test_struct.py (original) +++ python/branches/p3yk/Lib/test/test_struct.py Fri Feb 9 06:37:30 2007 @@ -114,7 +114,7 @@ for format in ('xcbhilfdt', 'xcBHILfdt'): format = prefix + format if verbose: - print "trying:", format + print("trying:", format) s = struct.pack(format, c, b, h, i, l, f, d, t) cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s) if (cp != c or bp != b or hp != h or ip != i or lp != l or @@ -169,7 +169,7 @@ for fmt, arg, big, lil, asy in tests: if verbose: - print "%r %r %r %r" % (fmt, arg, big, lil) + print("%r %r %r %r" % (fmt, arg, big, lil)) for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil), ('='+fmt, ISBIGENDIAN and big or lil)]: res = struct.pack(xfmt, arg) @@ -195,7 +195,7 @@ has_native_qQ = 0 if verbose: - print "Platform has native q/Q?", has_native_qQ and "Yes." or "No." + print("Platform has native q/Q?", has_native_qQ and "Yes." or "No.") any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless @@ -258,7 +258,7 @@ unpack=struct.unpack, unhexlify=binascii.unhexlify): if verbose: - print "trying std", self.formatpair, "on", x, "==", hex(x) + print("trying std", self.formatpair, "on", x, "==", hex(x)) # Try signed. code = self.signed_code @@ -313,7 +313,7 @@ # x is out of range -- verify pack realizes that. if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK: if verbose: - print "Skipping buggy range check for code", code + print("Skipping buggy range check for code", code) else: deprecated_err(pack, ">" + code, x) deprecated_err(pack, "<" + code, x) @@ -368,7 +368,7 @@ # x is out of range -- verify pack realizes that. if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK: if verbose: - print "Skipping buggy range check for code", code + print("Skipping buggy range check for code", code) else: deprecated_err(pack, ">" + code, x) deprecated_err(pack, "<" + code, x) @@ -627,13 +627,13 @@ falseFormat = prefix + 't' * len(false) if verbose: - print 'trying bool pack/unpack on', false, 'using format', falseFormat + print('trying bool pack/unpack on', false, 'using format', falseFormat) packedFalse = struct.pack(falseFormat, *false) unpackedFalse = struct.unpack(falseFormat, packedFalse) trueFormat = prefix + 't' * len(true) if verbose: - print 'trying bool pack/unpack on', true, 'using format', trueFormat + print('trying bool pack/unpack on', true, 'using format', trueFormat) packedTrue = struct.pack(trueFormat, *true) unpackedTrue = struct.unpack(trueFormat, packedTrue) @@ -650,7 +650,7 @@ raise TestFailed('%r did not unpack as false' % t) if prefix and verbose: - print 'trying size of bool with format %r' % (prefix+'t') + print('trying size of bool with format %r' % (prefix+'t')) packed = struct.pack(prefix+'t', 1) if len(packed) != struct.calcsize(prefix+'t'): @@ -659,7 +659,7 @@ if len(packed) != 1 and prefix: raise TestFailed('encoded bool is not one byte: %r' % packed) elif not prefix and verbose: - print 'size of bool in native format is %i' % (len(packed)) + print('size of bool in native format is %i' % (len(packed))) for c in '\x01\x7f\xff\x0f\xf0': if struct.unpack('>t', c)[0] is not True: Modified: python/branches/p3yk/Lib/test/test_sundry.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sundry.py (original) +++ python/branches/p3yk/Lib/test/test_sundry.py Fri Feb 9 06:37:30 2007 @@ -68,7 +68,7 @@ import tty # not available on Windows except ImportError: if verbose: - print "skipping tty" + print("skipping tty") # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it # can screw up all sorts of things (esp. if it prints!). Modified: python/branches/p3yk/Lib/test/test_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_support.py (original) +++ python/branches/p3yk/Lib/test/test_support.py Fri Feb 9 06:37:30 2007 @@ -106,8 +106,7 @@ (err, msg) = e if err != errno.EADDRINUSE: raise - print >>sys.__stderr__, \ - ' WARNING: failed to listen on port %d, trying another' % port + print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__) raise TestFailed, 'unable to find port to listen on' FUZZ = 1e-6 @@ -178,10 +177,9 @@ except UnicodeEncodeError: pass else: - print \ - 'WARNING: The filename %r CAN be encoded by the filesystem. ' \ + print('WARNING: The filename %r CAN be encoded by the filesystem. ' \ 'Unicode filename tests may not be effective' \ - % TESTFN_UNICODE_UNENCODEABLE + % TESTFN_UNICODE_UNENCODEABLE) # Make sure we can write to TESTFN, try in /tmp if we can't fp = None @@ -194,8 +192,8 @@ TESTFN = TMP_TESTFN del TMP_TESTFN except IOError: - print ('WARNING: tests will fail, unable to write to: %s or %s' % - (TESTFN, TMP_TESTFN)) + print(('WARNING: tests will fail, unable to write to: %s or %s' % + (TESTFN, TMP_TESTFN))) if fp is not None: fp.close() unlink(TESTFN) @@ -267,7 +265,7 @@ return open(fn) requires('urlfetch') - print >> get_original_stdout(), '\tfetching %s ...' % url + print('\tfetching %s ...' % url, file=get_original_stdout()) fn, _ = urllib.urlretrieve(url, filename) return open(fn) @@ -514,7 +512,7 @@ finally: sys.stdout = save_stdout if verbose: - print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t) + print('doctest (%s) ... %d tests with zero failures' % (module.__name__, t)) return f, t #======================================================================= Modified: python/branches/p3yk/Lib/test/test_thread.py ============================================================================== --- python/branches/p3yk/Lib/test/test_thread.py (original) +++ python/branches/p3yk/Lib/test/test_thread.py Fri Feb 9 06:37:30 2007 @@ -21,10 +21,10 @@ delay = random.random() * numtasks rmutex.release() if verbose: - print 'task', ident, 'will run for', round(delay, 1), 'sec' + print('task', ident, 'will run for', round(delay, 1), 'sec') time.sleep(delay) if verbose: - print 'task', ident, 'done' + print('task', ident, 'done') mutex.acquire() running = running - 1 if running == 0: @@ -37,7 +37,7 @@ mutex.acquire() next_ident = next_ident + 1 if verbose: - print 'creating task', next_ident + print('creating task', next_ident) thread.start_new_thread(task, (next_ident,)) running = running + 1 mutex.release() @@ -45,9 +45,9 @@ for i in range(numtasks): newtask() -print 'waiting for all tasks to complete' +print('waiting for all tasks to complete') done.acquire() -print 'all tasks done' +print('all tasks done') class barrier: def __init__(self, n): @@ -89,13 +89,13 @@ delay = random.random() * numtasks rmutex.release() if verbose: - print 'task', ident, 'will run for', round(delay, 1), 'sec' + print('task', ident, 'will run for', round(delay, 1), 'sec') time.sleep(delay) if verbose: - print 'task', ident, 'entering barrier', i + print('task', ident, 'entering barrier', i) bar.enter() if verbose: - print 'task', ident, 'leaving barrier', i + print('task', ident, 'leaving barrier', i) mutex.acquire() running -= 1 # Must release mutex before releasing done, else the main thread can @@ -106,7 +106,7 @@ if finished: done.release() -print '\n*** Barrier Test ***' +print('\n*** Barrier Test ***') if done.acquire(0): raise ValueError, "'done' should have remained acquired" bar = barrier(numtasks) @@ -114,10 +114,10 @@ for i in range(numtasks): thread.start_new_thread(task2, (i,)) done.acquire() -print 'all tasks done' +print('all tasks done') # not all platforms support changing thread stack size -print '\n*** Changing thread stack size ***' +print('\n*** Changing thread stack size ***') if thread.stack_size() != 0: raise ValueError, "initial stack_size not 0" @@ -132,10 +132,10 @@ try: thread.stack_size(4096) except ValueError: - print 'caught expected ValueError setting stack_size(4096)' + print('caught expected ValueError setting stack_size(4096)') except thread.error: tss_supported = 0 - print 'platform does not support changing thread stack size' + print('platform does not support changing thread stack size') if tss_supported: failed = lambda s, e: s != e @@ -144,17 +144,17 @@ thread.stack_size(tss) if failed(thread.stack_size(), tss): raise ValueError, fail_msg % tss - print 'successfully set stack_size(%d)' % tss + print('successfully set stack_size(%d)' % tss) for tss in (262144, 0x100000): - print 'trying stack_size = %d' % tss + print('trying stack_size = %d' % tss) next_ident = 0 for i in range(numtasks): newtask() - print 'waiting for all tasks to complete' + print('waiting for all tasks to complete') done.acquire() - print 'all tasks done' + print('all tasks done') # reset stack size to default thread.stack_size(0) Modified: python/branches/p3yk/Lib/test/test_threaded_import.py ============================================================================== --- python/branches/p3yk/Lib/test/test_threaded_import.py (original) +++ python/branches/p3yk/Lib/test/test_threaded_import.py Fri Feb 9 06:37:30 2007 @@ -28,14 +28,14 @@ def test_import_hangers(): import sys if verbose: - print "testing import hangers ...", + print("testing import hangers ...", end=' ') import test.threaded_import_hangers try: if test.threaded_import_hangers.errors: raise TestFailed(test.threaded_import_hangers.errors) elif verbose: - print "OK." + print("OK.") finally: # In case this test is run again, make sure the helper module # gets loaded from scratch again. @@ -61,12 +61,12 @@ done.acquire() for N in (20, 50) * 3: if verbose: - print "Trying", N, "threads ...", + print("Trying", N, "threads ...", end=' ') for i in range(N): thread.start_new_thread(task, ()) done.acquire() if verbose: - print "OK." + print("OK.") done.release() test_import_hangers() Modified: python/branches/p3yk/Lib/test/test_threadedtempfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_threadedtempfile.py (original) +++ python/branches/p3yk/Lib/test/test_threadedtempfile.py Fri Feb 9 06:37:30 2007 @@ -50,26 +50,26 @@ threads = [] thread_info = threading_setup() - print "Creating" + print("Creating") for i in range(NUM_THREADS): t = TempFileGreedy() threads.append(t) t.start() - print "Starting" + print("Starting") startEvent.set() - print "Reaping" + print("Reaping") ok = errors = 0 for t in threads: t.join() ok += t.ok_count errors += t.error_count if t.error_count: - print '%s errors:\n%s' % (t.getName(), t.errors.getvalue()) + print('%s errors:\n%s' % (t.getName(), t.errors.getvalue())) msg = "Done: errors %d ok %d" % (errors, ok) - print msg + print(msg) if errors: raise TestFailed(msg) Modified: python/branches/p3yk/Lib/test/test_threading.py ============================================================================== --- python/branches/p3yk/Lib/test/test_threading.py (original) +++ python/branches/p3yk/Lib/test/test_threading.py Fri Feb 9 06:37:30 2007 @@ -30,27 +30,27 @@ def run(self): delay = random.random() * 2 if verbose: - print 'task', self.getName(), 'will run for', delay, 'sec' + print('task', self.getName(), 'will run for', delay, 'sec') self.sema.acquire() self.mutex.acquire() self.nrunning.inc() if verbose: - print self.nrunning.get(), 'tasks are running' + print(self.nrunning.get(), 'tasks are running') self.testcase.assert_(self.nrunning.get() <= 3) self.mutex.release() time.sleep(delay) if verbose: - print 'task', self.getName(), 'done' + print('task', self.getName(), 'done') self.mutex.acquire() self.nrunning.dec() self.testcase.assert_(self.nrunning.get() >= 0) if verbose: - print self.getName(), 'is finished.', self.nrunning.get(), \ - 'tasks are running' + print(self.getName(), 'is finished.', self.nrunning.get(), \ + 'tasks are running') self.mutex.release() self.sema.release() @@ -77,23 +77,23 @@ t.start() if verbose: - print 'waiting for all tasks to complete' + print('waiting for all tasks to complete') for t in threads: t.join(NUMTASKS) self.assert_(not t.isAlive()) if verbose: - print 'all tasks done' + print('all tasks done') self.assertEqual(numrunning.get(), 0) # run with a small(ish) thread stack size (256kB) def test_various_ops_small_stack(self): if verbose: - print 'with 256kB thread stack size...' + print('with 256kB thread stack size...') try: threading.stack_size(262144) except thread.error: if verbose: - print 'platform does not support changing thread stack size' + print('platform does not support changing thread stack size') return self.test_various_ops() threading.stack_size(0) @@ -101,12 +101,12 @@ # run with a large thread stack size (1MB) def test_various_ops_large_stack(self): if verbose: - print 'with 1MB thread stack size...' + print('with 1MB thread stack size...') try: threading.stack_size(0x100000) except thread.error: if verbose: - print 'platform does not support changing thread stack size' + print('platform does not support changing thread stack size') return self.test_various_ops() threading.stack_size(0) @@ -138,7 +138,7 @@ import ctypes except ImportError: if verbose: - print "test_PyThreadState_SetAsyncExc can't import ctypes" + print("test_PyThreadState_SetAsyncExc can't import ctypes") return # can't do anything set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc @@ -172,31 +172,31 @@ t.setDaemon(True) # so if this fails, we don't hang Python at shutdown t.start() if verbose: - print " started worker thread" + print(" started worker thread") # Try a thread id that doesn't make sense. if verbose: - print " trying nonsensical thread id" + print(" trying nonsensical thread id") result = set_async_exc(ctypes.c_long(-1), exception) self.assertEqual(result, 0) # no thread states modified # Now raise an exception in the worker thread. if verbose: - print " waiting for worker thread to get started" + print(" waiting for worker thread to get started") worker_started.wait() if verbose: - print " verifying worker hasn't exited" + print(" verifying worker hasn't exited") self.assert_(not t.finished) if verbose: - print " attempting to raise asynch exception in worker" + print(" attempting to raise asynch exception in worker") result = set_async_exc(ctypes.c_long(t.id), exception) self.assertEqual(result, 1) # one thread state modified if verbose: - print " waiting for worker to say it caught the exception" + print(" waiting for worker to say it caught the exception") worker_saw_exception.wait(timeout=10) self.assert_(t.finished) if verbose: - print " all OK -- joining worker" + print(" all OK -- joining worker") if t.finished: t.join() # else the thread is still running, and we have no way to kill it Modified: python/branches/p3yk/Lib/test/test_tokenize.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tokenize.py (original) +++ python/branches/p3yk/Lib/test/test_tokenize.py Fri Feb 9 06:37:30 2007 @@ -118,12 +118,12 @@ if type == ENDMARKER: break type = tok_name[type] - print "%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals() + print("%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals()) def roundtrip(s): f = StringIO(s) source = untokenize(generate_tokens(f.readline)) - print source, + print(source, end=' ') # This is an example from the docs, set up as a doctest. def decistmt(s): @@ -165,7 +165,7 @@ def test_main(): if verbose: - print 'starting...' + print('starting...') next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL @@ -191,7 +191,7 @@ # Print still working message since this test can be really slow if next_time <= time.time(): next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - print >>sys.__stdout__, ' test_main still working, be patient...' + print(' test_main still working, be patient...', file=sys.__stdout__) sys.__stdout__.flush() test_roundtrip(f) @@ -217,7 +217,7 @@ run_doctest(test_tokenize, verbose) if verbose: - print 'finished' + print('finished') def test_rarrow(): """ Modified: python/branches/p3yk/Lib/test/test_trace.py ============================================================================== --- python/branches/p3yk/Lib/test/test_trace.py (original) +++ python/branches/p3yk/Lib/test/test_trace.py Fri Feb 9 06:37:30 2007 @@ -309,7 +309,7 @@ def test_trash_stack(self): def f(): for i in range(5): - print i # line tracing will raise an exception at this line + print(i) # line tracing will raise an exception at this line def g(frame, why, extra): if (why == 'line' and Modified: python/branches/p3yk/Lib/test/test_traceback.py ============================================================================== --- python/branches/p3yk/Lib/test/test_traceback.py (original) +++ python/branches/p3yk/Lib/test/test_traceback.py Fri Feb 9 06:37:30 2007 @@ -60,9 +60,9 @@ try: sys.path.insert(0, testdir) testfile = os.path.join(testdir, 'test_bug737473.py') - print >> open(testfile, 'w'), """ + print(""" def test(): - raise ValueError""" + raise ValueError""", file=open(testfile, 'w')) if 'test_bug737473' in sys.modules: del sys.modules['test_bug737473'] @@ -82,9 +82,9 @@ # three seconds are needed for this test to pass reliably :-( time.sleep(4) - print >> open(testfile, 'w'), """ + print(""" def test(): - raise NotImplementedError""" + raise NotImplementedError""", file=open(testfile, 'w')) reload(test_bug737473) try: test_bug737473.test() Modified: python/branches/p3yk/Lib/test/test_unicode.py ============================================================================== --- python/branches/p3yk/Lib/test/test_unicode.py (original) +++ python/branches/p3yk/Lib/test/test_unicode.py Fri Feb 9 06:37:30 2007 @@ -732,15 +732,15 @@ pass out = BitBucket() - print >>out, u'abc' - print >>out, u'abc', u'def' - print >>out, u'abc', 'def' - print >>out, 'abc', u'def' - print >>out, u'abc\n' - print >>out, u'abc\n', - print >>out, u'abc\n', - print >>out, u'def\n' - print >>out, u'def\n' + print(u'abc', file=out) + print(u'abc', u'def', file=out) + print(u'abc', 'def', file=out) + print('abc', u'def', file=out) + print(u'abc\n', file=out) + print(u'abc\n', end=' ', file=out) + print(u'abc\n', end=' ', file=out) + print(u'def\n', file=out) + print(u'def\n', file=out) def test_ucs4(self): if sys.maxunicode == 0xFFFF: Modified: python/branches/p3yk/Lib/test/test_userdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_userdict.py (original) +++ python/branches/p3yk/Lib/test/test_userdict.py Fri Feb 9 06:37:30 2007 @@ -79,7 +79,7 @@ self.assertEqual(u2b, u2c) class MyUserDict(UserDict.UserDict): - def display(self): print self + def display(self): print(self) m2 = MyUserDict(u2) m2a = m2.copy() Modified: python/branches/p3yk/Lib/test/test_uuid.py ============================================================================== --- python/branches/p3yk/Lib/test/test_uuid.py (original) +++ python/branches/p3yk/Lib/test/test_uuid.py Fri Feb 9 06:37:30 2007 @@ -307,9 +307,8 @@ def test_ifconfig_getnode(self): import sys - print >>sys.__stdout__, \ -""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms. - It is disabled until the code and/or test can be fixed properly.""" + print(""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms. + It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__) return import os @@ -336,9 +335,8 @@ def test_unixdll_getnode(self): import sys - print >>sys.__stdout__, \ -""" WARNING: uuid._unixdll_getnode is unreliable on many platforms. - It is disabled until the code and/or test can be fixed properly.""" + print(""" WARNING: uuid._unixdll_getnode is unreliable on many platforms. + It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__) return import os @@ -352,9 +350,8 @@ def test_getnode(self): import sys - print >>sys.__stdout__, \ -""" WARNING: uuid.getnode is unreliable on many platforms. - It is disabled until the code and/or test can be fixed properly.""" + print(""" WARNING: uuid.getnode is unreliable on many platforms. + It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__) return node1 = uuid.getnode() Modified: python/branches/p3yk/Lib/test/test_winreg.py ============================================================================== --- python/branches/p3yk/Lib/test/test_winreg.py (original) +++ python/branches/p3yk/Lib/test/test_winreg.py Fri Feb 9 06:37:30 2007 @@ -133,7 +133,7 @@ # Test on my local machine. TestAll(HKEY_CURRENT_USER) -print "Local registry tests worked" +print("Local registry tests worked") try: remote_name = sys.argv[sys.argv.index("--remote")+1] except (IndexError, ValueError): @@ -143,14 +143,14 @@ try: remote_key = ConnectRegistry(remote_name, HKEY_CURRENT_USER) except EnvironmentError as exc: - print "Could not connect to the remote machine -", exc.strerror + print("Could not connect to the remote machine -", exc.strerror) remote_key = None if remote_key is not None: TestAll(remote_key) - print "Remote registry tests worked" + print("Remote registry tests worked") else: - print "Remote registry calls can be tested using", - print "'test_winreg.py --remote \\\\machine_name'" + print("Remote registry calls can be tested using", end=' ') + print("'test_winreg.py --remote \\\\machine_name'") # perform minimal ConnectRegistry test which just invokes it h = ConnectRegistry(None, HKEY_LOCAL_MACHINE) h.Close() Modified: python/branches/p3yk/Lib/test/test_xml_etree.py ============================================================================== --- python/branches/p3yk/Lib/test/test_xml_etree.py (original) +++ python/branches/p3yk/Lib/test/test_xml_etree.py Fri Feb 9 06:37:30 2007 @@ -37,7 +37,7 @@ def check_method(method): if not callable(method): - print method, "not callable" + print(method, "not callable") def serialize(ET, elem, encoding=None): import StringIO Modified: python/branches/p3yk/Lib/test/test_xml_etree_c.py ============================================================================== --- python/branches/p3yk/Lib/test/test_xml_etree_c.py (original) +++ python/branches/p3yk/Lib/test/test_xml_etree_c.py Fri Feb 9 06:37:30 2007 @@ -35,7 +35,7 @@ def check_method(method): if not callable(method): - print method, "not callable" + print(method, "not callable") def serialize(ET, elem, encoding=None): import StringIO Modified: python/branches/p3yk/Lib/test/test_zipfile64.py ============================================================================== --- python/branches/p3yk/Lib/test/test_zipfile64.py (original) +++ python/branches/p3yk/Lib/test/test_zipfile64.py Fri Feb 9 06:37:30 2007 @@ -57,9 +57,9 @@ # Print still working message since this test can be really slow if next_time <= time.time(): next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - print >>sys.__stdout__, ( + print(( ' zipTest still writing %d of %d, be patient...' % - (num, filecount)) + (num, filecount)), file=sys.__stdout__) sys.__stdout__.flush() zipfp.close() @@ -70,9 +70,9 @@ # Print still working message since this test can be really slow if next_time <= time.time(): next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL - print >>sys.__stdout__, ( + print(( ' zipTest still reading %d of %d, be patient...' % - (num, filecount)) + (num, filecount)), file=sys.__stdout__) sys.__stdout__.flush() zipfp.close() Modified: python/branches/p3yk/Lib/test/time_hashlib.py ============================================================================== --- python/branches/p3yk/Lib/test/time_hashlib.py (original) +++ python/branches/p3yk/Lib/test/time_hashlib.py Fri Feb 9 06:37:30 2007 @@ -18,7 +18,7 @@ x = localCF(longStr).digest() end = time.time() - print ('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name + print(('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name) def test_create(): start = time.time() @@ -26,7 +26,7 @@ d = creatorFunc() end = time.time() - print ('%2.2f' % (end-start)), "seconds", '[20000 creations]' + print(('%2.2f' % (end-start)), "seconds", '[20000 creations]') def test_zero(): start = time.time() @@ -34,7 +34,7 @@ x = creatorFunc().digest() end = time.time() - print ('%2.2f' % (end-start)), "seconds", '[20000 "" digests]' + print(('%2.2f' % (end-start)), "seconds", '[20000 "" digests]') @@ -46,33 +46,33 @@ if hName in ('_md5', '_sha'): exec('import '+hName) exec('creatorFunc = '+hName+'.new') - print "testing speed of old", hName, "legacy interface" + print("testing speed of old", hName, "legacy interface") elif hName == '_hashlib' and len(sys.argv) > 3: import _hashlib exec('creatorFunc = _hashlib.%s' % sys.argv[2]) - print "testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2]) + print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])) elif hName == '_hashlib' and len(sys.argv) == 3: import _hashlib exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2]) - print "testing speed of _hashlib.new(%r)" % sys.argv[2] + print("testing speed of _hashlib.new(%r)" % sys.argv[2]) elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)): creatorFunc = getattr(hashlib, hName) - print "testing speed of hashlib."+hName, getattr(hashlib, hName) + print("testing speed of hashlib."+hName, getattr(hashlib, hName)) else: exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName) - print "testing speed of hashlib.new(%r)" % hName + print("testing speed of hashlib.new(%r)" % hName) try: test_create() except ValueError: - print - print "pass argument(s) naming the hash to run a speed test on:" - print " '_md5' and '_sha' test the legacy builtin md5 and sha" - print " '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib" - print " '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)" - print " 'hName' tests the hashlib.hName() implementation if it exists" - print " otherwise it uses hashlib.new(hName)." - print + print() + print("pass argument(s) naming the hash to run a speed test on:") + print(" '_md5' and '_sha' test the legacy builtin md5 and sha") + print(" '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib") + print(" '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)") + print(" 'hName' tests the hashlib.hName() implementation if it exists") + print(" otherwise it uses hashlib.new(hName).") + print() raise test_zero() Modified: python/branches/p3yk/Lib/textwrap.py ============================================================================== --- python/branches/p3yk/Lib/textwrap.py (original) +++ python/branches/p3yk/Lib/textwrap.py Fri Feb 9 06:37:30 2007 @@ -371,4 +371,4 @@ if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") - print dedent("Hello there.\n This is indented.") + print(dedent("Hello there.\n This is indented.")) Modified: python/branches/p3yk/Lib/this.py ============================================================================== --- python/branches/p3yk/Lib/this.py (original) +++ python/branches/p3yk/Lib/this.py Fri Feb 9 06:37:30 2007 @@ -25,4 +25,4 @@ for i in range(26): d[chr(i+c)] = chr((i+13) % 26 + c) -print "".join([d.get(c, c) for c in s]) +print("".join([d.get(c, c) for c in s])) Modified: python/branches/p3yk/Lib/threading.py ============================================================================== --- python/branches/p3yk/Lib/threading.py (original) +++ python/branches/p3yk/Lib/threading.py Fri Feb 9 06:37:30 2007 @@ -477,19 +477,19 @@ # Lib/traceback.py) exc_type, exc_value, exc_tb = self.__exc_info() try: - print>>self.__stderr, ( + print(( "Exception in thread " + self.getName() + - " (most likely raised during interpreter shutdown):") - print>>self.__stderr, ( - "Traceback (most recent call last):") + " (most likely raised during interpreter shutdown):"), file=self.__stderr) + print(( + "Traceback (most recent call last):"), file=self.__stderr) while exc_tb: - print>>self.__stderr, ( + print(( ' File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, - exc_tb.tb_frame.f_code.co_name)) + exc_tb.tb_frame.f_code.co_name)), file=self.__stderr) exc_tb = exc_tb.tb_next - print>>self.__stderr, ("%s: %s" % (exc_type, exc_value)) + print(("%s: %s" % (exc_type, exc_value)), file=self.__stderr) # Make sure that exc_tb gets deleted since it is a memory # hog; deleting everything else is just for thoroughness finally: @@ -790,7 +790,7 @@ def run(self): while self.count > 0: item = self.queue.get() - print item + print(item) self.count = self.count - 1 NP = 3 Modified: python/branches/p3yk/Lib/timeit.py ============================================================================== --- python/branches/p3yk/Lib/timeit.py (original) +++ python/branches/p3yk/Lib/timeit.py Fri Feb 9 06:37:30 2007 @@ -210,8 +210,8 @@ ["number=", "setup=", "repeat=", "time", "clock", "verbose", "help"]) except getopt.error as err: - print err - print "use -h/--help for command line help" + print(err) + print("use -h/--help for command line help") return 2 timer = default_timer stmt = "\n".join(args) or "pass" @@ -238,7 +238,7 @@ precision += 1 verbose += 1 if o in ("-h", "--help"): - print __doc__, + print(__doc__, end=' ') return 0 setup = "\n".join(setup) or "pass" # Include the current directory, so that local imports work (sys.path @@ -257,7 +257,7 @@ t.print_exc() return 1 if verbose: - print "%d loops -> %.*g secs" % (number, precision, x) + print("%d loops -> %.*g secs" % (number, precision, x)) if x >= 0.2: break try: @@ -267,18 +267,18 @@ return 1 best = min(r) if verbose: - print "raw times:", " ".join(["%.*g" % (precision, x) for x in r]) - print "%d loops," % number, + print("raw times:", " ".join(["%.*g" % (precision, x) for x in r])) + print("%d loops," % number, end=' ') usec = best * 1e6 / number if usec < 1000: - print "best of %d: %.*g usec per loop" % (repeat, precision, usec) + print("best of %d: %.*g usec per loop" % (repeat, precision, usec)) else: msec = usec / 1000 if msec < 1000: - print "best of %d: %.*g msec per loop" % (repeat, precision, msec) + print("best of %d: %.*g msec per loop" % (repeat, precision, msec)) else: sec = msec / 1000 - print "best of %d: %.*g sec per loop" % (repeat, precision, sec) + print("best of %d: %.*g sec per loop" % (repeat, precision, sec)) return None if __name__ == "__main__": Modified: python/branches/p3yk/Lib/tokenize.py ============================================================================== --- python/branches/p3yk/Lib/tokenize.py (original) +++ python/branches/p3yk/Lib/tokenize.py Fri Feb 9 06:37:30 2007 @@ -133,8 +133,8 @@ class StopTokenizing(Exception): pass def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing - print "%d,%d-%d,%d:\t%s\t%s" % \ - (srow, scol, erow, ecol, tok_name[type], repr(token)) + print("%d,%d-%d,%d:\t%s\t%s" % \ + (srow, scol, erow, ecol, tok_name[type], repr(token))) def tokenize(readline, tokeneater=printtoken): """ Modified: python/branches/p3yk/Lib/trace.py ============================================================================== --- python/branches/p3yk/Lib/trace.py (original) +++ python/branches/p3yk/Lib/trace.py Fri Feb 9 06:37:30 2007 @@ -221,8 +221,8 @@ pickle.load(open(self.infile, 'rb')) self.update(self.__class__(counts, calledfuncs, callers)) except (IOError, EOFError, ValueError) as err: - print >> sys.stderr, ("Skipping counts file %r: %s" - % (self.infile, err)) + print(("Skipping counts file %r: %s" + % (self.infile, err)), file=sys.stderr) def update(self, other): """Merge in the data from another CoverageResults""" @@ -247,30 +247,30 @@ @param coverdir """ if self.calledfuncs: - print - print "functions called:" + print() + print("functions called:") calls = self.calledfuncs.keys() calls.sort() for filename, modulename, funcname in calls: - print ("filename: %s, modulename: %s, funcname: %s" - % (filename, modulename, funcname)) + print(("filename: %s, modulename: %s, funcname: %s" + % (filename, modulename, funcname))) if self.callers: - print - print "calling relationships:" + print() + print("calling relationships:") calls = self.callers.keys() calls.sort() lastfile = lastcfile = "" for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls: if pfile != lastfile: - print - print "***", pfile, "***" + print() + print("***", pfile, "***") lastfile = pfile lastcfile = "" if cfile != pfile and lastcfile != cfile: - print " -->", cfile + print(" -->", cfile) lastcfile = cfile - print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc) + print(" %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)) # turn the counts data ("(filename, lineno) = count") into something # accessible on a per-file basis @@ -318,10 +318,10 @@ if summary and sums: mods = sums.keys() mods.sort() - print "lines cov% module (path)" + print("lines cov% module (path)") for m in mods: n_lines, percent, modulename, filename = sums[m] - print "%5d %3d%% %s (%s)" % sums[m] + print("%5d %3d%% %s (%s)" % sums[m]) if self.outfile: # try and store counts and module info into self.outfile @@ -329,7 +329,7 @@ pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1) except IOError as err: - print >> sys.stderr, "Can't save counts files because %s" % err + print("Can't save counts files because %s" % err, file=sys.stderr) def write_results_file(self, path, lines, lnotab, lines_hit): """Return a coverage results file in path.""" @@ -337,8 +337,8 @@ try: outfile = open(path, "w") except IOError as err: - print >> sys.stderr, ("trace: Could not open %r for writing: %s" - "- skipping" % (path, err)) + print(("trace: Could not open %r for writing: %s" + "- skipping" % (path, err)), file=sys.stderr) return 0, 0 n_lines = 0 @@ -423,8 +423,8 @@ try: prog = open(filename, "rU").read() except IOError as err: - print >> sys.stderr, ("Not printing coverage data for %r: %s" - % (filename, err)) + print(("Not printing coverage data for %r: %s" + % (filename, err)), file=sys.stderr) return {} code = compile(prog, filename, "exec") strs = find_strings(filename) @@ -596,8 +596,8 @@ ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: - print (" --- modulename: %s, funcname: %s" - % (modulename, code.co_name)) + print((" --- modulename: %s, funcname: %s" + % (modulename, code.co_name))) return self.localtrace else: return None @@ -611,8 +611,8 @@ self.counts[key] = self.counts.get(key, 0) + 1 bname = os.path.basename(filename) - print "%s(%d): %s" % (bname, lineno, - linecache.getline(filename, lineno)), + print("%s(%d): %s" % (bname, lineno, + linecache.getline(filename, lineno)), end=' ') return self.localtrace def localtrace_trace(self, frame, why, arg): @@ -622,8 +622,8 @@ lineno = frame.f_lineno bname = os.path.basename(filename) - print "%s(%d): %s" % (bname, lineno, - linecache.getline(filename, lineno)), + print("%s(%d): %s" % (bname, lineno, + linecache.getline(filename, lineno)), end=' ') return self.localtrace def localtrace_count(self, frame, why, arg): Modified: python/branches/p3yk/Lib/unittest.py ============================================================================== --- python/branches/p3yk/Lib/unittest.py (original) +++ python/branches/p3yk/Lib/unittest.py Fri Feb 9 06:37:30 2007 @@ -759,8 +759,8 @@ self.runTests() def usageExit(self, msg=None): - if msg: print msg - print self.USAGE % self.__dict__ + if msg: print(msg) + print(self.USAGE % self.__dict__) sys.exit(2) def parseArgs(self, argv): Modified: python/branches/p3yk/Lib/urllib.py ============================================================================== --- python/branches/p3yk/Lib/urllib.py (original) +++ python/branches/p3yk/Lib/urllib.py Fri Feb 9 06:37:30 2007 @@ -777,7 +777,7 @@ (user, realm, host)) return user, passwd except KeyboardInterrupt: - print + print() return None, None @@ -1453,17 +1453,17 @@ uqs = unquote(qs) t1 = time.time() if uqs != s: - print 'Wrong!' - print repr(s) - print repr(qs) - print repr(uqs) - print round(t1 - t0, 3), 'sec' + print('Wrong!') + print(repr(s)) + print(repr(qs)) + print(repr(uqs)) + print(round(t1 - t0, 3), 'sec') def reporthook(blocknum, blocksize, totalsize): # Report during remote transfers - print "Block number: %d, Block size: %d, Total size: %d" % ( - blocknum, blocksize, totalsize) + print("Block number: %d, Block size: %d, Total size: %d" % ( + blocknum, blocksize, totalsize)) # Test program def test(args=[]): @@ -1480,22 +1480,22 @@ args.append('https://synergy.as.cmu.edu/~geek/') try: for url in args: - print '-'*10, url, '-'*10 + print('-'*10, url, '-'*10) fn, h = urlretrieve(url, None, reporthook) - print fn + print(fn) if h: - print '======' - for k in h.keys(): print k + ':', h[k] - print '======' + print('======') + for k in h.keys(): print(k + ':', h[k]) + print('======') fp = open(fn, 'rb') data = fp.read() del fp if '\r' in data: table = string.maketrans("", "") data = data.translate(table, "\r") - print data + print(data) fn, h = None, None - print '-'*40 + print('-'*40) finally: urlcleanup() @@ -1504,17 +1504,17 @@ try: opts, args = getopt.getopt(sys.argv[1:], "th") except getopt.error as msg: - print msg - print "Use -h for help" + print(msg) + print("Use -h for help") return t = 0 for o, a in opts: if o == '-t': t = t + 1 if o == '-h': - print "Usage: python urllib.py [-t] [url ...]" - print "-t runs self-test;", - print "otherwise, contents of urls are printed" + print("Usage: python urllib.py [-t] [url ...]") + print("-t runs self-test;", end=' ') + print("otherwise, contents of urls are printed") return if t: if t > 1: @@ -1522,9 +1522,9 @@ test(args) else: if not args: - print "Use -h for help" + print("Use -h for help") for url in args: - print urlopen(url).read(), + print(urlopen(url).read(), end=' ') # Run test program when run as a script if __name__ == '__main__': Modified: python/branches/p3yk/Lib/urlparse.py ============================================================================== --- python/branches/p3yk/Lib/urlparse.py (original) +++ python/branches/p3yk/Lib/urlparse.py Fri Feb 9 06:37:30 2007 @@ -361,15 +361,15 @@ continue url = words[0] parts = urlparse(url) - print '%-10s : %s' % (url, parts) + print('%-10s : %s' % (url, parts)) abs = urljoin(base, url) if not base: base = abs wrapped = '' % abs - print '%-10s = %s' % (url, wrapped) + print('%-10s = %s' % (url, wrapped)) if len(words) == 3 and words[1] == '=': if wrapped != words[2]: - print 'EXPECTED', words[2], '!!!!!!!!!!' + print('EXPECTED', words[2], '!!!!!!!!!!') if __name__ == '__main__': test() Modified: python/branches/p3yk/Lib/uu.py ============================================================================== --- python/branches/p3yk/Lib/uu.py (original) +++ python/branches/p3yk/Lib/uu.py Fri Feb 9 06:37:30 2007 @@ -170,7 +170,7 @@ if isinstance(output, basestring): output = open(output, 'w') else: - print sys.argv[0], ': cannot do -t to stdout' + print(sys.argv[0], ': cannot do -t to stdout') sys.exit(1) decode(input, output) else: @@ -178,7 +178,7 @@ if isinstance(input, basestring): input = open(input, 'r') else: - print sys.argv[0], ': cannot do -t from stdin' + print(sys.argv[0], ': cannot do -t from stdin') sys.exit(1) encode(input, output) Modified: python/branches/p3yk/Lib/warnings.py ============================================================================== --- python/branches/p3yk/Lib/warnings.py (original) +++ python/branches/p3yk/Lib/warnings.py Fri Feb 9 06:37:30 2007 @@ -193,7 +193,7 @@ try: _setoption(arg) except _OptionError as msg: - print >>sys.stderr, "Invalid -W option ignored:", msg + print("Invalid -W option ignored:", msg, file=sys.stderr) # Helper for _processoptions() def _setoption(arg): Modified: python/branches/p3yk/Lib/webbrowser.py ============================================================================== --- python/branches/p3yk/Lib/webbrowser.py (original) +++ python/branches/p3yk/Lib/webbrowser.py Fri Feb 9 06:37:30 2007 @@ -626,21 +626,21 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'ntd') except getopt.error as msg: - print >>sys.stderr, msg - print >>sys.stderr, usage + print(msg, file=sys.stderr) + print(usage, file=sys.stderr) sys.exit(1) new_win = 0 for o, a in opts: if o == '-n': new_win = 1 elif o == '-t': new_win = 2 if len(args) != 1: - print >>sys.stderr, usage + print(usage, file=sys.stderr) sys.exit(1) url = args[0] open(url, new_win) - print "\a" + print("\a") if __name__ == "__main__": main() Modified: python/branches/p3yk/Lib/whichdb.py ============================================================================== --- python/branches/p3yk/Lib/whichdb.py (original) +++ python/branches/p3yk/Lib/whichdb.py Fri Feb 9 06:37:30 2007 @@ -114,4 +114,4 @@ if __name__ == "__main__": for filename in sys.argv[1:]: - print whichdb(filename) or "UNKNOWN", filename + print(whichdb(filename) or "UNKNOWN", filename) Modified: python/branches/p3yk/Lib/wsgiref/simple_server.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/simple_server.py (original) +++ python/branches/p3yk/Lib/wsgiref/simple_server.py Fri Feb 9 06:37:30 2007 @@ -165,11 +165,11 @@ def demo_app(environ,start_response): from StringIO import StringIO stdout = StringIO() - print >>stdout, "Hello world!" - print >>stdout + print("Hello world!", file=stdout) + print(file=stdout) h = environ.items(); h.sort() for k,v in h: - print >>stdout, k,'=',repr(v) + print(k,'=',repr(v), file=stdout) start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] @@ -186,7 +186,7 @@ if __name__ == '__main__': httpd = make_server('', 8000, demo_app) sa = httpd.socket.getsockname() - print "Serving HTTP on", sa[0], "port", sa[1], "..." + print("Serving HTTP on", sa[0], "port", sa[1], "...") import webbrowser webbrowser.open('http://localhost:8000/xyz?abc') httpd.handle_request() # serve one request, then exit Modified: python/branches/p3yk/Lib/xml/dom/pulldom.py ============================================================================== --- python/branches/p3yk/Lib/xml/dom/pulldom.py (original) +++ python/branches/p3yk/Lib/xml/dom/pulldom.py Fri Feb 9 06:37:30 2007 @@ -201,7 +201,7 @@ class ErrorHandler: def warning(self, exception): - print exception + print(exception) def error(self, exception): raise exception def fatalError(self, exception): Modified: python/branches/p3yk/Lib/xml/sax/handler.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/handler.py (original) +++ python/branches/p3yk/Lib/xml/sax/handler.py Fri Feb 9 06:37:30 2007 @@ -39,7 +39,7 @@ def warning(self, exception): "Handle a warning." - print exception + print(exception) # ===== CONTENTHANDLER ===== Modified: python/branches/p3yk/Lib/xmllib.py ============================================================================== --- python/branches/p3yk/Lib/xmllib.py (original) +++ python/branches/p3yk/Lib/xmllib.py Fri Feb 9 06:37:30 2007 @@ -809,11 +809,11 @@ def handle_xml(self, encoding, standalone): self.flush() - print 'xml: encoding =',encoding,'standalone =',standalone + print('xml: encoding =',encoding,'standalone =',standalone) def handle_doctype(self, tag, pubid, syslit, data): self.flush() - print 'DOCTYPE:',tag, repr(data) + print('DOCTYPE:',tag, repr(data)) def handle_data(self, data): self.testdata = self.testdata + data @@ -824,47 +824,47 @@ data = self.testdata if data: self.testdata = "" - print 'data:', repr(data) + print('data:', repr(data)) def handle_cdata(self, data): self.flush() - print 'cdata:', repr(data) + print('cdata:', repr(data)) def handle_proc(self, name, data): self.flush() - print 'processing:',name,repr(data) + print('processing:',name,repr(data)) def handle_comment(self, data): self.flush() r = repr(data) if len(r) > 68: r = r[:32] + '...' + r[-32:] - print 'comment:', r + print('comment:', r) def syntax_error(self, message): - print 'error at line %d:' % self.lineno, message + print('error at line %d:' % self.lineno, message) def unknown_starttag(self, tag, attrs): self.flush() if not attrs: - print 'start tag: <' + tag + '>' + print('start tag: <' + tag + '>') else: - print 'start tag: <' + tag, + print('start tag: <' + tag, end=' ') for name, value in attrs.items(): - print name + '=' + '"' + value + '"', - print '>' + print(name + '=' + '"' + value + '"', end=' ') + print('>') def unknown_endtag(self, tag): self.flush() - print 'end tag: ' + print('end tag: ') def unknown_entityref(self, ref): self.flush() - print '*** unknown entity ref: &' + ref + ';' + print('*** unknown entity ref: &' + ref + ';') def unknown_charref(self, ref): self.flush() - print '*** unknown char ref: &#' + ref + ';' + print('*** unknown char ref: &#' + ref + ';') def close(self): XMLParser.close(self) @@ -897,7 +897,7 @@ try: f = open(file, 'r') except IOError as msg: - print file, ":", msg + print(file, ":", msg) sys.exit(1) data = f.read() @@ -916,13 +916,13 @@ x.close() except Error as msg: t1 = time() - print msg + print(msg) if do_time: - print 'total time: %g' % (t1-t0) + print('total time: %g' % (t1-t0)) sys.exit(1) t1 = time() if do_time: - print 'total time: %g' % (t1-t0) + print('total time: %g' % (t1-t0)) if __name__ == '__main__': Modified: python/branches/p3yk/Lib/xmlrpclib.py ============================================================================== --- python/branches/p3yk/Lib/xmlrpclib.py (original) +++ python/branches/p3yk/Lib/xmlrpclib.py Fri Feb 9 06:37:30 2007 @@ -1310,7 +1310,7 @@ if not response: break if self.verbose: - print "body:", repr(response) + print("body:", repr(response)) p.feed(response) file.close() @@ -1450,18 +1450,18 @@ # server = ServerProxy("http://localhost:8000") # local server server = ServerProxy("http://time.xmlrpc.com/RPC2") - print server + print(server) try: - print server.currentTime.getCurrentTime() + print(server.currentTime.getCurrentTime()) except Error as v: - print "ERROR", v + print("ERROR", v) multi = MultiCall(server) multi.currentTime.getCurrentTime() multi.currentTime.getCurrentTime() try: for response in multi(): - print response + print(response) except Error as v: - print "ERROR", v + print("ERROR", v) Modified: python/branches/p3yk/Lib/zipfile.py ============================================================================== --- python/branches/p3yk/Lib/zipfile.py (original) +++ python/branches/p3yk/Lib/zipfile.py Fri Feb 9 06:37:30 2007 @@ -377,7 +377,7 @@ if not endrec: raise BadZipfile, "File is not a zip file" if self.debug > 1: - print endrec + print(endrec) size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory self.comment = endrec[8] # archive comment @@ -389,7 +389,7 @@ # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: - print "given, inferred, offset", offset_cd, x, concat + print("given, inferred, offset", offset_cd, x, concat) # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) @@ -403,7 +403,7 @@ raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: - print centdir + print(centdir) filename = fp.read(centdir[_CD_FILENAME_LENGTH]) # Create ZipInfo instance to store file information x = ZipInfo(filename) @@ -426,7 +426,7 @@ self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: - print "total", total + print("total", total) def namelist(self): @@ -443,10 +443,10 @@ def printdir(self): """Print a table of contents for the zip file.""" - print "%-46s %19s %12s" % ("File Name", "Modified ", "Size") + print("%-46s %19s %12s" % ("File Name", "Modified ", "Size")) for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time - print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size) + print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)) def testzip(self): """Read all the files and check the CRC.""" @@ -516,7 +516,7 @@ """Check for errors before writing a file to the archive.""" if zinfo.filename in self.NameToInfo: if self.debug: # Warning for duplicate names - print "Duplicate name:", zinfo.filename + print("Duplicate name:", zinfo.filename) if self.mode not in ("w", "a"): raise RuntimeError, 'write() requires mode "w" or "a"' if not self.fp: @@ -749,10 +749,10 @@ else: basename = name if self.debug: - print "Adding package in", pathname, "as", basename + print("Adding package in", pathname, "as", basename) fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: - print "Adding", arcname + print("Adding", arcname) self.write(fname, arcname) dirlist = os.listdir(pathname) dirlist.remove("__init__.py") @@ -768,12 +768,12 @@ fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: - print "Adding", arcname + print("Adding", arcname) self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: - print "Adding files from directory", pathname + print("Adding files from directory", pathname) for filename in os.listdir(pathname): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) @@ -781,7 +781,7 @@ fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: - print "Adding", arcname + print("Adding", arcname) self.write(fname, arcname) else: if pathname[-3:] != ".py": @@ -789,7 +789,7 @@ 'Files added with writepy() must end with ".py"' fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: - print "Adding file", arcname + print("Adding file", arcname) self.write(fname, arcname) def _get_codename(self, pathname, basename): @@ -809,11 +809,11 @@ os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime: import py_compile if self.debug: - print "Compiling", file_py + print("Compiling", file_py) try: py_compile.compile(file_py, file_pyc, None, True) except py_compile.PyCompileError as err: - print err.msg + print(err.msg) fname = file_pyc else: fname = file_pyc @@ -836,12 +836,12 @@ args = sys.argv[1:] if not args or args[0] not in ('-l', '-c', '-e', '-t'): - print USAGE + print(USAGE) sys.exit(1) if args[0] == '-l': if len(args) != 2: - print USAGE + print(USAGE) sys.exit(1) zf = ZipFile(args[1], 'r') zf.printdir() @@ -849,15 +849,15 @@ elif args[0] == '-t': if len(args) != 2: - print USAGE + print(USAGE) sys.exit(1) zf = ZipFile(args[1], 'r') zf.testzip() - print "Done testing" + print("Done testing") elif args[0] == '-e': if len(args) != 3: - print USAGE + print(USAGE) sys.exit(1) zf = ZipFile(args[1], 'r') @@ -878,7 +878,7 @@ elif args[0] == '-c': if len(args) < 3: - print USAGE + print(USAGE) sys.exit(1) def addToZip(zf, path, zippath): From g.brandl at gmx.net Fri Feb 9 13:12:55 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Fri, 09 Feb 2007 13:12:55 +0100 Subject: [Python-3000-checkins] r53685 - in python/branches/p3yk In-Reply-To: <20070209053251.71BCE1E4010@bag.python.org> References: <20070209053251.71BCE1E4010@bag.python.org> Message-ID: <45CC6547.2060506@gmx.net> guido.van.rossum schrieb: > Author: guido.van.rossum > Date: Fri Feb 9 06:32:43 2007 > New Revision: 53685 > > Modified: > python/branches/p3yk/Grammar/Grammar > python/branches/p3yk/Include/graminit.h > python/branches/p3yk/Makefile.pre.in > python/branches/p3yk/Modules/parsermodule.c > python/branches/p3yk/Python/ast.c > python/branches/p3yk/Python/bltinmodule.c > python/branches/p3yk/Python/graminit.c > python/branches/p3yk/Python/import.c > python/branches/p3yk/setup.py > Log: > Essential changes for print function changes. > Lib will be changed in a separate run. What about the legacy code in compile.c to compile the print statement, together with the PRINT_ITEM[_TO] opcodes in ceval.c and others? Can they be removed now? Georg -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 189 bytes Desc: OpenPGP digital signature Url : http://mail.python.org/pipermail/python-3000-checkins/attachments/20070209/0227dd25/attachment.pgp From python-3000-checkins at python.org Fri Feb 9 21:13:29 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 21:13:29 +0100 (CET) Subject: [Python-3000-checkins] r53701 - in python/branches/p3yk/Lib: Cookie.py ctypes/test/test_objects.py decimal.py difflib.py distutils/versionpredicate.py doctest.py nntplib.py smtplib.py telnetlib.py test/doctest_aliases.py test/sample_doctest.py test/test_code.py test/test_deque.py test/test_descrtut.py test/test_doctest.py test/test_doctest2.py test/test_generators.py test/test_genexps.py test/test_itertools.py test/test_syntax.py test/test_urllib2.py test/test_weakref.py test/test_xml_etree.py test/test_xml_etree_c.py Message-ID: <20070209201329.CE53A1E4012@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 21:13:25 2007 New Revision: 53701 Modified: python/branches/p3yk/Lib/Cookie.py python/branches/p3yk/Lib/ctypes/test/test_objects.py python/branches/p3yk/Lib/decimal.py python/branches/p3yk/Lib/difflib.py python/branches/p3yk/Lib/distutils/versionpredicate.py python/branches/p3yk/Lib/doctest.py python/branches/p3yk/Lib/nntplib.py python/branches/p3yk/Lib/smtplib.py python/branches/p3yk/Lib/telnetlib.py python/branches/p3yk/Lib/test/doctest_aliases.py python/branches/p3yk/Lib/test/sample_doctest.py python/branches/p3yk/Lib/test/test_code.py python/branches/p3yk/Lib/test/test_deque.py python/branches/p3yk/Lib/test/test_descrtut.py python/branches/p3yk/Lib/test/test_doctest.py python/branches/p3yk/Lib/test/test_doctest2.py python/branches/p3yk/Lib/test/test_generators.py python/branches/p3yk/Lib/test/test_genexps.py python/branches/p3yk/Lib/test/test_itertools.py python/branches/p3yk/Lib/test/test_syntax.py python/branches/p3yk/Lib/test/test_urllib2.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/test/test_xml_etree.py python/branches/p3yk/Lib/test/test_xml_etree_c.py Log: Fix a bunch of doctests with the -d option of refactor.py. We still have 27 failing tests (down from 39). Modified: python/branches/p3yk/Lib/Cookie.py ============================================================================== --- python/branches/p3yk/Lib/Cookie.py (original) +++ python/branches/p3yk/Lib/Cookie.py Fri Feb 9 21:13:25 2007 @@ -80,9 +80,9 @@ >>> C = Cookie.SmartCookie() >>> C["rocky"] = "road" >>> C["rocky"]["path"] = "/cookie" - >>> print(C.output(header="Cookie:")) + >>> print((C.output(header="Cookie:"))) Cookie: rocky=road; Path=/cookie - >>> print(C.output(attrs=[], header="Cookie:")) + >>> print((C.output(attrs=[], header="Cookie:"))) Cookie: rocky=road The load() method of a Cookie extracts cookies from a string. In a @@ -100,7 +100,7 @@ >>> C = Cookie.SmartCookie() >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') - >>> print(C) + >>> print((C)) Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" Each element of the Cookie also supports all of the RFC 2109 @@ -110,7 +110,7 @@ >>> C = Cookie.SmartCookie() >>> C["oreo"] = "doublestuff" >>> C["oreo"]["path"] = "/" - >>> print(C) + >>> print((C)) Set-Cookie: oreo=doublestuff; Path=/ Each dictionary element has a 'value' attribute, which gives you @@ -198,7 +198,7 @@ fact, this simply returns a SmartCookie. >>> C = Cookie.Cookie() - >>> print(C.__class__.__name__) + >>> print((C.__class__.__name__)) SmartCookie Modified: python/branches/p3yk/Lib/ctypes/test/test_objects.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_objects.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_objects.py Fri Feb 9 21:13:25 2007 @@ -13,7 +13,7 @@ >>> from ctypes import * >>> array = (c_char_p * 5)() ->>> print array._objects +>>> print(array._objects) None >>> @@ -34,14 +34,14 @@ ... _fields_ = [("x", c_int), ("y", c_int), ("array", c_char_p * 5)] ... >>> x = X() ->>> print x._objects +>>> print(x._objects) None >>> The'array' attribute of the 'x' object shares part of the memory buffer of 'x' ('_b_base_' is either None, or the root object owning the memory block): ->>> print x.array._b_base_ # doctest: +ELLIPSIS +>>> print(x.array._b_base_) # doctest: +ELLIPSIS >>> Modified: python/branches/p3yk/Lib/decimal.py ============================================================================== --- python/branches/p3yk/Lib/decimal.py (original) +++ python/branches/p3yk/Lib/decimal.py Fri Feb 9 21:13:25 2007 @@ -56,31 +56,31 @@ >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41") Decimal("-2.20") >>> dig = Decimal(1) ->>> print dig / Decimal(3) +>>> print(dig / Decimal(3)) 0.333333333 >>> getcontext().prec = 18 ->>> print dig / Decimal(3) +>>> print(dig / Decimal(3)) 0.333333333333333333 ->>> print dig.sqrt() +>>> print(dig.sqrt()) 1 ->>> print Decimal(3).sqrt() +>>> print(Decimal(3).sqrt()) 1.73205080756887729 ->>> print Decimal(3) ** 123 +>>> print(Decimal(3) ** 123) 4.85192780976896427E+58 >>> inf = Decimal(1) / Decimal(0) ->>> print inf +>>> print(inf) Infinity >>> neginf = Decimal(-1) / Decimal(0) ->>> print neginf +>>> print(neginf) -Infinity ->>> print neginf + inf +>>> print(neginf + inf) NaN ->>> print neginf * inf +>>> print(neginf * inf) -Infinity ->>> print dig / 0 +>>> print(dig / 0) Infinity >>> getcontext().traps[DivisionByZero] = 1 ->>> print dig / 0 +>>> print(dig / 0) Traceback (most recent call last): ... ... @@ -88,29 +88,29 @@ decimal.DivisionByZero: x / 0 >>> c = Context() >>> c.traps[InvalidOperation] = 0 ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 0 >>> c.divide(Decimal(0), Decimal(0)) Decimal("NaN") >>> c.traps[InvalidOperation] = 1 ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 1 >>> c.flags[InvalidOperation] = 0 ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 0 ->>> print c.divide(Decimal(0), Decimal(0)) +>>> print(c.divide(Decimal(0), Decimal(0))) Traceback (most recent call last): ... ... ... decimal.InvalidOperation: 0 / 0 ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 1 >>> c.flags[InvalidOperation] = 0 >>> c.traps[InvalidOperation] = 0 ->>> print c.divide(Decimal(0), Decimal(0)) +>>> print(c.divide(Decimal(0), Decimal(0))) NaN ->>> print c.flags[InvalidOperation] +>>> print(c.flags[InvalidOperation]) 1 >>> """ @@ -483,19 +483,19 @@ # as the doctest module doesn't understand __future__ statements """ >>> from __future__ import with_statement - >>> print getcontext().prec + >>> print(getcontext().prec) 28 >>> with localcontext(): ... ctx = getcontext() ... ctx.prec() += 2 - ... print ctx.prec - ... + ... print(ctx.prec) + ... 30 >>> with localcontext(ExtendedContext): - ... print getcontext().prec - ... + ... print(getcontext().prec) + ... 9 - >>> print getcontext().prec + >>> print(getcontext().prec) 28 """ if ctx is None: ctx = getcontext() Modified: python/branches/p3yk/Lib/difflib.py ============================================================================== --- python/branches/p3yk/Lib/difflib.py (original) +++ python/branches/p3yk/Lib/difflib.py Fri Feb 9 21:13:25 2007 @@ -76,7 +76,7 @@ sequences. As a rule of thumb, a .ratio() value over 0.6 means the sequences are close matches: - >>> print(round(s.ratio(), 3)) + >>> print((round(s.ratio(), 3))) 0.866 >>> @@ -84,7 +84,7 @@ .get_matching_blocks() is handy: >>> for block in s.get_matching_blocks(): - ... print("a[%d] and b[%d] match for %d elements" % block) + ... print(("a[%d] and b[%d] match for %d elements" % block)) a[0] and b[0] match for 8 elements a[8] and b[17] match for 21 elements a[29] and b[38] match for 0 elements @@ -97,7 +97,7 @@ use .get_opcodes(): >>> for opcode in s.get_opcodes(): - ... print("%6s a[%d:%d] b[%d:%d]" % opcode) + ... print(("%6s a[%d:%d] b[%d:%d]" % opcode)) equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:29] b[17:38] @@ -545,8 +545,8 @@ >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): - ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % - ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) + ... print((("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % + ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) @@ -1059,8 +1059,8 @@ >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n', ... ' ^ ^ ^ ', '+ ^ ^ ^ ') - >>> for line in results: print(repr(line)) - ... + >>> for line in results: print((repr(line))) + ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' '+ \t\tabcdefGhijkl\n' @@ -1165,7 +1165,7 @@ ... 'zero one tree four'.split(), 'Original', 'Current', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003', ... lineterm=''): - ... print(line) + ... print((line)) --- Original Sat Jan 26 23:30:50 1991 +++ Current Fri Jun 06 10:20:52 2003 @@ -1,4 +1,4 @@ Modified: python/branches/p3yk/Lib/distutils/versionpredicate.py ============================================================================== --- python/branches/p3yk/Lib/distutils/versionpredicate.py (original) +++ python/branches/p3yk/Lib/distutils/versionpredicate.py Fri Feb 9 21:13:25 2007 @@ -40,7 +40,7 @@ The str() of a `VersionPredicate` provides a normalized human-readable version of the expression:: - >>> print v + >>> print(v) pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3) The `satisfied_by()` method can be used to determine with a given Modified: python/branches/p3yk/Lib/doctest.py ============================================================================== --- python/branches/p3yk/Lib/doctest.py (original) +++ python/branches/p3yk/Lib/doctest.py Fri Feb 9 21:13:25 2007 @@ -1012,7 +1012,7 @@ >>> runner = DocTestRunner(verbose=False) >>> tests.sort(key = lambda test: test.name) >>> for test in tests: - ... print test.name, '->', runner.run(test) + ... print(test.name, '->', runner.run(test)) _TestClass -> (0, 2) _TestClass.__init__ -> (0, 2) _TestClass.get -> (0, 2) @@ -2419,7 +2419,7 @@ ... Ho hum ... ''' - >>> print script_from_examples(text) + >>> print(script_from_examples(text)) # Here are examples of simple math. # # Python has super accurate integer addition @@ -2554,7 +2554,7 @@ """val -> _TestClass object with associated value val. >>> t = _TestClass(123) - >>> print t.get() + >>> print(t.get()) 123 """ @@ -2574,7 +2574,7 @@ """get() -> return TestClass's associated value. >>> x = _TestClass(-42) - >>> print x.get() + >>> print(x.get()) -42 """ @@ -2606,7 +2606,7 @@ "blank lines": r""" Blank lines can be marked with : - >>> print 'foo\n\nbar\n' + >>> print('foo\n\nbar\n') foo bar @@ -2616,14 +2616,14 @@ "ellipsis": r""" If the ellipsis flag is used, then '...' can be used to elide substrings in the desired output: - >>> print range(1000) #doctest: +ELLIPSIS + >>> print(range(1000)) #doctest: +ELLIPSIS [0, 1, 2, ..., 999] """, "whitespace normalization": r""" If the whitespace normalization flag is used, then differences in whitespace are ignored. - >>> print range(30) #doctest: +NORMALIZE_WHITESPACE + >>> print(range(30)) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] Modified: python/branches/p3yk/Lib/nntplib.py ============================================================================== --- python/branches/p3yk/Lib/nntplib.py (original) +++ python/branches/p3yk/Lib/nntplib.py Fri Feb 9 21:13:25 2007 @@ -5,7 +5,7 @@ >>> from nntplib import NNTP >>> s = NNTP('news') >>> resp, count, first, last, name = s.group('comp.lang.python') ->>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last +>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) Group comp.lang.python has 51 articles, range 5770 to 5821 >>> resp, subs = s.xhdr('subject', first + '-' + last) >>> resp = s.quit() Modified: python/branches/p3yk/Lib/smtplib.py ============================================================================== --- python/branches/p3yk/Lib/smtplib.py (original) +++ python/branches/p3yk/Lib/smtplib.py Fri Feb 9 21:13:25 2007 @@ -15,7 +15,7 @@ >>> import smtplib >>> s=smtplib.SMTP("localhost") - >>> print s.help() + >>> print(s.help()) This is Sendmail version 8.8.4 Topics: HELO EHLO MAIL RCPT DATA Modified: python/branches/p3yk/Lib/telnetlib.py ============================================================================== --- python/branches/p3yk/Lib/telnetlib.py (original) +++ python/branches/p3yk/Lib/telnetlib.py Fri Feb 9 21:13:25 2007 @@ -8,7 +8,7 @@ >>> from telnetlib import Telnet >>> tn = Telnet('www.python.org', 79) # connect to finger port >>> tn.write('guido\r\n') ->>> print tn.read_all() +>>> print(tn.read_all()) Login Name TTY Idle When Where guido Guido van Rossum pts/2 snag.cnri.reston.. Modified: python/branches/p3yk/Lib/test/doctest_aliases.py ============================================================================== --- python/branches/p3yk/Lib/test/doctest_aliases.py (original) +++ python/branches/p3yk/Lib/test/doctest_aliases.py Fri Feb 9 21:13:25 2007 @@ -5,7 +5,7 @@ def f(self): ''' - >>> print TwoNames().f() + >>> print(TwoNames().f()) f ''' return 'f' Modified: python/branches/p3yk/Lib/test/sample_doctest.py ============================================================================== --- python/branches/p3yk/Lib/test/sample_doctest.py (original) +++ python/branches/p3yk/Lib/test/sample_doctest.py Fri Feb 9 21:13:25 2007 @@ -40,9 +40,9 @@ def w_blank(): """ >>> if 1: - ... print 'a' - ... print - ... print 'b' + ... print('a') + ... print() + ... print('b') a b Modified: python/branches/p3yk/Lib/test/test_code.py ============================================================================== --- python/branches/p3yk/Lib/test/test_code.py (original) +++ python/branches/p3yk/Lib/test/test_code.py Fri Feb 9 21:13:25 2007 @@ -50,9 +50,9 @@ consts: ('None',) >>> def attrs(obj): -... print obj.attr1 -... print obj.attr2 -... print obj.attr3 +... print(obj.attr1) +... print(obj.attr2) +... print(obj.attr3) >>> dump(attrs.func_code) name: attrs 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 Fri Feb 9 21:13:25 2007 @@ -504,7 +504,7 @@ >>> from collections import deque >>> d = deque('ghi') # make a new deque with three items >>> for elem in d: # iterate over the deque's elements -... print elem.upper() +... print(elem.upper()) G H I @@ -574,8 +574,8 @@ ... >>> for value in roundrobin('abc', 'd', 'efgh'): -... print value -... +... print(value) +... a d e @@ -593,7 +593,7 @@ ... d.append(pair) ... return list(d) ... ->>> print maketree('abcdefgh') +>>> print(maketree('abcdefgh')) [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]] """ Modified: python/branches/p3yk/Lib/test/test_descrtut.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descrtut.py (original) +++ python/branches/p3yk/Lib/test/test_descrtut.py Fri Feb 9 21:13:25 2007 @@ -36,28 +36,28 @@ Here's the new type at work: - >>> print defaultdict # show our type + >>> print(defaultdict) # show our type - >>> print type(defaultdict) # its metatype + >>> print(type(defaultdict)) # its metatype >>> a = defaultdict(default=0.0) # create an instance - >>> print a # show the instance + >>> print(a) # show the instance {} - >>> print type(a) # show its type + >>> print(type(a)) # show its type - >>> print a.__class__ # show its class + >>> print(a.__class__) # show its class - >>> print type(a) is a.__class__ # its type is its class + >>> print(type(a) is a.__class__) # its type is its class True >>> a[1] = 3.25 # modify the instance - >>> print a # show the new value + >>> print(a) # show the new value {1: 3.25} - >>> print a[1] # show the new item + >>> print(a[1]) # show the new item 3.25 - >>> print a[0] # a non-existant item + >>> print(a[0]) # a non-existant item 0.0 >>> a.merge({1:100, 2:200}) # use a dict method - >>> print sortdict(a) # show the result + >>> print(sortdict(a)) # show the result {1: 3.25, 2: 200} >>> @@ -65,13 +65,13 @@ dictionaries, such as the locals/globals dictionaries for the exec statement or the built-in function eval(): - >>> print sorted(a.keys()) + >>> print(sorted(a.keys())) [1, 2] >>> exec("x = 3; print x", a) 3 - >>> print sorted(a.keys(), key=lambda x: (str(type(x)), x)) + >>> print(sorted(a.keys(), key=lambda x: (str(type(x)), x))) [1, 2, '__builtins__', 'x'] - >>> print a['x'] + >>> print(a['x']) 3 >>> @@ -79,21 +79,21 @@ just like classic classes: >>> a.default = -1 - >>> print a["noway"] + >>> print(a["noway"]) -1 >>> a.default = -1000 - >>> print a["noway"] + >>> print(a["noway"]) -1000 >>> 'default' in dir(a) True >>> a.x1 = 100 >>> a.x2 = 200 - >>> print a.x1 + >>> print(a.x1) 100 >>> d = dir(a) >>> 'default' in d and 'x1' in d and 'x2' in d True - >>> print sortdict(a.__dict__) + >>> print(sortdict(a.__dict__)) {'default': -1000, 'x1': 100, 'x2': 200} >>> """ @@ -242,10 +242,10 @@ static methods in C++ or Java. Here's an example: >>> class C: - ... + ... ... @staticmethod ... def foo(x, y): - ... print "staticmethod", x, y + ... print("staticmethod", x, y) >>> C.foo(1, 2) staticmethod 1 2 @@ -259,7 +259,7 @@ >>> class C: ... @classmethod ... def foo(cls, y): - ... print "classmethod", cls, y + ... print("classmethod", cls, y) >>> C.foo(1) classmethod 1 @@ -285,7 +285,7 @@ >>> class E(C): ... @classmethod ... def foo(cls, y): # override C.foo - ... print "E.foo() called" + ... print("E.foo() called") ... C.foo(y) >>> E.foo(1) @@ -343,10 +343,10 @@ >>> a = C() >>> a.x = 10 - >>> print a.x + >>> print(a.x) 10 >>> a.x = -10 - >>> print a.x + >>> print(a.x) 0 >>> @@ -369,10 +369,10 @@ >>> a = C() >>> a.x = 10 - >>> print a.x + >>> print(a.x) 10 >>> a.x = -10 - >>> print a.x + >>> print(a.x) 0 >>> """ @@ -385,12 +385,12 @@ >>> class A: # implicit new-style class ... def save(self): -... print "called A.save()" +... print("called A.save()") >>> class B(A): ... pass >>> class C(A): ... def save(self): -... print "called C.save()" +... print("called C.save()") >>> class D(B, C): ... pass @@ -399,12 +399,12 @@ >>> class A(object): # explicit new-style class ... def save(self): -... print "called A.save()" +... print("called A.save()") >>> class B(A): ... pass >>> class C(A): ... def save(self): -... print "called C.save()" +... print("called C.save()") >>> class D(B, C): ... pass @@ -433,7 +433,7 @@ Cooperative methods and "super" ->>> print D().m() # "DCBA" +>>> print(D().m()) # "DCBA" DCBA """ @@ -443,7 +443,7 @@ >>> class A: ... def foo(self): -... print "called A.foo()" +... print("called A.foo()") >>> class B(A): ... pass Modified: python/branches/p3yk/Lib/test/test_doctest.py ============================================================================== --- python/branches/p3yk/Lib/test/test_doctest.py (original) +++ python/branches/p3yk/Lib/test/test_doctest.py Fri Feb 9 21:13:25 2007 @@ -14,7 +14,7 @@ """ Blah blah - >>> print sample_func(22) + >>> print(sample_func(22)) 44 Yee ha! @@ -23,7 +23,7 @@ class SampleClass: """ - >>> print 1 + >>> print(1) 1 >>> # comments get ignored. so are empty PS1 and PS2 prompts: @@ -34,33 +34,33 @@ >>> sc = SampleClass(3) >>> for i in range(10): ... sc = sc.double() - ... print sc.get(), + ... print(sc.get(), end=' ') 6 12 24 48 96 192 384 768 1536 3072 """ def __init__(self, val): """ - >>> print SampleClass(12).get() + >>> print(SampleClass(12).get()) 12 """ self.val = val def double(self): """ - >>> print SampleClass(12).double().get() + >>> print(SampleClass(12).double().get()) 24 """ return SampleClass(self.val + self.val) def get(self): """ - >>> print SampleClass(-5).get() + >>> print(SampleClass(-5).get()) -5 """ return self.val def a_staticmethod(v): """ - >>> print SampleClass.a_staticmethod(10) + >>> print(SampleClass.a_staticmethod(10)) 11 """ return v+1 @@ -68,16 +68,16 @@ def a_classmethod(cls, v): """ - >>> print SampleClass.a_classmethod(10) + >>> print(SampleClass.a_classmethod(10)) 12 - >>> print SampleClass(0).a_classmethod(10) + >>> print(SampleClass(0).a_classmethod(10)) 12 """ return v+2 a_classmethod = classmethod(a_classmethod) a_property = property(get, doc=""" - >>> print SampleClass(22).a_property + >>> print(SampleClass(22).a_property) 22 """) @@ -85,12 +85,12 @@ """ >>> x = SampleClass.NestedClass(5) >>> y = x.square() - >>> print y.get() + >>> print(y.get()) 25 """ def __init__(self, val=0): """ - >>> print SampleClass.NestedClass().get() + >>> print(SampleClass.NestedClass().get()) 0 """ self.val = val @@ -101,28 +101,28 @@ class SampleNewStyleClass(object): r""" - >>> print '1\n2\n3' + >>> print('1\n2\n3') 1 2 3 """ def __init__(self, val): """ - >>> print SampleNewStyleClass(12).get() + >>> print(SampleNewStyleClass(12).get()) 12 """ self.val = val def double(self): """ - >>> print SampleNewStyleClass(12).double().get() + >>> print(SampleNewStyleClass(12).double().get()) 24 """ return SampleNewStyleClass(self.val + self.val) def get(self): """ - >>> print SampleNewStyleClass(-5).get() + >>> print(SampleNewStyleClass(-5).get()) -5 """ return self.val @@ -278,7 +278,7 @@ >>> parser = doctest.DocTestParser() >>> test = parser.get_doctest(docstring, globs, 'some_test', ... 'some_file', 20) - >>> print test + >>> print(test) >>> len(test.examples) 2 @@ -368,7 +368,7 @@ >>> tests = finder.find(sample_func) - >>> print tests # doctest: +ELLIPSIS + >>> print(tests) # doctest: +ELLIPSIS [] The exact name depends on how test_doctest was invoked, so allow for @@ -420,7 +420,7 @@ >>> finder = doctest.DocTestFinder() >>> tests = finder.find(SampleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ @@ -435,7 +435,7 @@ >>> tests = finder.find(SampleNewStyleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 1 SampleNewStyleClass 1 SampleNewStyleClass.__init__ 1 SampleNewStyleClass.double @@ -474,7 +474,7 @@ >>> import test.test_doctest >>> tests = finder.find(m, module=test.test_doctest) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 1 some_module 3 some_module.SampleClass 3 some_module.SampleClass.NestedClass @@ -496,9 +496,9 @@ >>> from test import doctest_aliases >>> tests = excl_empty_finder.find(doctest_aliases) - >>> print len(tests) + >>> print(len(tests)) 2 - >>> print tests[0].name + >>> print(tests[0].name) test.doctest_aliases.TwoNames TwoNames.f and TwoNames.g are bound to the same object. @@ -514,7 +514,7 @@ >>> tests = doctest.DocTestFinder().find(SampleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ @@ -532,7 +532,7 @@ >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass 3 SampleClass.NestedClass 1 SampleClass.NestedClass.__init__ @@ -552,7 +552,7 @@ >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass) >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) + ... print('%2s %s' % (len(t.examples), t.name)) 3 SampleClass Line numbers @@ -603,9 +603,9 @@ >>> parser = doctest.DocTestParser() >>> for piece in parser.parse(s): ... if isinstance(piece, doctest.Example): - ... print 'Example:', (piece.source, piece.want, piece.lineno) + ... print('Example:', (piece.source, piece.want, piece.lineno)) ... else: - ... print ' Text:', repr(piece) + ... print(' Text:', repr(piece)) Text: '\n' Example: ('x, y = 2, 3 # no output expected\n', '', 1) Text: '' @@ -617,7 +617,7 @@ The `get_examples` method returns just the examples: >>> for piece in parser.get_examples(s): - ... print (piece.source, piece.want, piece.lineno) + ... print((piece.source, piece.want, piece.lineno)) ('x, y = 2, 3 # no output expected\n', '', 1) ('if 1:\n print x\n print y\n', '2\n3\n', 2) ('x+y\n', '5\n', 9) @@ -629,7 +629,7 @@ >>> (test.name, test.filename, test.lineno) ('name', 'filename', 5) >>> for piece in test.examples: - ... print (piece.source, piece.want, piece.lineno) + ... print((piece.source, piece.want, piece.lineno)) ('x, y = 2, 3 # no output expected\n', '', 1) ('if 1:\n print x\n print y\n', '2\n3\n', 2) ('x+y\n', '5\n', 9) @@ -996,7 +996,7 @@ (0, 1) An example from the docs: - >>> print range(20) #doctest: +NORMALIZE_WHITESPACE + >>> print(range(20)) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] @@ -1029,21 +1029,21 @@ ... also matches nothing: >>> for i in range(100): - ... print i**2, #doctest: +ELLIPSIS + ... print(i**2, end=' ') #doctest: +ELLIPSIS 0 1...4...9 16 ... 36 49 64 ... 9801 ... can be surprising; e.g., this test passes: >>> for i in range(21): #doctest: +ELLIPSIS - ... print i, + ... print(i, end=' ') 0 1 2 ...1...2...0 Examples from the docs: - >>> print range(20) # doctest:+ELLIPSIS + >>> print(range(20)) # doctest:+ELLIPSIS [0, 1, ..., 18, 19] - >>> print range(20) # doctest: +ELLIPSIS + >>> print(range(20)) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE [0, 1, ..., 18, 19] @@ -1063,7 +1063,7 @@ UncheckedBlowUpError: Nobody checks me. >>> import random - >>> print random.random() # doctest: +SKIP + >>> print(random.random()) # doctest: +SKIP 0.721216923889 The REPORT_UDIFF flag causes failures that involve multi-line expected @@ -1516,7 +1516,7 @@ >>> import test.test_doctest >>> name = 'test.test_doctest.sample_func' - >>> print doctest.testsource(test.test_doctest, name) + >>> print(doctest.testsource(test.test_doctest, name)) # Blah blah # print sample_func(22) @@ -1527,7 +1527,7 @@ >>> name = 'test.test_doctest.SampleNewStyleClass' - >>> print doctest.testsource(test.test_doctest, name) + >>> print(doctest.testsource(test.test_doctest, name)) print '1\n2\n3' # Expected: ## 1 @@ -1536,7 +1536,7 @@ >>> name = 'test.test_doctest.SampleClass.a_classmethod' - >>> print doctest.testsource(test.test_doctest, name) + >>> print(doctest.testsource(test.test_doctest, name)) print SampleClass.a_classmethod(10) # Expected: ## 12 @@ -2037,7 +2037,7 @@ Trailing spaces in expected output are significant: >>> x, y = 'foo', '' - >>> print x, y + >>> print(x, y) foo \n """ @@ -2054,7 +2054,7 @@ ... optionflags=doctest.DONT_ACCEPT_BLANKLINE) >>> import unittest >>> result = suite.run(unittest.TestResult()) - >>> print result.failures[0][1] # doctest: +ELLIPSIS + >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color @@ -2071,7 +2071,7 @@ Now, when we run the test: >>> result = suite.run(unittest.TestResult()) - >>> print result.failures[0][1] # doctest: +ELLIPSIS + >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color @@ -2092,7 +2092,7 @@ Then the default eporting options are ignored: >>> result = suite.run(unittest.TestResult()) - >>> print result.failures[0][1] # doctest: +ELLIPSIS + >>> print(result.failures[0][1]) # doctest: +ELLIPSIS Traceback ... Failed example: favorite_color Modified: python/branches/p3yk/Lib/test/test_doctest2.py ============================================================================== --- python/branches/p3yk/Lib/test/test_doctest2.py (original) +++ python/branches/p3yk/Lib/test/test_doctest2.py Fri Feb 9 21:13:25 2007 @@ -2,7 +2,7 @@ u"""A module to test whether doctest recognizes some 2.2 features, like static and class methods. ->>> print 'yup' # 1 +>>> print('yup') # 1 yup We include some (random) encoded (utf-8) text in the text surrounding @@ -17,7 +17,7 @@ class C(object): u"""Class C. - >>> print C() # 2 + >>> print(C()) # 2 42 @@ -31,13 +31,13 @@ def __init__(self): """C.__init__. - >>> print C() # 3 + >>> print(C()) # 3 42 """ def __str__(self): """ - >>> print C() # 4 + >>> print(C()) # 4 42 """ return "42" @@ -45,13 +45,13 @@ class D(object): """A nested D class. - >>> print "In D!" # 5 + >>> print("In D!") # 5 In D! """ def nested(self): """ - >>> print 3 # 6 + >>> print(3) # 6 3 """ @@ -59,7 +59,7 @@ """ >>> c = C() # 7 >>> c.x = 12 # 8 - >>> print c.x # 9 + >>> print(c.x) # 9 -12 """ return -self._x @@ -68,7 +68,7 @@ """ >>> c = C() # 10 >>> c.x = 12 # 11 - >>> print c.x # 12 + >>> print(c.x) # 12 -12 """ self._x = value @@ -76,7 +76,7 @@ x = property(getx, setx, doc="""\ >>> c = C() # 13 >>> c.x = 12 # 14 - >>> print c.x # 15 + >>> print(c.x) # 15 -12 """) @@ -85,9 +85,9 @@ """ A static method. - >>> print C.statm() # 16 + >>> print(C.statm()) # 16 666 - >>> print C().statm() # 17 + >>> print(C().statm()) # 17 666 """ return 666 @@ -97,9 +97,9 @@ """ A class method. - >>> print C.clsm(22) # 18 + >>> print(C.clsm(22)) # 18 22 - >>> print C().clsm(23) # 19 + >>> print(C().clsm(23)) # 19 23 """ return val Modified: python/branches/p3yk/Lib/test/test_generators.py ============================================================================== --- python/branches/p3yk/Lib/test/test_generators.py (original) +++ python/branches/p3yk/Lib/test/test_generators.py Fri Feb 9 21:13:25 2007 @@ -6,7 +6,7 @@ ... yield 2 >>> for i in f(): - ... print i + ... print(i) 1 2 >>> g = f() @@ -78,7 +78,7 @@ ... raise StopIteration ... except: ... yield 42 - >>> print list(g2()) + >>> print(list(g2())) [42] This may be surprising at first: @@ -105,14 +105,14 @@ >>> def creator(): ... r = yrange(5) - ... print "creator", r.next() + ... print("creator", r.next()) ... return r - ... + ... >>> def caller(): ... r = creator() ... for i in r: - ... print "caller", i - ... + ... print("caller", i) + ... >>> caller() creator 0 caller 1 @@ -161,7 +161,7 @@ ... return ... except: ... yield 1 - >>> print list(f1()) + >>> print(list(f1())) [] because, as in any function, return simply exits, but @@ -171,7 +171,7 @@ ... raise StopIteration ... except: ... yield 42 - >>> print list(f2()) + >>> print(list(f2())) [42] because StopIteration is captured by a bare "except", as is any @@ -221,7 +221,7 @@ ... finally: ... yield 10 ... yield 11 - >>> print list(f()) + >>> print(list(f())) [1, 2, 4, 5, 8, 9, 10, 11] >>> @@ -270,7 +270,7 @@ >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> # Print the nodes of the tree in in-order. >>> for x in t: - ... print x, + ... print(x, end=' ') A B C D E F G H I J K L M N O P Q R S T U V W X Y Z >>> # A non-recursive generator. @@ -291,7 +291,7 @@ >>> # Exercise the non-recursive generator. >>> for x in t: - ... print x, + ... print(x, end=' ') A B C D E F G H I J K L M N O P Q R S T U V W X Y Z """ @@ -345,9 +345,9 @@ >>> seq = range(1, 5) >>> for k in range(len(seq) + 2): -... print "%d-combs of %s:" % (k, seq) +... print("%d-combs of %s:" % (k, seq)) ... for c in gcomb(seq, k): -... print " ", c +... print(" ", c) 0-combs of [1, 2, 3, 4]: [] 1-combs of [1, 2, 3, 4]: @@ -383,7 +383,7 @@ >>> [s for s in dir(i) if not s.startswith('_')] ['close', 'gi_frame', 'gi_running', 'next', 'send', 'throw'] ->>> print i.next.__doc__ +>>> print(i.next.__doc__) x.next() -> the next value, or raise StopIteration >>> iter(i) is i True @@ -447,14 +447,14 @@ >>> gen = random.WichmannHill(42) >>> while 1: ... for s in sets: -... print "%s->%s" % (s, s.find()), -... print +... print("%s->%s" % (s, s.find()), end=' ') +... print() ... if len(roots) > 1: ... s1 = gen.choice(roots) ... roots.remove(s1) ... s2 = gen.choice(roots) ... s1.union(s2) -... print "merged", s1, "into", s2 +... print("merged", s1, "into", s2) ... else: ... break A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M @@ -576,7 +576,7 @@ >>> result = m235() >>> for i in range(3): -... print firstn(result, 15) +... print(firstn(result, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] @@ -613,7 +613,7 @@ >>> m235 = LazyList(m235()) >>> for i in range(5): -... print [m235[j] for j in range(15*i, 15*(i+1))] +... print([m235[j] for j in range(15*i, 15*(i+1))]) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] @@ -684,7 +684,7 @@ >>> it = m235() >>> for i in range(5): -... print firstn(it, 15) +... print(firstn(it, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] @@ -890,13 +890,13 @@ ... yield i ... >>> g = f() ->>> print g.next() +>>> print(g.next()) 0 ->>> print g.next() +>>> print(g.next()) 1 ->>> print g.next() +>>> print(g.next()) 2 ->>> print g.next() +>>> print(g.next()) Traceback (most recent call last): StopIteration """ @@ -1291,7 +1291,7 @@ possible use of conjoin, just to generate the full cross-product. >>> for c in conjoin([lambda: iter((0, 1))] * 3): -... print c +... print(c) [0, 0, 0] [0, 0, 1] [0, 1, 0] @@ -1311,7 +1311,7 @@ >>> for n in range(10): ... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n))) -... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n +... print(n, len(all), all[0] == [0] * n, all[-1] == [1] * n) 0 1 True True 1 2 True True 2 4 True True @@ -1331,7 +1331,7 @@ >>> for row2col in q.solve(): ... count += 1 ... if count <= LIMIT: -... print "Solution", count +... print("Solution", count) ... q.printsolution(row2col) Solution 1 +-+-+-+-+-+-+-+-+ @@ -1370,7 +1370,7 @@ | | | | |Q| | | | +-+-+-+-+-+-+-+-+ ->>> print count, "solutions in all." +>>> print(count, "solutions in all.") 92 solutions in all. And run a Knight's Tour on a 10x10 board. Note that there are about @@ -1382,7 +1382,7 @@ >>> for x in k.solve(): ... count += 1 ... if count <= LIMIT: -... print "Solution", count +... print("Solution", count) ... k.printsolution(x) ... else: ... break @@ -1460,7 +1460,7 @@ Sending a value into a started generator: >>> def f(): -... print (yield 1) +... print((yield 1)) ... yield 2 >>> g = f() >>> g.next() @@ -1507,16 +1507,16 @@ >>> seq = [] >>> c = coroutine(seq) >>> c.next() ->>> print seq +>>> print(seq) [] >>> c.send(10) ->>> print seq +>>> print(seq) [10] >>> c.send(10) ->>> print seq +>>> print(seq) [10, 20] >>> c.send(10) ->>> print seq +>>> print(seq) [10, 20, 30] @@ -1553,9 +1553,9 @@ >>> def f(): ... while True: ... try: -... print (yield) +... print((yield)) ... except ValueError as v: -... print "caught ValueError (%s)" % (v), +... print("caught ValueError (%s)" % (v), end=' ') >>> import sys >>> g = f() >>> g.next() @@ -1616,7 +1616,7 @@ ... TypeError ->>> print g.gi_frame +>>> print(g.gi_frame) None >>> g.send(2) @@ -1639,7 +1639,7 @@ >>> def f(): ... try: yield ... except GeneratorExit: -... print "exiting" +... print("exiting") >>> g = f() >>> g.next() @@ -1660,7 +1660,7 @@ >>> def f(): ... try: yield ... finally: -... print "exiting" +... print("exiting") >>> g = f() >>> g.next() Modified: python/branches/p3yk/Lib/test/test_genexps.py ============================================================================== --- python/branches/p3yk/Lib/test/test_genexps.py (original) +++ python/branches/p3yk/Lib/test/test_genexps.py Fri Feb 9 21:13:25 2007 @@ -157,12 +157,12 @@ >>> def creator(): ... r = yrange(5) - ... print "creator", r.next() + ... print("creator", r.next()) ... return r >>> def caller(): ... r = creator() ... for i in r: - ... print "caller", i + ... print("caller", i) >>> caller() creator 0 caller 1 @@ -221,7 +221,7 @@ >>> set(attr for attr in dir(g) if not attr.startswith('__')) >= expected True - >>> print g.next.__doc__ + >>> print(g.next.__doc__) x.next() -> the next value, or raise StopIteration >>> import types >>> isinstance(g, types.GeneratorType) Modified: python/branches/p3yk/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_itertools.py (original) +++ python/branches/p3yk/Lib/test/test_itertools.py Fri Feb 9 21:13:25 2007 @@ -764,24 +764,24 @@ >>> amounts = [120.15, 764.05, 823.14] >>> for checknum, amount in izip(count(1200), amounts): -... print 'Check %d is for $%.2f' % (checknum, amount) -... +... print('Check %d is for $%.2f' % (checknum, amount)) +... Check 1200 is for $120.15 Check 1201 is for $764.05 Check 1202 is for $823.14 >>> import operator >>> for cube in imap(operator.pow, xrange(1,4), repeat(3)): -... print cube -... +... print(cube) +... 1 8 27 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele'] >>> for name in islice(reportlines, 3, None, 2): -... print name.title() -... +... print(name.title()) +... Alex Laura Martin @@ -792,8 +792,8 @@ >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>> di = sorted(sorted(d.iteritems()), key=itemgetter(1)) >>> for k, g in groupby(di, itemgetter(1)): -... print k, map(itemgetter(0), g) -... +... print(k, map(itemgetter(0), g)) +... 1 ['a', 'c', 'e'] 2 ['b', 'd', 'f'] 3 ['g'] @@ -803,8 +803,8 @@ # same group. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): -... print map(operator.itemgetter(1), g) -... +... print(map(operator.itemgetter(1), g)) +... [1] [4, 5, 6] [10] Modified: python/branches/p3yk/Lib/test/test_syntax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_syntax.py (original) +++ python/branches/p3yk/Lib/test/test_syntax.py Fri Feb 9 21:13:25 2007 @@ -247,7 +247,7 @@ ... finally: ... for abc in range(10): ... continue - ... print abc + ... print(abc) >>> test() 9 @@ -328,11 +328,11 @@ isn't, there should be a syntax error. >>> try: - ... print 1 + ... print(1) ... break - ... print 2 + ... print(2) ... finally: - ... print 3 + ... print(3) Traceback (most recent call last): ... SyntaxError: 'break' outside loop (, line 3) Modified: python/branches/p3yk/Lib/test/test_urllib2.py ============================================================================== --- python/branches/p3yk/Lib/test/test_urllib2.py (original) +++ python/branches/p3yk/Lib/test/test_urllib2.py Fri Feb 9 21:13:25 2007 @@ -101,7 +101,7 @@ >>> r.has_header("Not-there") False - >>> print r.get_header("Not-there") + >>> print(r.get_header("Not-there")) None >>> r.get_header("Not-there", "default") 'default' 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 Fri Feb 9 21:13:25 2007 @@ -1072,7 +1072,7 @@ ... >>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable >>> r = weakref.ref(obj) ->>> print r() is obj +>>> print(r() is obj) True >>> import weakref @@ -1085,7 +1085,7 @@ >>> o is o2 True >>> del o, o2 ->>> print r() +>>> print(r()) None >>> import weakref @@ -1140,9 +1140,9 @@ >>> try: ... id2obj(a_id) ... except KeyError: -... print 'OK' +... print('OK') ... else: -... print 'WeakValueDictionary error' +... print('WeakValueDictionary error') OK """ Modified: python/branches/p3yk/Lib/test/test_xml_etree.py ============================================================================== --- python/branches/p3yk/Lib/test/test_xml_etree.py (original) +++ python/branches/p3yk/Lib/test/test_xml_etree.py Fri Feb 9 21:13:25 2007 @@ -184,9 +184,9 @@ >>> element = ET.fromstring("text") >>> ET.ElementTree(element).write(sys.stdout) text - >>> print ET.tostring(element) + >>> print(ET.tostring(element)) text - >>> print ET.tostring(element, "ascii") + >>> print(ET.tostring(element, "ascii")) text >>> _, ids = ET.XMLID("text") @@ -301,7 +301,7 @@ >>> document = xinclude_loader("C1.xml") >>> ElementInclude.include(document, xinclude_loader) - >>> print serialize(ET, document) # C1 + >>> print(serialize(ET, document)) # C1

120 Mz is adequate for an average home user.

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

This document has been accessed 324387 times.

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

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

<?xml version='1.0'?> Modified: python/branches/p3yk/Lib/test/test_xml_etree_c.py ============================================================================== --- python/branches/p3yk/Lib/test/test_xml_etree_c.py (original) +++ python/branches/p3yk/Lib/test/test_xml_etree_c.py Fri Feb 9 21:13:25 2007 @@ -176,9 +176,9 @@ >>> element = ET.fromstring("text") >>> ET.ElementTree(element).write(sys.stdout) text - >>> print ET.tostring(element) + >>> print(ET.tostring(element)) text - >>> print ET.tostring(element, "ascii") + >>> print(ET.tostring(element, "ascii")) text >>> _, ids = ET.XMLID("text") From python-3000-checkins at python.org Fri Feb 9 21:33:44 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 21:33:44 +0100 (CET) Subject: [Python-3000-checkins] r53702 - python/branches/p3yk/Lib/Cookie.py python/branches/p3yk/Lib/difflib.py Message-ID: <20070209203344.E05831E4012@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 21:33:44 2007 New Revision: 53702 Modified: python/branches/p3yk/Lib/Cookie.py python/branches/p3yk/Lib/difflib.py Log: Revert doubly-converted doctests. Modified: python/branches/p3yk/Lib/Cookie.py ============================================================================== --- python/branches/p3yk/Lib/Cookie.py (original) +++ python/branches/p3yk/Lib/Cookie.py Fri Feb 9 21:33:44 2007 @@ -80,9 +80,9 @@ >>> C = Cookie.SmartCookie() >>> C["rocky"] = "road" >>> C["rocky"]["path"] = "/cookie" - >>> print((C.output(header="Cookie:"))) + >>> print(C.output(header="Cookie:")) Cookie: rocky=road; Path=/cookie - >>> print((C.output(attrs=[], header="Cookie:"))) + >>> print(C.output(attrs=[], header="Cookie:")) Cookie: rocky=road The load() method of a Cookie extracts cookies from a string. In a @@ -100,7 +100,7 @@ >>> C = Cookie.SmartCookie() >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') - >>> print((C)) + >>> print(C) Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" Each element of the Cookie also supports all of the RFC 2109 @@ -110,7 +110,7 @@ >>> C = Cookie.SmartCookie() >>> C["oreo"] = "doublestuff" >>> C["oreo"]["path"] = "/" - >>> print((C)) + >>> print(C) Set-Cookie: oreo=doublestuff; Path=/ Each dictionary element has a 'value' attribute, which gives you @@ -198,7 +198,7 @@ fact, this simply returns a SmartCookie. >>> C = Cookie.Cookie() - >>> print((C.__class__.__name__)) + >>> print(C.__class__.__name__) SmartCookie Modified: python/branches/p3yk/Lib/difflib.py ============================================================================== --- python/branches/p3yk/Lib/difflib.py (original) +++ python/branches/p3yk/Lib/difflib.py Fri Feb 9 21:33:44 2007 @@ -76,7 +76,7 @@ sequences. As a rule of thumb, a .ratio() value over 0.6 means the sequences are close matches: - >>> print((round(s.ratio(), 3))) + >>> print(round(s.ratio(), 3)) 0.866 >>> @@ -84,7 +84,7 @@ .get_matching_blocks() is handy: >>> for block in s.get_matching_blocks(): - ... print(("a[%d] and b[%d] match for %d elements" % block)) + ... print("a[%d] and b[%d] match for %d elements" % block) a[0] and b[0] match for 8 elements a[8] and b[17] match for 21 elements a[29] and b[38] match for 0 elements @@ -97,7 +97,7 @@ use .get_opcodes(): >>> for opcode in s.get_opcodes(): - ... print(("%6s a[%d:%d] b[%d:%d]" % opcode)) + ... print("%6s a[%d:%d] b[%d:%d]" % opcode) equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:29] b[17:38] @@ -545,8 +545,8 @@ >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): - ... print((("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % - ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))) + ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % + ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) @@ -1059,8 +1059,8 @@ >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n', ... ' ^ ^ ^ ', '+ ^ ^ ^ ') - >>> for line in results: print((repr(line))) - ... + >>> for line in results: print(repr(line)) + ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' '+ \t\tabcdefGhijkl\n' @@ -1165,7 +1165,7 @@ ... 'zero one tree four'.split(), 'Original', 'Current', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003', ... lineterm=''): - ... print((line)) + ... print(line) --- Original Sat Jan 26 23:30:50 1991 +++ Current Fri Jun 06 10:20:52 2003 @@ -1,4 +1,4 @@ From python-3000-checkins at python.org Fri Feb 9 21:50:08 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 21:50:08 +0100 (CET) Subject: [Python-3000-checkins] r53703 - python/branches/p3yk/Lib/test/regrtest.py Message-ID: <20070209205008.CE44C1E401C@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 21:50:08 2007 New Revision: 53703 Modified: python/branches/p3yk/Lib/test/regrtest.py Log: Fix an unfortunate mis-conversion: sometimes "print x," must be converted to "print(x, end=' ')", but other times it must be converted to "print(x, end='')". There's no easy way to find out, because it depends on whether x ends with a newline. I'm sure I'll find more like this. Modified: python/branches/p3yk/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk/Lib/test/regrtest.py (original) +++ python/branches/p3yk/Lib/test/regrtest.py Fri Feb 9 21:50:08 2007 @@ -738,19 +738,19 @@ elif op == 'delete': print("***", pair(a0, a1), "of expected output missing:") for line in a[a0:a1]: - print("-", line, end=' ') + print("-", line, end='') elif op == 'replace': print("*** mismatch between", pair(a0, a1), "of expected", \ "output and", pair(b0, b1), "of actual output:") for line in difflib.ndiff(a[a0:a1], b[b0:b1]): - print(line, end=' ') + print(line, end='') elif op == 'insert': print("***", pair(b0, b1), "of actual output doesn't appear", \ "in expected output after line", str(a1)+":") for line in b[b0:b1]: - print("+", line, end=' ') + print("+", line, end='') else: print("get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1)) From python-3000-checkins at python.org Fri Feb 9 22:28:13 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Fri, 9 Feb 2007 22:28:13 +0100 (CET) Subject: [Python-3000-checkins] r53704 - in python/branches/p3yk: Doc/lib/libdis.tex Doc/ref/ref6.tex Include/Python-ast.h Include/opcode.h Lib/compiler/ast.py Lib/compiler/pyassem.py Lib/compiler/pycodegen.py Lib/compiler/transformer.py Lib/opcode.py Lib/symbol.py Lib/test/test_ast.py Lib/test/test_class.py Lib/test/test_code.py Lib/test/test_descrtut.py Lib/test/test_dis.py Lib/test/test_extcall.py Lib/test/test_parser.py Lib/test/test_pkg.py Lib/test/test_popen.py Lib/test/test_subprocess.py Lib/test/test_syntax.py Lib/test/test_tokenize.py Lib/test/test_traceback.py Parser/Python.asdl Python/Python-ast.c Python/bltinmodule.c Python/ceval.c Python/compile.c Python/symtable.c Python/sysmodule.c Tools/compiler/ast.txt Message-ID: <20070209212813.61B5D1E4012@bag.python.org> Author: georg.brandl Date: Fri Feb 9 22:28:07 2007 New Revision: 53704 Modified: python/branches/p3yk/Doc/lib/libdis.tex python/branches/p3yk/Doc/ref/ref6.tex python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Include/opcode.h python/branches/p3yk/Lib/compiler/ast.py python/branches/p3yk/Lib/compiler/pyassem.py python/branches/p3yk/Lib/compiler/pycodegen.py python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/opcode.py python/branches/p3yk/Lib/symbol.py python/branches/p3yk/Lib/test/test_ast.py python/branches/p3yk/Lib/test/test_class.py python/branches/p3yk/Lib/test/test_code.py python/branches/p3yk/Lib/test/test_descrtut.py python/branches/p3yk/Lib/test/test_dis.py python/branches/p3yk/Lib/test/test_extcall.py python/branches/p3yk/Lib/test/test_parser.py python/branches/p3yk/Lib/test/test_pkg.py python/branches/p3yk/Lib/test/test_popen.py python/branches/p3yk/Lib/test/test_subprocess.py python/branches/p3yk/Lib/test/test_syntax.py python/branches/p3yk/Lib/test/test_tokenize.py python/branches/p3yk/Lib/test/test_traceback.py python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/bltinmodule.c python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/compile.c python/branches/p3yk/Python/symtable.c python/branches/p3yk/Python/sysmodule.c python/branches/p3yk/Tools/compiler/ast.txt Log: * Remove PRINT_ITEM(_TO), PRINT_NEWLINE(_TO) opcodes. * Fix some docstrings and one Print -> print. * Fix test_{class,code,descrtut,dis,extcall,parser,popen,pkg,subprocess,syntax,traceback}. These were the ones that generated code with a print statement. In most remaining failing tests there's an issue with the soft space. Modified: python/branches/p3yk/Doc/lib/libdis.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libdis.tex (original) +++ python/branches/p3yk/Doc/lib/libdis.tex Fri Feb 9 22:28:07 2007 @@ -353,27 +353,6 @@ expression statement is terminated with \code{POP_STACK}. \end{opcodedesc} -\begin{opcodedesc}{PRINT_ITEM}{} -Prints TOS to the file-like object bound to \code{sys.stdout}. There -is one such instruction for each item in the \keyword{print} statement. -\end{opcodedesc} - -\begin{opcodedesc}{PRINT_ITEM_TO}{} -Like \code{PRINT_ITEM}, but prints the item second from TOS to the -file-like object at TOS. This is used by the extended print statement. -\end{opcodedesc} - -\begin{opcodedesc}{PRINT_NEWLINE}{} -Prints a new line on \code{sys.stdout}. This is generated as the -last operation of a \keyword{print} statement, unless the statement -ends with a comma. -\end{opcodedesc} - -\begin{opcodedesc}{PRINT_NEWLINE_TO}{} -Like \code{PRINT_NEWLINE}, but prints the new line on the file-like -object on the TOS. This is used by the extended print statement. -\end{opcodedesc} - \begin{opcodedesc}{BREAK_LOOP}{} Terminates a loop due to a \keyword{break} statement. \end{opcodedesc} Modified: python/branches/p3yk/Doc/ref/ref6.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref6.tex (original) +++ python/branches/p3yk/Doc/ref/ref6.tex Fri Feb 9 22:28:07 2007 @@ -12,7 +12,6 @@ \productioncont{| \token{augmented_assignment_stmt}} \productioncont{| \token{pass_stmt}} \productioncont{| \token{del_stmt}} - \productioncont{| \token{print_stmt}} \productioncont{| \token{return_stmt}} \productioncont{| \token{yield_stmt}} \productioncont{| \token{raise_stmt}} @@ -370,60 +369,6 @@ \indexii{attribute}{deletion} -\section{The \keyword{print} statement \label{print}} -\stindex{print} - -\begin{productionlist} - \production{print_stmt} - {"print" ( \optional{\token{expression} ("," \token{expression})* \optional{","}}} - \productioncont{| ">>" \token{expression} - \optional{("," \token{expression})+ \optional{","}} )} -\end{productionlist} - -\keyword{print} evaluates each expression in turn and writes the -resulting object to standard output (see below). If an object is not -a string, it is first converted to a string using the rules for string -conversions. The (resulting or original) string is then written. A -space is written before each object is (converted and) written, unless -the output system believes it is positioned at the beginning of a -line. This is the case (1) when no characters have yet been written -to standard output, (2) when the last character written to standard -output is \character{\e n}, or (3) when the last write operation on -standard output was not a \keyword{print} statement. (In some cases -it may be functional to write an empty string to standard output for -this reason.) \note{Objects which act like file objects but which are -not the built-in file objects often do not properly emulate this -aspect of the file object's behavior, so it is best not to rely on -this.} -\index{output} -\indexii{writing}{values} - -A \character{\e n} character is written at the end, unless the -\keyword{print} statement ends with a comma. This is the only action -if the statement contains just the keyword \keyword{print}. -\indexii{trailing}{comma} -\indexii{newline}{suppression} - -Standard output is defined as the file object named \code{stdout} -in the built-in module \module{sys}. If no such object exists, or if -it does not have a \method{write()} method, a \exception{RuntimeError} -exception is raised. -\indexii{standard}{output} -\refbimodindex{sys} -\withsubitem{(in module sys)}{\ttindex{stdout}} -\exindex{RuntimeError} - -\keyword{print} also has an extended\index{extended print statement} -form, defined by the second portion of the syntax described above. -This form is sometimes referred to as ``\keyword{print} chevron.'' -In this form, the first expression after the \code{>>} must -evaluate to a ``file-like'' object, specifically an object that has a -\method{write()} method as described above. With this extended form, -the subsequent expressions are printed to this file object. If the -first expression evaluates to \code{None}, then \code{sys.stdout} is -used as the file for output. - - \section{The \keyword{return} statement \label{return}} \stindex{return} Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Fri Feb 9 22:28:07 2007 @@ -62,12 +62,11 @@ }; enum _stmt_kind {FunctionDef_kind=1, ClassDef_kind=2, Return_kind=3, - Delete_kind=4, Assign_kind=5, AugAssign_kind=6, Print_kind=7, - For_kind=8, While_kind=9, If_kind=10, With_kind=11, - Raise_kind=12, TryExcept_kind=13, TryFinally_kind=14, - Assert_kind=15, Import_kind=16, ImportFrom_kind=17, - Global_kind=18, Expr_kind=19, Pass_kind=20, Break_kind=21, - Continue_kind=22}; + Delete_kind=4, Assign_kind=5, AugAssign_kind=6, For_kind=7, + While_kind=8, If_kind=9, With_kind=10, Raise_kind=11, + TryExcept_kind=12, TryFinally_kind=13, Assert_kind=14, + Import_kind=15, ImportFrom_kind=16, Global_kind=17, + Expr_kind=18, Pass_kind=19, Break_kind=20, Continue_kind=21}; struct _stmt { enum _stmt_kind kind; union { @@ -105,12 +104,6 @@ } AugAssign; struct { - expr_ty dest; - asdl_seq *values; - bool nl; - } Print; - - struct { expr_ty target; expr_ty iter; asdl_seq *body; @@ -392,9 +385,6 @@ #define AugAssign(a0, a1, a2, a3, a4, a5) _Py_AugAssign(a0, a1, a2, a3, a4, a5) stmt_ty _Py_AugAssign(expr_ty target, operator_ty op, expr_ty value, int lineno, int col_offset, PyArena *arena); -#define Print(a0, a1, a2, a3, a4, a5) _Py_Print(a0, a1, a2, a3, a4, a5) -stmt_ty _Py_Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int - col_offset, PyArena *arena); #define For(a0, a1, a2, a3, a4, a5, a6) _Py_For(a0, a1, a2, a3, a4, a5, a6) stmt_ty _Py_For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena); Modified: python/branches/p3yk/Include/opcode.h ============================================================================== --- python/branches/p3yk/Include/opcode.h (original) +++ python/branches/p3yk/Include/opcode.h Fri Feb 9 22:28:07 2007 @@ -61,10 +61,7 @@ #define GET_ITER 68 #define PRINT_EXPR 70 -#define PRINT_ITEM 71 -#define PRINT_NEWLINE 72 -#define PRINT_ITEM_TO 73 -#define PRINT_NEWLINE_TO 74 + #define INPLACE_LSHIFT 75 #define INPLACE_RSHIFT 76 #define INPLACE_AND 77 Modified: python/branches/p3yk/Lib/compiler/ast.py ============================================================================== --- python/branches/p3yk/Lib/compiler/ast.py (original) +++ python/branches/p3yk/Lib/compiler/ast.py Fri Feb 9 22:28:07 2007 @@ -998,50 +998,6 @@ def __repr__(self): return "Power((%s, %s))" % (repr(self.left), repr(self.right)) -class Print(Node): - def __init__(self, nodes, dest, lineno=None): - self.nodes = nodes - self.dest = dest - self.lineno = lineno - - def getChildren(self): - children = [] - children.extend(flatten(self.nodes)) - children.append(self.dest) - return tuple(children) - - def getChildNodes(self): - nodelist = [] - nodelist.extend(flatten_nodes(self.nodes)) - if self.dest is not None: - nodelist.append(self.dest) - return tuple(nodelist) - - def __repr__(self): - return "Print(%s, %s)" % (repr(self.nodes), repr(self.dest)) - -class Printnl(Node): - def __init__(self, nodes, dest, lineno=None): - self.nodes = nodes - self.dest = dest - self.lineno = lineno - - def getChildren(self): - children = [] - children.extend(flatten(self.nodes)) - children.append(self.dest) - return tuple(children) - - def getChildNodes(self): - nodelist = [] - nodelist.extend(flatten_nodes(self.nodes)) - if self.dest is not None: - nodelist.append(self.dest) - return tuple(nodelist) - - def __repr__(self): - return "Printnl(%s, %s)" % (repr(self.nodes), repr(self.dest)) - class Raise(Node): def __init__(self, expr1, expr2, expr3, lineno=None): self.expr1 = expr1 Modified: python/branches/p3yk/Lib/compiler/pyassem.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pyassem.py (original) +++ python/branches/p3yk/Lib/compiler/pyassem.py Fri Feb 9 22:28:07 2007 @@ -783,8 +783,7 @@ 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, - # PRINT_EXPR? - 'PRINT_ITEM': -1, + 'PRINT_EXPR': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'BUILD_CLASS': -2, Modified: python/branches/p3yk/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk/Lib/compiler/pycodegen.py Fri Feb 9 22:28:07 2007 @@ -1130,29 +1130,6 @@ opcode = callfunc_opcode_info[have_star, have_dstar] self.emit(opcode, kw << 8 | pos) - def visitPrint(self, node, newline=0): - self.set_lineno(node) - if node.dest: - self.visit(node.dest) - for child in node.nodes: - if node.dest: - self.emit('DUP_TOP') - self.visit(child) - if node.dest: - self.emit('ROT_TWO') - self.emit('PRINT_ITEM_TO') - else: - self.emit('PRINT_ITEM') - if node.dest and not newline: - self.emit('POP_TOP') - - def visitPrintnl(self, node): - self.visitPrint(node, newline=1) - if node.dest: - self.emit('PRINT_NEWLINE_TO') - else: - self.emit('PRINT_NEWLINE') - def visitReturn(self, node): self.set_lineno(node) self.visit(node.value) Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Fri Feb 9 22:28:07 2007 @@ -387,26 +387,6 @@ return AugAssign(lval, op[1], exprNode, lineno=op[2]) raise WalkerError, "can't get here" - def print_stmt(self, nodelist): - # print ([ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ]) - items = [] - if len(nodelist) == 1: - start = 1 - dest = None - elif nodelist[1][0] == token.RIGHTSHIFT: - assert len(nodelist) == 3 \ - or nodelist[3][0] == token.COMMA - dest = self.com_node(nodelist[2]) - start = 4 - else: - dest = None - start = 1 - for i in range(start, len(nodelist), 2): - items.append(self.com_node(nodelist[i])) - if nodelist[-1][0] == token.COMMA: - return Print(items, dest, lineno=nodelist[0][2]) - return Printnl(items, dest, lineno=nodelist[0][2]) - def del_stmt(self, nodelist): return self.com_assign(nodelist[1], OP_DELETE) @@ -1480,7 +1460,6 @@ symbol.simple_stmt, symbol.compound_stmt, symbol.expr_stmt, - symbol.print_stmt, symbol.del_stmt, symbol.pass_stmt, symbol.break_stmt, Modified: python/branches/p3yk/Lib/opcode.py ============================================================================== --- python/branches/p3yk/Lib/opcode.py (original) +++ python/branches/p3yk/Lib/opcode.py Fri Feb 9 22:28:07 2007 @@ -100,10 +100,7 @@ def_op('GET_ITER', 68) def_op('PRINT_EXPR', 70) -def_op('PRINT_ITEM', 71) -def_op('PRINT_NEWLINE', 72) -def_op('PRINT_ITEM_TO', 73) -def_op('PRINT_NEWLINE_TO', 74) + def_op('INPLACE_LSHIFT', 75) def_op('INPLACE_RSHIFT', 76) def_op('INPLACE_AND', 77) Modified: python/branches/p3yk/Lib/symbol.py ============================================================================== --- python/branches/p3yk/Lib/symbol.py (original) +++ python/branches/p3yk/Lib/symbol.py Fri Feb 9 22:28:07 2007 @@ -30,74 +30,73 @@ small_stmt = 273 expr_stmt = 274 augassign = 275 -print_stmt = 276 -del_stmt = 277 -pass_stmt = 278 -flow_stmt = 279 -break_stmt = 280 -continue_stmt = 281 -return_stmt = 282 -yield_stmt = 283 -raise_stmt = 284 -import_stmt = 285 -import_name = 286 -import_from = 287 -import_as_name = 288 -dotted_as_name = 289 -import_as_names = 290 -dotted_as_names = 291 -dotted_name = 292 -global_stmt = 293 -assert_stmt = 294 -compound_stmt = 295 -if_stmt = 296 -while_stmt = 297 -for_stmt = 298 -try_stmt = 299 -with_stmt = 300 -with_var = 301 -except_clause = 302 -suite = 303 -testlist_safe = 304 -old_test = 305 -old_lambdef = 306 -test = 307 -or_test = 308 -and_test = 309 -not_test = 310 -comparison = 311 -comp_op = 312 -expr = 313 -xor_expr = 314 -and_expr = 315 -shift_expr = 316 -arith_expr = 317 -term = 318 -factor = 319 -power = 320 -atom = 321 -listmaker = 322 -testlist_gexp = 323 -lambdef = 324 -trailer = 325 -subscriptlist = 326 -subscript = 327 -sliceop = 328 -exprlist = 329 -testlist = 330 -dictsetmaker = 331 -classdef = 332 -arglist = 333 -argument = 334 -list_iter = 335 -list_for = 336 -list_if = 337 -gen_iter = 338 -gen_for = 339 -gen_if = 340 -testlist1 = 341 -encoding_decl = 342 -yield_expr = 343 +del_stmt = 276 +pass_stmt = 277 +flow_stmt = 278 +break_stmt = 279 +continue_stmt = 280 +return_stmt = 281 +yield_stmt = 282 +raise_stmt = 283 +import_stmt = 284 +import_name = 285 +import_from = 286 +import_as_name = 287 +dotted_as_name = 288 +import_as_names = 289 +dotted_as_names = 290 +dotted_name = 291 +global_stmt = 292 +assert_stmt = 293 +compound_stmt = 294 +if_stmt = 295 +while_stmt = 296 +for_stmt = 297 +try_stmt = 298 +with_stmt = 299 +with_var = 300 +except_clause = 301 +suite = 302 +testlist_safe = 303 +old_test = 304 +old_lambdef = 305 +test = 306 +or_test = 307 +and_test = 308 +not_test = 309 +comparison = 310 +comp_op = 311 +expr = 312 +xor_expr = 313 +and_expr = 314 +shift_expr = 315 +arith_expr = 316 +term = 317 +factor = 318 +power = 319 +atom = 320 +listmaker = 321 +testlist_gexp = 322 +lambdef = 323 +trailer = 324 +subscriptlist = 325 +subscript = 326 +sliceop = 327 +exprlist = 328 +testlist = 329 +dictsetmaker = 330 +classdef = 331 +arglist = 332 +argument = 333 +list_iter = 334 +list_for = 335 +list_if = 336 +gen_iter = 337 +gen_for = 338 +gen_if = 339 +testlist1 = 340 +encoding_decl = 341 +yield_expr = 342 #--end constants-- sym_name = {} Modified: python/branches/p3yk/Lib/test/test_ast.py ============================================================================== --- python/branches/p3yk/Lib/test/test_ast.py (original) +++ python/branches/p3yk/Lib/test/test_ast.py Fri Feb 9 22:28:07 2007 @@ -30,8 +30,6 @@ "v = 1", # AugAssign "v += 1", - # Print - "print >>f, 1, ", # For "for v in v:pass", # While @@ -157,7 +155,6 @@ ('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]), ('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]), ('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]), -('Module', [('Print', (1, 0), ('Name', (1, 8), 'f', ('Load',)), [('Num', (1, 11), 1)], False)]), ('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]), ('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]), ('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]), Modified: python/branches/p3yk/Lib/test/test_class.py ============================================================================== --- python/branches/p3yk/Lib/test/test_class.py (original) +++ python/branches/p3yk/Lib/test/test_class.py Fri Feb 9 22:28:07 2007 @@ -127,7 +127,7 @@ method_template = """\ def __%(method)s__(self, *args): - print "__%(method)s__:", args + print("__%(method)s__:", args) """ d = {} Modified: python/branches/p3yk/Lib/test/test_code.py ============================================================================== --- python/branches/p3yk/Lib/test/test_code.py (original) +++ python/branches/p3yk/Lib/test/test_code.py Fri Feb 9 22:28:07 2007 @@ -58,7 +58,7 @@ name: attrs argcount: 1 kwonlyargcount: 0 -names: ('attr1', 'attr2', 'attr3') +names: ('print', 'attr1', 'attr2', 'attr3') varnames: ('obj',) cellvars: () freevars: () Modified: python/branches/p3yk/Lib/test/test_descrtut.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descrtut.py (original) +++ python/branches/p3yk/Lib/test/test_descrtut.py Fri Feb 9 22:28:07 2007 @@ -36,28 +36,28 @@ Here's the new type at work: - >>> print(defaultdict) # show our type + >>> print(defaultdict) # show our type - >>> print(type(defaultdict)) # its metatype + >>> print(type(defaultdict)) # its metatype >>> a = defaultdict(default=0.0) # create an instance - >>> print(a) # show the instance + >>> print(a) # show the instance {} - >>> print(type(a)) # show its type + >>> print(type(a)) # show its type - >>> print(a.__class__) # show its class + >>> print(a.__class__) # show its class - >>> print(type(a) is a.__class__) # its type is its class + >>> print(type(a) is a.__class__) # its type is its class True >>> a[1] = 3.25 # modify the instance - >>> print(a) # show the new value + >>> print(a) # show the new value {1: 3.25} - >>> print(a[1]) # show the new item + >>> print(a[1]) # show the new item 3.25 - >>> print(a[0]) # a non-existant item + >>> print(a[0]) # a non-existant item 0.0 >>> a.merge({1:100, 2:200}) # use a dict method - >>> print(sortdict(a)) # show the result + >>> print(sortdict(a)) # show the result {1: 3.25, 2: 200} >>> @@ -67,10 +67,11 @@ >>> print(sorted(a.keys())) [1, 2] - >>> exec("x = 3; print x", a) + >>> a['print'] = print # need the print function here + >>> exec("x = 3; print(x)", a) 3 >>> print(sorted(a.keys(), key=lambda x: (str(type(x)), x))) - [1, 2, '__builtins__', 'x'] + [1, 2, '__builtins__', 'print', 'x'] >>> print(a['x']) 3 >>> Modified: python/branches/p3yk/Lib/test/test_dis.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dis.py (original) +++ python/branches/p3yk/Lib/test/test_dis.py Fri Feb 9 22:28:07 2007 @@ -12,12 +12,13 @@ return 1 dis_f = """\ - %-4d 0 LOAD_FAST 0 (a) - 3 PRINT_ITEM - 4 PRINT_NEWLINE + %-4d 0 LOAD_GLOBAL 0 (print) + 3 LOAD_FAST 0 (a) + 6 CALL_FUNCTION 1 + 9 POP_TOP - %-4d 5 LOAD_CONST 1 (1) - 8 RETURN_VALUE + %-4d 10 LOAD_CONST 1 (1) + 13 RETURN_VALUE """%(_f.func_code.co_firstlineno + 1, _f.func_code.co_firstlineno + 2) Modified: python/branches/p3yk/Lib/test/test_extcall.py ============================================================================== --- python/branches/p3yk/Lib/test/test_extcall.py (original) +++ python/branches/p3yk/Lib/test/test_extcall.py Fri Feb 9 22:28:07 2007 @@ -260,8 +260,8 @@ lambda x: '%s="%s"' % (x, x), defargs) if vararg: arglist.append('*' + vararg) if kwarg: arglist.append('**' + kwarg) - decl = (('def %s(%s): print "ok %s", a, b, d, e, v, ' + - 'type(k) is type ("") and k or sortdict(k)') + decl = (('def %s(%s): print("ok %s", a, b, d, e, v, ' + + 'type(k) is type ("") and k or sortdict(k))') % (name, ', '.join(arglist), name)) exec(decl) func = eval(name) Modified: python/branches/p3yk/Lib/test/test_parser.py ============================================================================== --- python/branches/p3yk/Lib/test/test_parser.py (original) +++ python/branches/p3yk/Lib/test/test_parser.py Fri Feb 9 22:28:07 2007 @@ -85,14 +85,6 @@ self.check_expr("(x for x in range(10))") self.check_expr("foo(x for x in range(10))") - def test_print(self): - self.check_suite("print") - self.check_suite("print 1") - self.check_suite("print 1,") - self.check_suite("print >>fp") - self.check_suite("print >>fp, 1") - self.check_suite("print >>fp, 1,") - def test_simple_expression(self): # expr_stmt self.check_suite("a") @@ -359,29 +351,6 @@ (0, '')))) self.check_bad_tree(tree, "def f():\n return 1\n yield 1") - def test_print_chevron_comma(self): - # Illegal input: print >>fp, - tree = \ - (257, - (264, - (265, - (266, - (268, - (1, 'print'), - (35, '>>'), - (290, - (291, - (292, - (293, - (295, - (296, - (297, - (298, (299, (300, (301, (302, (303, (1, 'fp')))))))))))))), - (12, ','))), - (4, ''))), - (0, '')) - self.check_bad_tree(tree, "print >>fp,") - def test_a_comma_comma_c(self): # Illegal input: a,,c tree = \ Modified: python/branches/p3yk/Lib/test/test_pkg.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pkg.py (original) +++ python/branches/p3yk/Lib/test/test_pkg.py Fri Feb 9 22:28:07 2007 @@ -81,122 +81,122 @@ ("t2", [ ("t2", None), - ("t2 __init__"+os.extsep+"py", "'doc for t2'; print __name__, 'loading'"), + ("t2 __init__"+os.extsep+"py", "'doc for t2'; print(__name__, 'loading')"), ("t2 sub", None), ("t2 sub __init__"+os.extsep+"py", ""), ("t2 sub subsub", None), - ("t2 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t2 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ], """ import t2 -print t2.__doc__ +print(t2.__doc__) import t2.sub import t2.sub.subsub -print t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__ +print(t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__) import t2 from t2 import * -print dir() +print(dir()) from t2 import sub from t2.sub import subsub from t2.sub.subsub import spam -print sub.__name__, subsub.__name__ -print sub.subsub.__name__ -print dir() +print(sub.__name__, subsub.__name__) +print(sub.subsub.__name__) +print(dir()) import t2.sub import t2.sub.subsub -print t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__ +print(t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__) from t2 import * -print dir() +print(dir()) """), ("t3", [ ("t3", None), - ("t3 __init__"+os.extsep+"py", "print __name__, 'loading'"), + ("t3 __init__"+os.extsep+"py", "print(__name__, 'loading')"), ("t3 sub", None), ("t3 sub __init__"+os.extsep+"py", ""), ("t3 sub subsub", None), - ("t3 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t3 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ], """ import t3.sub.subsub -print t3.__name__, t3.sub.__name__, t3.sub.subsub.__name__ +print(t3.__name__, t3.sub.__name__, t3.sub.subsub.__name__) reload(t3) reload(t3.sub) reload(t3.sub.subsub) """), ("t4", [ - ("t4"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (t4"+os.extsep+"py)'"), + ("t4"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (t4"+os.extsep+"py)')"), ("t4", None), - ("t4 __init__"+os.extsep+"py", "print __name__, 'loading'"), - ("t4 sub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)'"), + ("t4 __init__"+os.extsep+"py", "print(__name__, 'loading')"), + ("t4 sub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)')"), ("t4 sub", None), ("t4 sub __init__"+os.extsep+"py", ""), - ("t4 sub subsub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)'"), + ("t4 sub subsub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)')"), ("t4 sub subsub", None), - ("t4 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t4 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ], """ from t4.sub.subsub import * -print "t4.sub.subsub.spam =", spam +print("t4.sub.subsub.spam =", spam) """), ("t5", [ ("t5", None), ("t5 __init__"+os.extsep+"py", "import t5.foo"), - ("t5 string"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t5 string"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ("t5 foo"+os.extsep+"py", - "print __name__, 'loading'; from . import string; print string.spam"), + "print(__name__, 'loading'); from . import string; print(string.spam)"), ], """ import t5 from t5 import * -print dir() +print(dir()) import t5 -print fixdir(dir(t5)) -print fixdir(dir(t5.foo)) -print fixdir(dir(t5.string)) +print(fixdir(dir(t5))) +print(fixdir(dir(t5.foo))) +print(fixdir(dir(t5.string))) """), ("t6", [ ("t6", None), ("t6 __init__"+os.extsep+"py", "__all__ = ['spam', 'ham', 'eggs']"), - ("t6 spam"+os.extsep+"py", "print __name__, 'loading'"), - ("t6 ham"+os.extsep+"py", "print __name__, 'loading'"), - ("t6 eggs"+os.extsep+"py", "print __name__, 'loading'"), + ("t6 spam"+os.extsep+"py", "print(__name__, 'loading')"), + ("t6 ham"+os.extsep+"py", "print(__name__, 'loading')"), + ("t6 eggs"+os.extsep+"py", "print(__name__, 'loading')"), ], """ import t6 -print fixdir(dir(t6)) +print(fixdir(dir(t6))) from t6 import * -print fixdir(dir(t6)) -print dir() +print(fixdir(dir(t6))) +print(dir()) """), ("t7", [ - ("t7"+os.extsep+"py", "print 'Importing t7"+os.extsep+"py'"), + ("t7"+os.extsep+"py", "print('Importing t7"+os.extsep+"py')"), ("t7", None), - ("t7 __init__"+os.extsep+"py", "print __name__, 'loading'"), - ("t7 sub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)'"), + ("t7 __init__"+os.extsep+"py", "print(__name__, 'loading')"), + ("t7 sub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)')"), ("t7 sub", None), ("t7 sub __init__"+os.extsep+"py", ""), - ("t7 sub subsub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)'"), + ("t7 sub subsub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)')"), ("t7 sub subsub", None), - ("t7 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"), + ("t7 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"), ], """ t7, sub, subsub = None, None, None import t7 as tas -print fixdir(dir(tas)) +print(fixdir(dir(tas))) verify(not t7) from t7 import sub as subpar -print fixdir(dir(subpar)) +print(fixdir(dir(subpar))) verify(not t7 and not sub) from t7.sub import subsub as subsubsub -print fixdir(dir(subsubsub)) +print(fixdir(dir(subsubsub))) verify(not t7 and not sub and not subsub) from t7.sub.subsub import spam as ham -print "t7.sub.subsub.spam =", ham +print("t7.sub.subsub.spam =", ham) verify(not t7 and not sub and not subsub) """), Modified: python/branches/p3yk/Lib/test/test_popen.py ============================================================================== --- python/branches/p3yk/Lib/test/test_popen.py (original) +++ python/branches/p3yk/Lib/test/test_popen.py Fri Feb 9 22:28:07 2007 @@ -19,7 +19,7 @@ class PopenTest(unittest.TestCase): def _do_test_commandline(self, cmdline, expected): - cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline) + cmd = '%s -c "import sys; print(sys.argv)" %s' % (python, cmdline) data = os.popen(cmd).read() got = eval(data)[1:] # strip off argv[0] self.assertEqual(got, expected) Modified: python/branches/p3yk/Lib/test/test_subprocess.py ============================================================================== --- python/branches/p3yk/Lib/test/test_subprocess.py (original) +++ python/branches/p3yk/Lib/test/test_subprocess.py Fri Feb 9 22:28:07 2007 @@ -84,7 +84,7 @@ def test_stdin_none(self): # .stdin is None when not redirected - p = subprocess.Popen([sys.executable, "-c", 'print "banana"'], + p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() self.assertEqual(p.stdin, None) @@ -92,16 +92,16 @@ def test_stdout_none(self): # .stdout is None when not redirected p = subprocess.Popen([sys.executable, "-c", - 'print " this bit of output is from a ' + 'print(" this bit of output is from a ' 'test of stdout in a different ' - 'process ..."'], + 'process ...")'], stdin=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() self.assertEqual(p.stdout, None) def test_stderr_none(self): # .stderr is None when not redirected - p = subprocess.Popen([sys.executable, "-c", 'print "banana"'], + p = subprocess.Popen([sys.executable, "-c", 'print("banana")'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) p.wait() self.assertEqual(p.stderr, None) Modified: python/branches/p3yk/Lib/test/test_syntax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_syntax.py (original) +++ python/branches/p3yk/Lib/test/test_syntax.py Fri Feb 9 22:28:07 2007 @@ -423,7 +423,7 @@ source = re.sub('(?m)^ *:', '', """\ :def foo(x): : def bar(): - : print x + : print(x) : del x :""") self._check_error(source, "nested scope") Modified: python/branches/p3yk/Lib/test/test_tokenize.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tokenize.py (original) +++ python/branches/p3yk/Lib/test/test_tokenize.py Fri Feb 9 22:28:07 2007 @@ -43,9 +43,9 @@ There are some standard formatting practices that are easy to get right. >>> roundtrip("if x == 1:\\n" -... " print x\\n") +... " print(x)\\n") if x == 1: - print x + print(x) Some people use different formatting conventions, which makes untokenize a little trickier. Note that this test involves trailing @@ -53,29 +53,29 @@ two trailing blanks apparent in the expected output. >>> roundtrip("if x == 1 : \\n" -... " print x\\n") +... " print(x)\\n") if x == 1 :\x20\x20 - print x + print(x) Comments need to go in the right place. >>> roundtrip("if x == 1:\\n" ... " # A comment by itself.\\n" -... " print x # Comment here, too.\\n" +... " print(x) # Comment here, too.\\n" ... " # Another comment.\\n" ... "after_if = True\\n") if x == 1: # A comment by itself. - print x # Comment here, too. + print(x) # Comment here, too. # Another comment. after_if = True >>> roundtrip("if (x # The comments need to go in the right place\\n" ... " == 1):\\n" -... " print 'x == 1'\\n") +... " print('x == 1')\\n") if (x # The comments need to go in the right place == 1): - print 'x == 1' + print('x == 1') """ @@ -130,9 +130,9 @@ """Substitute Decimals for floats in a string of statements. >>> from decimal import Decimal - >>> s = 'print +21.3e-5*-.1234/81.7' + >>> s = 'print(+21.3e-5*-.1234/81.7)' >>> decistmt(s) - "print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')" + "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))" The format of the exponent is inherited from the platform C library. Known cases are "e-007" (Windows) and "e-07" (not Windows). Since Modified: python/branches/p3yk/Lib/test/test_traceback.py ============================================================================== --- python/branches/p3yk/Lib/test/test_traceback.py (original) +++ python/branches/p3yk/Lib/test/test_traceback.py Fri Feb 9 22:28:07 2007 @@ -25,7 +25,7 @@ import test.badsyntax_nocaret def syntax_error_bad_indentation(self): - compile("def spam():\n print 1\n print 2", "?", "exec") + compile("def spam():\n print(1)\n print(2)", "?", "exec") def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, @@ -48,9 +48,9 @@ err = self.get_exception_format(self.syntax_error_bad_indentation, IndentationError) self.assert_(len(err) == 4) - self.assert_(err[1].strip() == "print 2") + self.assert_(err[1].strip() == "print(2)") self.assert_("^" in err[2]) - self.assert_(err[1].find("2") == err[2].find("^")) + self.assert_(err[1].find(")") == err[2].find("^")) def test_bug737473(self): import sys, os, tempfile, time Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Fri Feb 9 22:28:07 2007 @@ -18,9 +18,6 @@ | Assign(expr* targets, expr value) | AugAssign(expr target, operator op, expr value) - -- not sure if bool is allowed, can always use int - | Print(expr? dest, expr* values, bool nl) - -- use 'orelse' because else is a keyword in target languages | For(expr target, expr iter, stmt* body, stmt* orelse) | While(expr test, stmt* body, stmt* orelse) Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Fri Feb 9 22:28:07 2007 @@ -61,12 +61,6 @@ "op", "value", }; -static PyTypeObject *Print_type; -static char *Print_fields[]={ - "dest", - "values", - "nl", -}; static PyTypeObject *For_type; static char *For_fields[]={ "target", @@ -480,8 +474,6 @@ if (!Assign_type) return 0; AugAssign_type = make_type("AugAssign", stmt_type, AugAssign_fields, 3); if (!AugAssign_type) return 0; - Print_type = make_type("Print", stmt_type, Print_fields, 3); - if (!Print_type) return 0; For_type = make_type("For", stmt_type, For_fields, 4); if (!For_type) return 0; While_type = make_type("While", stmt_type, While_fields, 3); @@ -949,25 +941,6 @@ } stmt_ty -Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int col_offset, - PyArena *arena) -{ - stmt_ty p; - p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); - return NULL; - } - p->kind = Print_kind; - p->v.Print.dest = dest; - p->v.Print.values = values; - p->v.Print.nl = nl; - p->lineno = lineno; - p->col_offset = col_offset; - return p; -} - -stmt_ty For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena) { @@ -2118,25 +2091,6 @@ goto failed; Py_DECREF(value); break; - case Print_kind: - result = PyType_GenericNew(Print_type, NULL, NULL); - if (!result) goto failed; - value = ast2obj_expr(o->v.Print.dest); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "dest", value) == -1) - goto failed; - Py_DECREF(value); - value = ast2obj_list(o->v.Print.values, ast2obj_expr); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "values", value) == -1) - goto failed; - Py_DECREF(value); - value = ast2obj_bool(o->v.Print.nl); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "nl", value) == -1) - goto failed; - Py_DECREF(value); - break; case For_kind: result = PyType_GenericNew(For_type, NULL, NULL); if (!result) goto failed; @@ -3149,7 +3103,6 @@ return; if (PyDict_SetItemString(d, "AugAssign", (PyObject*)AugAssign_type) < 0) return; - if (PyDict_SetItemString(d, "Print", (PyObject*)Print_type) < 0) return; if (PyDict_SetItemString(d, "For", (PyObject*)For_type) < 0) return; if (PyDict_SetItemString(d, "While", (PyObject*)While_type) < 0) return; if (PyDict_SetItemString(d, "If", (PyObject*)If_type) < 0) return; Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Fri Feb 9 22:28:07 2007 @@ -1398,7 +1398,7 @@ if (dummy_args == NULL) return NULL; - if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:Print", + if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print", kwlist, &sep, &end, &file)) return NULL; if (file == NULL || file == Py_None) Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Fri Feb 9 22:28:07 2007 @@ -524,7 +524,6 @@ register PyObject *w; register PyObject *u; register PyObject *t; - register PyObject *stream = NULL; /* for PRINT opcodes */ register PyObject **fastlocals, **freevars; PyObject *retval = NULL; /* Return value */ PyThreadState *tstate = PyThreadState_GET(); @@ -1508,81 +1507,6 @@ Py_XDECREF(x); break; - case PRINT_ITEM_TO: - w = stream = POP(); - /* fall through to PRINT_ITEM */ - - case PRINT_ITEM: - v = POP(); - if (stream == NULL || stream == Py_None) { - w = PySys_GetObject("stdout"); - if (w == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "lost sys.stdout"); - err = -1; - } - } - /* PyFile_SoftSpace() can exececute arbitrary code - if sys.stdout is an instance with a __getattr__. - If __getattr__ raises an exception, w will - be freed, so we need to prevent that temporarily. */ - Py_XINCREF(w); - if (w != NULL && PyFile_SoftSpace(w, 0)) - err = PyFile_WriteString(" ", w); - if (err == 0) - err = PyFile_WriteObject(v, w, Py_PRINT_RAW); - if (err == 0) { - /* XXX move into writeobject() ? */ - if (PyString_Check(v)) { - char *s = PyString_AS_STRING(v); - Py_ssize_t len = PyString_GET_SIZE(v); - if (len == 0 || - !isspace(Py_CHARMASK(s[len-1])) || - s[len-1] == ' ') - PyFile_SoftSpace(w, 1); - } -#ifdef Py_USING_UNICODE - else if (PyUnicode_Check(v)) { - Py_UNICODE *s = PyUnicode_AS_UNICODE(v); - Py_ssize_t len = PyUnicode_GET_SIZE(v); - if (len == 0 || - !Py_UNICODE_ISSPACE(s[len-1]) || - s[len-1] == ' ') - PyFile_SoftSpace(w, 1); - } -#endif - else - PyFile_SoftSpace(w, 1); - } - Py_XDECREF(w); - Py_DECREF(v); - Py_XDECREF(stream); - stream = NULL; - if (err == 0) - continue; - break; - - case PRINT_NEWLINE_TO: - w = stream = POP(); - /* fall through to PRINT_NEWLINE */ - - case PRINT_NEWLINE: - if (stream == NULL || stream == Py_None) { - w = PySys_GetObject("stdout"); - if (w == NULL) - PyErr_SetString(PyExc_RuntimeError, - "lost sys.stdout"); - } - if (w != NULL) { - err = PyFile_WriteString("\n", w); - if (err == 0) - PyFile_SoftSpace(w, 0); - } - Py_XDECREF(stream); - stream = NULL; - break; - - #ifdef CASE_TOO_BIG default: switch (opcode) { #endif Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Fri Feb 9 22:28:07 2007 @@ -734,14 +734,6 @@ case PRINT_EXPR: return -1; - case PRINT_ITEM: - return -1; - case PRINT_NEWLINE: - return 0; - case PRINT_ITEM_TO: - return -2; - case PRINT_NEWLINE_TO: - return -1; case INPLACE_LSHIFT: case INPLACE_RSHIFT: case INPLACE_AND: @@ -1626,43 +1618,6 @@ } static int -compiler_print(struct compiler *c, stmt_ty s) -{ - int i, n; - bool dest; - - assert(s->kind == Print_kind); - n = asdl_seq_LEN(s->v.Print.values); - dest = false; - if (s->v.Print.dest) { - VISIT(c, expr, s->v.Print.dest); - dest = true; - } - for (i = 0; i < n; i++) { - expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i); - if (dest) { - ADDOP(c, DUP_TOP); - VISIT(c, expr, e); - ADDOP(c, ROT_TWO); - ADDOP(c, PRINT_ITEM_TO); - } - else { - VISIT(c, expr, e); - ADDOP(c, PRINT_ITEM); - } - } - if (s->v.Print.nl) { - if (dest) - ADDOP(c, PRINT_NEWLINE_TO) - else - ADDOP(c, PRINT_NEWLINE) - } - else if (dest) - ADDOP(c, POP_TOP); - return 1; -} - -static int compiler_if(struct compiler *c, stmt_ty s) { basicblock *end, *next; @@ -2236,8 +2191,6 @@ break; case AugAssign_kind: return compiler_augassign(c, s); - case Print_kind: - return compiler_print(c, s); case For_kind: return compiler_for(c, s); case While_kind: Modified: python/branches/p3yk/Python/symtable.c ============================================================================== --- python/branches/p3yk/Python/symtable.c (original) +++ python/branches/p3yk/Python/symtable.c Fri Feb 9 22:28:07 2007 @@ -990,11 +990,6 @@ VISIT(st, expr, s->v.AugAssign.target); VISIT(st, expr, s->v.AugAssign.value); break; - case Print_kind: - if (s->v.Print.dest) - VISIT(st, expr, s->v.Print.dest); - VISIT_SEQ(st, expr, s->v.Print.values); - break; case For_kind: VISIT(st, expr, s->v.For.target); VISIT(st, expr, s->v.For.iter); Modified: python/branches/p3yk/Python/sysmodule.c ============================================================================== --- python/branches/p3yk/Python/sysmodule.c (original) +++ python/branches/p3yk/Python/sysmodule.c Fri Feb 9 22:28:07 2007 @@ -904,7 +904,7 @@ Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\ \n\ stdin -- standard input file object; used by raw_input() and input()\n\ -stdout -- standard output file object; used by the print statement\n\ +stdout -- standard output file object; used by print()\n\ stderr -- standard error object; used for error messages\n\ By assigning other file objects (or objects that behave like files)\n\ to these, it is possible to redirect all of the interpreter's I/O.\n\ Modified: python/branches/p3yk/Tools/compiler/ast.txt ============================================================================== --- python/branches/p3yk/Tools/compiler/ast.txt (original) +++ python/branches/p3yk/Tools/compiler/ast.txt Fri Feb 9 22:28:07 2007 @@ -34,8 +34,6 @@ Return: value Yield: value Const: value* -Print: nodes!, dest& -Printnl: nodes!, dest& Discard: expr AugAssign: node, op*, expr Assign: nodes!, expr From python-3000-checkins at python.org Fri Feb 9 22:54:59 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 22:54:59 +0100 (CET) Subject: [Python-3000-checkins] r53705 - in python/branches/p3yk/Lib/test: output/test_cProfile test_deque.py test_set.py Message-ID: <20070209215459.C9A441E4012@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 22:54:58 2007 New Revision: 53705 Modified: python/branches/p3yk/Lib/test/output/test_cProfile python/branches/p3yk/Lib/test/test_deque.py python/branches/p3yk/Lib/test/test_set.py Log: Some more tests pass now. (Also test_compiler.py with -u all.) Modified: python/branches/p3yk/Lib/test/output/test_cProfile ============================================================================== --- python/branches/p3yk/Lib/test/output/test_cProfile (original) +++ python/branches/p3yk/Lib/test/output/test_cProfile Fri Feb 9 22:54:58 2007 @@ -29,12 +29,12 @@ :1() -> 1 0.270 1.000 test_cProfile.py:30(testfunc) test_cProfile.py:103(subhelper) -> 16 0.016 0.016 test_cProfile.py:115(__getattr__) 8 0.000 0.000 {range} -test_cProfile.py:115(__getattr__) -> +test_cProfile.py:115(__getattr__) -> test_cProfile.py:30(testfunc) -> 1 0.014 0.130 test_cProfile.py:40(factorial) 2 0.040 0.600 test_cProfile.py:60(helper) test_cProfile.py:40(factorial) -> 20/3 0.130 0.147 test_cProfile.py:40(factorial) 20 0.020 0.020 test_cProfile.py:53(mul) -test_cProfile.py:53(mul) -> +test_cProfile.py:53(mul) -> test_cProfile.py:60(helper) -> 4 0.116 0.120 test_cProfile.py:78(helper1) 2 0.000 0.140 test_cProfile.py:89(helper2_indirect) 6 0.234 0.300 test_cProfile.py:93(helper2) @@ -47,10 +47,10 @@ 8 0.000 0.008 {hasattr} {exec} -> 1 0.000 1.000 :1() {hasattr} -> 12 0.012 0.012 test_cProfile.py:115(__getattr__) -{method 'append' of 'list' objects} -> -{method 'disable' of '_lsprof.Profiler' objects} -> -{range} -> -{sys.exc_info} -> +{method 'append' of 'list' objects} -> +{method 'disable' of '_lsprof.Profiler' objects} -> +{range} -> +{sys.exc_info} -> Ordered by: standard name @@ -71,11 +71,11 @@ test_cProfile.py:89(helper2_indirect) <- 2 0.000 0.140 test_cProfile.py:60(helper) test_cProfile.py:93(helper2) <- 6 0.234 0.300 test_cProfile.py:60(helper) 2 0.078 0.100 test_cProfile.py:89(helper2_indirect) -{exec} <- +{exec} <- {hasattr} <- 4 0.000 0.004 test_cProfile.py:78(helper1) 8 0.000 0.008 test_cProfile.py:93(helper2) {method 'append' of 'list' objects} <- 4 0.000 0.000 test_cProfile.py:78(helper1) -{method 'disable' of '_lsprof.Profiler' objects} <- +{method 'disable' of '_lsprof.Profiler' objects} <- {range} <- 8 0.000 0.000 test_cProfile.py:103(subhelper) {sys.exc_info} <- 4 0.000 0.000 test_cProfile.py:78(helper1) Modified: python/branches/p3yk/Lib/test/test_deque.py ============================================================================== --- python/branches/p3yk/Lib/test/test_deque.py (original) +++ python/branches/p3yk/Lib/test/test_deque.py Fri Feb 9 22:54:58 2007 @@ -245,7 +245,7 @@ d.append(d) try: fo = open(test_support.TESTFN, "wb") - print(d, end=' ', file=fo) + fo.write(str(d)) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(d)) Modified: python/branches/p3yk/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk/Lib/test/test_set.py (original) +++ python/branches/p3yk/Lib/test/test_set.py Fri Feb 9 22:54:58 2007 @@ -265,7 +265,7 @@ w.value = s try: fo = open(test_support.TESTFN, "wb") - print >> fo, s, + fo.write(str(s)) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(s)) @@ -594,7 +594,7 @@ def test_print(self): try: fo = open(test_support.TESTFN, "wb") - print >> fo, self.set, + fo.write(str(self.set)) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(self.set)) @@ -1506,7 +1506,7 @@ test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() - print counts + print(counts) if __name__ == "__main__": test_main(verbose=True) From python-3000-checkins at python.org Fri Feb 9 23:09:02 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 23:09:02 +0100 (CET) Subject: [Python-3000-checkins] r53706 - python/branches/p3yk/Lib/test/test_generators.py Message-ID: <20070209220902.9C2501E4012@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 23:09:01 2007 New Revision: 53706 Modified: python/branches/p3yk/Lib/test/test_generators.py Log: Fix another test. Modified: python/branches/p3yk/Lib/test/test_generators.py ============================================================================== --- python/branches/p3yk/Lib/test/test_generators.py (original) +++ python/branches/p3yk/Lib/test/test_generators.py Fri Feb 9 23:09:01 2007 @@ -107,12 +107,12 @@ ... r = yrange(5) ... print("creator", r.next()) ... return r - ... + ... >>> def caller(): ... r = creator() ... for i in r: ... print("caller", i) - ... + ... >>> caller() creator 0 caller 1 @@ -270,8 +270,8 @@ >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> # Print the nodes of the tree in in-order. >>> for x in t: - ... print(x, end=' ') - A B C D E F G H I J K L M N O P Q R S T U V W X Y Z + ... print(' '+x, end='') + A B C D E F G H I J K L M N O P Q R S T U V W X Y Z >>> # A non-recursive generator. >>> def inorder(node): @@ -291,8 +291,8 @@ >>> # Exercise the non-recursive generator. >>> for x in t: - ... print(x, end=' ') - A B C D E F G H I J K L M N O P Q R S T U V W X Y Z + ... print(' '+x, end='') + A B C D E F G H I J K L M N O P Q R S T U V W X Y Z """ @@ -447,7 +447,7 @@ >>> gen = random.WichmannHill(42) >>> while 1: ... for s in sets: -... print("%s->%s" % (s, s.find()), end=' ') +... print(" %s->%s" % (s, s.find()), end='') ... print() ... if len(roots) > 1: ... s1 = gen.choice(roots) @@ -457,31 +457,31 @@ ... print("merged", s1, "into", s2) ... else: ... break -A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M + A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M merged D into G -A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M + A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M merged C into F -A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M + A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M merged L into A -A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M + A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M merged H into E -A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M + A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M merged B into E -A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M + A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M merged J into G -A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M + A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M merged E into G -A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M + A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M merged M into G -A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G + A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G merged I into K -A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G + A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G merged K into A -A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G + A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G merged F into A -A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G + A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G merged A into G -A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G + A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G """ # Emacs turd ' @@ -1555,7 +1555,7 @@ ... try: ... print((yield)) ... except ValueError as v: -... print("caught ValueError (%s)" % (v), end=' ') +... print("caught ValueError (%s)" % (v)) >>> import sys >>> g = f() >>> g.next() From python-3000-checkins at python.org Fri Feb 9 23:11:22 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 23:11:22 +0100 (CET) Subject: [Python-3000-checkins] r53707 - python/branches/p3yk/Lib/test/list_tests.py Message-ID: <20070209221122.8FFFE1E4012@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 23:11:20 2007 New Revision: 53707 Modified: python/branches/p3yk/Lib/test/list_tests.py Log: Two tests fixed with one fix. Modified: python/branches/p3yk/Lib/test/list_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/list_tests.py (original) +++ python/branches/p3yk/Lib/test/list_tests.py Fri Feb 9 23:11:20 2007 @@ -54,7 +54,7 @@ d.append(400) try: fo = open(test_support.TESTFN, "wb") - print(d, end=' ', file=fo) + fo.write(str(d)) fo.close() fo = open(test_support.TESTFN, "rb") self.assertEqual(fo.read(), repr(d)) From python-3000-checkins at python.org Fri Feb 9 23:16:54 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 23:16:54 +0100 (CET) Subject: [Python-3000-checkins] r53708 - python/branches/p3yk/Lib/pdb.py Message-ID: <20070209221654.F3AE91E4012@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 23:16:54 2007 New Revision: 53708 Modified: python/branches/p3yk/Lib/pdb.py Log: Fix a bogus end=' ' here. Modified: python/branches/p3yk/Lib/pdb.py ============================================================================== --- python/branches/p3yk/Lib/pdb.py (original) +++ python/branches/p3yk/Lib/pdb.py Fri Feb 9 23:16:54 2007 @@ -740,7 +740,7 @@ else: s = s + ' ' if lineno == self.curframe.f_lineno: s = s + '->' - print(s + '\t' + line, end=' ', file=self.stdout) + print(s + '\t' + line, end='', file=self.stdout) self.lineno = lineno except KeyboardInterrupt: pass From python-3000-checkins at python.org Fri Feb 9 23:18:41 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 23:18:41 +0100 (CET) Subject: [Python-3000-checkins] r53709 - python/branches/p3yk/Lib/test/test_zipfile.py Message-ID: <20070209221841.9CEC71E4012@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 23:18:41 2007 New Revision: 53709 Modified: python/branches/p3yk/Lib/test/test_zipfile.py Log: More prints embedded in strings. Modified: python/branches/p3yk/Lib/test/test_zipfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_zipfile.py (original) +++ python/branches/p3yk/Lib/test/test_zipfile.py Fri Feb 9 23:18:41 2007 @@ -282,11 +282,11 @@ os.mkdir(TESTFN2) try: fp = open(os.path.join(TESTFN2, "mod1.py"), "w") - fp.write("print 42\n") + fp.write("print(42)\n") fp.close() fp = open(os.path.join(TESTFN2, "mod2.py"), "w") - fp.write("print 42 * 42\n") + fp.write("print(42 * 42)\n") fp.close() fp = open(os.path.join(TESTFN2, "mod2.txt"), "w") From python-3000-checkins at python.org Fri Feb 9 23:27:37 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 23:27:37 +0100 (CET) Subject: [Python-3000-checkins] r53710 - python/branches/p3yk/Lib/test/test_pyexpat.py Message-ID: <20070209222737.5B0CD1E4012@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 23:27:36 2007 New Revision: 53710 Modified: python/branches/p3yk/Lib/test/test_pyexpat.py Log: Found another difference between old and new print: old print would suppress the softspace after \t. Modified: python/branches/p3yk/Lib/test/test_pyexpat.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pyexpat.py (original) +++ python/branches/p3yk/Lib/test/test_pyexpat.py Fri Feb 9 23:27:36 2007 @@ -10,25 +10,25 @@ class Outputter: def StartElementHandler(self, name, attrs): - print('Start element:\n\t', repr(name), sortdict(attrs)) + print('Start element:\n\t' + repr(name), sortdict(attrs)) def EndElementHandler(self, name): - print('End element:\n\t', repr(name)) + print('End element:\n\t' + repr(name)) def CharacterDataHandler(self, data): data = data.strip() if data: print('Character data:') - print('\t', repr(data)) + print('\t' + repr(data)) def ProcessingInstructionHandler(self, target, data): - print('PI:\n\t', repr(target), repr(data)) + print('PI:\n\t' + repr(target), repr(data)) def StartNamespaceDeclHandler(self, prefix, uri): - print('NS decl:\n\t', repr(prefix), repr(uri)) + print('NS decl:\n\t' + repr(prefix), repr(uri)) def EndNamespaceDeclHandler(self, prefix): - print('End of NS decl:\n\t', repr(prefix)) + print('End of NS decl:\n\t' + repr(prefix)) def StartCdataSectionHandler(self): print('Start of CDATA section') @@ -37,7 +37,7 @@ print('End of CDATA section') def CommentHandler(self, text): - print('Comment:\n\t', repr(text)) + print('Comment:\n\t' + repr(text)) def NotationDeclHandler(self, *args): name, base, sysid, pubid = args @@ -45,7 +45,7 @@ def UnparsedEntityDeclHandler(self, *args): entityName, base, systemId, publicId, notationName = args - print('Unparsed entity decl:\n\t', args) + print('Unparsed entity decl:\n\t' + str(args)) def NotStandaloneHandler(self, userData): print('Not standalone') From python-3000-checkins at python.org Fri Feb 9 23:28:29 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 23:28:29 +0100 (CET) Subject: [Python-3000-checkins] r53711 - python/branches/p3yk/Lib/test/output/test_profile Message-ID: <20070209222829.146A41E4012@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 23:28:28 2007 New Revision: 53711 Modified: python/branches/p3yk/Lib/test/output/test_profile Log: Trivial fix for test_profile.py. Modified: python/branches/p3yk/Lib/test/output/test_profile ============================================================================== --- python/branches/p3yk/Lib/test/output/test_profile (original) +++ python/branches/p3yk/Lib/test/output/test_profile Fri Feb 9 23:28:28 2007 @@ -27,24 +27,24 @@ Ordered by: standard name Function called... -:0(append) -> -:0(exc_info) -> +:0(append) -> +:0(exc_info) -> :0(exec) -> :1()(1) 1.000 :0(hasattr) -> test_profile.py:115(__getattr__)(12) 0.028 -:0(range) -> -:0(setprofile) -> +:0(range) -> +:0(setprofile) -> :1() -> test_profile.py:30(testfunc)(1) 1.000 profile:0(profiler) -> profile:0(testfunc())(1) 1.000 profile:0(testfunc()) -> :0(exec)(1) 1.000 :0(setprofile)(1) 0.000 test_profile.py:103(subhelper) -> :0(range)(8) 0.000 test_profile.py:115(__getattr__)(16) 0.028 -test_profile.py:115(__getattr__) -> +test_profile.py:115(__getattr__) -> test_profile.py:30(testfunc) -> test_profile.py:40(factorial)(1) 0.170 test_profile.py:60(helper)(2) 0.600 test_profile.py:40(factorial) -> test_profile.py:40(factorial)(20) 0.170 test_profile.py:53(mul)(20) 0.020 -test_profile.py:53(mul) -> +test_profile.py:53(mul) -> test_profile.py:60(helper) -> test_profile.py:78(helper1)(4) 0.120 test_profile.py:89(helper2_indirect)(2) 0.140 test_profile.py:93(helper2)(6) 0.400 @@ -68,7 +68,7 @@ :0(range) <- test_profile.py:103(subhelper)(8) 0.080 :0(setprofile) <- profile:0(testfunc())(1) 1.000 :1() <- :0(exec)(1) 1.000 -profile:0(profiler) <- +profile:0(profiler) <- profile:0(testfunc()) <- profile:0(profiler)(1) 0.000 test_profile.py:103(subhelper) <- test_profile.py:93(helper2)(8) 0.400 test_profile.py:115(__getattr__) <- :0(hasattr)(12) 0.012 From python-3000-checkins at python.org Fri Feb 9 23:36:03 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 23:36:03 +0100 (CET) Subject: [Python-3000-checkins] r53712 - in python/branches/p3yk/Lib/email: iterators.py test/test_email.py test/test_email_renamed.py Message-ID: <20070209223603.55C711E4013@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 23:36:02 2007 New Revision: 53712 Modified: python/branches/p3yk/Lib/email/iterators.py python/branches/p3yk/Lib/email/test/test_email.py python/branches/p3yk/Lib/email/test/test_email_renamed.py Log: Fairly subtle fix for failing tests. Modified: python/branches/p3yk/Lib/email/iterators.py ============================================================================== --- python/branches/p3yk/Lib/email/iterators.py (original) +++ python/branches/p3yk/Lib/email/iterators.py Fri Feb 9 23:36:02 2007 @@ -63,9 +63,9 @@ if fp is None: fp = sys.stdout tab = ' ' * (level * 4) - print(tab + msg.get_content_type(), end=' ', file=fp) + print(tab + msg.get_content_type(), end='', file=fp) if include_default: - print('[%s]' % msg.get_default_type(), file=fp) + print(' [%s]' % msg.get_default_type(), file=fp) else: print(file=fp) if msg.is_multipart(): Modified: python/branches/p3yk/Lib/email/test/test_email.py ============================================================================== --- python/branches/p3yk/Lib/email/test/test_email.py (original) +++ python/branches/p3yk/Lib/email/test/test_email.py Fri Feb 9 23:36:02 2007 @@ -54,10 +54,9 @@ if first != second: sfirst = str(first) ssecond = str(second) - diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) - fp = StringIO() - print(NL, NL.join(diff), file=fp) - raise self.failureException, fp.getvalue() + diff = difflib.ndiff(sfirst.splitlines(True), + ssecond.splitlines(True)) + raise self.failureException(NL + "".join(diff)) def _msgobj(self, filename): fp = openfile(findfile(filename)) Modified: python/branches/p3yk/Lib/email/test/test_email_renamed.py ============================================================================== --- python/branches/p3yk/Lib/email/test/test_email_renamed.py (original) +++ python/branches/p3yk/Lib/email/test/test_email_renamed.py Fri Feb 9 23:36:02 2007 @@ -55,10 +55,9 @@ if first != second: sfirst = str(first) ssecond = str(second) - diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) - fp = StringIO() - print(NL, NL.join(diff), file=fp) - raise self.failureException, fp.getvalue() + diff = difflib.ndiff(sfirst.splitlines(True), + ssecond.splitlines(True)) + raise self.failureException(NL + "".join(diff)) def _msgobj(self, filename): fp = openfile(findfile(filename)) From python-3000-checkins at python.org Fri Feb 9 23:43:10 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 23:43:10 +0100 (CET) Subject: [Python-3000-checkins] r53713 - python/branches/p3yk/Lib/test/test_tokenize.py Message-ID: <20070209224310.C191D1E401A@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 23:43:10 2007 New Revision: 53713 Modified: python/branches/p3yk/Lib/test/test_tokenize.py Log: Fix the roundtripping function. Modified: python/branches/p3yk/Lib/test/test_tokenize.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tokenize.py (original) +++ python/branches/p3yk/Lib/test/test_tokenize.py Fri Feb 9 23:43:10 2007 @@ -123,7 +123,7 @@ def roundtrip(s): f = StringIO(s) source = untokenize(generate_tokens(f.readline)) - print(source, end=' ') + print(source, end="") # This is an example from the docs, set up as a doctest. def decistmt(s): From python-3000-checkins at python.org Fri Feb 9 23:43:47 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 9 Feb 2007 23:43:47 +0100 (CET) Subject: [Python-3000-checkins] r53714 - python/branches/p3yk/Lib/test/test_doctest.py Message-ID: <20070209224347.975C71E4021@bag.python.org> Author: guido.van.rossum Date: Fri Feb 9 23:43:47 2007 New Revision: 53714 Modified: python/branches/p3yk/Lib/test/test_doctest.py Log: Redue the failure rate to 13 tests. Bah. Modified: python/branches/p3yk/Lib/test/test_doctest.py ============================================================================== --- python/branches/p3yk/Lib/test/test_doctest.py (original) +++ python/branches/p3yk/Lib/test/test_doctest.py Fri Feb 9 23:43:47 2007 @@ -35,7 +35,7 @@ >>> for i in range(10): ... sc = sc.double() ... print(sc.get(), end=' ') - 6 12 24 48 96 192 384 768 1536 3072 + 6 12 24 48 96 192 384 768 1536 3072 """ def __init__(self, val): """ @@ -166,10 +166,10 @@ These attributes are set by the constructor. `source` and `want` are required; the other attributes all have default values: - >>> example = doctest.Example('print 1', '1\n') + >>> example = doctest.Example('print(1)', '1\n') >>> (example.source, example.want, example.exc_msg, ... example.lineno, example.indent, example.options) - ('print 1\n', '1\n', None, 0, 0, {}) + ('print(1)\n', '1\n', None, 0, 0, {}) The first three attributes (`source`, `want`, and `exc_msg`) may be specified positionally; the remaining arguments should be specified as @@ -186,22 +186,22 @@ The constructor normalizes the `source` string to end in a newline: Source spans a single line: no terminating newline. - >>> e = doctest.Example('print 1', '1\n') + >>> e = doctest.Example('print(1)', '1\n') >>> e.source, e.want - ('print 1\n', '1\n') + ('print(1)\n', '1\n') - >>> e = doctest.Example('print 1\n', '1\n') + >>> e = doctest.Example('print(1)\n', '1\n') >>> e.source, e.want - ('print 1\n', '1\n') + ('print(1)\n', '1\n') Source spans multiple lines: require terminating newline. - >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n') + >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n') >>> e.source, e.want - ('print 1;\nprint 2\n', '1\n2\n') + ('print(1);\nprint(2)\n', '1\n2\n') - >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n') + >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n') >>> e.source, e.want - ('print 1;\nprint 2\n', '1\n2\n') + ('print(1);\nprint(2)\n', '1\n2\n') Empty source string (which should never appear in real examples) >>> e = doctest.Example('', '') @@ -211,13 +211,13 @@ The constructor normalizes the `want` string to end in a newline, unless it's the empty string: - >>> e = doctest.Example('print 1', '1\n') + >>> e = doctest.Example('print(1)', '1\n') >>> e.source, e.want - ('print 1\n', '1\n') + ('print(1)\n', '1\n') - >>> e = doctest.Example('print 1', '1') + >>> e = doctest.Example('print(1)', '1') >>> e.source, e.want - ('print 1\n', '1\n') + ('print(1)\n', '1\n') >>> e = doctest.Example('print', '') >>> e.source, e.want @@ -265,12 +265,12 @@ constructor: >>> docstring = ''' - ... >>> print 12 + ... >>> print(12) ... 12 ... ... Non-example text. ... - ... >>> print 'another\example' + ... >>> print('another\example') ... another ... example ... ''' @@ -284,9 +284,9 @@ 2 >>> e1, e2 = test.examples >>> (e1.source, e1.want, e1.lineno) - ('print 12\n', '12\n', 1) + ('print(12)\n', '12\n', 1) >>> (e2.source, e2.want, e2.lineno) - ("print 'another\\example'\n", 'another\nexample\n', 6) + ("print('another\\example')\n", 'another\nexample\n', 6) Source information (name, filename, and line number) is available as attributes on the doctest object: @@ -307,7 +307,7 @@ expected output of an example, then `DocTest` will raise a ValueError: >>> docstring = r''' - ... >>> print 'bad\nindentation' + ... >>> print('bad\nindentation') ... bad ... indentation ... ''' @@ -319,8 +319,8 @@ continuation lines, then `DocTest` will raise a ValueError: >>> docstring = r''' - ... >>> print ('bad indentation', - ... ... 2) + ... >>> print(('bad indentation', + ... ... 2)) ... ('bad', 'indentation') ... ''' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) @@ -330,18 +330,18 @@ If there's no blank space after a PS1 prompt ('>>>'), then `DocTest` will raise a ValueError: - >>> docstring = '>>>print 1\n1' + >>> docstring = '>>>print(1)\n1' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): - ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1' + ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)' If there's no blank space after a PS2 prompt ('...'), then `DocTest` will raise a ValueError: - >>> docstring = '>>> if 1:\n...print 1\n1' + >>> docstring = '>>> if 1:\n...print(1)\n1' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): - ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1' + ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)' """ @@ -382,7 +382,7 @@ >>> e = tests[0].examples[0] >>> (e.source, e.want, e.lineno) - ('print sample_func(22)\n', '44\n', 3) + ('print(sample_func(22))\n', '44\n', 3) By default, tests are created for objects with no docstring: @@ -452,7 +452,7 @@ >>> m = new.module('some_module') >>> def triple(val): ... ''' - ... >>> print triple(11) + ... >>> print(triple(11)) ... 33 ... ''' ... return val*3 @@ -461,11 +461,11 @@ ... 'SampleClass': SampleClass, ... '__doc__': ''' ... Module docstring. - ... >>> print 'module' + ... >>> print('module') ... module ... ''', ... '__test__': { - ... 'd': '>>> print 6\n6\n>>> print 7\n7\n', + ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n', ... 'c': triple}}) >>> finder = doctest.DocTestFinder() @@ -570,8 +570,8 @@ ... ... ... ... >>> for x in range(10): - ... ... print x, - ... 0 1 2 3 4 5 6 7 8 9 + ... ... print(x, end=' ') + ... 0 1 2 3 4 5 6 7 8 9 ... >>> x//2 ... 6 ... ''' @@ -591,8 +591,8 @@ >>> s = ''' ... >>> x, y = 2, 3 # no output expected ... >>> if 1: - ... ... print x - ... ... print y + ... ... print(x) + ... ... print(y) ... 2 ... 3 ... @@ -609,7 +609,7 @@ Text: '\n' Example: ('x, y = 2, 3 # no output expected\n', '', 1) Text: '' - Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2) + Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) Text: '\nSome text.\n' Example: ('x+y\n', '5\n', 9) Text: '' @@ -619,7 +619,7 @@ >>> for piece in parser.get_examples(s): ... print((piece.source, piece.want, piece.lineno)) ('x, y = 2, 3 # no output expected\n', '', 1) - ('if 1:\n print x\n print y\n', '2\n3\n', 2) + ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) ('x+y\n', '5\n', 9) The `get_doctest` method creates a Test from the examples, along with the @@ -631,7 +631,7 @@ >>> for piece in test.examples: ... print((piece.source, piece.want, piece.lineno)) ('x, y = 2, 3 # no output expected\n', '', 1) - ('if 1:\n print x\n print y\n', '2\n3\n', 2) + ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) ('x+y\n', '5\n', 9) """ @@ -645,7 +645,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print x + ... >>> print(x) ... 12 ... >>> x//2 ... 6 @@ -666,7 +666,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print x + ... >>> print(x) ... 14 ... >>> x//2 ... 6 @@ -679,13 +679,13 @@ Expecting nothing ok Trying: - print x + print(x) Expecting: 14 ********************************************************************** File ..., line 4, in f Failed example: - print x + print(x) Expected: 14 Got: @@ -704,7 +704,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print x + ... >>> print(x) ... 12 ... >>> x//2 ... 6 @@ -717,7 +717,7 @@ Expecting nothing ok Trying: - print x + print(x) Expecting: 12 ok @@ -747,7 +747,7 @@ Expecting nothing ok Trying: - print x + print(x) Expecting: 12 ok @@ -774,7 +774,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print x//0 + ... >>> print(x//0) ... Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero ... ''' @@ -790,7 +790,7 @@ >>> def f(x): ... ''' ... >>> x = 12 - ... >>> print 'pre-exception output', x//0 + ... >>> print('pre-exception output', x//0) ... pre-exception output ... Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero @@ -801,7 +801,7 @@ ********************************************************************** File ..., line 4, in f Failed example: - print 'pre-exception output', x//0 + print('pre-exception output', x//0) Exception raised: ... ZeroDivisionError: integer division or modulo by zero @@ -942,7 +942,7 @@ and the '' marker: >>> def f(x): - ... '>>> print "a\\n\\nb"\na\n\nb\n' + ... '>>> print("a\\n\\nb")\na\n\nb\n' >>> # Without the flag: >>> test = doctest.DocTestFinder().find(f)[0] @@ -957,7 +957,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print "a\n\nb" + print("a\n\nb") Expected: a @@ -972,7 +972,7 @@ treated as equal: >>> def f(x): - ... '>>> print 1, 2, 3\n 1 2\n 3' + ... '>>> print(1, 2, 3)\n 1 2\n 3' >>> # Without the flag: >>> test = doctest.DocTestFinder().find(f)[0] @@ -981,7 +981,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print 1, 2, 3 + print(1, 2, 3) Expected: 1 2 3 @@ -1004,7 +1004,7 @@ output to match any substring in the actual output: >>> def f(x): - ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n' + ... '>>> print(range(15))\n[0, 1, 2, ..., 14]\n' >>> # Without the flag: >>> test = doctest.DocTestFinder().find(f)[0] @@ -1013,7 +1013,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(15) + print(range(15)) Expected: [0, 1, 2, ..., 14] Got: @@ -1071,7 +1071,7 @@ >>> def f(x): ... r''' - ... >>> print '\n'.join('abcdefg') + ... >>> print('\n'.join('abcdefg')) ... a ... B ... c @@ -1088,7 +1088,7 @@ ********************************************************************** File ..., line 3, in f Failed example: - print '\n'.join('abcdefg') + print('\n'.join('abcdefg')) Expected: a B @@ -1115,7 +1115,7 @@ ********************************************************************** File ..., line 3, in f Failed example: - print '\n'.join('abcdefg') + print('\n'.join('abcdefg')) Differences (unified diff with -expected +actual): @@ -1,7 +1,7 @@ a @@ -1140,7 +1140,7 @@ ********************************************************************** File ..., line 3, in f Failed example: - print '\n'.join('abcdefg') + print('\n'.join('abcdefg')) Differences (context diff with expected followed by actual): *************** *** 1,7 **** @@ -1168,7 +1168,7 @@ >>> def f(x): ... r''' - ... >>> print "a b c d e f g h i j k l m" + ... >>> print("a b c d e f g h i j k l m") ... a b c d e f g h i j k 1 m ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1178,7 +1178,7 @@ ********************************************************************** File ..., line 3, in f Failed example: - print "a b c d e f g h i j k l m" + print("a b c d e f g h i j k l m") Differences (ndiff with -expected +actual): - a b c d e f g h i j k 1 m ? ^ @@ -1191,15 +1191,15 @@ >>> def f(x): ... r''' - ... >>> print 1 # first success + ... >>> print(1) # first success ... 1 - ... >>> print 2 # first failure + ... >>> print(2) # first failure ... 200 - ... >>> print 3 # second failure + ... >>> print(3) # second failure ... 300 - ... >>> print 4 # second success + ... >>> print(4) # second success ... 4 - ... >>> print 5 # third failure + ... >>> print(5) # third failure ... 500 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1209,7 +1209,7 @@ ********************************************************************** File ..., line 5, in f Failed example: - print 2 # first failure + print(2) # first failure Expected: 200 Got: @@ -1221,18 +1221,18 @@ >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test) ... # doctest: +ELLIPSIS Trying: - print 1 # first success + print(1) # first success Expecting: 1 ok Trying: - print 2 # first failure + print(2) # first failure Expecting: 200 ********************************************************************** File ..., line 5, in f Failed example: - print 2 # first failure + print(2) # first failure Expected: 200 Got: @@ -1244,15 +1244,15 @@ >>> def f(x): ... r''' - ... >>> print 1 # first success + ... >>> print(1) # first success ... 1 ... >>> raise ValueError(2) # first failure ... 200 - ... >>> print 3 # second failure + ... >>> print(3) # second failure ... 300 - ... >>> print 4 # second success + ... >>> print(4) # second success ... 4 - ... >>> print 5 # third failure + ... >>> print(5) # third failure ... 500 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1298,10 +1298,10 @@ example with a comment of the form ``# doctest: +OPTION``: >>> def f(x): r''' - ... >>> print range(10) # should fail: no ellipsis + ... >>> print(range(10)) # should fail: no ellipsis ... [0, 1, ..., 9] ... - ... >>> print range(10) # doctest: +ELLIPSIS + ... >>> print(range(10)) # doctest: +ELLIPSIS ... [0, 1, ..., 9] ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1310,7 +1310,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # should fail: no ellipsis + print(range(10)) # should fail: no ellipsis Expected: [0, 1, ..., 9] Got: @@ -1321,11 +1321,11 @@ comment of the form ``# doctest: -OPTION``: >>> def f(x): r''' - ... >>> print range(10) + ... >>> print(range(10)) ... [0, 1, ..., 9] ... ... >>> # should fail: no ellipsis - ... >>> print range(10) # doctest: -ELLIPSIS + ... >>> print(range(10)) # doctest: -ELLIPSIS ... [0, 1, ..., 9] ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1335,7 +1335,7 @@ ********************************************************************** File ..., line 6, in f Failed example: - print range(10) # doctest: -ELLIPSIS + print(range(10)) # doctest: -ELLIPSIS Expected: [0, 1, ..., 9] Got: @@ -1346,13 +1346,13 @@ do not change the options for surrounding examples: >>> def f(x): r''' - ... >>> print range(10) # Should fail: no ellipsis + ... >>> print(range(10)) # Should fail: no ellipsis ... [0, 1, ..., 9] ... - ... >>> print range(10) # doctest: +ELLIPSIS + ... >>> print(range(10)) # doctest: +ELLIPSIS ... [0, 1, ..., 9] ... - ... >>> print range(10) # Should fail: no ellipsis + ... >>> print(range(10)) # Should fail: no ellipsis ... [0, 1, ..., 9] ... ''' >>> test = doctest.DocTestFinder().find(f)[0] @@ -1361,7 +1361,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # Should fail: no ellipsis + print(range(10)) # Should fail: no ellipsis Expected: [0, 1, ..., 9] Got: @@ -1369,7 +1369,7 @@ ********************************************************************** File ..., line 8, in f Failed example: - print range(10) # Should fail: no ellipsis + print(range(10)) # Should fail: no ellipsis Expected: [0, 1, ..., 9] Got: @@ -1380,9 +1380,9 @@ may be separated by whitespace, commas, or both: >>> def f(x): r''' - ... >>> print range(10) # Should fail + ... >>> print(range(10)) # Should fail ... [0, 1, ..., 9] - ... >>> print range(10) # Should succeed + ... >>> print(range(10)) # Should succeed ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ... [0, 1, ..., 9] ... ''' @@ -1392,7 +1392,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # Should fail + print(range(10)) # Should fail Expected: [0, 1, ..., 9] Got: @@ -1400,9 +1400,9 @@ (1, 2) >>> def f(x): r''' - ... >>> print range(10) # Should fail + ... >>> print(range(10)) # Should fail ... [0, 1, ..., 9] - ... >>> print range(10) # Should succeed + ... >>> print(range(10)) # Should succeed ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE ... [0, 1, ..., 9] ... ''' @@ -1412,7 +1412,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # Should fail + print(range(10)) # Should fail Expected: [0, 1, ..., 9] Got: @@ -1420,9 +1420,9 @@ (1, 2) >>> def f(x): r''' - ... >>> print range(10) # Should fail + ... >>> print(range(10)) # Should fail ... [0, 1, ..., 9] - ... >>> print range(10) # Should succeed + ... >>> print(range(10)) # Should succeed ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... [0, 1, ..., 9] ... ''' @@ -1432,7 +1432,7 @@ ********************************************************************** File ..., line 2, in f Failed example: - print range(10) # Should fail + print(range(10)) # Should fail Expected: [0, 1, ..., 9] Got: @@ -1443,7 +1443,7 @@ long as a continuation prompt is used: >>> def f(x): r''' - ... >>> print range(10) + ... >>> print(range(10)) ... ... # doctest: +ELLIPSIS ... [0, 1, ..., 9] ... ''' @@ -1456,12 +1456,12 @@ >>> def f(x): r''' ... >>> for x in range(10): # doctest: +ELLIPSIS - ... ... print x, - ... 0 1 2 ... 9 + ... ... print(x, end=' ') + ... 0 1 2 ... 9 ... ... >>> for x in range(10): - ... ... print x, # doctest: +ELLIPSIS - ... 0 1 2 ... 9 + ... ... print(x, end=' ') # doctest: +ELLIPSIS + ... 0 1 2 ... 9 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) @@ -1473,8 +1473,8 @@ >>> def f(x): r''' ... Should fail (option directive not on the last line): ... >>> for x in range(10): # doctest: +ELLIPSIS - ... ... print x, # doctest: +NORMALIZE_WHITESPACE - ... 0 1 2...9 + ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE + ... 0 1 2...9 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> doctest.DocTestRunner(verbose=False).run(test) @@ -1486,13 +1486,13 @@ `register_option`: >>> # Error: Option not registered - >>> s = '>>> print 12 #doctest: +BADOPTION' + >>> s = '>>> print(12) #doctest: +BADOPTION' >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0) Traceback (most recent call last): ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION' >>> # Error: No + or - prefix - >>> s = '>>> print 12 #doctest: ELLIPSIS' + >>> s = '>>> print(12) #doctest: ELLIPSIS' >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0) Traceback (most recent call last): ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS' @@ -1519,7 +1519,7 @@ >>> print(doctest.testsource(test.test_doctest, name)) # Blah blah # - print sample_func(22) + print(sample_func(22)) # Expected: ## 44 # @@ -1528,7 +1528,7 @@ >>> name = 'test.test_doctest.SampleNewStyleClass' >>> print(doctest.testsource(test.test_doctest, name)) - print '1\n2\n3' + print('1\n2\n3') # Expected: ## 1 ## 2 @@ -1537,10 +1537,10 @@ >>> name = 'test.test_doctest.SampleClass.a_classmethod' >>> print(doctest.testsource(test.test_doctest, name)) - print SampleClass.a_classmethod(10) + print(SampleClass.a_classmethod(10)) # Expected: ## 12 - print SampleClass(0).a_classmethod(10) + print(SampleClass(0).a_classmethod(10)) # Expected: ## 12 @@ -1552,7 +1552,7 @@ >>> s = ''' ... >>> x = 12 - ... >>> print x + ... >>> print(x) ... 12 ... ''' @@ -1560,7 +1560,7 @@ >>> import tempfile >>> real_stdin = sys.stdin - >>> sys.stdin = _FakeInput(['next', 'print x', 'continue']) + >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue']) Run the debugger on the docstring, and then restore sys.stdin. @@ -1571,7 +1571,7 @@ 12 --Return-- > (1)()->None - (Pdb) print x + (Pdb) print(x) 12 (Pdb) continue @@ -1601,7 +1601,7 @@ >>> import tempfile >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ - ... 'print x', # print data defined by the example + ... 'print(x)', # print data defined by the example ... 'continue', # stop debugging ... '']) @@ -1610,7 +1610,7 @@ --Return-- > (1)()->None -> import pdb; pdb.set_trace() - (Pdb) print x + (Pdb) print(x) 42 (Pdb) continue (0, 2) @@ -1628,9 +1628,9 @@ >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ - ... 'print y', # print data defined in the function + ... 'print(y)', # print data defined in the function ... 'up', # out of function - ... 'print x', # print data defined by the example + ... 'print(x)', # print data defined by the example ... 'continue', # stop debugging ... '']) @@ -1641,12 +1641,12 @@ --Return-- > (3)calls_set_trace()->None -> import pdb; pdb.set_trace() - (Pdb) print y + (Pdb) print(y) 2 (Pdb) up > (1)() -> calls_set_trace() - (Pdb) print x + (Pdb) print(x) 1 (Pdb) continue (0, 2) @@ -1658,7 +1658,7 @@ ... >>> def f(x): ... ... g(x*2) ... >>> def g(x): - ... ... print x+3 + ... ... print(x+3) ... ... import pdb; pdb.set_trace() ... >>> f(3) ... ''' @@ -1680,7 +1680,7 @@ -> import pdb; pdb.set_trace() (Pdb) list 1 def g(x): - 2 print x+3 + 2 print(x+3) 3 -> import pdb; pdb.set_trace() [EOF] (Pdb) next @@ -1737,11 +1737,11 @@ >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0) >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput([ - ... 'print y', # print data defined in the function - ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z', - ... 'up', 'print x', - ... 'up', 'print y', - ... 'up', 'print foo', + ... 'print(y)', # print data defined in the function + ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)', + ... 'up', 'print(x)', + ... 'up', 'print(y)', + ... 'up', 'print(foo)', ... 'continue', # stop debugging ... '']) @@ -1751,7 +1751,7 @@ ... sys.stdin = real_stdin > (5)calls_set_trace() -> self.f1() - (Pdb) print y + (Pdb) print(y) 1 (Pdb) step --Call-- @@ -1773,22 +1773,22 @@ (Pdb) step > (13)f2() -> z = 2 - (Pdb) print z + (Pdb) print(z) 1 (Pdb) up > (9)f1() -> self.f2() - (Pdb) print x + (Pdb) print(x) 1 (Pdb) up > (5)calls_set_trace() -> self.f1() - (Pdb) print y + (Pdb) print(y) 1 (Pdb) up > (1)() -> calls_set_trace() - (Pdb) print foo + (Pdb) print(foo) *** NameError: name 'foo' is not defined (Pdb) continue (0, 2) @@ -2099,9 +2099,9 @@ ... Failed example: if 1: - print 'a' - print - print 'b' + print('a') + print() + print('b') Differences (ndiff with -expected +actual): a - @@ -2185,9 +2185,9 @@ ok Trying: if 1: - print 'a' - print - print 'b' + print('a') + print() + print('b') Expecting: a @@ -2279,19 +2279,19 @@ >>> t = Tester(globs={'x': 42}, verbose=0) >>> t.runstring(r''' ... >>> x = x * 2 -... >>> print x +... >>> print(x) ... 42 ... ''', 'XYZ') ********************************************************************** Line 3, in XYZ Failed example: - print x + print(x) Expected: 42 Got: 84 (1, 2) ->>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2') +>>> t.runstring(">>> x = x * 2\n>>> print(x)\n84\n", 'example2') (0, 2) >>> t.summarize() ********************************************************************** From python-3000-checkins at python.org Sat Feb 10 00:20:23 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 00:20:23 +0100 (CET) Subject: [Python-3000-checkins] r53715 - in python/branches/p3yk: Include/ceval.h Include/fileobject.h Lib/StringIO.py Lib/bsddb/dbrecio.py Lib/code.py Lib/doctest.py Lib/idlelib/PyShell.py Lib/idlelib/run.py Lib/socket.py Lib/test/test_doctest.txt Lib/test/test_file.py Lib/test/test_inspect.py Lib/test/test_softspace.py Modules/bz2module.c Modules/cStringIO.c Objects/fileobject.c Python/ceval.c Python/pythonrun.c Python/sysmodule.c Message-ID: <20070209232023.968FA1E4012@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 00:20:19 2007 New Revision: 53715 Removed: python/branches/p3yk/Lib/test/test_softspace.py Modified: python/branches/p3yk/Include/ceval.h python/branches/p3yk/Include/fileobject.h python/branches/p3yk/Lib/StringIO.py python/branches/p3yk/Lib/bsddb/dbrecio.py python/branches/p3yk/Lib/code.py python/branches/p3yk/Lib/doctest.py python/branches/p3yk/Lib/idlelib/PyShell.py python/branches/p3yk/Lib/idlelib/run.py python/branches/p3yk/Lib/socket.py python/branches/p3yk/Lib/test/test_doctest.txt python/branches/p3yk/Lib/test/test_file.py python/branches/p3yk/Lib/test/test_inspect.py python/branches/p3yk/Modules/bz2module.c python/branches/p3yk/Modules/cStringIO.c python/branches/p3yk/Objects/fileobject.c python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/pythonrun.c python/branches/p3yk/Python/sysmodule.c Log: Kill off softspace completely (except in formatter.py which seems to have a different feature with the same name). The change to test_doctest.txt reduces the doctest failures to 3. Modified: python/branches/p3yk/Include/ceval.h ============================================================================== --- python/branches/p3yk/Include/ceval.h (original) +++ python/branches/p3yk/Include/ceval.h Sat Feb 10 00:20:19 2007 @@ -40,8 +40,6 @@ flag was set, else return 0. */ PyAPI_FUNC(int) PyEval_MergeCompilerFlags(PyCompilerFlags *cf); -PyAPI_FUNC(int) Py_FlushLine(void); - PyAPI_FUNC(int) Py_AddPendingCall(int (*func)(void *), void *arg); PyAPI_FUNC(int) Py_MakePendingCalls(void); Modified: python/branches/p3yk/Include/fileobject.h ============================================================================== --- python/branches/p3yk/Include/fileobject.h (original) +++ python/branches/p3yk/Include/fileobject.h Sat Feb 10 00:20:19 2007 @@ -13,7 +13,6 @@ PyObject *f_name; PyObject *f_mode; int (*f_close)(FILE *); - int f_softspace; /* Flag used by 'print' command */ int f_binary; /* Flag which indicates whether the file is open in binary (1) or text (0) mode */ char* f_buf; /* Allocated readahead buffer */ @@ -41,7 +40,6 @@ PyAPI_FUNC(PyObject *) PyFile_Name(PyObject *); PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int); PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int); -PyAPI_FUNC(int) PyFile_SoftSpace(PyObject *, int); PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *); PyAPI_FUNC(int) PyObject_AsFileDescriptor(PyObject *); Modified: python/branches/p3yk/Lib/StringIO.py ============================================================================== --- python/branches/p3yk/Lib/StringIO.py (original) +++ python/branches/p3yk/Lib/StringIO.py Sat Feb 10 00:20:19 2007 @@ -60,7 +60,6 @@ self.buflist = [] self.pos = 0 self.closed = False - self.softspace = 0 def __iter__(self): return self Modified: python/branches/p3yk/Lib/bsddb/dbrecio.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbrecio.py (original) +++ python/branches/p3yk/Lib/bsddb/dbrecio.py Sat Feb 10 00:20:19 2007 @@ -39,7 +39,6 @@ self.len = None self.pos = 0 self.closed = 0 - self.softspace = 0 def close(self): if not self.closed: Modified: python/branches/p3yk/Lib/code.py ============================================================================== --- python/branches/p3yk/Lib/code.py (original) +++ python/branches/p3yk/Lib/code.py Sat Feb 10 00:20:19 2007 @@ -12,19 +12,6 @@ __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] -def softspace(file, newvalue): - oldvalue = 0 - try: - oldvalue = file.softspace - except AttributeError: - pass - try: - file.softspace = newvalue - except (AttributeError, TypeError): - # "attribute-less object" or "read-only attributes" - pass - return oldvalue - class InteractiveInterpreter: """Base class for InteractiveConsole. @@ -105,9 +92,6 @@ raise except: self.showtraceback() - else: - if softspace(sys.stdout, 0): - print() def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. Modified: python/branches/p3yk/Lib/doctest.py ============================================================================== --- python/branches/p3yk/Lib/doctest.py (original) +++ python/branches/p3yk/Lib/doctest.py Sat Feb 10 00:20:19 2007 @@ -240,16 +240,10 @@ # that a trailing newline is missing. if result and not result.endswith("\n"): result += "\n" - # Prevent softspace from screwing up the next test case, in - # case they used print with a trailing comma in an example. - if hasattr(self, "softspace"): - del self.softspace return result - def truncate(self, size=None): + def truncate(self, size=None): StringIO.truncate(self, size) - if hasattr(self, "softspace"): - del self.softspace # Worst-case linear-time ellipsis matching. def _ellipsis_match(want, got): Modified: python/branches/p3yk/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/PyShell.py (original) +++ python/branches/p3yk/Lib/idlelib/PyShell.py Sat Feb 10 00:20:19 2007 @@ -1223,7 +1223,6 @@ self.text.insert("end-1c", "\n") self.text.mark_set("iomark", "end-1c") self.set_line_and_column() - sys.stdout.softspace = 0 def write(self, s, tags=()): try: @@ -1242,7 +1241,6 @@ def __init__(self, shell, tags, encoding=None): self.shell = shell self.tags = tags - self.softspace = 0 self.encoding = encoding def write(self, s): Modified: python/branches/p3yk/Lib/idlelib/run.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/run.py (original) +++ python/branches/p3yk/Lib/idlelib/run.py Sat Feb 10 00:20:19 2007 @@ -190,12 +190,7 @@ tb[i] = fn, ln, nm, line def flush_stdout(): - try: - if sys.stdout.softspace: - sys.stdout.softspace = 0 - sys.stdout.write("\n") - except (AttributeError, EOFError): - pass + """XXX How to do this now?""" def exit(): """Exit subprocess, possibly after first deleting sys.exitfunc Modified: python/branches/p3yk/Lib/socket.py ============================================================================== --- python/branches/p3yk/Lib/socket.py (original) +++ python/branches/p3yk/Lib/socket.py Sat Feb 10 00:20:19 2007 @@ -202,7 +202,7 @@ default_bufsize = 8192 name = "" - __slots__ = ["mode", "bufsize", "softspace", + __slots__ = ["mode", "bufsize", # "closed" is a property, see below "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", "_close"] @@ -213,7 +213,6 @@ if bufsize < 0: bufsize = self.default_bufsize self.bufsize = bufsize - self.softspace = False if bufsize == 0: self._rbufsize = 1 elif bufsize == 1: Modified: python/branches/p3yk/Lib/test/test_doctest.txt ============================================================================== --- python/branches/p3yk/Lib/test/test_doctest.txt (original) +++ python/branches/p3yk/Lib/test/test_doctest.txt Sat Feb 10 00:20:19 2007 @@ -9,9 +9,9 @@ We can make this fail by disabling the blank-line feature. >>> if 1: - ... print 'a' - ... print - ... print 'b' + ... print('a') + ... print() + ... print('b') a b Modified: python/branches/p3yk/Lib/test/test_file.py ============================================================================== --- python/branches/p3yk/Lib/test/test_file.py (original) +++ python/branches/p3yk/Lib/test/test_file.py Sat Feb 10 00:20:19 2007 @@ -30,14 +30,10 @@ def testAttributes(self): # verify expected attributes exist f = self.f - softspace = f.softspace f.name # merely shouldn't blow up f.mode # ditto f.closed # ditto - # verify softspace is writable - f.softspace = softspace # merely shouldn't blow up - # verify the others aren't for attr in 'name', 'mode', 'closed': self.assertRaises((AttributeError, TypeError), setattr, f, attr, 'oops') Modified: python/branches/p3yk/Lib/test/test_inspect.py ============================================================================== --- python/branches/p3yk/Lib/test/test_inspect.py (original) +++ python/branches/p3yk/Lib/test/test_inspect.py Sat Feb 10 00:20:19 2007 @@ -61,7 +61,6 @@ self.istest(inspect.ismodule, 'mod') self.istest(inspect.istraceback, 'tb') self.istest(inspect.isdatadescriptor, '__builtin__.file.closed') - self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace') if hasattr(types, 'GetSetDescriptorType'): self.istest(inspect.isgetsetdescriptor, 'type(tb.tb_frame).f_locals') Deleted: /python/branches/p3yk/Lib/test/test_softspace.py ============================================================================== --- /python/branches/p3yk/Lib/test/test_softspace.py Sat Feb 10 00:20:19 2007 +++ (empty file) @@ -1,14 +0,0 @@ -from test import test_support -import StringIO - -# SF bug 480215: softspace confused in nested print -f = StringIO.StringIO() -class C: - def __str__(self): - print('a', file=f) - return 'b' - -print(C(), 'c ', 'd\t', 'e', file=f) -print('f', 'g', file=f) -# In 2.2 & earlier, this printed ' a\nbc d\te\nf g\n' -test_support.vereq(f.getvalue(), 'a\nb c d\te\nf g\n') Modified: python/branches/p3yk/Modules/bz2module.c ============================================================================== --- python/branches/p3yk/Modules/bz2module.c (original) +++ python/branches/p3yk/Modules/bz2module.c Sat Feb 10 00:20:19 2007 @@ -102,8 +102,6 @@ char* f_bufend; /* Points after last occupied position */ char* f_bufptr; /* Current buffer position */ - int f_softspace; /* Flag used by 'print' command */ - int f_univ_newline; /* Handle any newline convention */ int f_newlinetypes; /* Types of newlines seen */ int f_skipnextlf; /* Skip next \n */ @@ -813,8 +811,6 @@ goto cleanup; } - self->f_softspace = 0; - Py_BEGIN_ALLOW_THREADS BZ2_bzWrite (&bzerror, self->fp, buf, len); self->pos += len; @@ -934,8 +930,6 @@ } } - self->f_softspace = 0; - /* Since we are releasing the global lock, the following code may *not* execute Python code. */ Py_BEGIN_ALLOW_THREADS @@ -1265,18 +1259,6 @@ /* ===================================================================== */ -/* Members of BZ2File_Type. */ - -#undef OFF -#define OFF(x) offsetof(BZ2FileObject, x) - -static PyMemberDef BZ2File_members[] = { - {"softspace", T_INT, OFF(f_softspace), 0, - "flag indicating that a space needs to be printed; used by print"}, - {NULL} /* Sentinel */ -}; - -/* ===================================================================== */ /* Slot definitions for BZ2File_Type. */ static int @@ -1501,7 +1483,7 @@ (getiterfunc)BZ2File_getiter, /*tp_iter*/ (iternextfunc)BZ2File_iternext, /*tp_iternext*/ BZ2File_methods, /*tp_methods*/ - BZ2File_members, /*tp_members*/ + 0, /*tp_members*/ BZ2File_getset, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ Modified: python/branches/p3yk/Modules/cStringIO.c ============================================================================== --- python/branches/p3yk/Modules/cStringIO.c (original) +++ python/branches/p3yk/Modules/cStringIO.c Sat Feb 10 00:20:19 2007 @@ -57,7 +57,6 @@ Py_ssize_t pos, string_size; Py_ssize_t buf_size; - int softspace; } Oobject; /* Declarations for objects of type StringI */ @@ -489,13 +488,6 @@ {NULL, NULL} /* sentinel */ }; -static PyMemberDef O_memberlist[] = { - {"softspace", T_INT, offsetof(Oobject, softspace), 0, - "flag indicating that a space needs to be printed; used by print"}, - /* getattr(f, "closed") is implemented without this table */ - {NULL} /* Sentinel */ -}; - static void O_dealloc(Oobject *self) { if (self->buf != NULL) @@ -536,7 +528,7 @@ PyObject_SelfIter, /*tp_iter */ (iternextfunc)IO_iternext, /*tp_iternext */ O_methods, /*tp_methods */ - O_memberlist, /*tp_members */ + 0, /*tp_members */ file_getsetlist, /*tp_getset */ }; @@ -549,7 +541,6 @@ return NULL; self->pos=0; self->string_size = 0; - self->softspace = 0; self->buf = (char *)malloc(size); if (!self->buf) { Modified: python/branches/p3yk/Objects/fileobject.c ============================================================================== --- python/branches/p3yk/Objects/fileobject.c (original) +++ python/branches/p3yk/Objects/fileobject.c Sat Feb 10 00:20:19 2007 @@ -118,7 +118,6 @@ f->f_mode = PyString_FromString(mode); f->f_close = close; - f->f_softspace = 0; f->f_binary = strchr(mode,'b') != NULL; f->f_buf = NULL; f->f_univ_newline = (strchr(mode, 'U') != NULL); @@ -1523,7 +1522,6 @@ return err_closed(); if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n)) return NULL; - f->f_softspace = 0; Py_BEGIN_ALLOW_THREADS errno = 0; n2 = fwrite(s, 1, n, f->f_fp); @@ -1626,7 +1624,6 @@ /* Since we are releasing the global lock, the following code may *not* execute Python code. */ Py_BEGIN_ALLOW_THREADS - f->f_softspace = 0; errno = 0; for (i = 0; i < j; i++) { line = PyList_GET_ITEM(list, i); @@ -1786,8 +1783,6 @@ #define OFF(x) offsetof(PyFileObject, x) static PyMemberDef file_memberlist[] = { - {"softspace", T_INT, OFF(f_softspace), 0, - "flag indicating that a space needs to be printed; used by print"}, {"mode", T_OBJECT, OFF(f_mode), RO, "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"}, {"name", T_OBJECT, OFF(f_name), RO, @@ -2094,8 +2089,7 @@ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ - /* softspace is writable: we must supply tp_setattro */ - PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ file_doc, /* tp_doc */ @@ -2119,42 +2113,6 @@ PyObject_Del, /* tp_free */ }; -/* Interface for the 'soft space' between print items. */ - -int -PyFile_SoftSpace(PyObject *f, int newflag) -{ - long oldflag = 0; - if (f == NULL) { - /* Do nothing */ - } - else if (PyFile_Check(f)) { - oldflag = ((PyFileObject *)f)->f_softspace; - ((PyFileObject *)f)->f_softspace = newflag; - } - else { - PyObject *v; - v = PyObject_GetAttrString(f, "softspace"); - if (v == NULL) - PyErr_Clear(); - else { - if (PyInt_CheckExact(v)) - oldflag = PyInt_AsLong(v); - assert(oldflag < INT_MAX); - Py_DECREF(v); - } - v = PyInt_FromLong((long)newflag); - if (v == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(f, "softspace", v) != 0) - PyErr_Clear(); - Py_DECREF(v); - } - } - return (int)oldflag; -} - /* Interfaces to write objects/strings to file-like objects */ int Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Sat Feb 10 00:20:19 2007 @@ -3349,17 +3349,6 @@ return result; } -int -Py_FlushLine(void) -{ - PyObject *f = PySys_GetObject("stdout"); - if (f == NULL) - return 0; - if (!PyFile_SoftSpace(f, 0)) - return 0; - return PyFile_WriteString("\n", f); -} - /* External interface to call any callable object. The arg must be a tuple or NULL. */ Modified: python/branches/p3yk/Python/pythonrun.c ============================================================================== --- python/branches/p3yk/Python/pythonrun.c (original) +++ python/branches/p3yk/Python/pythonrun.c Sat Feb 10 00:20:19 2007 @@ -795,8 +795,6 @@ return -1; } Py_DECREF(v); - if (Py_FlushLine()) - PyErr_Clear(); return 0; } @@ -883,8 +881,6 @@ return -1; } Py_DECREF(v); - if (Py_FlushLine()) - PyErr_Clear(); return 0; } @@ -902,8 +898,6 @@ return -1; } Py_DECREF(v); - if (Py_FlushLine()) - PyErr_Clear(); return 0; } @@ -1018,8 +1012,6 @@ int exitcode = 0; PyErr_Fetch(&exception, &value, &tb); - if (Py_FlushLine()) - PyErr_Clear(); fflush(stdout); if (value == NULL || value == Py_None) goto done; @@ -1097,8 +1089,6 @@ v2 = Py_None; Py_INCREF(v2); } - if (Py_FlushLine()) - PyErr_Clear(); fflush(stdout); PySys_WriteStderr("Error in sys.excepthook:\n"); PyErr_Display(exception2, v2, tb2); @@ -1128,8 +1118,6 @@ if (f == NULL) fprintf(stderr, "lost sys.stderr\n"); else { - if (Py_FlushLine()) - PyErr_Clear(); fflush(stdout); if (tb && tb != Py_None) err = PyTraceBack_Print(tb, f); @@ -1597,8 +1585,6 @@ Py_DECREF(exitfunc); } - if (Py_FlushLine()) - PyErr_Clear(); } static void @@ -1855,4 +1841,3 @@ #ifdef __cplusplus } #endif - Modified: python/branches/p3yk/Python/sysmodule.c ============================================================================== --- python/branches/p3yk/Python/sysmodule.c (original) +++ python/branches/p3yk/Python/sysmodule.c Sat Feb 10 00:20:19 2007 @@ -104,8 +104,6 @@ } if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) return NULL; - if (Py_FlushLine() != 0) - return NULL; outf = PySys_GetObject("stdout"); if (outf == NULL) { PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); @@ -113,8 +111,7 @@ } if (PyFile_WriteObject(o, outf, 0) != 0) return NULL; - PyFile_SoftSpace(outf, 1); - if (Py_FlushLine() != 0) + if (PyFile_WriteString("\n", outf) != 0) return NULL; if (PyObject_SetAttrString(builtins, "_", o) != 0) return NULL; From python-3000-checkins at python.org Sat Feb 10 00:27:02 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 00:27:02 +0100 (CET) Subject: [Python-3000-checkins] r53716 - in python/branches/p3yk: Python/frozen.c Tools/freeze/bkfile.py Tools/freeze/freeze.py Tools/freeze/hello.py Tools/freeze/makeconfig.py Tools/freeze/makefreeze.py Tools/freeze/parsesetup.py Tools/freeze/winmakemakefile.py Message-ID: <20070209232702.E2DB61E4014@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 00:27:01 2007 New Revision: 53716 Modified: python/branches/p3yk/Python/frozen.c python/branches/p3yk/Tools/freeze/bkfile.py python/branches/p3yk/Tools/freeze/freeze.py python/branches/p3yk/Tools/freeze/hello.py python/branches/p3yk/Tools/freeze/makeconfig.py python/branches/p3yk/Tools/freeze/makefreeze.py python/branches/p3yk/Tools/freeze/parsesetup.py python/branches/p3yk/Tools/freeze/winmakemakefile.py Log: Fix test_frozen. Modified: python/branches/p3yk/Python/frozen.c ============================================================================== --- python/branches/p3yk/Python/frozen.c (original) +++ python/branches/p3yk/Python/frozen.c Sat Feb 10 00:27:01 2007 @@ -12,14 +12,15 @@ the appropriate bytes from M___main__.c. */ static unsigned char M___hello__[] = { - 99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, - 0,64,0,0,0,115,9,0,0,0,100,0,0,71,72,100, - 1,0,83,40,2,0,0,0,115,14,0,0,0,72,101,108, - 108,111,32,119,111,114,108,100,46,46,46,78,40,0,0,0, - 0,40,0,0,0,0,40,0,0,0,0,40,0,0,0,0, - 115,8,0,0,0,104,101,108,108,111,46,112,121,115,8,0, - 0,0,60,109,111,100,117,108,101,62,1,0,0,0,115,0, - 0,0,0, + 99,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0, + 0,64,0,0,0,115,14,0,0,0,101,0,0,100,0,0, + 131,1,0,1,100,1,0,83,40,2,0,0,0,115,14,0, + 0,0,72,101,108,108,111,32,119,111,114,108,100,46,46,46, + 78,40,1,0,0,0,116,5,0,0,0,112,114,105,110,116, + 40,0,0,0,0,40,0,0,0,0,40,0,0,0,0,115, + 8,0,0,0,104,101,108,108,111,46,112,121,115,8,0,0, + 0,60,109,111,100,117,108,101,62,1,0,0,0,115,0,0, + 0,0, }; #define SIZE (int)sizeof(M___hello__) Modified: python/branches/p3yk/Tools/freeze/bkfile.py ============================================================================== --- python/branches/p3yk/Tools/freeze/bkfile.py (original) +++ python/branches/p3yk/Tools/freeze/bkfile.py Sat Feb 10 00:27:01 2007 @@ -25,7 +25,6 @@ self.readline = self.__file.readline self.readlines = self.__file.readlines self.seek = self.__file.seek - self.softspace = self.__file.softspace self.tell = self.__file.tell self.truncate = self.__file.truncate self.write = self.__file.write Modified: python/branches/p3yk/Tools/freeze/freeze.py ============================================================================== --- python/branches/p3yk/Tools/freeze/freeze.py (original) +++ python/branches/p3yk/Tools/freeze/freeze.py Sat Feb 10 00:27:01 2007 @@ -162,7 +162,7 @@ # proces option arguments for o, a in opts: if o == '-h': - print __doc__ + print(__doc__) return if o == '-d': debug = debug + 1 @@ -222,7 +222,7 @@ if win: extensions_c = 'frozen_extensions.c' if ishome: - print "(Using Python source directory)" + print("(Using Python source directory)") binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_h_dir = exec_prefix @@ -310,7 +310,7 @@ if odir and not os.path.isdir(odir): try: os.mkdir(odir) - print "Created output directory", odir + print("Created output directory", odir) except os.error as msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) base = '' @@ -371,7 +371,7 @@ if debug > 0: mf.report() - print + print() dict = mf.modules if error_if_any_missing: @@ -479,18 +479,18 @@ # Done! if odir: - print 'Now run "make" in', odir, - print 'to build the target:', base_target + print('Now run "make" in', odir, end=' ') + print('to build the target:', base_target) else: - print 'Now run "make" to build the target:', base_target + print('Now run "make" to build the target:', base_target) # Print usage message and exit def usage(msg): sys.stdout = sys.stderr - print "Error:", msg - print "Use ``%s -h'' for help" % sys.argv[0] + print("Error:", msg) + print("Use ``%s -h'' for help" % sys.argv[0]) sys.exit(2) Modified: python/branches/p3yk/Tools/freeze/hello.py ============================================================================== --- python/branches/p3yk/Tools/freeze/hello.py (original) +++ python/branches/p3yk/Tools/freeze/hello.py Sat Feb 10 00:27:01 2007 @@ -1 +1 @@ -print 'Hello world...' +print('Hello world...') Modified: python/branches/p3yk/Tools/freeze/makeconfig.py ============================================================================== --- python/branches/p3yk/Tools/freeze/makeconfig.py (original) +++ python/branches/p3yk/Tools/freeze/makeconfig.py Sat Feb 10 00:27:01 2007 @@ -40,8 +40,8 @@ def test(): import sys if not sys.argv[3:]: - print 'usage: python makeconfig.py config.c.in outputfile', - print 'modulename ...' + print('usage: python makeconfig.py config.c.in outputfile', end=' ') + print('modulename ...') sys.exit(2) if sys.argv[1] == '-': infp = sys.stdin Modified: python/branches/p3yk/Tools/freeze/makefreeze.py ============================================================================== --- python/branches/p3yk/Tools/freeze/makefreeze.py (original) +++ python/branches/p3yk/Tools/freeze/makefreeze.py Sat Feb 10 00:27:01 2007 @@ -43,7 +43,7 @@ outfp = bkfile.open(base + file, 'w') files.append(file) if debug: - print "freezing", mod, "..." + print("freezing", mod, "...") str = marshal.dumps(m.__code__) size = len(str) if m.__path__: @@ -53,7 +53,7 @@ writecode(outfp, mangled, str) outfp.close() if debug: - print "generating table of frozen modules" + print("generating table of frozen modules") outfp = bkfile.open(base + 'frozen.c', 'w') for mod, mangled, size in done: outfp.write('extern unsigned char M_%s[];\n' % mangled) Modified: python/branches/p3yk/Tools/freeze/parsesetup.py ============================================================================== --- python/branches/p3yk/Tools/freeze/parsesetup.py (original) +++ python/branches/p3yk/Tools/freeze/parsesetup.py Sat Feb 10 00:27:01 2007 @@ -84,29 +84,29 @@ import sys import os if not sys.argv[1:]: - print 'usage: python parsesetup.py Makefile*|Setup* ...' + print('usage: python parsesetup.py Makefile*|Setup* ...') sys.exit(2) for arg in sys.argv[1:]: base = os.path.basename(arg) if base[:8] == 'Makefile': - print 'Make style parsing:', arg + print('Make style parsing:', arg) v = getmakevars(arg) prdict(v) elif base[:5] == 'Setup': - print 'Setup style parsing:', arg + print('Setup style parsing:', arg) m, v = getsetupinfo(arg) prdict(m) prdict(v) else: - print arg, 'is neither a Makefile nor a Setup file' - print '(name must begin with "Makefile" or "Setup")' + print(arg, 'is neither a Makefile nor a Setup file') + print('(name must begin with "Makefile" or "Setup")') def prdict(d): keys = d.keys() keys.sort() for key in keys: value = d[key] - print "%-15s" % key, str(value) + print("%-15s" % key, str(value)) if __name__ == '__main__': test() Modified: python/branches/p3yk/Tools/freeze/winmakemakefile.py ============================================================================== --- python/branches/p3yk/Tools/freeze/winmakemakefile.py (original) +++ python/branches/p3yk/Tools/freeze/winmakemakefile.py Sat Feb 10 00:27:01 2007 @@ -52,29 +52,29 @@ def realwork(vars, moddefns, target): version_suffix = "%r%r" % sys.version_info[:2] - print "# Makefile for Microsoft Visual C++ generated by freeze.py script" - print - print 'target = %s' % target - print 'pythonhome = %s' % vars['prefix'] - print - print 'DEBUG=0 # Set to 1 to use the _d versions of Python.' - print '!IF $(DEBUG)' - print 'debug_suffix=_d' - print 'c_debug=/Zi /Od /DDEBUG /D_DEBUG' - print 'l_debug=/DEBUG' - print 'temp_dir=Build\\Debug' - print '!ELSE' - print 'debug_suffix=' - print 'c_debug=/Ox' - print 'l_debug=' - print 'temp_dir=Build\\Release' - print '!ENDIF' - print - - print '# The following line assumes you have built Python using the standard instructions' - print '# Otherwise fix the following line to point to the library.' - print 'pythonlib = "$(pythonhome)/pcbuild/python%s$(debug_suffix).lib"' % version_suffix - print + print("# Makefile for Microsoft Visual C++ generated by freeze.py script") + print() + print('target = %s' % target) + print('pythonhome = %s' % vars['prefix']) + print() + print('DEBUG=0 # Set to 1 to use the _d versions of Python.') + print('!IF $(DEBUG)') + print('debug_suffix=_d') + print('c_debug=/Zi /Od /DDEBUG /D_DEBUG') + print('l_debug=/DEBUG') + print('temp_dir=Build\\Debug') + print('!ELSE') + print('debug_suffix=') + print('c_debug=/Ox') + print('l_debug=') + print('temp_dir=Build\\Release') + print('!ENDIF') + print() + + print('# The following line assumes you have built Python using the standard instructions') + print('# Otherwise fix the following line to point to the library.') + print('pythonlib = "$(pythonhome)/pcbuild/python%s$(debug_suffix).lib"' % version_suffix) + print() # We only ever write one "entry point" symbol - either # "main" or "WinMain". Therefore, there is no need to @@ -88,59 +88,59 @@ target_ext = ".dll" - print "# As the target uses Python%s.dll, we must use this compiler option!" % version_suffix - print "cdl = /MD" - print - print "all: $(target)$(debug_suffix)%s" % (target_ext) - print - - print '$(temp_dir):' - print ' if not exist $(temp_dir)\. mkdir $(temp_dir)' - print + print("# As the target uses Python%s.dll, we must use this compiler option!" % version_suffix) + print("cdl = /MD") + print() + print("all: $(target)$(debug_suffix)%s" % (target_ext)) + print() + + print('$(temp_dir):') + print(' if not exist $(temp_dir)\. mkdir $(temp_dir)') + print() objects = [] libs = ["shell32.lib", "comdlg32.lib", "wsock32.lib", "user32.lib", "oleaut32.lib"] for moddefn in moddefns: - print "# Module", moddefn.name + print("# Module", moddefn.name) for file in moddefn.sourceFiles: base = os.path.basename(file) base, ext = os.path.splitext(base) objects.append(base + ".obj") - print '$(temp_dir)\%s.obj: "%s"' % (base, file) - print "\t@$(CC) -c -nologo /Fo$* $(cdl) $(c_debug) /D BUILD_FREEZE", - print '"-I$(pythonhome)/Include" "-I$(pythonhome)/PC" \\' - print "\t\t$(cflags) $(cdebug) $(cinclude) \\" + print('$(temp_dir)\%s.obj: "%s"' % (base, file)) + print("\t@$(CC) -c -nologo /Fo$* $(cdl) $(c_debug) /D BUILD_FREEZE", end=' ') + print('"-I$(pythonhome)/Include" "-I$(pythonhome)/PC" \\') + print("\t\t$(cflags) $(cdebug) $(cinclude) \\") extra = moddefn.GetCompilerOptions() if extra: - print "\t\t%s \\" % (' '.join(extra),) - print '\t\t"%s"' % file - print + print("\t\t%s \\" % (' '.join(extra),)) + print('\t\t"%s"' % file) + print() # Add .lib files this module needs for modlib in moddefn.GetLinkerLibs(): if modlib not in libs: libs.append(modlib) - print "ADDN_LINK_FILES=", - for addn in vars['addn_link']: print '"%s"' % (addn), - print ; print - - print "OBJS=", - for obj in objects: print '"$(temp_dir)\%s"' % (obj), - print ; print - - print "LIBS=", - for lib in libs: print '"%s"' % (lib), - print ; print - - print "$(target)$(debug_suffix)%s: $(temp_dir) $(OBJS)" % (target_ext) - print "\tlink -out:$(target)$(debug_suffix)%s %s" % (target_ext, target_link_flags), - print "\t$(OBJS) \\" - print "\t$(LIBS) \\" - print "\t$(ADDN_LINK_FILES) \\" - print "\t$(pythonlib) $(lcustom) $(l_debug)\\" - print "\t$(resources)" - print - print "clean:" - print "\t-rm -f *.obj" - print "\t-rm -f $(target).exe" + print("ADDN_LINK_FILES=", end=' ') + for addn in vars['addn_link']: print('"%s"' % (addn), end=' ') + print() ; print() + + print("OBJS=", end=' ') + for obj in objects: print('"$(temp_dir)\%s"' % (obj), end=' ') + print() ; print() + + print("LIBS=", end=' ') + for lib in libs: print('"%s"' % (lib), end=' ') + print() ; print() + + print("$(target)$(debug_suffix)%s: $(temp_dir) $(OBJS)" % (target_ext)) + print("\tlink -out:$(target)$(debug_suffix)%s %s" % (target_ext, target_link_flags), end=' ') + print("\t$(OBJS) \\") + print("\t$(LIBS) \\") + print("\t$(ADDN_LINK_FILES) \\") + print("\t$(pythonlib) $(lcustom) $(l_debug)\\") + print("\t$(resources)") + print() + print("clean:") + print("\t-rm -f *.obj") + print("\t-rm -f $(target).exe") From python-3000-checkins at python.org Sat Feb 10 00:38:28 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 00:38:28 +0100 (CET) Subject: [Python-3000-checkins] r53717 - python/branches/p3yk/Tools/freeze Message-ID: <20070209233828.A66BB1E4012@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 00:38:28 2007 New Revision: 53717 Modified: python/branches/p3yk/Tools/freeze/ (props changed) Log: Ignore *.py[co]. From python-3000-checkins at python.org Sat Feb 10 00:39:59 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 00:39:59 +0100 (CET) Subject: [Python-3000-checkins] r53718 - python/branches/p3yk/Lib/test/test_doctest.py Message-ID: <20070209233959.8DEAB1E4012@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 00:39:59 2007 New Revision: 53718 Modified: python/branches/p3yk/Lib/test/test_doctest.py Log: Fix the remaining doctest failures. One was a modified line that was echoed in an exception; the other two were softspace problems, fixed clumsily but effectively. Modified: python/branches/p3yk/Lib/test/test_doctest.py ============================================================================== --- python/branches/p3yk/Lib/test/test_doctest.py (original) +++ python/branches/p3yk/Lib/test/test_doctest.py Sat Feb 10 00:39:59 2007 @@ -325,7 +325,7 @@ ... ''' >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) Traceback (most recent call last): - ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)' + ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))' If there's no blank space after a PS1 prompt ('>>>'), then `DocTest` will raise a ValueError: @@ -1028,14 +1028,18 @@ ... also matches nothing: - >>> for i in range(100): - ... print(i**2, end=' ') #doctest: +ELLIPSIS - 0 1...4...9 16 ... 36 49 64 ... 9801 + >>> if 1: + ... for i in range(100): + ... print(i**2, end=' ') #doctest: +ELLIPSIS + ... print('!') + 0 1...4...9 16 ... 36 49 64 ... 9801 ! ... can be surprising; e.g., this test passes: - >>> for i in range(21): #doctest: +ELLIPSIS - ... print(i, end=' ') + >>> if 1: #doctest: +ELLIPSIS + ... for i in range(20): + ... print(i, end=' ') + ... print(20) 0 1 2 ...1...2...0 Examples from the docs: From python-3000-checkins at python.org Sat Feb 10 00:52:15 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 00:52:15 +0100 (CET) Subject: [Python-3000-checkins] r53719 - python/branches/p3yk/Misc/NEWS Message-ID: <20070209235215.04E041E4012@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 00:52:14 2007 New Revision: 53719 Modified: python/branches/p3yk/Misc/NEWS Log: News about softspace. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Sat Feb 10 00:52:14 2007 @@ -36,7 +36,15 @@ Core and Builtins ----------------- -- PEP 3105: print is now a function. +- PEP 3105: print is now a function. Also (not in the PEP) the + 'softspace' attribute of files is now gone (since print() doesn't use + it). A side effect of this change is that you can get incomplete + output lines in interactive sessions: + + >>> print(42, end="") + 42>>> + + We may be able to fix this after the I/O library rewrite. - PEP 3102: keyword-only arguments. From python-3000-checkins at python.org Sat Feb 10 02:11:46 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 02:11:46 +0100 (CET) Subject: [Python-3000-checkins] r53721 - in python/branches/p3yk: Lib/test/test_dictviews.py Objects/dictobject.c Message-ID: <20070210011146.DB9431E4012@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 02:11:45 2007 New Revision: 53721 Added: python/branches/p3yk/Lib/test/test_dictviews.py (contents, props changed) Modified: python/branches/p3yk/Objects/dictobject.c Log: Very preliminary work on dict views. Added: python/branches/p3yk/Lib/test/test_dictviews.py ============================================================================== --- (empty file) +++ python/branches/p3yk/Lib/test/test_dictviews.py Sat Feb 10 02:11:45 2007 @@ -0,0 +1,25 @@ +import unittest +from test import test_support + +class DictSetTest(unittest.TestCase): + + def test_dict_keys(self): + d = {1: 10, "a": "ABC"} + keys = d.KEYS() + self.assertEqual(set(keys), {1, "a"}) + + def test_dict_items(self): + d = {1: 10, "a": "ABC"} + items = d.ITEMS() + self.assertEqual(set(items), {(1, 10), ("a", "ABC")}) + + def test_dict_values(self): + d = {1: 10, "a": "ABC"} + values = d.VALUES() + self.assertEqual(set(values), {10, "ABC"}) + +def test_main(): + test_support.run_unittest(DictSetTest) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Sat Feb 10 02:11:45 2007 @@ -1808,8 +1808,8 @@ "D.values() -> list of D's values"); PyDoc_STRVAR(update__doc__, -"D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\n\ -(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]"); +"D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\ +\n(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]"); PyDoc_STRVAR(fromkeys__doc__, "dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\ @@ -1830,6 +1830,15 @@ PyDoc_STRVAR(iteritems__doc__, "D.iteritems() -> an iterator over the (key, value) items of D"); +/* Forward */ +static PyObject *dictkeys_new(PyObject *); +static PyObject *dictitems_new(PyObject *); +static PyObject *dictvalues_new(PyObject *); + +PyDoc_STRVAR(KEYS__doc__, "D.KEYS() -> a set-like object for D's keys"); +PyDoc_STRVAR(ITEMS__doc__, "D.ITEMS() -> a set-like object for D's items"); +PyDoc_STRVAR(VALUES__doc__, "D.VALUES() -> a set-like object for D's values"); + static PyMethodDef mapp_methods[] = { {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, contains__doc__}, @@ -1845,6 +1854,12 @@ popitem__doc__}, {"keys", (PyCFunction)dict_keys, METH_NOARGS, keys__doc__}, + {"KEYS", (PyCFunction)dictkeys_new, METH_NOARGS, + KEYS__doc__}, + {"ITEMS", (PyCFunction)dictitems_new, METH_NOARGS, + ITEMS__doc__}, + {"VALUES", (PyCFunction)dictvalues_new, METH_NOARGS, + VALUES__doc__}, {"items", (PyCFunction)dict_items, METH_NOARGS, items__doc__}, {"values", (PyCFunction)dict_values, METH_NOARGS, @@ -2078,10 +2093,12 @@ return PyInt_FromSize_t(len); } -PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); +PyDoc_STRVAR(length_hint_doc, + "Private method returning an estimate of len(list(it))."); static PyMethodDef dictiter_methods[] = { - {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, length_hint_doc}, + {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, + length_hint_doc}, {NULL, NULL} /* sentinel */ }; @@ -2317,3 +2334,225 @@ dictiter_methods, /* tp_methods */ 0, }; + + +/* View objects for keys(), items(), values(). */ +/* While this is incomplete, we use KEYS(), ITEMS(), VALUES(). */ + +/* The instance lay-out is the same for all three; but the type differs. */ + +typedef struct { + PyObject_HEAD + dictobject *ds_dict; +} dictviewobject; + + +static void +dictview_dealloc(dictviewobject *ds) +{ + Py_XDECREF(ds->ds_dict); + PyObject_Del(ds); +} + +static PyObject * +dictview_length_hint(dictviewobject *ds) +{ + Py_ssize_t len = 0; + if (ds->ds_dict != NULL) + len = ds->ds_dict->ma_used; + return PyInt_FromSize_t(len); +} + +static PyObject * +dictview_new(PyObject *dict, PyTypeObject *type) +{ + dictviewobject *ds; + if (dict == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyDict_Check(dict)) { + /* XXX Get rid of this restriction later */ + PyErr_Format(PyExc_TypeError, + "%s() requires a dict argument, not '%s'", + type->tp_name, dict->ob_type->tp_name); + return NULL; + } + ds = PyObject_New(dictviewobject, type); + if (ds == NULL) + return NULL; + Py_INCREF(dict); + ds->ds_dict = (dictobject *)dict; + return (PyObject *)ds; +} + +/* dict_keys */ + +static PyObject * +dictkeys_iter(dictviewobject *ds) +{ + if (ds->ds_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(ds->ds_dict, &PyDictIterKey_Type); +} + +static PyMethodDef dictkeys_methods[] = { + {"__length_hint__", (PyCFunction)dictview_length_hint, METH_NOARGS, + length_hint_doc}, + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyDictKeys_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "dict_keys", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictkeys_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictkeys_methods, /* tp_methods */ + 0, +}; + +static PyObject * +dictkeys_new(PyObject *dict) +{ + return dictview_new(dict, &PyDictKeys_Type); +} + +/* dict_items */ + +static PyObject * +dictitems_iter(dictviewobject *ds) +{ + if (ds->ds_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(ds->ds_dict, &PyDictIterItem_Type); +} + +static PyMethodDef dictitems_methods[] = { + {"__length_hint__", (PyCFunction)dictview_length_hint, METH_NOARGS, + length_hint_doc}, + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyDictItems_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "dict_items", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictitems_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictitems_methods, /* tp_methods */ + 0, +}; + +static PyObject * +dictitems_new(PyObject *dict) +{ + return dictview_new(dict, &PyDictItems_Type); +} + +/* dict_values */ + +static PyObject * +dictvalues_iter(dictviewobject *ds) +{ + if (ds->ds_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(ds->ds_dict, &PyDictIterValue_Type); +} + +static PyMethodDef dictvalues_methods[] = { + {"__length_hint__", (PyCFunction)dictview_length_hint, METH_NOARGS, + length_hint_doc}, + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyDictValues_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "dict_values", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictvalues_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictvalues_methods, /* tp_methods */ + 0, +}; + +static PyObject * +dictvalues_new(PyObject *dict) +{ + return dictview_new(dict, &PyDictValues_Type); +} From python-3000-checkins at python.org Sat Feb 10 05:54:20 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 05:54:20 +0100 (CET) Subject: [Python-3000-checkins] r53723 - in python/branches/p3yk: Lib/test/test_dictviews.py Objects/dictobject.c Message-ID: <20070210045420.039D81E4012@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 05:54:19 2007 New Revision: 53723 Modified: python/branches/p3yk/Lib/test/test_dictviews.py python/branches/p3yk/Objects/dictobject.c Log: Endow dict views with a proper length method. Modified: python/branches/p3yk/Lib/test/test_dictviews.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dictviews.py (original) +++ python/branches/p3yk/Lib/test/test_dictviews.py Sat Feb 10 05:54:19 2007 @@ -7,16 +7,19 @@ d = {1: 10, "a": "ABC"} keys = d.KEYS() self.assertEqual(set(keys), {1, "a"}) + self.assertEqual(len(keys), 2) def test_dict_items(self): d = {1: 10, "a": "ABC"} items = d.ITEMS() self.assertEqual(set(items), {(1, 10), ("a", "ABC")}) + self.assertEqual(len(items), 2) def test_dict_values(self): d = {1: 10, "a": "ABC"} values = d.VALUES() self.assertEqual(set(values), {10, "ABC"}) + self.assertEqual(len(values), 2) def test_main(): test_support.run_unittest(DictSetTest) Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Sat Feb 10 05:54:19 2007 @@ -2354,13 +2354,13 @@ PyObject_Del(ds); } -static PyObject * -dictview_length_hint(dictviewobject *ds) +static Py_ssize_t +dictview_len(dictviewobject *ds) { Py_ssize_t len = 0; if (ds->ds_dict != NULL) len = ds->ds_dict->ma_used; - return PyInt_FromSize_t(len); + return len; } static PyObject * @@ -2397,9 +2397,18 @@ return dictiter_new(ds->ds_dict, &PyDictIterKey_Type); } +static PySequenceMethods dictkeys_as_sequence = { + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)0, /* sq_contains */ +}; + static PyMethodDef dictkeys_methods[] = { - {"__length_hint__", (PyCFunction)dictview_length_hint, METH_NOARGS, - length_hint_doc}, {NULL, NULL} /* sentinel */ }; @@ -2417,7 +2426,7 @@ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ - 0, /* tp_as_sequence */ + &dictkeys_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ @@ -2454,9 +2463,18 @@ return dictiter_new(ds->ds_dict, &PyDictIterItem_Type); } +static PySequenceMethods dictitems_as_sequence = { + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)0, /* sq_contains */ +}; + static PyMethodDef dictitems_methods[] = { - {"__length_hint__", (PyCFunction)dictview_length_hint, METH_NOARGS, - length_hint_doc}, {NULL, NULL} /* sentinel */ }; @@ -2474,7 +2492,7 @@ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ - 0, /* tp_as_sequence */ + &dictitems_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ @@ -2511,9 +2529,18 @@ return dictiter_new(ds->ds_dict, &PyDictIterValue_Type); } +static PySequenceMethods dictvalues_as_sequence = { + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)0, /* sq_contains */ +}; + static PyMethodDef dictvalues_methods[] = { - {"__length_hint__", (PyCFunction)dictview_length_hint, METH_NOARGS, - length_hint_doc}, {NULL, NULL} /* sentinel */ }; @@ -2531,7 +2558,7 @@ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ - 0, /* tp_as_sequence */ + &dictvalues_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ From python-3000-checkins at python.org Sat Feb 10 19:55:07 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 19:55:07 +0100 (CET) Subject: [Python-3000-checkins] r53724 - in python/branches/p3yk: Lib/test/test_dictviews.py Objects/dictobject.c Message-ID: <20070210185507.1C61B1E4003@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 19:55:06 2007 New Revision: 53724 Modified: python/branches/p3yk/Lib/test/test_dictviews.py python/branches/p3yk/Objects/dictobject.c Log: Implement __contains__ for dict_keys and dict_items. (Not for dict_values, where it can't be done faster than the default implementation which just iterates the elements.) Modified: python/branches/p3yk/Lib/test/test_dictviews.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dictviews.py (original) +++ python/branches/p3yk/Lib/test/test_dictviews.py Sat Feb 10 19:55:06 2007 @@ -3,17 +3,39 @@ class DictSetTest(unittest.TestCase): + def test_constructors_not_callable(self): + kt = type({}.KEYS()) + self.assertRaises(TypeError, kt, {}) + self.assertRaises(TypeError, kt) + it = type({}.ITEMS()) + self.assertRaises(TypeError, it, {}) + self.assertRaises(TypeError, it) + vt = type({}.VALUES()) + self.assertRaises(TypeError, vt, {}) + self.assertRaises(TypeError, vt) + def test_dict_keys(self): d = {1: 10, "a": "ABC"} keys = d.KEYS() self.assertEqual(set(keys), {1, "a"}) self.assertEqual(len(keys), 2) + self.assert_(1 in keys) + self.assert_("a" in keys) + self.assert_(10 not in keys) + self.assert_("Z" not in keys) def test_dict_items(self): d = {1: 10, "a": "ABC"} items = d.ITEMS() self.assertEqual(set(items), {(1, 10), ("a", "ABC")}) self.assertEqual(len(items), 2) + self.assert_((1, 10) in items) + self.assert_(("a", "ABC") in items) + self.assert_((1, 11) not in items) + self.assert_(1 not in items) + self.assert_(() not in items) + self.assert_((1,) not in items) + self.assert_((1, 2, 3) not in items) def test_dict_values(self): d = {1: 10, "a": "ABC"} Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Sat Feb 10 19:55:06 2007 @@ -2336,37 +2336,40 @@ }; +/***********************************************/ /* View objects for keys(), items(), values(). */ +/***********************************************/ + /* While this is incomplete, we use KEYS(), ITEMS(), VALUES(). */ /* The instance lay-out is the same for all three; but the type differs. */ typedef struct { PyObject_HEAD - dictobject *ds_dict; + dictobject *dv_dict; } dictviewobject; static void -dictview_dealloc(dictviewobject *ds) +dictview_dealloc(dictviewobject *dv) { - Py_XDECREF(ds->ds_dict); - PyObject_Del(ds); + Py_XDECREF(dv->dv_dict); + PyObject_Del(dv); } static Py_ssize_t -dictview_len(dictviewobject *ds) +dictview_len(dictviewobject *dv) { Py_ssize_t len = 0; - if (ds->ds_dict != NULL) - len = ds->ds_dict->ma_used; + if (dv->dv_dict != NULL) + len = dv->dv_dict->ma_used; return len; } static PyObject * dictview_new(PyObject *dict, PyTypeObject *type) { - dictviewobject *ds; + dictviewobject *dv; if (dict == NULL) { PyErr_BadInternalCall(); return NULL; @@ -2378,23 +2381,31 @@ type->tp_name, dict->ob_type->tp_name); return NULL; } - ds = PyObject_New(dictviewobject, type); - if (ds == NULL) + dv = PyObject_New(dictviewobject, type); + if (dv == NULL) return NULL; Py_INCREF(dict); - ds->ds_dict = (dictobject *)dict; - return (PyObject *)ds; + dv->dv_dict = (dictobject *)dict; + return (PyObject *)dv; } -/* dict_keys */ +/*** dict_keys ***/ static PyObject * -dictkeys_iter(dictviewobject *ds) +dictkeys_iter(dictviewobject *dv) { - if (ds->ds_dict == NULL) { + if (dv->dv_dict == NULL) { Py_RETURN_NONE; } - return dictiter_new(ds->ds_dict, &PyDictIterKey_Type); + return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); +} + +static int +dictkeys_contains(dictviewobject *dv, PyObject *obj) +{ + if (dv->dv_dict == NULL) + return 0; + return PyDict_Contains((PyObject *)dv->dv_dict, obj); } static PySequenceMethods dictkeys_as_sequence = { @@ -2405,7 +2416,7 @@ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ - (objobjproc)0, /* sq_contains */ + (objobjproc)dictkeys_contains, /* sq_contains */ }; static PyMethodDef dictkeys_methods[] = { @@ -2452,15 +2463,34 @@ return dictview_new(dict, &PyDictKeys_Type); } -/* dict_items */ +/*** dict_items ***/ static PyObject * -dictitems_iter(dictviewobject *ds) +dictitems_iter(dictviewobject *dv) { - if (ds->ds_dict == NULL) { + if (dv->dv_dict == NULL) { Py_RETURN_NONE; } - return dictiter_new(ds->ds_dict, &PyDictIterItem_Type); + return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); +} + +static int +dictitems_contains(dictviewobject *dv, PyObject *obj) +{ + PyObject *key, *value, *found; + if (dv->dv_dict == NULL) + return 0; + if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) + return 0; + key = PyTuple_GET_ITEM(obj, 0); + value = PyTuple_GET_ITEM(obj, 1); + found = PyDict_GetItem((PyObject *)dv->dv_dict, key); + if (found == NULL) { + if (PyErr_Occurred()) + return -1; + return 0; + } + return PyObject_RichCompareBool(value, found, Py_EQ); } static PySequenceMethods dictitems_as_sequence = { @@ -2471,7 +2501,7 @@ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ - (objobjproc)0, /* sq_contains */ + (objobjproc)dictitems_contains, /* sq_contains */ }; static PyMethodDef dictitems_methods[] = { @@ -2518,15 +2548,15 @@ return dictview_new(dict, &PyDictItems_Type); } -/* dict_values */ +/*** dict_values ***/ static PyObject * -dictvalues_iter(dictviewobject *ds) +dictvalues_iter(dictviewobject *dv) { - if (ds->ds_dict == NULL) { + if (dv->dv_dict == NULL) { Py_RETURN_NONE; } - return dictiter_new(ds->ds_dict, &PyDictIterValue_Type); + return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); } static PySequenceMethods dictvalues_as_sequence = { From python-3000-checkins at python.org Sat Feb 10 23:53:18 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 10 Feb 2007 23:53:18 +0100 (CET) Subject: [Python-3000-checkins] r53727 - python/branches/p3yk/setup.py Message-ID: <20070210225318.9817A1E4004@bag.python.org> Author: guido.van.rossum Date: Sat Feb 10 23:53:17 2007 New Revision: 53727 Modified: python/branches/p3yk/setup.py Log: Random change to make this work unchanged when dict.keys() returns a dict view. Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Sat Feb 10 23:53:17 2007 @@ -688,8 +688,7 @@ # ignore this header, it didn't contain a version number if db_setup_debug: print("db.h: unsupported version", db_ver, "in", d) - db_found_vers = db_ver_inc_map.keys() - db_found_vers.sort() + db_found_vers = sorted(db_ver_inc_map.keys()) while db_found_vers: db_ver = db_found_vers.pop() From brett at python.org Sun Feb 11 00:16:21 2007 From: brett at python.org (Brett Cannon) Date: Sat, 10 Feb 2007 15:16:21 -0800 Subject: [Python-3000-checkins] r53724 - in python/branches/p3yk: Lib/test/test_dictviews.py Objects/dictobject.c In-Reply-To: <20070210185507.1C61B1E4003@bag.python.org> References: <20070210185507.1C61B1E4003@bag.python.org> Message-ID: On 2/10/07, guido.van.rossum wrote: > Author: guido.van.rossum > Date: Sat Feb 10 19:55:06 2007 > New Revision: 53724 > > Modified: > python/branches/p3yk/Lib/test/test_dictviews.py > python/branches/p3yk/Objects/dictobject.c > Log: > Implement __contains__ for dict_keys and dict_items. > (Not for dict_values, where it can't be done faster than > the default implementation which just iterates the elements.) What default implementation? I assume you don't mean the default way for dicts since you are already using that for keys and items. -Brett From guido at python.org Sun Feb 11 00:21:49 2007 From: guido at python.org (Guido van Rossum) Date: Sat, 10 Feb 2007 15:21:49 -0800 Subject: [Python-3000-checkins] r53724 - in python/branches/p3yk: Lib/test/test_dictviews.py Objects/dictobject.c In-Reply-To: References: <20070210185507.1C61B1E4003@bag.python.org> Message-ID: I meant the default implementation for 'in' which simply iterates over the collection. While 'in' can be implemented efficiently using the dict lookup for keys() and items(), for values() this doesn't work -- if you want to know if a particular value is in dict.values(), you have to iterate over the entire dict until you find it. (I had dreams of caching this by converting the values to a set, but was rudely awakened when I realized that values don't need to be hashable. So dict.values(), unlike dict.keys() and dict.items(), cannot return an object that behaves and is as efficient as a set, without copying anything; the only property I plan to implement (and have already done so) is __iter__ which gives all the values in random order. --Guido On 2/10/07, Brett Cannon wrote: > On 2/10/07, guido.van.rossum wrote: > > Author: guido.van.rossum > > Date: Sat Feb 10 19:55:06 2007 > > New Revision: 53724 > > > > Modified: > > python/branches/p3yk/Lib/test/test_dictviews.py > > python/branches/p3yk/Objects/dictobject.c > > Log: > > Implement __contains__ for dict_keys and dict_items. > > (Not for dict_values, where it can't be done faster than > > the default implementation which just iterates the elements.) > > What default implementation? I assume you don't mean the default way > for dicts since you are already using that for keys and items. > > -Brett > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From brett at python.org Sun Feb 11 00:34:11 2007 From: brett at python.org (Brett Cannon) Date: Sat, 10 Feb 2007 15:34:11 -0800 Subject: [Python-3000-checkins] r53724 - in python/branches/p3yk: Lib/test/test_dictviews.py Objects/dictobject.c In-Reply-To: References: <20070210185507.1C61B1E4003@bag.python.org> Message-ID: On 2/10/07, Guido van Rossum wrote: > I meant the default implementation for 'in' which simply iterates over > the collection. While 'in' can be implemented efficiently using the > dict lookup for keys() and items(), for values() this doesn't work -- > if you want to know if a particular value is in dict.values(), you > have to iterate over the entire dict until you find it. Ah, OK. So just 'in' get the iterator for the dict values view and iterate through. Makes sense now. > (I had dreams > of caching this by converting the values to a set, but was rudely > awakened when I realized that values don't need to be hashable. So > dict.values(), unlike dict.keys() and dict.items(), cannot return an > object that behaves and is as efficient as a set, without copying > anything; the only property I plan to implement (and have already done > so) is __iter__ which gives all the values in random order. > Yeah, unless you want partial caching for those that are hashable, but at that point it probably isn't worth it. -Brett > --Guido > > On 2/10/07, Brett Cannon wrote: > > On 2/10/07, guido.van.rossum wrote: > > > Author: guido.van.rossum > > > Date: Sat Feb 10 19:55:06 2007 > > > New Revision: 53724 > > > > > > Modified: > > > python/branches/p3yk/Lib/test/test_dictviews.py > > > python/branches/p3yk/Objects/dictobject.c > > > Log: > > > Implement __contains__ for dict_keys and dict_items. > > > (Not for dict_values, where it can't be done faster than > > > the default implementation which just iterates the elements.) > > > > What default implementation? I assume you don't mean the default way > > for dicts since you are already using that for keys and items. > > > > -Brett > > _______________________________________________ > > Python-3000-checkins mailing list > > Python-3000-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-3000-checkins > > > > > -- > --Guido van Rossum (home page: http://www.python.org/~guido/) > From guido at python.org Sun Feb 11 00:50:48 2007 From: guido at python.org (Guido van Rossum) Date: Sat, 10 Feb 2007 15:50:48 -0800 Subject: [Python-3000-checkins] r53724 - in python/branches/p3yk: Lib/test/test_dictviews.py Objects/dictobject.c In-Reply-To: References: <20070210185507.1C61B1E4003@bag.python.org> Message-ID: On 2/10/07, Brett Cannon wrote: > > (I had dreams > > of caching this by converting the values to a set, but was rudely > > awakened when I realized that values don't need to be hashable. So > > dict.values(), unlike dict.keys() and dict.items(), cannot return an > > object that behaves and is as efficient as a set, without copying > > anything; the only property I plan to implement (and have already done > > so) is __iter__ which gives all the values in random order. > > Yeah, unless you want partial caching for those that are hashable, but > at that point it probably isn't worth it. I'd rather make it obvious that the values() view isn't all that useful, rather than trying to hide the flaws until they pop up when you least expect them. After all, the list returned by the current values() method isn't all that useful either, so it's not like people expect a lot from .values(). -- --Guido van Rossum (home page: http://www.python.org/~guido/) From python-3000-checkins at python.org Sun Feb 11 07:12:16 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 07:12:16 +0100 (CET) Subject: [Python-3000-checkins] r53732 - in python/branches/p3yk: Include/abstract.h Lib/ConfigParser.py Lib/Cookie.py Lib/UserDict.py Lib/_LWPCookieJar.py Lib/_strptime.py Lib/_threading_local.py Lib/base64.py Lib/compiler/ast.py Lib/compiler/misc.py Lib/compiler/pyassem.py Lib/cookielib.py Lib/copy.py Lib/csv.py Lib/ctypes/test/__init__.py Lib/difflib.py Lib/distutils/sysconfig.py Lib/dumbdbm.py Lib/encodings/punycode.py Lib/filecmp.py Lib/htmlentitydefs.py Lib/httplib.py Lib/mailbox.py Lib/mailcap.py Lib/mhlib.py Lib/pickle.py Lib/profile.py Lib/pstats.py Lib/pyclbr.py Lib/rfc822.py Lib/shelve.py Lib/symbol.py Lib/symtable.py Lib/test/fork_wait.py Lib/test/mapping_tests.py Lib/test/pickletester.py Lib/test/string_tests.py Lib/test/test_anydbm.py Lib/test/test_array.py Lib/test/test_bsddb.py Lib/test/test_builtin.py Lib/test/test_cfgparser.py Lib/test/test_cgi.py Lib/test/test_compile.py Lib/test/test_cookie.py Lib/test/test_copy.py Lib/test/test_descr.py Lib/test/test_dictviews.py Lib/test/test_iter.py Lib/test/test_iterlen.py Lib/test/test_itertools.py Lib/test/test_mailbox.py Lib/test/test_mhlib.py Lib/test/test_richcmp.py Lib/test/test_site.py Lib/test/test_support.py Lib/test/test_urllib2.py Lib/test/test_userdict.py Lib/test/test_uuid.py Lib/test/test_weakref.py Lib/test/test_xmlrpc.py Lib/threading.py Lib/token.py Lib/trace.py Lib/urllib2.py Lib/weakref.py Lib/xml/etree/ElementTree.py Misc/NEWS Modules/cPickle.c Modules/collectionsmodule.c Objects/abstract.c Objects/dictobject.c Objects/typeobject.c Message-ID: <20070211061216.19A551E4008@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 07:12:03 2007 New Revision: 53732 Modified: python/branches/p3yk/Include/abstract.h python/branches/p3yk/Lib/ConfigParser.py python/branches/p3yk/Lib/Cookie.py python/branches/p3yk/Lib/UserDict.py python/branches/p3yk/Lib/_LWPCookieJar.py python/branches/p3yk/Lib/_strptime.py python/branches/p3yk/Lib/_threading_local.py python/branches/p3yk/Lib/base64.py python/branches/p3yk/Lib/compiler/ast.py python/branches/p3yk/Lib/compiler/misc.py python/branches/p3yk/Lib/compiler/pyassem.py python/branches/p3yk/Lib/cookielib.py python/branches/p3yk/Lib/copy.py python/branches/p3yk/Lib/csv.py python/branches/p3yk/Lib/ctypes/test/__init__.py python/branches/p3yk/Lib/difflib.py python/branches/p3yk/Lib/distutils/sysconfig.py python/branches/p3yk/Lib/dumbdbm.py python/branches/p3yk/Lib/encodings/punycode.py python/branches/p3yk/Lib/filecmp.py python/branches/p3yk/Lib/htmlentitydefs.py python/branches/p3yk/Lib/httplib.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/mailcap.py python/branches/p3yk/Lib/mhlib.py python/branches/p3yk/Lib/pickle.py python/branches/p3yk/Lib/profile.py python/branches/p3yk/Lib/pstats.py python/branches/p3yk/Lib/pyclbr.py python/branches/p3yk/Lib/rfc822.py python/branches/p3yk/Lib/shelve.py python/branches/p3yk/Lib/symbol.py python/branches/p3yk/Lib/symtable.py python/branches/p3yk/Lib/test/fork_wait.py python/branches/p3yk/Lib/test/mapping_tests.py python/branches/p3yk/Lib/test/pickletester.py python/branches/p3yk/Lib/test/string_tests.py python/branches/p3yk/Lib/test/test_anydbm.py python/branches/p3yk/Lib/test/test_array.py python/branches/p3yk/Lib/test/test_bsddb.py python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_cfgparser.py python/branches/p3yk/Lib/test/test_cgi.py python/branches/p3yk/Lib/test/test_compile.py python/branches/p3yk/Lib/test/test_cookie.py python/branches/p3yk/Lib/test/test_copy.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_dictviews.py python/branches/p3yk/Lib/test/test_iter.py python/branches/p3yk/Lib/test/test_iterlen.py python/branches/p3yk/Lib/test/test_itertools.py python/branches/p3yk/Lib/test/test_mailbox.py python/branches/p3yk/Lib/test/test_mhlib.py python/branches/p3yk/Lib/test/test_richcmp.py python/branches/p3yk/Lib/test/test_site.py python/branches/p3yk/Lib/test/test_support.py python/branches/p3yk/Lib/test/test_urllib2.py python/branches/p3yk/Lib/test/test_userdict.py python/branches/p3yk/Lib/test/test_uuid.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/test/test_xmlrpc.py python/branches/p3yk/Lib/threading.py python/branches/p3yk/Lib/token.py python/branches/p3yk/Lib/trace.py python/branches/p3yk/Lib/urllib2.py python/branches/p3yk/Lib/weakref.py python/branches/p3yk/Lib/xml/etree/ElementTree.py python/branches/p3yk/Misc/NEWS python/branches/p3yk/Modules/cPickle.c python/branches/p3yk/Modules/collectionsmodule.c python/branches/p3yk/Objects/abstract.c python/branches/p3yk/Objects/dictobject.c python/branches/p3yk/Objects/typeobject.c Log: - PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone; and .keys(), .items(), .values() return dict views. The dict views aren't fully functional yet; in particular, they can't be compared to sets yet. but they are useful as "iterator wells". There are still 27 failing unit tests; I expect that many of these have fairly trivial fixes, but there are so many, I could use help. Modified: python/branches/p3yk/Include/abstract.h ============================================================================== --- python/branches/p3yk/Include/abstract.h (original) +++ python/branches/p3yk/Include/abstract.h Sun Feb 11 07:12:03 2007 @@ -1127,37 +1127,28 @@ */ - /* Implemented as macro: + PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o); - PyObject *PyMapping_Keys(PyObject *o); - - On success, return a list of the keys in object o. On - failure, return NULL. This is equivalent to the Python - expression: o.keys(). + /* + On success, return a list or tuple of the keys in object o. + On failure, return NULL. */ -#define PyMapping_Keys(O) PyObject_CallMethod(O,"keys",NULL) - - /* Implemented as macro: - PyObject *PyMapping_Values(PyObject *o); + PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o); - On success, return a list of the values in object o. On - failure, return NULL. This is equivalent to the Python - expression: o.values(). + /* + On success, return a list or tuple of the values in object o. + On failure, return NULL. */ -#define PyMapping_Values(O) PyObject_CallMethod(O,"values",NULL) - - /* Implemented as macro: - PyObject *PyMapping_Items(PyObject *o); + PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o); - On success, return a list of the items in object o, where - each item is a tuple containing a key-value pair. On - failure, return NULL. This is equivalent to the Python - expression: o.items(). + /* + On success, return a list or tuple of the items in object o, + where each item is a tuple containing a key-value pair. + On failure, return NULL. */ -#define PyMapping_Items(O) PyObject_CallMethod(O,"items",NULL) PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key); Modified: python/branches/p3yk/Lib/ConfigParser.py ============================================================================== --- python/branches/p3yk/Lib/ConfigParser.py (original) +++ python/branches/p3yk/Lib/ConfigParser.py Sun Feb 11 07:12:03 2007 @@ -214,7 +214,7 @@ def sections(self): """Return a list of section names, excluding [DEFAULT]""" # self._sections will never have [DEFAULT] in it - return self._sections.keys() + return list(self._sections.keys()) def add_section(self, section): """Create a new section in the configuration. @@ -242,7 +242,7 @@ opts.update(self._defaults) if '__name__' in opts: del opts['__name__'] - return opts.keys() + return list(opts.keys()) def read(self, filenames): """Read and parse a filename or a list of filenames. @@ -547,7 +547,7 @@ if vars: for key, value in vars.items(): d[self.optionxform(key)] = value - options = d.keys() + options = list(d.keys()) if "__name__" in options: options.remove("__name__") if raw: Modified: python/branches/p3yk/Lib/Cookie.py ============================================================================== --- python/branches/p3yk/Lib/Cookie.py (original) +++ python/branches/p3yk/Lib/Cookie.py Sun Feb 11 07:12:03 2007 @@ -488,8 +488,7 @@ # Now add any defined attributes if attrs is None: attrs = self._reserved - items = self.items() - items.sort() + items = sorted(self.items()) for K,V in items: if V == "": continue if K not in attrs: continue @@ -582,8 +581,7 @@ def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"): """Return a string suitable for HTTP.""" result = [] - items = self.items() - items.sort() + items = sorted(self.items()) for K,V in items: result.append( V.output(attrs, header) ) return sep.join(result) @@ -593,8 +591,7 @@ def __repr__(self): L = [] - items = self.items() - items.sort() + items = sorted(self.items()) for K,V in items: L.append( '%s=%s' % (K,repr(V.value) ) ) return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L)) @@ -602,8 +599,7 @@ def js_output(self, attrs=None): """Return a string suitable for JavaScript.""" result = [] - items = self.items() - items.sort() + items = sorted(self.items()) for K,V in items: result.append( V.js_output(attrs) ) return _nulljoin(result) Modified: python/branches/p3yk/Lib/UserDict.py ============================================================================== --- python/branches/p3yk/Lib/UserDict.py (original) +++ python/branches/p3yk/Lib/UserDict.py Sun Feb 11 07:12:03 2007 @@ -42,9 +42,9 @@ return c def keys(self): return self.data.keys() def items(self): return self.data.items() - def iteritems(self): return self.data.iteritems() - def iterkeys(self): return self.data.iterkeys() - def itervalues(self): return self.data.itervalues() + def iteritems(self): return self.data.items() + def iterkeys(self): return self.data.keys() + def itervalues(self): return self.data.values() def values(self): return self.data.values() def update(self, dict=None, **kwargs): if dict is None: @@ -111,12 +111,12 @@ # fourth level uses definitions from lower levels def itervalues(self): - for _, v in self.iteritems(): + for _, v in self.items(): yield v def values(self): - return [v for _, v in self.iteritems()] + return [v for _, v in self.items()] def items(self): - return list(self.iteritems()) + return list(self.items()) def clear(self): for key in self.keys(): del self[key] @@ -140,7 +140,7 @@ return value def popitem(self): try: - k, v = self.iteritems().next() + k, v = self.items().next() except StopIteration: raise KeyError, 'container is empty' del self[k] @@ -152,6 +152,9 @@ elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups for k, v in other.iteritems(): self[k] = v + elif hasattr(other, 'items'): # items may also save memory and lookups + for k, v in other.items(): + self[k] = v elif hasattr(other, 'keys'): for k in other.keys(): self[k] = other[k] @@ -166,14 +169,14 @@ except KeyError: return default def __repr__(self): - return repr(dict(self.iteritems())) + return repr(dict(self.items())) def __eq__(self, other): if isinstance(other, DictMixin): - other = dict(other.iteritems()) - return dict(self.iteritems()) == other + other = dict(other.items()) + return dict(self.items()) == other def __ne__(self, other): if isinstance(other, DictMixin): - other = dict(other.iteritems()) - return dict(self.iteritems()) != other + other = dict(other.items()) + return dict(self.items()) != other def __len__(self): return len(self.keys()) Modified: python/branches/p3yk/Lib/_LWPCookieJar.py ============================================================================== --- python/branches/p3yk/Lib/_LWPCookieJar.py (original) +++ python/branches/p3yk/Lib/_LWPCookieJar.py Sun Feb 11 07:12:03 2007 @@ -37,8 +37,7 @@ if cookie.comment: h.append(("comment", cookie.comment)) if cookie.comment_url: h.append(("commenturl", cookie.comment_url)) - keys = cookie._rest.keys() - keys.sort() + keys = sorted(cookie._rest.keys()) for k in keys: h.append((k, str(cookie._rest[k]))) Modified: python/branches/p3yk/Lib/_strptime.py ============================================================================== --- python/branches/p3yk/Lib/_strptime.py (original) +++ python/branches/p3yk/Lib/_strptime.py Sun Feb 11 07:12:03 2007 @@ -338,7 +338,7 @@ # values weekday = julian = -1 found_dict = found.groupdict() - for group_key in found_dict.iterkeys(): + for group_key in found_dict.keys(): # Directives not explicitly handled below: # c, x, X # handled by making out of other directives Modified: python/branches/p3yk/Lib/_threading_local.py ============================================================================== --- python/branches/p3yk/Lib/_threading_local.py (original) +++ python/branches/p3yk/Lib/_threading_local.py Sun Feb 11 07:12:03 2007 @@ -28,8 +28,7 @@ >>> log = [] >>> def f(): - ... items = mydata.__dict__.items() - ... items.sort() + ... items = sorted(mydata.__dict__.items()) ... log.append(items) ... mydata.number = 11 ... log.append(mydata.number) Modified: python/branches/p3yk/Lib/base64.py ============================================================================== --- python/branches/p3yk/Lib/base64.py (original) +++ python/branches/p3yk/Lib/base64.py Sun Feb 11 07:12:03 2007 @@ -126,9 +126,7 @@ 8: 'I', 17: 'R', 26: '2', } -_b32tab = _b32alphabet.items() -_b32tab.sort() -_b32tab = [v for k, v in _b32tab] +_b32tab = [v for k, v in sorted(_b32alphabet.items())] _b32rev = dict([(v, int(k)) for k, v in _b32alphabet.items()]) Modified: python/branches/p3yk/Lib/compiler/ast.py ============================================================================== --- python/branches/p3yk/Lib/compiler/ast.py (original) +++ python/branches/p3yk/Lib/compiler/ast.py Sun Feb 11 07:12:03 2007 @@ -1337,6 +1337,6 @@ def __repr__(self): return "Yield(%s)" % (repr(self.value),) -for name, obj in globals().items(): +for name, obj in list(globals().items()): if isinstance(obj, type) and issubclass(obj, Node): nodes[name.lower()] = obj Modified: python/branches/p3yk/Lib/compiler/misc.py ============================================================================== --- python/branches/p3yk/Lib/compiler/misc.py (original) +++ python/branches/p3yk/Lib/compiler/misc.py Sun Feb 11 07:12:03 2007 @@ -18,7 +18,7 @@ def add(self, elt): self.elts[elt] = elt def elements(self): - return self.elts.keys() + return list(self.elts.keys()) def has_elt(self, elt): return elt in self.elts def remove(self, elt): Modified: python/branches/p3yk/Lib/compiler/pyassem.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pyassem.py (original) +++ python/branches/p3yk/Lib/compiler/pyassem.py Sun Feb 11 07:12:03 2007 @@ -504,7 +504,7 @@ if name in cells] for name in self.cellvars: del cells[name] - self.cellvars = self.cellvars + cells.keys() + self.cellvars = self.cellvars + list(cells.keys()) self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): @@ -573,7 +573,7 @@ # similarly for other opcodes... - for name, obj in locals().items(): + for name, obj in list(locals().items()): if name[:9] == "_convert_": opname = name[9:] _converters[opname] = obj Modified: python/branches/p3yk/Lib/cookielib.py ============================================================================== --- python/branches/p3yk/Lib/cookielib.py (original) +++ python/branches/p3yk/Lib/cookielib.py Sun Feb 11 07:12:03 2007 @@ -1171,8 +1171,7 @@ def vals_sorted_by_key(adict): - keys = adict.keys() - keys.sort() + keys = sorted(adict.keys()) return map(adict.get, keys) def deepvalues(mapping): Modified: python/branches/p3yk/Lib/copy.py ============================================================================== --- python/branches/p3yk/Lib/copy.py (original) +++ python/branches/p3yk/Lib/copy.py Sun Feb 11 07:12:03 2007 @@ -230,7 +230,7 @@ def _deepcopy_dict(x, memo): y = {} memo[id(x)] = y - for key, value in x.iteritems(): + for key, value in x.items(): y[deepcopy(key, memo)] = deepcopy(value, memo) return y d[dict] = _deepcopy_dict @@ -302,7 +302,7 @@ if state is not None: y.__dict__.update(state) if slotstate is not None: - for key, value in slotstate.iteritems(): + for key, value in slotstate.items(): setattr(y, key, value) return y @@ -337,7 +337,7 @@ def __getstate__(self): return {'a': self.a, 'arg': self.arg} def __setstate__(self, state): - for key, value in state.iteritems(): + for key, value in state.items(): setattr(self, key, value) def __deepcopy__(self, memo=None): new = self.__class__(deepcopy(self.arg, memo)) Modified: python/branches/p3yk/Lib/csv.py ============================================================================== --- python/branches/p3yk/Lib/csv.py (original) +++ python/branches/p3yk/Lib/csv.py Sun Feb 11 07:12:03 2007 @@ -278,7 +278,7 @@ charFrequency[char] = metaFrequency for char in charFrequency.keys(): - items = charFrequency[char].items() + items = list(charFrequency[char].items()) if len(items) == 1 and items[0][0] == 0: continue # get the mode of the frequencies @@ -308,7 +308,7 @@ consistency -= 0.01 if len(delims) == 1: - delim = delims.keys()[0] + delim = list(delims.keys())[0] skipinitialspace = (data[0].count(delim) == data[0].count("%c " % delim)) return (delim, skipinitialspace) @@ -367,7 +367,7 @@ if len(row) != columns: continue # skip rows that have irregular number of columns - for col in columnTypes.keys(): + for col in list(columnTypes.keys()): for thisType in [int, int, float, complex]: try: Modified: python/branches/p3yk/Lib/ctypes/test/__init__.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/__init__.py (original) +++ python/branches/p3yk/Lib/ctypes/test/__init__.py Sun Feb 11 07:12:03 2007 @@ -41,7 +41,7 @@ hasattr(package.__loader__, '_files')): path = package.__name__.replace(".", os.path.sep) mask = os.path.join(path, mask) - for fnm in package.__loader__._files.iterkeys(): + for fnm in package.__loader__._files.keys(): if fnmatch.fnmatchcase(fnm, mask): yield os.path.splitext(fnm)[0].replace(os.path.sep, ".") else: Modified: python/branches/p3yk/Lib/difflib.py ============================================================================== --- python/branches/p3yk/Lib/difflib.py (original) +++ python/branches/p3yk/Lib/difflib.py Sun Feb 11 07:12:03 2007 @@ -331,7 +331,7 @@ junkdict = {} if isjunk: for d in populardict, b2j: - for elt in d.keys(): + for elt in list(d.keys()): if isjunk(elt): junkdict[elt] = 1 del d[elt] Modified: python/branches/p3yk/Lib/distutils/sysconfig.py ============================================================================== --- python/branches/p3yk/Lib/distutils/sysconfig.py (original) +++ python/branches/p3yk/Lib/distutils/sysconfig.py Sun Feb 11 07:12:03 2007 @@ -271,7 +271,7 @@ # do variable interpolation here while notdone: - for name in notdone.keys(): + for name in list(notdone): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: Modified: python/branches/p3yk/Lib/dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/dumbdbm.py (original) +++ python/branches/p3yk/Lib/dumbdbm.py Sun Feb 11 07:12:03 2007 @@ -109,7 +109,7 @@ f = self._open(self._dirfile, 'w') self._chmod(self._dirfile) - for key, pos_and_siz_pair in self._index.iteritems(): + for key, pos_and_siz_pair in self._index.items(): f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -202,7 +202,7 @@ return key in self._index def iterkeys(self): - return self._index.iterkeys() + return self._index.keys() __iter__ = iterkeys def __len__(self): Modified: python/branches/p3yk/Lib/encodings/punycode.py ============================================================================== --- python/branches/p3yk/Lib/encodings/punycode.py (original) +++ python/branches/p3yk/Lib/encodings/punycode.py Sun Feb 11 07:12:03 2007 @@ -17,8 +17,7 @@ base.append(c) else: extended[c] = 1 - extended = extended.keys() - extended.sort() + extended = sorted(extended.keys()) return "".join(base).encode("ascii"),extended def selective_len(str, max): Modified: python/branches/p3yk/Lib/filecmp.py ============================================================================== --- python/branches/p3yk/Lib/filecmp.py (original) +++ python/branches/p3yk/Lib/filecmp.py Sun Feb 11 07:12:03 2007 @@ -187,7 +187,7 @@ def phase4_closure(self): # Recursively call phase4() on subdirectories self.phase4() - for sd in self.subdirs.itervalues(): + for sd in self.subdirs.values(): sd.phase4_closure() def report(self): # Print a report on the differences between a and b @@ -217,13 +217,13 @@ def report_partial_closure(self): # Print reports on self and on subdirs self.report() - for sd in self.subdirs.itervalues(): + for sd in self.subdirs.values(): print() sd.report() def report_full_closure(self): # Report on self and subdirs recursively self.report() - for sd in self.subdirs.itervalues(): + for sd in self.subdirs.values(): print() sd.report_full_closure() Modified: python/branches/p3yk/Lib/htmlentitydefs.py ============================================================================== --- python/branches/p3yk/Lib/htmlentitydefs.py (original) +++ python/branches/p3yk/Lib/htmlentitydefs.py Sun Feb 11 07:12:03 2007 @@ -263,7 +263,7 @@ # (or a character reference if the character is outside the Latin-1 range) entitydefs = {} -for (name, codepoint) in name2codepoint.iteritems(): +for (name, codepoint) in name2codepoint.items(): codepoint2name[codepoint] = name if codepoint <= 0xff: entitydefs[name] = chr(codepoint) Modified: python/branches/p3yk/Lib/httplib.py ============================================================================== --- python/branches/p3yk/Lib/httplib.py (original) +++ python/branches/p3yk/Lib/httplib.py Sun Feb 11 07:12:03 2007 @@ -611,7 +611,7 @@ """Return list of (header, value) tuples.""" if self.msg is None: raise ResponseNotReady() - return self.msg.items() + return list(self.msg.items()) class HTTPConnection: @@ -902,7 +902,7 @@ if thelen is not None: self.putheader('Content-Length',thelen) - for hdr, value in headers.iteritems(): + for hdr, value in headers.items(): self.putheader(hdr, value) self.endheaders() Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Sun Feb 11 07:12:03 2007 @@ -95,11 +95,11 @@ def keys(self): """Return a list of keys.""" - return list(self.iterkeys()) + return list(self.keys()) def itervalues(self): """Return an iterator over all messages.""" - for key in self.iterkeys(): + for key in self.keys(): try: value = self[key] except KeyError: @@ -107,15 +107,15 @@ yield value def __iter__(self): - return self.itervalues() + return self.values() def values(self): """Return a list of messages. Memory intensive.""" - return list(self.itervalues()) + return list(self.values()) def iteritems(self): """Return an iterator over (key, message) tuples.""" - for key in self.iterkeys(): + for key in self.keys(): try: value = self[key] except KeyError: @@ -124,7 +124,7 @@ def items(self): """Return a list of (key, message) tuples. Memory intensive.""" - return list(self.iteritems()) + return list(self.items()) def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" @@ -136,7 +136,7 @@ def clear(self): """Delete all messages.""" - for key in self.iterkeys(): + for key in self.keys(): self.discard(key) def pop(self, key, default=None): @@ -150,7 +150,7 @@ def popitem(self): """Delete an arbitrary (key, message) pair and return it.""" - for key in self.iterkeys(): + for key in self.keys(): return (key, self.pop(key)) # This is only run once. else: raise KeyError('No messages in mailbox') @@ -158,7 +158,7 @@ def update(self, arg=None): """Change the messages that correspond to certain keys.""" if hasattr(arg, 'iteritems'): - source = arg.iteritems() + source = arg.items() elif hasattr(arg, 'items'): source = arg.items() else: @@ -477,7 +477,7 @@ def next(self): """Return the next message in a one-time iteration.""" if not hasattr(self, '_onetime_keys'): - self._onetime_keys = self.iterkeys() + self._onetime_keys = self.keys() while True: try: return self[self._onetime_keys.next()] @@ -950,7 +950,7 @@ def __len__(self): """Return a count of messages in the mailbox.""" - return len(list(self.iterkeys())) + return len(list(self.keys())) def lock(self): """Lock the mailbox.""" @@ -1038,7 +1038,7 @@ f = open(os.path.join(self._path, '.mh_sequences'), 'r+') try: os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC)) - for name, keys in sequences.iteritems(): + for name, keys in sequences.items(): if len(keys) == 0: continue f.write('%s:' % name) @@ -1067,7 +1067,7 @@ sequences = self.get_sequences() prev = 0 changes = [] - for key in self.iterkeys(): + for key in self.keys(): if key - 1 != prev: changes.append((key, prev + 1)) if hasattr(os, 'link'): @@ -1091,7 +1091,7 @@ """Inspect a new MHMessage and update sequences appropriately.""" pending_sequences = message.get_sequences() all_sequences = self.get_sequences() - for name, key_list in all_sequences.iteritems(): + for name, key_list in all_sequences.items(): if name in pending_sequences: key_list.append(key) elif key in key_list: Modified: python/branches/p3yk/Lib/mailcap.py ============================================================================== --- python/branches/p3yk/Lib/mailcap.py (original) +++ python/branches/p3yk/Lib/mailcap.py Sun Feb 11 07:12:03 2007 @@ -24,7 +24,7 @@ continue morecaps = readmailcapfile(fp) fp.close() - for key, value in morecaps.iteritems(): + for key, value in morecaps.items(): if not key in caps: caps[key] = value else: Modified: python/branches/p3yk/Lib/mhlib.py ============================================================================== --- python/branches/p3yk/Lib/mhlib.py (original) +++ python/branches/p3yk/Lib/mhlib.py Sun Feb 11 07:12:03 2007 @@ -314,7 +314,7 @@ """Write the set of sequences back to the folder.""" fullname = self.getsequencesfilename() f = None - for key, seq in sequences.iteritems(): + for key, seq in sequences.items(): s = IntSet('', ' ') s.fromlist(seq) if not f: f = open(fullname, 'w') Modified: python/branches/p3yk/Lib/pickle.py ============================================================================== --- python/branches/p3yk/Lib/pickle.py (original) +++ python/branches/p3yk/Lib/pickle.py Sun Feb 11 07:12:03 2007 @@ -666,7 +666,7 @@ write(MARK + DICT) self.memoize(obj) - self._batch_setitems(obj.iteritems()) + self._batch_setitems(iter(obj.items())) dispatch[DictionaryType] = save_dict if not PyStringMap is None: Modified: python/branches/p3yk/Lib/profile.py ============================================================================== --- python/branches/p3yk/Lib/profile.py (original) +++ python/branches/p3yk/Lib/profile.py Sun Feb 11 07:12:03 2007 @@ -439,10 +439,10 @@ def snapshot_stats(self): self.stats = {} - for func, (cc, ns, tt, ct, callers) in self.timings.iteritems(): + for func, (cc, ns, tt, ct, callers) in self.timings.items(): callers = callers.copy() nc = 0 - for callcnt in callers.itervalues(): + for callcnt in callers.values(): nc += callcnt self.stats[func] = cc, nc, tt, ct, callers Modified: python/branches/p3yk/Lib/pstats.py ============================================================================== --- python/branches/p3yk/Lib/pstats.py (original) +++ python/branches/p3yk/Lib/pstats.py Sun Feb 11 07:12:03 2007 @@ -163,7 +163,7 @@ self.fcn_list = None - for func, stat in other.stats.iteritems(): + for func, stat in other.stats.items(): if func in self.stats: old_func_stat = self.stats[func] else: @@ -199,7 +199,7 @@ if not self.sort_arg_dict: self.sort_arg_dict = dict = {} bad_list = {} - for word, tup in self.sort_arg_dict_default.iteritems(): + for word, tup in self.sort_arg_dict_default.items(): fragment = word while fragment: if not fragment: @@ -234,7 +234,7 @@ connector = ", " stats_list = [] - for func, (cc, nc, tt, ct, callers) in self.stats.iteritems(): + for func, (cc, nc, tt, ct, callers) in self.stats.items(): stats_list.append((cc, nc, tt, ct) + func + (func_std_string(func), func)) @@ -254,12 +254,12 @@ oldstats = self.stats self.stats = newstats = {} max_name_len = 0 - for func, (cc, nc, tt, ct, callers) in oldstats.iteritems(): + for func, (cc, nc, tt, ct, callers) in oldstats.items(): newfunc = func_strip_path(func) if len(func_std_string(newfunc)) > max_name_len: max_name_len = len(func_std_string(newfunc)) newcallers = {} - for func2, caller in callers.iteritems(): + for func2, caller in callers.items(): newcallers[func_strip_path(func2)] = caller if newfunc in newstats: @@ -282,10 +282,10 @@ def calc_callees(self): if self.all_callees: return self.all_callees = all_callees = {} - for func, (cc, nc, tt, ct, callers) in self.stats.iteritems(): + for func, (cc, nc, tt, ct, callers) in self.stats.items(): if not func in all_callees: all_callees[func] = {} - for func2, caller in callers.iteritems(): + for func2, caller in callers.items(): if not func2 in all_callees: all_callees[func2] = {} all_callees[func2][func] = caller @@ -394,9 +394,9 @@ print("Function ".ljust(name_size) + column_title, file=self.stream) # print sub-header only if we have new-style callers subheader = False - for cc, nc, tt, ct, callers in self.stats.itervalues(): + for cc, nc, tt, ct, callers in self.stats.values(): if callers: - value = callers.itervalues().next() + value = iter(callers.values()).next() subheader = isinstance(value, tuple) break if subheader: @@ -407,8 +407,7 @@ if not call_dict: print(file=self.stream) return - clist = call_dict.keys() - clist.sort() + clist = sorted(call_dict.keys()) indent = "" for func in clist: name = func_std_string(func) @@ -508,9 +507,9 @@ def add_callers(target, source): """Combine two caller lists in a single list.""" new_callers = {} - for func, caller in target.iteritems(): + for func, caller in target.items(): new_callers[func] = caller - for func, caller in source.iteritems(): + for func, caller in source.items(): if func in new_callers: new_callers[func] = caller + new_callers[func] else: @@ -520,7 +519,7 @@ def count_calls(callers): """Sum the caller statistics to get total number of calls received.""" nc = 0 - for calls in callers.itervalues(): + for calls in callers.values(): nc += calls return nc @@ -642,7 +641,7 @@ self.stats.sort_stats(*line.split()) else: print("Valid sort keys (unique prefixes are accepted):", file=self.stream) - for (key, value) in Stats.sort_arg_dict_default.iteritems(): + for (key, value) in Stats.sort_arg_dict_default.items(): print("%s -- %s" % (key, value[1]), file=self.stream) return 0 def help_sort(self): Modified: python/branches/p3yk/Lib/pyclbr.py ============================================================================== --- python/branches/p3yk/Lib/pyclbr.py (original) +++ python/branches/p3yk/Lib/pyclbr.py Sun Feb 11 07:12:03 2007 @@ -329,7 +329,7 @@ for obj in objs: if isinstance(obj, Class): print("class", obj.name, obj.super, obj.lineno) - methods = sorted(obj.methods.iteritems(), key=itemgetter(1)) + methods = sorted(obj.methods.items(), key=itemgetter(1)) for name, lineno in methods: if name != "__path__": print(" def", name, lineno) Modified: python/branches/p3yk/Lib/rfc822.py ============================================================================== --- python/branches/p3yk/Lib/rfc822.py (original) +++ python/branches/p3yk/Lib/rfc822.py Sun Feb 11 07:12:03 2007 @@ -437,18 +437,18 @@ def keys(self): """Get all of a message's header field names.""" - return self.dict.keys() + return list(self.dict.keys()) def values(self): """Get all of a message's header field values.""" - return self.dict.values() + return list(self.dict.values()) def items(self): """Get all of a message's headers. Returns a list of name, value tuples. """ - return self.dict.items() + return list(self.dict.items()) def __str__(self): return ''.join(self.headers) Modified: python/branches/p3yk/Lib/shelve.py ============================================================================== --- python/branches/p3yk/Lib/shelve.py (original) +++ python/branches/p3yk/Lib/shelve.py Sun Feb 11 07:12:03 2007 @@ -144,7 +144,7 @@ def sync(self): if self.writeback and self.cache: self.writeback = False - for key, entry in self.cache.iteritems(): + for key, entry in self.cache.items(): self[key] = entry self.writeback = True self.cache = {} Modified: python/branches/p3yk/Lib/symbol.py ============================================================================== --- python/branches/p3yk/Lib/symbol.py (original) +++ python/branches/p3yk/Lib/symbol.py Sun Feb 11 07:12:03 2007 @@ -100,7 +100,7 @@ #--end constants-- sym_name = {} -for _name, _value in globals().items(): +for _name, _value in list(globals().items()): if type(_value) is type(0): sym_name[_value] = _name Modified: python/branches/p3yk/Lib/symtable.py ============================================================================== --- python/branches/p3yk/Lib/symtable.py (original) +++ python/branches/p3yk/Lib/symtable.py Sun Feb 11 07:12:03 2007 @@ -13,7 +13,7 @@ def symtable(code, filename, compile_type): raw = _symtable.symtable(code, filename, compile_type) - for top in raw.itervalues(): + for top in raw.values(): if top.name == 'top': break return newSymbolTable(top, filename) Modified: python/branches/p3yk/Lib/test/fork_wait.py ============================================================================== --- python/branches/p3yk/Lib/test/fork_wait.py (original) +++ python/branches/p3yk/Lib/test/fork_wait.py Sun Feb 11 07:12:03 2007 @@ -51,8 +51,7 @@ time.sleep(LONGSLEEP) - a = self.alive.keys() - a.sort() + a = sorted(self.alive.keys()) self.assertEquals(a, range(NUM_THREADS)) prefork_lives = self.alive.copy() Modified: python/branches/p3yk/Lib/test/mapping_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/mapping_tests.py (original) +++ python/branches/p3yk/Lib/test/mapping_tests.py Sun Feb 11 07:12:03 2007 @@ -73,13 +73,13 @@ self.assert_(hasattr(iter, '__iter__')) x = list(iter) self.assert_(set(x)==set(lst)==set(ref)) - check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys()) + check_iterandlist(d.keys(), d.keys(), self.reference.keys()) check_iterandlist(iter(d), d.keys(), self.reference.keys()) - check_iterandlist(d.itervalues(), d.values(), self.reference.values()) - check_iterandlist(d.iteritems(), d.items(), self.reference.items()) + check_iterandlist(d.values(), d.values(), self.reference.values()) + check_iterandlist(d.items(), d.items(), self.reference.items()) #get - key, value = d.iteritems().next() - knownkey, knownvalue = self.other.iteritems().next() + key, value = d.items().next() + knownkey, knownvalue = self.other.items().next() self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.failIf(knownkey in d) @@ -104,8 +104,8 @@ self.assertEqual(dict(p), self.reference) d = self._full_mapping(self.reference) #setdefault - key, value = d.iteritems().next() - knownkey, knownvalue = self.other.iteritems().next() + key, value = d.items().next() + knownkey, knownvalue = self.other.items().next() self.assertEqual(d.setdefault(key, knownvalue), value) self.assertEqual(d[key], value) self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue) @@ -183,7 +183,7 @@ # Iterator d = self._empty_mapping() - d.update(self.other.iteritems()) + d.update(self.other.items()) self.assertEqual(d.items(), self.other.items()) # FIXME: Doesn't work with UserDict @@ -400,7 +400,7 @@ # iterator d = self._full_mapping({1:3, 2:4}) - d.update(self._full_mapping({1:2, 3:4, 5:6}).iteritems()) + d.update(self._full_mapping({1:2, 3:4, 5:6}).items()) self.assertEqual(d, {1:2, 2:4, 3:4, 5:6}) class SimpleUserDict: Modified: python/branches/p3yk/Lib/test/pickletester.py ============================================================================== --- python/branches/p3yk/Lib/test/pickletester.py (original) +++ python/branches/p3yk/Lib/test/pickletester.py Sun Feb 11 07:12:03 2007 @@ -438,7 +438,7 @@ for proto in protocols: s = self.dumps(d, proto) x = self.loads(s) - self.assertEqual(x.keys(), [1]) + self.assertEqual(list(x.keys()), [1]) self.assert_(x[1] is x) def test_recursive_inst(self): @@ -461,7 +461,7 @@ x = self.loads(s) self.assertEqual(len(x), 1) self.assertEqual(dir(x[0]), dir(i)) - self.assertEqual(x[0].attr.keys(), [1]) + self.assertEqual(list(x[0].attr.keys()), [1]) self.assert_(x[0].attr[1] is x) def test_garyp(self): Modified: python/branches/p3yk/Lib/test/string_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/string_tests.py (original) +++ python/branches/p3yk/Lib/test/string_tests.py Sun Feb 11 07:12:03 2007 @@ -40,7 +40,7 @@ elif isinstance(obj, dict): return dict([ (self.fixtype(key), self.fixtype(value)) - for (key, value) in obj.iteritems() + for (key, value) in obj.items() ]) else: return obj Modified: python/branches/p3yk/Lib/test/test_anydbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_anydbm.py (original) +++ python/branches/p3yk/Lib/test/test_anydbm.py Sun Feb 11 07:12:03 2007 @@ -72,10 +72,8 @@ f.close() def keys_helper(self, f): - keys = f.keys() - keys.sort() - dkeys = self._dict.keys() - dkeys.sort() + keys = sorted(f.keys()) + dkeys = sorted(self._dict.keys()) self.assertEqual(keys, dkeys) return keys Modified: python/branches/p3yk/Lib/test/test_array.py ============================================================================== --- python/branches/p3yk/Lib/test/test_array.py (original) +++ python/branches/p3yk/Lib/test/test_array.py Sun Feb 11 07:12:03 2007 @@ -729,7 +729,7 @@ self.assertEqual(s.color, "blue") s.color = "red" self.assertEqual(s.color, "red") - self.assertEqual(s.__dict__.keys(), ["color"]) + self.assertEqual(list(s.__dict__.keys()), ["color"]) def test_nounicode(self): a = array.array(self.typecode, self.example) Modified: python/branches/p3yk/Lib/test/test_bsddb.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bsddb.py (original) +++ python/branches/p3yk/Lib/test/test_bsddb.py Sun Feb 11 07:12:03 2007 @@ -15,7 +15,7 @@ def setUp(self): self.f = self.openmethod[0](self.fname, self.openflag, cachesize=32768) self.d = dict(q='Guido', w='van', e='Rossum', r='invented', t='Python', y='') - for k, v in self.d.iteritems(): + for k, v in self.d.items(): self.f[k] = v def tearDown(self): @@ -29,7 +29,7 @@ pass def test_getitem(self): - for k, v in self.d.iteritems(): + for k, v in self.d.items(): self.assertEqual(self.f[k], v) def test_len(self): @@ -48,7 +48,7 @@ return self.f.close() self.f = self.openmethod[0](self.fname, 'w') - for k, v in self.d.iteritems(): + for k, v in self.d.items(): self.assertEqual(self.f[k], v) def assertSetEquals(self, seqn1, seqn2): @@ -61,9 +61,9 @@ self.assertSetEquals(d.keys(), f.keys()) self.assertSetEquals(d.values(), f.values()) self.assertSetEquals(d.items(), f.items()) - self.assertSetEquals(d.iterkeys(), f.iterkeys()) - self.assertSetEquals(d.itervalues(), f.itervalues()) - self.assertSetEquals(d.iteritems(), f.iteritems()) + self.assertSetEquals(d.keys(), f.keys()) + self.assertSetEquals(d.values(), f.values()) + self.assertSetEquals(d.items(), f.items()) def test_iter_while_modifying_values(self): if not hasattr(self.f, '__iter__'): @@ -94,7 +94,7 @@ if not hasattr(self.f, 'iteritems'): return - di = self.d.iteritems() + di = self.d.items() while 1: try: k, v = di.next() @@ -105,7 +105,7 @@ # it should behave the same as a dict. modifying values # of existing keys should not break iteration. (adding # or removing keys should) - fi = self.f.iteritems() + fi = self.f.items() while 1: try: k, v = fi.next() @@ -159,7 +159,7 @@ # test the iterator interface (if present) if hasattr(self.f, 'iteritems'): if debug: print("D") - i = self.f.iteritems() + i = self.f.items() k,v = i.next() if debug: print("E") self.f[k] = "please don't deadlock" @@ -198,7 +198,7 @@ # do the bsddb._DBWithCursor _iter_mixin internals leak cursors? nc1 = len(self.f._cursor_refs) # create iterator - i = self.f.iteritems() + i = self.f.items() nc2 = len(self.f._cursor_refs) # use the iterator (should run to the first yeild, creating the cursor) k, v = i.next() @@ -240,7 +240,7 @@ new = dict(y='life', u='of', i='brian') self.f.update(new) self.d.update(new) - for k, v in self.d.iteritems(): + for k, v in self.d.items(): self.assertEqual(self.f[k], v) def test_keyordering(self): Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Sun Feb 11 07:12:03 2007 @@ -290,8 +290,8 @@ if key == 'a': return 12 raise KeyError - def keys(self): - return list('xyz') + def __iter__(self): + return iter('xyz') m = M() g = globals() @@ -313,8 +313,8 @@ if key == 'a': return 12 return dict.__getitem__(self, key) - def keys(self): - return list('xyz') + def __iter__(self): + return iter('xyz') d = D() self.assertEqual(eval('a', g, d), 12) @@ -346,8 +346,8 @@ class C: def __getitem__(self, item): raise KeyError(item) - def keys(self): - return 'a' + def __iter__(self): + return 'a' # XXX Not quite faithful to the SF bug... self.assertRaises(TypeError, eval, 'dir()', globals(), C()) # Done outside of the method test_z to get the correct scope @@ -522,8 +522,8 @@ unicode("123"): unicode("112233") } - for (cls, inps) in inputs.iteritems(): - for (inp, exp) in inps.iteritems(): + for (cls, inps) in inputs.items(): + for (inp, exp) in inps.items(): # make sure the output goes through __getitem__ # even if func is None self.assertEqual( Modified: python/branches/p3yk/Lib/test/test_cfgparser.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cfgparser.py (original) +++ python/branches/p3yk/Lib/test/test_cfgparser.py Sun Feb 11 07:12:03 2007 @@ -7,18 +7,13 @@ class SortedDict(UserDict.UserDict): def items(self): - result = self.data.items() - result.sort() - return result + return sorted(self.data.items()) def keys(self): - result = self.data.keys() - result.sort() - return result + return sorted(self.data.keys()) def values(self): - result = self.items() - return [i[1] for i in values] + return [i[1] for i in self.items()] def iteritems(self): return iter(self.items()) def iterkeys(self): return iter(self.keys()) Modified: python/branches/p3yk/Lib/test/test_cgi.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cgi.py (original) +++ python/branches/p3yk/Lib/test/test_cgi.py Sun Feb 11 07:12:03 2007 @@ -118,9 +118,7 @@ ] def norm(seq): - if isinstance(seq, list): - seq.sort(key=repr) - return seq + return sorted(seq, key=repr) def first_elts(list): return map(lambda x:x[0], list) Modified: python/branches/p3yk/Lib/test/test_compile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compile.py (original) +++ python/branches/p3yk/Lib/test/test_compile.py Sun Feb 11 07:12:03 2007 @@ -53,8 +53,8 @@ raise KeyError def __setitem__(self, key, value): self.results = (key, value) - def keys(self): - return list('xyz') + def __iter__(self): + return iter('xyz') m = M() g = globals() Modified: python/branches/p3yk/Lib/test/test_cookie.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cookie.py (original) +++ python/branches/p3yk/Lib/test/test_cookie.py Sun Feb 11 07:12:03 2007 @@ -38,7 +38,7 @@ C.load(case['data']) self.assertEqual(repr(C), case['repr']) self.assertEqual(C.output(sep='\n'), case['output']) - for k, v in sorted(case['dict'].iteritems()): + for k, v in sorted(case['dict'].items()): self.assertEqual(C[k].value, v) def test_load(self): Modified: python/branches/p3yk/Lib/test/test_copy.py ============================================================================== --- python/branches/p3yk/Lib/test/test_copy.py (original) +++ python/branches/p3yk/Lib/test/test_copy.py Sun Feb 11 07:12:03 2007 @@ -491,7 +491,7 @@ def test_reduce_5tuple(self): class C(dict): def __reduce__(self): - return (C, (), self.__dict__, None, self.iteritems()) + return (C, (), self.__dict__, None, self.items()) def __eq__(self, other): return (dict(self) == dict(other) and self.__dict__ == other.__dict__) Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Sun Feb 11 07:12:03 2007 @@ -183,7 +183,7 @@ d = dict({1: 2, 'a': 'b'}) vereq(d, {1: 2, 'a': 'b'}) vereq(d, dict(d.items())) - vereq(d, dict(d.iteritems())) + vereq(d, dict(d.items())) d = dict({'one':1, 'two':2}) vereq(d, dict(one=1, two=2)) vereq(d, dict(**d)) @@ -541,10 +541,10 @@ class C(spam.spamdict): def foo(self): return 1 a = C() - vereq(a.items(), []) + vereq(list(a.items()), []) vereq(a.foo(), 1) a['foo'] = 'bar' - vereq(a.items(), [('foo', 'bar')]) + vereq(list(a.items()), [('foo', 'bar')]) vereq(a.getstate(), 0) a.setstate(100) vereq(a.getstate(), 100) @@ -714,7 +714,7 @@ # named _get_x and/or _set_x are found def __new__(metaclass, name, bases, dict): hits = {} - for key, val in dict.iteritems(): + for key, val in dict.items(): if key.startswith("_get_"): key = key[5:] get, set = hits.get(key, (None, None)) @@ -725,7 +725,7 @@ get, set = hits.get(key, (None, None)) set = val hits[key] = get, set - for key, (get, set) in hits.iteritems(): + for key, (get, set) in hits.items(): dict[key] = property(get, set) return super(autoproperty, metaclass).__new__(metaclass, name, bases, dict) @@ -820,9 +820,9 @@ type({}).__init__(self) C.__init__(self) d = D() - vereq(d.keys(), []) + vereq(list(d.keys()), []) d["hello"] = "world" - vereq(d.items(), [("hello", "world")]) + vereq(list(d.items()), [("hello", "world")]) vereq(d["hello"], "world") vereq(d.getstate(), 0) d.setstate(10) @@ -2676,9 +2676,7 @@ cPickle = None def sorteditems(d): - L = d.items() - L.sort() - return L + return sorted(d.items()) global C class C(object): @@ -3193,7 +3191,7 @@ def meth(self): pass if verbose: print("Testing dict-proxy iterkeys...") - keys = [ key for key in C.__dict__.iterkeys() ] + keys = [ key for key in C.__dict__.keys() ] keys.sort() vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) @@ -3202,7 +3200,7 @@ def meth(self): pass if verbose: print("Testing dict-proxy itervalues...") - values = [ values for values in C.__dict__.itervalues() ] + values = [ values for values in C.__dict__.values() ] vereq(len(values), 5) def dictproxyiteritems(): @@ -3210,7 +3208,7 @@ def meth(self): pass if verbose: print("Testing dict-proxy iteritems...") - keys = [ key for (key, value) in C.__dict__.iteritems() ] + keys = [ key for (key, value) in C.__dict__.items() ] keys.sort() vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) Modified: python/branches/p3yk/Lib/test/test_dictviews.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dictviews.py (original) +++ python/branches/p3yk/Lib/test/test_dictviews.py Sun Feb 11 07:12:03 2007 @@ -4,19 +4,19 @@ class DictSetTest(unittest.TestCase): def test_constructors_not_callable(self): - kt = type({}.KEYS()) + kt = type({}.keys()) self.assertRaises(TypeError, kt, {}) self.assertRaises(TypeError, kt) - it = type({}.ITEMS()) + it = type({}.items()) self.assertRaises(TypeError, it, {}) self.assertRaises(TypeError, it) - vt = type({}.VALUES()) + vt = type({}.values()) self.assertRaises(TypeError, vt, {}) self.assertRaises(TypeError, vt) def test_dict_keys(self): d = {1: 10, "a": "ABC"} - keys = d.KEYS() + keys = d.keys() self.assertEqual(set(keys), {1, "a"}) self.assertEqual(len(keys), 2) self.assert_(1 in keys) @@ -26,7 +26,7 @@ def test_dict_items(self): d = {1: 10, "a": "ABC"} - items = d.ITEMS() + items = d.items() self.assertEqual(set(items), {(1, 10), ("a", "ABC")}) self.assertEqual(len(items), 2) self.assert_((1, 10) in items) @@ -39,7 +39,7 @@ def test_dict_values(self): d = {1: 10, "a": "ABC"} - values = d.VALUES() + values = d.values() self.assertEqual(set(values), {10, "ABC"}) self.assertEqual(len(values), 2) Modified: python/branches/p3yk/Lib/test/test_iter.py ============================================================================== --- python/branches/p3yk/Lib/test/test_iter.py (original) +++ python/branches/p3yk/Lib/test/test_iter.py Sun Feb 11 07:12:03 2007 @@ -365,8 +365,8 @@ d = {"one": 1, "two": 2, "three": 3} self.assertEqual(max(d), "two") self.assertEqual(min(d), "one") - self.assertEqual(max(d.itervalues()), 3) - self.assertEqual(min(iter(d.itervalues())), 1) + self.assertEqual(max(d.values()), 3) + self.assertEqual(min(iter(d.values())), 1) f = open(TESTFN, "w") try: @@ -402,7 +402,7 @@ for i in range(5)] self.assertEqual(map(None, d, SequenceClass(5), - iter(d.iterkeys())), + iter(d.keys())), expected) f = open(TESTFN, "w") @@ -437,7 +437,7 @@ [(0,), (1,), (2,)]) d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(d.items(), list(zip(d, d.itervalues()))) + self.assertEqual(d.items(), list(zip(d, d.values()))) # Generate all ints starting at constructor arg. class IntsFrom: @@ -559,13 +559,13 @@ d = {"one": 1, "two": 2, "three": 3, 1j: 2j} for k in d: self.assert_(k in d) - self.assert_(k not in d.itervalues()) + self.assert_(k not in d.values()) for v in d.values(): - self.assert_(v in d.itervalues()) + self.assert_(v in d.values()) self.assert_(v not in d) - for k, v in d.iteritems(): - self.assert_((k, v) in d.iteritems()) - self.assert_((v, k) not in d.iteritems()) + for k, v in d.items(): + self.assert_((k, v) in d.items()) + self.assert_((v, k) not in d.items()) f = open(TESTFN, "w") try: @@ -600,9 +600,9 @@ d = {"one": 3, "two": 3, "three": 3, 1j: 2j} for k in d: self.assertEqual(countOf(d, k), 1) - self.assertEqual(countOf(d.itervalues(), 3), 3) - self.assertEqual(countOf(d.itervalues(), 2j), 1) - self.assertEqual(countOf(d.itervalues(), 1j), 0) + self.assertEqual(countOf(d.values(), 3), 3) + self.assertEqual(countOf(d.values(), 2j), 1) + self.assertEqual(countOf(d.values(), 1j), 0) f = open(TESTFN, "w") try: @@ -744,7 +744,7 @@ else: self.fail("should have raised TypeError") - a, b, c = {1: 42, 2: 42, 3: 42}.itervalues() + a, b, c = {1: 42, 2: 42, 3: 42}.values() self.assertEqual((a, b, c), (42, 42, 42)) f = open(TESTFN, "w") @@ -841,7 +841,7 @@ # XXX For a more thorough test, see towards the end of: # http://mail.python.org/pipermail/python-dev/2002-July/026512.html a = {1:1, 2:2, 0:0, 4:4, 3:3} - for b in iter(a), a.iterkeys(), a.iteritems(), a.itervalues(): + for b in iter(a), a.keys(), a.items(), a.values(): b = iter(a) self.assertEqual(len(list(b)), 5) self.assertEqual(list(b), []) Modified: python/branches/p3yk/Lib/test/test_iterlen.py ============================================================================== --- python/branches/p3yk/Lib/test/test_iterlen.py (original) +++ python/branches/p3yk/Lib/test/test_iterlen.py Sun Feb 11 07:12:03 2007 @@ -139,14 +139,14 @@ def setUp(self): d = dict.fromkeys(xrange(n)) - self.it = d.iteritems() + self.it = d.items() self.mutate = d.popitem class TestDictValues(TestTemporarilyImmutable): def setUp(self): d = dict.fromkeys(xrange(n)) - self.it = d.itervalues() + self.it = d.values() self.mutate = d.popitem class TestSet(TestTemporarilyImmutable): Modified: python/branches/p3yk/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_itertools.py (original) +++ python/branches/p3yk/Lib/test/test_itertools.py Sun Feb 11 07:12:03 2007 @@ -790,7 +790,7 @@ >>> from operator import itemgetter >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) ->>> di = sorted(sorted(d.iteritems()), key=itemgetter(1)) +>>> di = sorted(sorted(d.items()), key=itemgetter(1)) >>> for k, g in groupby(di, itemgetter(1)): ... print(k, map(itemgetter(0), g)) ... @@ -823,7 +823,7 @@ ... return imap(function, count()) >>> def iteritems(mapping): -... return izip(mapping.iterkeys(), mapping.itervalues()) +... return izip(mapping.keys(), mapping.values()) >>> def nth(iterable, n): ... "Returns the nth item" Modified: python/branches/p3yk/Lib/test/test_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_mailbox.py Sun Feb 11 07:12:03 2007 @@ -24,7 +24,7 @@ # Inspect a mailbox.Message representation of the sample message self.assert_(isinstance(msg, email.message.Message)) self.assert_(isinstance(msg, mailbox.Message)) - for key, value in _sample_headers.iteritems(): + for key, value in _sample_headers.items(): self.assert_(value in msg.get_all(key)) self.assert_(msg.is_multipart()) self.assert_(len(msg.get_payload()) == len(_sample_payloads)) @@ -174,7 +174,7 @@ def test_iterkeys(self): # Get keys using iterkeys() - self._check_iteration(self._box.iterkeys, do_keys=True, do_values=False) + self._check_iteration(self._box.keys, do_keys=True, do_values=False) def test_keys(self): # Get keys using keys() @@ -182,7 +182,7 @@ def test_itervalues(self): # Get values using itervalues() - self._check_iteration(self._box.itervalues, do_keys=False, + self._check_iteration(self._box.values, do_keys=False, do_values=True) def test_iter(self): @@ -196,7 +196,7 @@ def test_iteritems(self): # Get keys and values using iteritems() - self._check_iteration(self._box.iteritems, do_keys=True, + self._check_iteration(self._box.items, do_keys=True, do_values=True) def test_items(self): @@ -424,12 +424,12 @@ self.assertRaises(NotImplementedError, lambda: box.__delitem__('')) self.assertRaises(NotImplementedError, lambda: box.discard('')) self.assertRaises(NotImplementedError, lambda: box.__setitem__('', '')) - self.assertRaises(NotImplementedError, lambda: box.iterkeys()) self.assertRaises(NotImplementedError, lambda: box.keys()) - self.assertRaises(NotImplementedError, lambda: box.itervalues().next()) + self.assertRaises(NotImplementedError, lambda: box.keys()) + self.assertRaises(NotImplementedError, lambda: box.values().next()) self.assertRaises(NotImplementedError, lambda: box.__iter__().next()) self.assertRaises(NotImplementedError, lambda: box.values()) - self.assertRaises(NotImplementedError, lambda: box.iteritems().next()) + self.assertRaises(NotImplementedError, lambda: box.items().next()) self.assertRaises(NotImplementedError, lambda: box.items()) self.assertRaises(NotImplementedError, lambda: box.get('')) self.assertRaises(NotImplementedError, lambda: box.__getitem__('')) @@ -709,7 +709,7 @@ mtime = os.path.getmtime(self._path) self._box = self._factory(self._path) self.assert_(len(self._box) == 3) - for key in self._box.iterkeys(): + for key in self._box.keys(): self.assert_(self._box.get_string(key) in values) self._box.close() self.assert_(mtime == os.path.getmtime(self._path)) Modified: python/branches/p3yk/Lib/test/test_mhlib.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mhlib.py (original) +++ python/branches/p3yk/Lib/test/test_mhlib.py Sun Feb 11 07:12:03 2007 @@ -46,7 +46,7 @@ return r def writeProfile(dict): - contents = [ "%s: %s\n" % (k, v) for k, v in dict.iteritems() ] + contents = [ "%s: %s\n" % (k, v) for k, v in dict.items() ] writeFile(_mhprofile, "".join(contents)) def writeContext(folder): @@ -61,7 +61,7 @@ def writeMessage(folder, n, headers, body): folder = normF(folder) - headers = "".join([ "%s: %s\n" % (k, v) for k, v in headers.iteritems() ]) + headers = "".join([ "%s: %s\n" % (k, v) for k, v in headers.items() ]) contents = "%s\n%s\n" % (headers,body) mkdirs(os.path.join(_mhpath, folder)) writeFile(os.path.join(_mhpath, folder, str(n)), contents) Modified: python/branches/p3yk/Lib/test/test_richcmp.py ============================================================================== --- python/branches/p3yk/Lib/test/test_richcmp.py (original) +++ python/branches/p3yk/Lib/test/test_richcmp.py Sun Feb 11 07:12:03 2007 @@ -131,7 +131,7 @@ self.checkequal("gt", a, b, [False, False, False, True, True ]) self.checkequal("ge", a, b, [False, False, True, True, True ]) - for ops in opmap.itervalues(): + for ops in opmap.values(): for op in ops: # calls __bool__, which should fail self.assertRaises(TypeError, bool, op(a, b)) @@ -150,7 +150,7 @@ continue # the combination int, int is useless ta = typea(a) tb = typeb(b) - for ops in opmap.itervalues(): + for ops in opmap.values(): for op in ops: realoutcome = op(a, b) testoutcome = op(ta, tb) Modified: python/branches/p3yk/Lib/test/test_site.py ============================================================================== --- python/branches/p3yk/Lib/test/test_site.py (original) +++ python/branches/p3yk/Lib/test/test_site.py Sun Feb 11 07:12:03 2007 @@ -204,7 +204,7 @@ if sys.platform == "win32": import locale if locale.getdefaultlocale()[1].startswith('cp'): - for value in encodings.aliases.aliases.itervalues(): + for value in encodings.aliases.aliases.values(): if value == "mbcs": break else: Modified: python/branches/p3yk/Lib/test/test_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_support.py (original) +++ python/branches/p3yk/Lib/test/test_support.py Sun Feb 11 07:12:03 2007 @@ -239,8 +239,7 @@ def sortdict(dict): "Like repr(dict), but in sorted order." - items = dict.items() - items.sort() + items = sorted(dict.items()) reprpairs = ["%r: %r" % pair for pair in items] withcommas = ", ".join(reprpairs) return "{%s}" % withcommas @@ -305,7 +304,7 @@ return self def __exit__(self, *ignore_exc): - for envvar, value in self._reset.iteritems(): + for envvar, value in self._reset.items(): self._environ[envvar] = value for unset in self._unset: del self._environ[unset] Modified: python/branches/p3yk/Lib/test/test_urllib2.py ============================================================================== --- python/branches/p3yk/Lib/test/test_urllib2.py (original) +++ python/branches/p3yk/Lib/test/test_urllib2.py Sun Feb 11 07:12:03 2007 @@ -90,8 +90,7 @@ >>> r.header_items() [('Spam-eggs', 'blah')] >>> r.add_header("Foo-Bar", "baz") - >>> items = r.header_items() - >>> items.sort() + >>> items = sorted(r.header_items()) >>> items [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')] @@ -235,7 +234,7 @@ class MockHeaders(dict): def getheaders(self, name): - return self.values() + return list(self.values()) class MockResponse(StringIO.StringIO): def __init__(self, code, msg, headers, data, url=None): Modified: python/branches/p3yk/Lib/test/test_userdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_userdict.py (original) +++ python/branches/p3yk/Lib/test/test_userdict.py Sun Feb 11 07:12:03 2007 @@ -208,7 +208,7 @@ if other is not None: for (key, value) in other: self[key] = value - for (key, value) in kwargs.iteritems(): + for (key, value) in kwargs.items(): self[key] = value def __getitem__(self, key): try: @@ -234,7 +234,7 @@ return list(self.keylist) def copy(self): d = self.__class__() - for key, value in self.iteritems(): + for key, value in self.items(): d[key] = value return d @classmethod @@ -278,13 +278,13 @@ self.assertEqual(len(s), 2) # iteritems - self.assertEqual(list(s.iteritems()), [(10,'ten'), (30, 'thirty')]) + self.assertEqual(list(s.items()), [(10,'ten'), (30, 'thirty')]) # iterkeys - self.assertEqual(list(s.iterkeys()), [10, 30]) + self.assertEqual(list(s.keys()), [10, 30]) # itervalues - self.assertEqual(list(s.itervalues()), ['ten', 'thirty']) + self.assertEqual(list(s.values()), ['ten', 'thirty']) # values self.assertEqual(s.values(), ['ten', 'thirty']) Modified: python/branches/p3yk/Lib/test/test_uuid.py ============================================================================== --- python/branches/p3yk/Lib/test/test_uuid.py (original) +++ python/branches/p3yk/Lib/test/test_uuid.py Sun Feb 11 07:12:03 2007 @@ -295,7 +295,7 @@ if TestUUID.last_node: if TestUUID.last_node != node: msg = "different sources disagree on node:\n" - for s, n in TestUUID.source2node.iteritems(): + for s, n in TestUUID.source2node.items(): msg += " from source %r, node was %012x\n" % (s, n) # There's actually no reason to expect the MAC addresses # to agree across various methods -- e.g., a box may have 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 Sun Feb 11 07:12:03 2007 @@ -839,7 +839,7 @@ def check_iters(self, dict): # item iterator: items = dict.items() - for item in dict.iteritems(): + for item in dict.items(): items.remove(item) self.assert_(len(items) == 0, "iteritems() did not touch all items") @@ -851,13 +851,13 @@ # key iterator, via iterkeys(): keys = dict.keys() - for k in dict.iterkeys(): + for k in dict.keys(): keys.remove(k) self.assert_(len(keys) == 0, "iterkeys() did not touch all keys") # value iterator: values = dict.values() - for v in dict.itervalues(): + for v in dict.values(): values.remove(v) self.assert_(len(values) == 0, "itervalues() did not touch all values") @@ -1093,7 +1093,7 @@ ... def __init__(self, ob, callback=None, **annotations): ... super(ExtendedRef, self).__init__(ob, callback) ... self.__counter = 0 -... for k, v in annotations.iteritems(): +... for k, v in annotations.items(): ... setattr(self, k, v) ... def __call__(self): ... '''Return a pair containing the referent and the number of @@ -1104,7 +1104,7 @@ ... self.__counter += 1 ... ob = (ob, self.__counter) ... return ob -... +... >>> class A: # not in docs from here, just testing the ExtendedRef ... pass ... Modified: python/branches/p3yk/Lib/test/test_xmlrpc.py ============================================================================== --- python/branches/p3yk/Lib/test/test_xmlrpc.py (original) +++ python/branches/p3yk/Lib/test/test_xmlrpc.py Sun Feb 11 07:12:03 2007 @@ -145,7 +145,7 @@ if not setdefaultencoding_existed: del sys.setdefaultencoding - items = d.items() + items = list(d.items()) if have_unicode: self.assertEquals(s, u"abc \x95") self.assert_(isinstance(s, unicode)) Modified: python/branches/p3yk/Lib/threading.py ============================================================================== --- python/branches/p3yk/Lib/threading.py (original) +++ python/branches/p3yk/Lib/threading.py Sun Feb 11 07:12:03 2007 @@ -707,7 +707,7 @@ def enumerate(): _active_limbo_lock.acquire() - active = _active.values() + _limbo.values() + active = list(_active.values()) + list(_limbo.values()) _active_limbo_lock.release() return active Modified: python/branches/p3yk/Lib/token.py ============================================================================== --- python/branches/p3yk/Lib/token.py (original) +++ python/branches/p3yk/Lib/token.py Sun Feb 11 07:12:03 2007 @@ -68,7 +68,7 @@ #--end constants-- tok_name = {} -for _name, _value in globals().items(): +for _name, _value in list(globals().items()): if type(_value) is type(0): tok_name[_value] = _name Modified: python/branches/p3yk/Lib/trace.py ============================================================================== --- python/branches/p3yk/Lib/trace.py (original) +++ python/branches/p3yk/Lib/trace.py Sun Feb 11 07:12:03 2007 @@ -282,7 +282,7 @@ # accumulate summary info, if needed sums = {} - for filename, count in per_file.iteritems(): + for filename, count in per_file.items(): # skip some "files" we don't care about... if filename == "": continue Modified: python/branches/p3yk/Lib/urllib2.py ============================================================================== --- python/branches/p3yk/Lib/urllib2.py (original) +++ python/branches/p3yk/Lib/urllib2.py Sun Feb 11 07:12:03 2007 @@ -281,7 +281,7 @@ def header_items(self): hdrs = self.unredirected_hdrs.copy() hdrs.update(self.headers) - return hdrs.items() + return list(hdrs.items()) class OpenerDirector: def __init__(self): @@ -710,7 +710,7 @@ domains = self.passwd.get(realm, {}) for default_port in True, False: reduced_authuri = self.reduce_uri(authuri, default_port) - for uris, authinfo in domains.iteritems(): + for uris, authinfo in domains.items(): for uri in uris: if self.is_suburi(uri, reduced_authuri): return authinfo @@ -1318,21 +1318,21 @@ # first check for old ones t = time.time() if self.soonest <= t: - for k, v in self.timeout.items(): + for k, v in list(self.timeout.items()): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] - self.soonest = min(self.timeout.values()) + self.soonest = min(list(self.timeout.values())) # then check the size if len(self.cache) == self.max_conns: - for k, v in self.timeout.items(): + for k, v in list(self.timeout.items()): if v == self.soonest: del self.cache[k] del self.timeout[k] break - self.soonest = min(self.timeout.values()) + self.soonest = min(list(self.timeout.values())) class GopherHandler(BaseHandler): def gopher_open(self, req): Modified: python/branches/p3yk/Lib/weakref.py ============================================================================== --- python/branches/p3yk/Lib/weakref.py (original) +++ python/branches/p3yk/Lib/weakref.py Sun Feb 11 07:12:03 2007 @@ -100,16 +100,16 @@ return L def iteritems(self): - for wr in self.data.itervalues(): + for wr in self.data.values(): value = wr() if value is not None: yield wr.key, value def iterkeys(self): - return self.data.iterkeys() + return self.data.keys() def __iter__(self): - return self.data.iterkeys() + return self.data.keys() def itervaluerefs(self): """Return an iterator that yields the weak references to the values. @@ -121,10 +121,10 @@ keep the values around longer than needed. """ - return self.data.itervalues() + return self.data.values() def itervalues(self): - for wr in self.data.itervalues(): + for wr in self.data.values(): obj = wr() if obj is not None: yield obj @@ -268,7 +268,7 @@ return L def iteritems(self): - for wr, value in self.data.iteritems(): + for wr, value in self.data.items(): key = wr() if key is not None: yield key, value @@ -283,19 +283,19 @@ keep the keys around longer than needed. """ - return self.data.iterkeys() + return self.data.keys() def iterkeys(self): - for wr in self.data.iterkeys(): + for wr in self.data.keys(): obj = wr() if obj is not None: yield obj def __iter__(self): - return self.iterkeys() + return self.keys() def itervalues(self): - return self.data.itervalues() + return self.data.values() def keyrefs(self): """Return a list of weak references to the keys. Modified: python/branches/p3yk/Lib/xml/etree/ElementTree.py ============================================================================== --- python/branches/p3yk/Lib/xml/etree/ElementTree.py (original) +++ python/branches/p3yk/Lib/xml/etree/ElementTree.py Sun Feb 11 07:12:03 2007 @@ -645,7 +645,7 @@ elif tag is ProcessingInstruction: file.write("" % _escape_cdata(node.text, encoding)) else: - items = node.items() + items = list(node.items()) xmlns_items = [] # new namespaces in this scope try: if isinstance(tag, QName) or tag[:1] == "{": Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Sun Feb 11 07:12:03 2007 @@ -36,6 +36,9 @@ Core and Builtins ----------------- +- PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone; + and .keys(), .items(), .values() return dict views. + - PEP 3105: print is now a function. Also (not in the PEP) the 'softspace' attribute of files is now gone (since print() doesn't use it). A side effect of this change is that you can get incomplete Modified: python/branches/p3yk/Modules/cPickle.c ============================================================================== --- python/branches/p3yk/Modules/cPickle.c (original) +++ python/branches/p3yk/Modules/cPickle.c Sun Feb 11 07:12:03 2007 @@ -1752,7 +1752,7 @@ int res = -1; char s[3]; int len; - PyObject *iter; + PyObject *items, *iter; if (self->fast && !fast_save_enter(self, args)) goto finally; @@ -1784,7 +1784,11 @@ goto finally; /* Materialize the dict items. */ - iter = PyObject_CallMethod(args, "iteritems", "()"); + items = PyObject_CallMethod(args, "items", "()"); + if (items == NULL) + goto finally; + iter = PyObject_GetIter(items); + Py_DECREF(items); if (iter == NULL) goto finally; res = batch_dict(self, iter); Modified: python/branches/p3yk/Modules/collectionsmodule.c ============================================================================== --- python/branches/p3yk/Modules/collectionsmodule.c (original) +++ python/branches/p3yk/Modules/collectionsmodule.c Sun Feb 11 07:12:03 2007 @@ -1140,6 +1140,7 @@ */ PyObject *args; PyObject *items; + PyObject *iteritems; PyObject *result; if (dd->default_factory == NULL || dd->default_factory == Py_None) args = PyTuple_New(0); @@ -1147,14 +1148,20 @@ args = PyTuple_Pack(1, dd->default_factory); if (args == NULL) return NULL; - items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()"); + items = PyObject_CallMethod((PyObject *)dd, "items", "()"); if (items == NULL) { Py_DECREF(args); return NULL; } - result = PyTuple_Pack(5, dd->dict.ob_type, args, - Py_None, Py_None, items); + iteritems = PyObject_GetIter(items); Py_DECREF(items); + if (iteritems == NULL) { + Py_DECREF(args); + return NULL; + } + result = PyTuple_Pack(5, dd->dict.ob_type, args, + Py_None, Py_None, iteritems); + Py_DECREF(iteritems); Py_DECREF(args); return result; } Modified: python/branches/p3yk/Objects/abstract.c ============================================================================== --- python/branches/p3yk/Objects/abstract.c (original) +++ python/branches/p3yk/Objects/abstract.c Sun Feb 11 07:12:03 2007 @@ -1657,6 +1657,54 @@ return 0; } +PyObject * +PyMapping_Keys(PyObject *o) +{ + PyObject *keys; + PyObject *fast; + + if (PyDict_CheckExact(o)) + return PyDict_Keys(o); + keys = PyObject_CallMethod(o, "keys", NULL); + if (keys == NULL) + return NULL; + fast = PySequence_Fast(keys, "o.keys() are not iterable"); + Py_DECREF(keys); + return fast; +} + +PyObject * +PyMapping_Items(PyObject *o) +{ + PyObject *items; + PyObject *fast; + + if (PyDict_CheckExact(o)) + return PyDict_Items(o); + items = PyObject_CallMethod(o, "items", NULL); + if (items == NULL) + return NULL; + fast = PySequence_Fast(items, "o.items() are not iterable"); + Py_DECREF(items); + return fast; +} + +PyObject * +PyMapping_Values(PyObject *o) +{ + PyObject *values; + PyObject *fast; + + if (PyDict_CheckExact(o)) + return PyDict_Values(o); + values = PyObject_CallMethod(o, "values", NULL); + if (values == NULL) + return NULL; + fast = PySequence_Fast(values, "o.values() are not iterable"); + Py_DECREF(values); + return fast; +} + /* Operations on callable objects */ /* XXX PyCallable_Check() is in object.c */ Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Sun Feb 11 07:12:03 2007 @@ -1760,6 +1760,7 @@ extern PyTypeObject PyDictIterItem_Type; /* Forward */ static PyObject *dictiter_new(dictobject *, PyTypeObject *); +#if 0 static PyObject * dict_iterkeys(dictobject *dict) { @@ -1777,6 +1778,7 @@ { return dictiter_new(dict, &PyDictIterItem_Type); } +#endif PyDoc_STRVAR(contains__doc__, @@ -1798,6 +1800,7 @@ "D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\ 2-tuple; but raise KeyError if D is empty"); +#if 0 PyDoc_STRVAR(keys__doc__, "D.keys() -> list of D's keys"); @@ -1806,6 +1809,7 @@ PyDoc_STRVAR(values__doc__, "D.values() -> list of D's values"); +#endif PyDoc_STRVAR(update__doc__, "D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\ @@ -1821,6 +1825,7 @@ PyDoc_STRVAR(copy__doc__, "D.copy() -> a shallow copy of D"); +#if 0 PyDoc_STRVAR(iterkeys__doc__, "D.iterkeys() -> an iterator over the keys of D"); @@ -1829,6 +1834,7 @@ PyDoc_STRVAR(iteritems__doc__, "D.iteritems() -> an iterator over the (key, value) items of D"); +#endif /* Forward */ static PyObject *dictkeys_new(PyObject *); @@ -1852,18 +1858,20 @@ pop__doc__}, {"popitem", (PyCFunction)dict_popitem, METH_NOARGS, popitem__doc__}, +#if 0 {"keys", (PyCFunction)dict_keys, METH_NOARGS, keys__doc__}, - {"KEYS", (PyCFunction)dictkeys_new, METH_NOARGS, - KEYS__doc__}, - {"ITEMS", (PyCFunction)dictitems_new, METH_NOARGS, - ITEMS__doc__}, - {"VALUES", (PyCFunction)dictvalues_new, METH_NOARGS, - VALUES__doc__}, {"items", (PyCFunction)dict_items, METH_NOARGS, items__doc__}, {"values", (PyCFunction)dict_values, METH_NOARGS, values__doc__}, +#endif + {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, + KEYS__doc__}, + {"items", (PyCFunction)dictitems_new, METH_NOARGS, + ITEMS__doc__}, + {"values", (PyCFunction)dictvalues_new, METH_NOARGS, + VALUES__doc__}, {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, update__doc__}, {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, @@ -1872,12 +1880,14 @@ clear__doc__}, {"copy", (PyCFunction)dict_copy, METH_NOARGS, copy__doc__}, +#if 0 {"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS, iterkeys__doc__}, {"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS, itervalues__doc__}, {"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS, iteritems__doc__}, +#endif {NULL, NULL} /* sentinel */ }; Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Sun Feb 11 07:12:03 2007 @@ -2601,7 +2601,11 @@ Py_INCREF(dictitems); } else { - dictitems = PyObject_CallMethod(obj, "iteritems", ""); + PyObject *items = PyObject_CallMethod(obj, "items", ""); + if (items == NULL) + goto end; + dictitems = PyObject_GetIter(items); + Py_DECREF(items); if (dictitems == NULL) goto end; } From python-3000-checkins at python.org Sun Feb 11 08:05:22 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 08:05:22 +0100 (CET) Subject: [Python-3000-checkins] r53734 - python/branches/p3yk/Lib/test/test_with.py Message-ID: <20070211070522.997FD1E4008@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 08:05:21 2007 New Revision: 53734 Modified: python/branches/p3yk/Lib/test/test_with.py Log: With the help of the improved fixer, test_with.py is now fixed. Modified: python/branches/p3yk/Lib/test/test_with.py ============================================================================== --- python/branches/p3yk/Lib/test/test_with.py (original) +++ python/branches/p3yk/Lib/test/test_with.py Sun Feb 11 08:05:21 2007 @@ -550,13 +550,13 @@ def testSingleComplexTarget(self): targets = {1: [0, 1, 2]} with mock_contextmanager_generator() as targets[1][0]: - self.assertEqual(targets.keys(), [1]) + self.assertEqual(list(targets.keys()), [1]) self.assertEqual(targets[1][0].__class__, MockResource) - with mock_contextmanager_generator() as targets.values()[0][1]: - self.assertEqual(targets.keys(), [1]) + with mock_contextmanager_generator() as list(targets.values())[0][1]: + self.assertEqual(list(targets.keys()), [1]) self.assertEqual(targets[1][1].__class__, MockResource) with mock_contextmanager_generator() as targets[2]: - keys = targets.keys() + keys = list(targets.keys()) keys.sort() self.assertEqual(keys, [1, 2]) class C: pass @@ -571,7 +571,7 @@ targets = {1: [0, 1, 2]} with C() as (targets[1][0], targets[1][1], targets[1][2]): self.assertEqual(targets, {1: [1, 2, 3]}) - with C() as (targets.values()[0][2], targets.values()[0][1], targets.values()[0][0]): + with C() as (list(targets.values())[0][2], list(targets.values())[0][1], list(targets.values())[0][0]): self.assertEqual(targets, {1: [3, 2, 1]}) with C() as (targets[1], targets[2], targets[3]): self.assertEqual(targets, {1: 1, 2: 2, 3: 3}) From python-3000-checkins at python.org Sun Feb 11 19:44:57 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 19:44:57 +0100 (CET) Subject: [Python-3000-checkins] r53738 - in python/branches/p3yk/Lib: test/test_sax.py xml/sax/xmlreader.py Message-ID: <20070211184457.45EBD1E400C@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 19:44:55 2007 New Revision: 53738 Modified: python/branches/p3yk/Lib/test/test_sax.py python/branches/p3yk/Lib/xml/sax/xmlreader.py Log: Make test_sax pass. Modified: python/branches/p3yk/Lib/test/test_sax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sax.py (original) +++ python/branches/p3yk/Lib/test/test_sax.py Sun Feb 11 19:44:55 2007 @@ -358,11 +358,11 @@ (attrs.getQNames() == [] or attrs.getQNames() == ["ns:attr"]) and \ len(attrs) == 1 and \ (ns_uri, "attr") in attrs and \ - attrs.keys() == [(ns_uri, "attr")] and \ + list(attrs.keys()) == [(ns_uri, "attr")] and \ attrs.get((ns_uri, "attr")) == "val" and \ attrs.get((ns_uri, "attr"), 25) == "val" and \ - attrs.items() == [((ns_uri, "attr"), "val")] and \ - attrs.values() == ["val"] and \ + list(attrs.items()) == [((ns_uri, "attr"), "val")] and \ + list(attrs.values()) == ["val"] and \ attrs.getValue((ns_uri, "attr")) == "val" and \ attrs[(ns_uri, "attr")] == "val" @@ -698,7 +698,7 @@ # Bug report: http://www.python.org/sf/1511497 import sys old_modules = sys.modules.copy() - for modname in sys.modules.keys(): + for modname in list(sys.modules.keys()): if modname.startswith("xml."): del sys.modules[modname] try: @@ -734,8 +734,7 @@ outf.write(result.getvalue()) outf.close() -items = locals().items() -items.sort() +items = sorted(locals().items()) for (name, value) in items: if name[ : 5] == "test_": confirm(value(), name) Modified: python/branches/p3yk/Lib/xml/sax/xmlreader.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/xmlreader.py (original) +++ python/branches/p3yk/Lib/xml/sax/xmlreader.py Sun Feb 11 19:44:55 2007 @@ -304,10 +304,10 @@ return name def getNames(self): - return self._attrs.keys() + return list(self._attrs.keys()) def getQNames(self): - return self._attrs.keys() + return list(self._attrs.keys()) def __len__(self): return len(self._attrs) @@ -316,7 +316,7 @@ return self._attrs[name] def keys(self): - return self._attrs.keys() + return list(self._attrs.keys()) def __contains__(self, name): return name in self._attrs @@ -328,10 +328,10 @@ return self.__class__(self._attrs) def items(self): - return self._attrs.items() + return list(self._attrs.items()) def values(self): - return self._attrs.values() + return list(self._attrs.values()) # ===== ATTRIBUTESNSIMPL ===== @@ -363,7 +363,7 @@ return self._qnames[name] def getQNames(self): - return self._qnames.values() + return list(self._qnames.values()) def copy(self): return self.__class__(self._attrs, self._qnames) From python-3000-checkins at python.org Sun Feb 11 19:53:00 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 19:53:00 +0100 (CET) Subject: [Python-3000-checkins] r53739 - python/branches/p3yk/Lib/test/test_builtin.py Message-ID: <20070211185300.CC98F1E400C@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 19:53:00 2007 New Revision: 53739 Modified: python/branches/p3yk/Lib/test/test_builtin.py Log: Another fix. Partly reverted the tweaks done by the previous fix. Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Sun Feb 11 19:53:00 2007 @@ -290,8 +290,8 @@ if key == 'a': return 12 raise KeyError - def __iter__(self): - return iter('xyz') + def keys(self): + return list('xyz') m = M() g = globals() @@ -313,8 +313,8 @@ if key == 'a': return 12 return dict.__getitem__(self, key) - def __iter__(self): - return iter('xyz') + def keys(self): + return list('xyz') d = D() self.assertEqual(eval('a', g, d), 12) @@ -346,8 +346,8 @@ class C: def __getitem__(self, item): raise KeyError(item) - def __iter__(self): - return 'a' # XXX Not quite faithful to the SF bug... + def keys(self): + return 1 # used to be 'a' but that's no longer an error self.assertRaises(TypeError, eval, 'dir()', globals(), C()) # Done outside of the method test_z to get the correct scope From python-3000-checkins at python.org Sun Feb 11 19:54:19 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 19:54:19 +0100 (CET) Subject: [Python-3000-checkins] r53740 - python/branches/p3yk/Lib/test/test_grp.py python/branches/p3yk/Lib/test/test_pwd.py Message-ID: <20070211185419.1066B1E400C@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 19:54:18 2007 New Revision: 53740 Modified: python/branches/p3yk/Lib/test/test_grp.py python/branches/p3yk/Lib/test/test_pwd.py Log: Two more trivial fixes. Modified: python/branches/p3yk/Lib/test/test_grp.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grp.py (original) +++ python/branches/p3yk/Lib/test/test_grp.py Sun Feb 11 19:54:18 2007 @@ -50,7 +50,7 @@ bynames[n] = g bygids[g] = n - allnames = bynames.keys() + allnames = list(bynames.keys()) namei = 0 fakename = allnames[namei] while fakename in bynames: Modified: python/branches/p3yk/Lib/test/test_pwd.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pwd.py (original) +++ python/branches/p3yk/Lib/test/test_pwd.py Sun Feb 11 19:54:18 2007 @@ -55,7 +55,7 @@ bynames[n] = u byuids[u] = n - allnames = bynames.keys() + allnames = list(bynames.keys()) namei = 0 fakename = allnames[namei] while fakename in bynames: From python-3000-checkins at python.org Sun Feb 11 23:59:49 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 11 Feb 2007 23:59:49 +0100 (CET) Subject: [Python-3000-checkins] r53742 - in python/branches/p3yk/Lib: pprint.py test/mapping_tests.py test/test_weakref.py weakref.py Message-ID: <20070211225949.762B51E400C@bag.python.org> Author: guido.van.rossum Date: Sun Feb 11 23:59:48 2007 New Revision: 53742 Modified: python/branches/p3yk/Lib/pprint.py python/branches/p3yk/Lib/test/mapping_tests.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/weakref.py Log: Nailed test_weakref.py. Pfew, messy! Modified: python/branches/p3yk/Lib/pprint.py ============================================================================== --- python/branches/p3yk/Lib/pprint.py (original) +++ python/branches/p3yk/Lib/pprint.py Sun Feb 11 23:59:48 2007 @@ -141,8 +141,7 @@ if length: context[objid] = 1 indent = indent + self._indent_per_level - items = object.items() - items.sort() + items = sorted(object.items()) key, ent = items[0] rep = self._repr(key, context, level) write(rep) Modified: python/branches/p3yk/Lib/test/mapping_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/mapping_tests.py (original) +++ python/branches/p3yk/Lib/test/mapping_tests.py Sun Feb 11 23:59:48 2007 @@ -49,7 +49,7 @@ #Indexing for key, value in self.reference.items(): self.assertEqual(d[key], value) - knownkey = self.other.keys()[0] + knownkey = list(self.other.keys())[0] self.failUnlessRaises(KeyError, lambda:d[knownkey]) #len self.assertEqual(len(p), 0) @@ -73,13 +73,16 @@ self.assert_(hasattr(iter, '__iter__')) x = list(iter) self.assert_(set(x)==set(lst)==set(ref)) - check_iterandlist(d.keys(), d.keys(), self.reference.keys()) - check_iterandlist(iter(d), d.keys(), self.reference.keys()) - check_iterandlist(d.values(), d.values(), self.reference.values()) - check_iterandlist(d.items(), d.items(), self.reference.items()) + check_iterandlist(iter(d.keys()), list(d.keys()), + self.reference.keys()) + check_iterandlist(iter(d), list(d.keys()), self.reference.keys()) + check_iterandlist(iter(d.values()), list(d.values()), + self.reference.values()) + check_iterandlist(iter(d.items()), list(d.items()), + self.reference.items()) #get - key, value = d.items().next() - knownkey, knownvalue = self.other.items().next() + key, value = iter(d.items()).next() + knownkey, knownvalue = iter(self.other.items()).next() self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.failIf(knownkey in d) @@ -104,8 +107,8 @@ self.assertEqual(dict(p), self.reference) d = self._full_mapping(self.reference) #setdefault - key, value = d.items().next() - knownkey, knownvalue = self.other.items().next() + key, value = iter(d.items()).next() + knownkey, knownvalue = iter(self.other.items()).next() self.assertEqual(d.setdefault(key, knownvalue), value) self.assertEqual(d[key], value) self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue) @@ -137,21 +140,21 @@ def test_keys(self): d = self._empty_mapping() - self.assertEqual(d.keys(), []) + self.assertEqual(list(d.keys()), []) d = self.reference - self.assert_(self.inmapping.keys()[0] in d.keys()) - self.assert_(self.other.keys()[0] not in d.keys()) + self.assert_(list(self.inmapping.keys())[0] in d.keys()) + self.assert_(list(self.other.keys())[0] not in d.keys()) self.assertRaises(TypeError, d.keys, None) def test_values(self): d = self._empty_mapping() - self.assertEqual(d.values(), []) + self.assertEqual(list(d.values()), []) self.assertRaises(TypeError, d.values, None) def test_items(self): d = self._empty_mapping() - self.assertEqual(d.items(), []) + self.assertEqual(list(d.items()), []) self.assertRaises(TypeError, d.items, None) @@ -161,7 +164,8 @@ def test_getitem(self): d = self.reference - self.assertEqual(d[self.inmapping.keys()[0]], self.inmapping.values()[0]) + self.assertEqual(d[list(self.inmapping.keys())[0]], + list(self.inmapping.values())[0]) self.assertRaises(TypeError, d.__getitem__) @@ -169,7 +173,7 @@ # mapping argument d = self._empty_mapping() d.update(self.other) - self.assertEqual(d.items(), self.other.items()) + self.assertEqual(list(d.items()), list(self.other.items())) # No argument d = self._empty_mapping() @@ -179,12 +183,12 @@ # item sequence d = self._empty_mapping() d.update(self.other.items()) - self.assertEqual(d.items(), self.other.items()) + self.assertEqual(list(d.items()), list(self.other.items())) # Iterator d = self._empty_mapping() d.update(self.other.items()) - self.assertEqual(d.items(), self.other.items()) + self.assertEqual(list(d.items()), list(self.other.items())) # FIXME: Doesn't work with UserDict # self.assertRaises((TypeError, AttributeError), d.update, None) @@ -200,10 +204,8 @@ return self.d[i] d.clear() d.update(SimpleUserDict()) - i1 = d.items() - i2 = self.reference.items() - i1.sort() - i2.sort() + i1 = sorted(d.items()) + i2 = sorted(self.reference.items()) self.assertEqual(i1, i2) class Exc(Exception): pass @@ -266,13 +268,15 @@ def test_get(self): d = self._empty_mapping() - self.assert_(d.get(self.other.keys()[0]) is None) - self.assertEqual(d.get(self.other.keys()[0], 3), 3) + self.assert_(d.get(list(self.other.keys())[0]) is None) + self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) d = self.reference - self.assert_(d.get(self.other.keys()[0]) is None) - self.assertEqual(d.get(self.other.keys()[0], 3), 3) - self.assertEqual(d.get(self.inmapping.keys()[0]), self.inmapping.values()[0]) - self.assertEqual(d.get(self.inmapping.keys()[0], 3), self.inmapping.values()[0]) + self.assert_(d.get(list(self.other.keys())[0]) is None) + self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) + self.assertEqual(d.get(list(self.inmapping.keys())[0]), + list(self.inmapping.values())[0]) + self.assertEqual(d.get(list(self.inmapping.keys())[0], 3), + list(self.inmapping.values())[0]) self.assertRaises(TypeError, d.get) self.assertRaises(TypeError, d.get, None, None, None) @@ -287,9 +291,9 @@ def test_pop(self): d = self._empty_mapping() - k, v = self.inmapping.items()[0] + k, v = list(self.inmapping.items())[0] d[k] = v - self.assertRaises(KeyError, d.pop, self.other.keys()[0]) + self.assertRaises(KeyError, d.pop, list(self.other.keys())[0]) self.assertEqual(d.pop(k), v) self.assertEqual(len(d), 0) 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 Sun Feb 11 23:59:48 2007 @@ -844,19 +844,19 @@ self.assert_(len(items) == 0, "iteritems() did not touch all items") # key iterator, via __iter__(): - keys = dict.keys() + keys = list(dict.keys()) for k in dict: keys.remove(k) self.assert_(len(keys) == 0, "__iter__() did not touch all keys") # key iterator, via iterkeys(): - keys = dict.keys() + keys = list(dict.keys()) for k in dict.keys(): keys.remove(k) self.assert_(len(keys) == 0, "iterkeys() did not touch all keys") # value iterator: - values = dict.values() + values = list(dict.values()) for v in dict.values(): values.remove(v) self.assert_(len(values) == 0, Modified: python/branches/p3yk/Lib/weakref.py ============================================================================== --- python/branches/p3yk/Lib/weakref.py (original) +++ python/branches/p3yk/Lib/weakref.py Sun Feb 11 23:59:48 2007 @@ -106,10 +106,10 @@ yield wr.key, value def iterkeys(self): - return self.data.keys() + return iter(self.data.keys()) def __iter__(self): - return self.data.keys() + return iter(self.data.keys()) def itervaluerefs(self): """Return an iterator that yields the weak references to the values. @@ -292,10 +292,10 @@ yield obj def __iter__(self): - return self.keys() + return iter(self.keys()) def itervalues(self): - return self.data.values() + return iter(self.data.values()) def keyrefs(self): """Return a list of weak references to the keys. From python-3000-checkins at python.org Mon Feb 12 00:06:19 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 12 Feb 2007 00:06:19 +0100 (CET) Subject: [Python-3000-checkins] r53743 - in python/branches/p3yk: Lib/optparse.py Python/Python-ast.c Message-ID: <20070211230619.C67211E400C@bag.python.org> Author: georg.brandl Date: Mon Feb 12 00:06:17 2007 New Revision: 53743 Modified: python/branches/p3yk/Lib/optparse.py python/branches/p3yk/Python/Python-ast.c Log: Checkin the regenerated Python-ast.c and fix test_optparse. Modified: python/branches/p3yk/Lib/optparse.py ============================================================================== --- python/branches/p3yk/Lib/optparse.py (original) +++ python/branches/p3yk/Lib/optparse.py Mon Feb 12 00:06:17 2007 @@ -611,8 +611,7 @@ else: setattr(self, attr, None) if attrs: - attrs = attrs.keys() - attrs.sort() + attrs = sorted(attrs.keys()) raise OptionError( "invalid keyword arguments: %s" % ", ".join(attrs), self) Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Mon Feb 12 00:06:17 2007 @@ -3080,7 +3080,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__", "53349") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53704") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) From python-3000-checkins at python.org Mon Feb 12 01:07:02 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 12 Feb 2007 01:07:02 +0100 (CET) Subject: [Python-3000-checkins] r53746 - python/branches/p3yk/Lib/logging/config.py Message-ID: <20070212000702.985851E400C@bag.python.org> Author: guido.van.rossum Date: Mon Feb 12 01:07:01 2007 New Revision: 53746 Modified: python/branches/p3yk/Lib/logging/config.py Log: Make test_logging pass. Modified: python/branches/p3yk/Lib/logging/config.py ============================================================================== --- python/branches/p3yk/Lib/logging/config.py (original) +++ python/branches/p3yk/Lib/logging/config.py Mon Feb 12 01:07:01 2007 @@ -202,7 +202,7 @@ #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. - existing = root.manager.loggerDict.keys() + existing = list(root.manager.loggerDict.keys()) #now set up the new ones... for log in llist: sectname = "logger_%s" % log From python-3000-checkins at python.org Mon Feb 12 01:22:56 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 12 Feb 2007 01:22:56 +0100 (CET) Subject: [Python-3000-checkins] r53747 - python/branches/p3yk/Lib/mailbox.py Message-ID: <20070212002256.2A47D1E400C@bag.python.org> Author: guido.van.rossum Date: Mon Feb 12 01:22:55 2007 New Revision: 53747 Modified: python/branches/p3yk/Lib/mailbox.py Log: Fix another unit test. Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Mon Feb 12 01:22:55 2007 @@ -95,7 +95,7 @@ def keys(self): """Return a list of keys.""" - return list(self.keys()) + return list(self.iterkeys()) def itervalues(self): """Return an iterator over all messages.""" @@ -111,7 +111,7 @@ def values(self): """Return a list of messages. Memory intensive.""" - return list(self.values()) + return list(self.itervalues()) def iteritems(self): """Return an iterator over (key, message) tuples.""" @@ -124,7 +124,7 @@ def items(self): """Return a list of (key, message) tuples. Memory intensive.""" - return list(self.items()) + return list(self.iteritems()) def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" @@ -477,7 +477,7 @@ def next(self): """Return the next message in a one-time iteration.""" if not hasattr(self, '_onetime_keys'): - self._onetime_keys = self.keys() + self._onetime_keys = iter(self.keys()) while True: try: return self[self._onetime_keys.next()] From python-3000-checkins at python.org Mon Feb 12 01:23:56 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 12 Feb 2007 01:23:56 +0100 (CET) Subject: [Python-3000-checkins] r53748 - python/branches/p3yk/Lib/test/test_marshal.py Message-ID: <20070212002356.A97A11E400C@bag.python.org> Author: guido.van.rossum Date: Mon Feb 12 01:23:56 2007 New Revision: 53748 Modified: python/branches/p3yk/Lib/test/test_marshal.py Log: Fix unittest. Modified: python/branches/p3yk/Lib/test/test_marshal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_marshal.py (original) +++ python/branches/p3yk/Lib/test/test_marshal.py Mon Feb 12 01:23:56 2007 @@ -167,7 +167,7 @@ os.unlink(test_support.TESTFN) def test_list(self): - lst = self.d.items() + lst = list(self.d.items()) new = marshal.loads(marshal.dumps(lst)) self.assertEqual(lst, new) marshal.dump(lst, open(test_support.TESTFN, "wb")) From python-3000-checkins at python.org Mon Feb 12 03:23:41 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 12 Feb 2007 03:23:41 +0100 (CET) Subject: [Python-3000-checkins] r53749 - in python/branches/p3yk: Lib/test/test_dictviews.py Objects/dictobject.c Message-ID: <20070212022341.BBBB81E4004@bag.python.org> Author: guido.van.rossum Date: Mon Feb 12 03:23:40 2007 New Revision: 53749 Modified: python/branches/p3yk/Lib/test/test_dictviews.py python/branches/p3yk/Objects/dictobject.c Log: Make dict.keys() and dict.items() comparable to sets, using == and !=. (PEP 3106 requires subset comparisons too, those will come later if someone really wants them. :-) Modified: python/branches/p3yk/Lib/test/test_dictviews.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dictviews.py (original) +++ python/branches/p3yk/Lib/test/test_dictviews.py Mon Feb 12 03:23:40 2007 @@ -17,18 +17,33 @@ def test_dict_keys(self): d = {1: 10, "a": "ABC"} keys = d.keys() - self.assertEqual(set(keys), {1, "a"}) self.assertEqual(len(keys), 2) + self.assertEqual(set(keys), {1, "a"}) + self.assertEqual(keys, {1, "a"}) + self.assertNotEqual(keys, {1, "a", "b"}) + self.assertNotEqual(keys, {1, "b"}) + self.assertNotEqual(keys, {1}) + self.assertNotEqual(keys, 42) self.assert_(1 in keys) self.assert_("a" in keys) self.assert_(10 not in keys) self.assert_("Z" not in keys) + self.assertEqual(d.keys(), d.keys()) + e = {1: 11, "a": "def"} + self.assertEqual(d.keys(), e.keys()) + del e["a"] + self.assertNotEqual(d.keys(), e.keys()) def test_dict_items(self): d = {1: 10, "a": "ABC"} items = d.items() - self.assertEqual(set(items), {(1, 10), ("a", "ABC")}) self.assertEqual(len(items), 2) + self.assertEqual(set(items), {(1, 10), ("a", "ABC")}) + self.assertEqual(items, {(1, 10), ("a", "ABC")}) + self.assertNotEqual(items, {(1, 10), ("a", "ABC"), "junk"}) + self.assertNotEqual(items, {(1, 10), ("a", "def")}) + self.assertNotEqual(items, {(1, 10)}) + self.assertNotEqual(items, 42) self.assert_((1, 10) in items) self.assert_(("a", "ABC") in items) self.assert_((1, 11) not in items) @@ -36,6 +51,17 @@ self.assert_(() not in items) self.assert_((1,) not in items) self.assert_((1, 2, 3) not in items) + self.assertEqual(d.items(), d.items()) + e = d.copy() + self.assertEqual(d.items(), e.items()) + e["a"] = "def" + self.assertNotEqual(d.items(), e.items()) + + def test_dict_mixed_keys_items(self): + d = {(1, 1): 11, (2, 2): 22} + e = {1: 1, 2: 2} + self.assertEqual(d.keys(), e.items()) + self.assertNotEqual(d.items(), e.keys()) def test_dict_values(self): d = {1: 10, "a": "ABC"} Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Mon Feb 12 03:23:40 2007 @@ -2399,6 +2399,83 @@ return (PyObject *)dv; } +/* Forward */ +PyTypeObject PyDictKeys_Type; +PyTypeObject PyDictItems_Type; +PyTypeObject PyDictValues_Type; + +#define PyDictKeys_Check(obj) ((obj)->ob_type == &PyDictKeys_Type) +#define PyDictItems_Check(obj) ((obj)->ob_type == &PyDictItems_Type) +#define PyDictValues_Check(obj) ((obj)->ob_type == &PyDictValues_Type) + +/* This excludes Values, since they are not sets. */ +# define PyDictViewSet_Check(obj) \ + (PyDictKeys_Check(obj) || PyDictItems_Check(obj)) + +static int +all_contained_in(PyObject *self, PyObject *other) +{ + PyObject *iter = PyObject_GetIter(self); + int ok = 1; + + if (iter == NULL) + return -1; + for (;;) { + PyObject *next = PyIter_Next(iter); + if (next == NULL) { + if (PyErr_Occurred()) + ok = -1; + break; + } + ok = PySequence_Contains(other, next); + Py_DECREF(next); + if (ok <= 0) + break; + } + Py_DECREF(iter); + return ok; +} + +static PyObject * +dictview_richcompare(PyObject *self, PyObject *other, int op) +{ + assert(self != NULL); + assert(PyDictViewSet_Check(self)); + assert(other != NULL); + if ((op == Py_EQ || op == Py_NE) && + (PyAnySet_Check(other) || PyDictViewSet_Check(other))) + { + Py_ssize_t len_self, len_other; + int ok; + PyObject *result; + + len_self = PyObject_Size(self); + if (len_self < 0) + return NULL; + len_other = PyObject_Size(other); + if (len_other < 0) + return NULL; + if (len_self != len_other) + ok = 0; + else if (len_self == 0) + ok = 1; + else + ok = all_contained_in(self, other); + if (ok < 0) + return NULL; + if (ok == (op == Py_EQ)) + result = Py_True; + else + result = Py_False; + Py_INCREF(result); + return result; + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } +} + /*** dict_keys ***/ static PyObject * @@ -2459,7 +2536,7 @@ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + dictview_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)dictkeys_iter, /* tp_iter */ 0, /* tp_iternext */ @@ -2544,7 +2621,7 @@ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + dictview_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)dictitems_iter, /* tp_iter */ 0, /* tp_iternext */ From python-3000-checkins at python.org Tue Feb 13 06:46:40 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 13 Feb 2007 06:46:40 +0100 (CET) Subject: [Python-3000-checkins] r53759 - python/branches/p3yk/BROKEN Message-ID: <20070213054640.EED551E4009@bag.python.org> Author: guido.van.rossum Date: Tue Feb 13 06:46:39 2007 New Revision: 53759 Added: python/branches/p3yk/BROKEN (contents, props changed) Log: List of broken tests at this time. If you fix a test, please update this file. Added: python/branches/p3yk/BROKEN ============================================================================== --- (empty file) +++ python/branches/p3yk/BROKEN Tue Feb 13 06:46:39 2007 @@ -0,0 +1,4 @@ + test_bsddb test_bsddb3 test_compile test_dict test_dumbdbm + test_importhooks test_iter test_iterlen test_minidom test_mutants + test_os test_pickletools test_plistlib test_richcmp test_shelve + test_unittest test_userdict From python-3000-checkins at python.org Tue Feb 13 20:55:24 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 13 Feb 2007 20:55:24 +0100 (CET) Subject: [Python-3000-checkins] r53773 - python/branches/p3yk/Misc/NEWS Message-ID: <20070213195524.6E8611E4011@bag.python.org> Author: guido.van.rossum Date: Tue Feb 13 20:55:23 2007 New Revision: 53773 Modified: python/branches/p3yk/Misc/NEWS Log: Get rid of some old TO TO items. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Tue Feb 13 20:55:23 2007 @@ -14,22 +14,14 @@ - See PEP 3000, 3100. -- Test merging certain changes from the 2.5 HEAD code. - - Weed really old/weird stuff from the library. - Unify range() and xrange(). -- Revamp the dict API: keys(), values(), items() return iterators, etc. - -- Add the bytes type. - - Rework the standard I/O library to use bytes for binary files. - Make strings all Unicode. -- Get rid of classic class implementation. - - Get rid of various compatibility-related flags (e.g. division flags). @@ -51,7 +43,7 @@ - PEP 3102: keyword-only arguments. -- Int/Long unification is mostly complete. The 'long' built-in type +- Int/Long unification is complete. The 'long' built-in type and literals with trailing 'L' or 'l' have been removed. Performance may be sub-optimal (haven't really benchmarked). From python-3000-checkins at python.org Wed Feb 14 18:49:05 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 14 Feb 2007 18:49:05 +0100 (CET) Subject: [Python-3000-checkins] r53779 - in python/branches/p3yk: BROKEN Lib/test/test_dict.py Message-ID: <20070214174905.76EB01E400A@bag.python.org> Author: guido.van.rossum Date: Wed Feb 14 18:49:04 2007 New Revision: 53779 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/test/test_dict.py Log: Fix for test_dict.py, thanks to Eduardo O Padoan. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Wed Feb 14 18:49:04 2007 @@ -1,4 +1,4 @@ - test_bsddb test_bsddb3 test_compile test_dict test_dumbdbm + test_bsddb test_bsddb3 test_compile test_dumbdbm test_importhooks test_iter test_iterlen test_minidom test_mutants test_os test_pickletools test_plistlib test_richcmp test_shelve test_unittest test_userdict Modified: python/branches/p3yk/Lib/test/test_dict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dict.py (original) +++ python/branches/p3yk/Lib/test/test_dict.py Wed Feb 14 18:49:04 2007 @@ -19,7 +19,7 @@ def test_keys(self): d = {} - self.assertEqual(d.keys(), []) + self.assertEqual(set(d.keys()), set()) d = {'a': 1, 'b': 2} k = d.keys() self.assert_('a' in d) @@ -29,18 +29,18 @@ def test_values(self): d = {} - self.assertEqual(d.values(), []) + self.assertEqual(set(d.values()), set()) d = {1:2} - self.assertEqual(d.values(), [2]) + self.assertEqual(set(d.values()), {2}) self.assertRaises(TypeError, d.values, None) def test_items(self): d = {} - self.assertEqual(d.items(), []) + self.assertEqual(set(d.items()), set()) d = {1:2} - self.assertEqual(d.items(), [(1, 2)]) + self.assertEqual(set(d.items()), {(1, 2)}) self.assertRaises(TypeError, d.items, None) From python-3000-checkins at python.org Thu Feb 15 04:49:09 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 15 Feb 2007 04:49:09 +0100 (CET) Subject: [Python-3000-checkins] r53780 - in python/branches/p3yk/Lib: UserDict.py test/mapping_tests.py test/test_userdict.py Message-ID: <20070215034909.BDCBC1E4026@bag.python.org> Author: guido.van.rossum Date: Thu Feb 15 04:49:08 2007 New Revision: 53780 Modified: python/branches/p3yk/Lib/UserDict.py python/branches/p3yk/Lib/test/mapping_tests.py python/branches/p3yk/Lib/test/test_userdict.py Log: Fix the damage to UserDict and its tests. Clearly this is not the right way to fix this; UserDict and MixinDict ought to be redesigned with the new dict API in mind. But I'm not claiming to be in charge of library redesign, I only want zero failing tests. Modified: python/branches/p3yk/Lib/UserDict.py ============================================================================== --- python/branches/p3yk/Lib/UserDict.py (original) +++ python/branches/p3yk/Lib/UserDict.py Thu Feb 15 04:49:08 2007 @@ -42,9 +42,6 @@ return c def keys(self): return self.data.keys() def items(self): return self.data.items() - def iteritems(self): return self.data.items() - def iterkeys(self): return self.data.keys() - def itervalues(self): return self.data.values() def values(self): return self.data.values() def update(self, dict=None, **kwargs): if dict is None: @@ -91,6 +88,8 @@ # methods, progressively more efficiency comes with defining # __contains__(), __iter__(), and iteritems(). + # XXX It would make more sense to expect __iter__ to be primitive. + # second level definitions support higher levels def __iter__(self): for k in self.keys(): @@ -103,20 +102,20 @@ return True # third level takes advantage of second level definitions + def iterkeys(self): + return self.__iter__() def iteritems(self): for k in self: yield (k, self[k]) - def iterkeys(self): - return self.__iter__() # fourth level uses definitions from lower levels def itervalues(self): - for _, v in self.items(): + for _, v in self.iteritems(): yield v def values(self): - return [v for _, v in self.items()] + return [v for _, v in self.iteritems()] def items(self): - return list(self.items()) + return list(self.iteritems()) def clear(self): for key in self.keys(): del self[key] @@ -140,7 +139,7 @@ return value def popitem(self): try: - k, v = self.items().next() + k, v = self.iteritems().next() except StopIteration: raise KeyError, 'container is empty' del self[k] @@ -169,14 +168,14 @@ except KeyError: return default def __repr__(self): - return repr(dict(self.items())) + return repr(dict(self.iteritems())) def __eq__(self, other): if isinstance(other, DictMixin): - other = dict(other.items()) - return dict(self.items()) == other + other = dict(other.iteritems()) + return dict(self.iteritems()) == other def __ne__(self, other): if isinstance(other, DictMixin): - other = dict(other.items()) - return dict(self.items()) != other + other = dict(other.iteritems()) + return dict(self.iteritems()) != other def __len__(self): return len(self.keys()) Modified: python/branches/p3yk/Lib/test/mapping_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/mapping_tests.py (original) +++ python/branches/p3yk/Lib/test/mapping_tests.py Thu Feb 15 04:49:08 2007 @@ -317,7 +317,7 @@ def test_keys(self): BasicTestMappingProtocol.test_keys(self) d = self._empty_mapping() - self.assertEqual(d.keys(), []) + self.assertEqual(list(d.keys()), []) d = self._full_mapping({'a': 1, 'b': 2}) k = d.keys() self.assert_('a' in k) @@ -327,13 +327,13 @@ def test_values(self): BasicTestMappingProtocol.test_values(self) d = self._full_mapping({1:2}) - self.assertEqual(d.values(), [2]) + self.assertEqual(list(d.values()), [2]) def test_items(self): BasicTestMappingProtocol.test_items(self) d = self._full_mapping({1:2}) - self.assertEqual(d.items(), [(1, 2)]) + self.assertEqual(list(d.items()), [(1, 2)]) def test_contains(self): d = self._empty_mapping() Modified: python/branches/p3yk/Lib/test/test_userdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_userdict.py (original) +++ python/branches/p3yk/Lib/test/test_userdict.py Thu Feb 15 04:49:08 2007 @@ -92,7 +92,7 @@ # Test keys, items, values self.assertEqual(u2.keys(), d2.keys()) self.assertEqual(u2.items(), d2.items()) - self.assertEqual(u2.values(), d2.values()) + self.assertEqual(list(u2.values()), list(d2.values())) # Test "in". for i in u2.keys(): From python-3000-checkins at python.org Thu Feb 15 05:01:06 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 15 Feb 2007 05:01:06 +0100 (CET) Subject: [Python-3000-checkins] r53781 - in python/branches/p3yk: BROKEN Lib/UserDict.py Lib/test/test_richcmp.py Message-ID: <20070215040106.8EB931E4017@bag.python.org> Author: guido.van.rossum Date: Thu Feb 15 05:01:01 2007 New Revision: 53781 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/UserDict.py python/branches/p3yk/Lib/test/test_richcmp.py Log: Some more test now pass. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Thu Feb 15 05:01:01 2007 @@ -1,4 +1,3 @@ test_bsddb test_bsddb3 test_compile test_dumbdbm test_importhooks test_iter test_iterlen test_minidom test_mutants - test_os test_pickletools test_plistlib test_richcmp test_shelve - test_unittest test_userdict + test_os test_plistlib Modified: python/branches/p3yk/Lib/UserDict.py ============================================================================== --- python/branches/p3yk/Lib/UserDict.py (original) +++ python/branches/p3yk/Lib/UserDict.py Thu Feb 15 05:01:01 2007 @@ -117,7 +117,7 @@ def items(self): return list(self.iteritems()) def clear(self): - for key in self.keys(): + for key in list(self.iterkeys()): del self[key] def setdefault(self, key, default=None): try: Modified: python/branches/p3yk/Lib/test/test_richcmp.py ============================================================================== --- python/branches/p3yk/Lib/test/test_richcmp.py (original) +++ python/branches/p3yk/Lib/test/test_richcmp.py Thu Feb 15 05:01:01 2007 @@ -265,7 +265,7 @@ imag1a = {} for i in range(50): imag1a[random.randrange(100)*1j] = random.randrange(100)*1j - items = imag1a.items() + items = list(imag1a.items()) random.shuffle(items) imag1b = {} for k, v in items: From python-3000-checkins at python.org Wed Feb 21 22:18:25 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Wed, 21 Feb 2007 22:18:25 +0100 (CET) Subject: [Python-3000-checkins] r53841 - in python/branches/p3yk: BROKEN Lib/plat-mac/plistlib.py Message-ID: <20070221211825.11DA31E4002@bag.python.org> Author: brett.cannon Date: Wed Feb 21 22:18:18 2007 New Revision: 53841 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/plat-mac/plistlib.py Log: Fix plistlib to work with dict views. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Wed Feb 21 22:18:18 2007 @@ -1,3 +1,3 @@ test_bsddb test_bsddb3 test_compile test_dumbdbm test_importhooks test_iter test_iterlen test_minidom test_mutants - test_os test_plistlib + test_os Modified: python/branches/p3yk/Lib/plat-mac/plistlib.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/plistlib.py (original) +++ python/branches/p3yk/Lib/plat-mac/plistlib.py Wed Feb 21 22:18:18 2007 @@ -268,8 +268,7 @@ def writeDict(self, d): self.beginElement("dict") - items = d.items() - items.sort() + items = sorted(d.items()) for key, value in items: if not isinstance(key, (str, unicode)): raise TypeError("keys must be strings") From python-3000-checkins at python.org Wed Feb 21 22:57:56 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Wed, 21 Feb 2007 22:57:56 +0100 (CET) Subject: [Python-3000-checkins] r53843 - in python/branches/p3yk: BROKEN Lib/test/mapping_tests.py Message-ID: <20070221215756.B03C01E4002@bag.python.org> Author: brett.cannon Date: Wed Feb 21 22:57:55 2007 New Revision: 53843 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/test/mapping_tests.py Log: Fix test_os from breakage due to dict views. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Wed Feb 21 22:57:55 2007 @@ -1,3 +1,2 @@ test_bsddb test_bsddb3 test_compile test_dumbdbm test_importhooks test_iter test_iterlen test_minidom test_mutants - test_os Modified: python/branches/p3yk/Lib/test/mapping_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/mapping_tests.py (original) +++ python/branches/p3yk/Lib/test/mapping_tests.py Wed Feb 21 22:57:55 2007 @@ -101,7 +101,7 @@ #update p.update(self.reference) self.assertEqual(dict(p), self.reference) - items = p.items() + items = list(p.items()) p = self._empty_mapping() p.update(items) self.assertEqual(dict(p), self.reference) From python-3000-checkins at python.org Wed Feb 21 23:00:00 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Wed, 21 Feb 2007 23:00:00 +0100 (CET) Subject: [Python-3000-checkins] r53844 - in python/branches/p3yk: BROKEN Lib/test/test_mutants.py Message-ID: <20070221220000.C9CE61E4002@bag.python.org> Author: brett.cannon Date: Wed Feb 21 22:59:58 2007 New Revision: 53844 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/test/test_mutants.py Log: Fix test_mutants for dict views. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Wed Feb 21 22:59:58 2007 @@ -1,2 +1,2 @@ test_bsddb test_bsddb3 test_compile test_dumbdbm - test_importhooks test_iter test_iterlen test_minidom test_mutants + test_importhooks test_iter test_iterlen test_minidom Modified: python/branches/p3yk/Lib/test/test_mutants.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mutants.py (original) +++ python/branches/p3yk/Lib/test/test_mutants.py Wed Feb 21 22:59:58 2007 @@ -116,7 +116,7 @@ for i in xrange(numentries): d[Horrid(random.choice(candidates))] = \ Horrid(random.choice(candidates)) - return d.keys() + return list(d.keys()) # Test one pair of randomly generated dicts, each with n entries. # Note that dict comparison is trivial if they don't have the same number From python-3000-checkins at python.org Wed Feb 21 23:05:45 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Wed, 21 Feb 2007 23:05:45 +0100 (CET) Subject: [Python-3000-checkins] r53845 - in python/branches/p3yk: BROKEN Lib/test/test_minidom.py Lib/xml/dom/minidom.py Message-ID: <20070221220545.4E1611E4002@bag.python.org> Author: brett.cannon Date: Wed Feb 21 23:05:37 2007 New Revision: 53845 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/test/test_minidom.py python/branches/p3yk/Lib/xml/dom/minidom.py Log: Fix xml.dom.minidom so it works again after the dict views introduction. There are some methods in minidom that return dict.keys() directly. There were left alone since the tests passed without touching them, but it might be prudent to just wrap them in a 'list' call to be safe for people expecting a list. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Wed Feb 21 23:05:37 2007 @@ -1,2 +1,2 @@ test_bsddb test_bsddb3 test_compile test_dumbdbm - test_importhooks test_iter test_iterlen test_minidom + test_importhooks test_iter test_iterlen Modified: python/branches/p3yk/Lib/test/test_minidom.py ============================================================================== --- python/branches/p3yk/Lib/test/test_minidom.py (original) +++ python/branches/p3yk/Lib/test/test_minidom.py Wed Feb 21 23:05:37 2007 @@ -565,10 +565,8 @@ def _testCloneElementCopiesAttributes(e1, e2, test): attrs1 = e1.attributes attrs2 = e2.attributes - keys1 = attrs1.keys() - keys2 = attrs2.keys() - keys1.sort() - keys2.sort() + keys1 = sorted(attrs1.keys()) + keys2 = sorted(attrs2.keys()) confirm(keys1 == keys2, "clone of element has same attribute keys") for i in range(len(keys1)): a1 = attrs1.item(i) @@ -1351,8 +1349,7 @@ # --- MAIN PROGRAM -names = globals().keys() -names.sort() +names = sorted(globals().keys()) failed = [] Modified: python/branches/p3yk/Lib/xml/dom/minidom.py ============================================================================== --- python/branches/p3yk/Lib/xml/dom/minidom.py (original) +++ python/branches/p3yk/Lib/xml/dom/minidom.py Wed Feb 21 23:05:37 2007 @@ -256,7 +256,7 @@ def _call_user_data_handler(self, operation, src, dst): if hasattr(self, "_user_data"): - for key, (data, handler) in self._user_data.items(): + for key, (data, handler) in list(self._user_data.items()): if handler is not None: handler.handle(operation, key, data, src, dst) @@ -480,7 +480,7 @@ def item(self, index): try: - return self[self._attrs.keys()[index]] + return self[list(self._attrs.keys())[index]] except IndexError: return None @@ -672,7 +672,7 @@ return self.tagName def unlink(self): - for attr in self._attrs.values(): + for attr in list(self._attrs.values()): attr.unlink() self._attrs = None self._attrsNS = None @@ -805,8 +805,7 @@ writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() - a_names = attrs.keys() - a_names.sort() + a_names = sorted(attrs.keys()) for a_name in a_names: writer.write(" %s=\"" % a_name) From python-3000-checkins at python.org Thu Feb 22 05:45:16 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 05:45:16 +0100 (CET) Subject: [Python-3000-checkins] r53852 - in python/branches/p3yk: BROKEN Lib/test/test_iterlen.py Message-ID: <20070222044516.EFE571E400F@bag.python.org> Author: brett.cannon Date: Thu Feb 22 05:45:13 2007 New Revision: 53852 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/test/test_iterlen.py Log: Fix test_iterlen by returning the iterator of dict views. Problem is that iteritems and itervalues' previous object were both an iterator *and* and iterable. The tests expected an iterator but were given an iterable. Should the 2to3 conversion for iter(values|items|keys) change the code to ``iter(dict.keys())`` to be more compatible? Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Thu Feb 22 05:45:13 2007 @@ -1,2 +1,2 @@ test_bsddb test_bsddb3 test_compile test_dumbdbm - test_importhooks test_iter test_iterlen + test_importhooks test_iter Modified: python/branches/p3yk/Lib/test/test_iterlen.py ============================================================================== --- python/branches/p3yk/Lib/test/test_iterlen.py (original) +++ python/branches/p3yk/Lib/test/test_iterlen.py Thu Feb 22 05:45:13 2007 @@ -139,14 +139,14 @@ def setUp(self): d = dict.fromkeys(xrange(n)) - self.it = d.items() + self.it = iter(d.items()) self.mutate = d.popitem class TestDictValues(TestTemporarilyImmutable): def setUp(self): d = dict.fromkeys(xrange(n)) - self.it = d.values() + self.it = iter(d.values()) self.mutate = d.popitem class TestSet(TestTemporarilyImmutable): From python-3000-checkins at python.org Thu Feb 22 05:49:10 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 05:49:10 +0100 (CET) Subject: [Python-3000-checkins] r53853 - in python/branches/p3yk: BROKEN Lib/test/test_iter.py Message-ID: <20070222044910.7CB5C1E4002@bag.python.org> Author: brett.cannon Date: Thu Feb 22 05:49:03 2007 New Revision: 53853 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/test/test_iter.py Log: Fix test_iter after the dict views conversion. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Thu Feb 22 05:49:03 2007 @@ -1,2 +1,2 @@ test_bsddb test_bsddb3 test_compile test_dumbdbm - test_importhooks test_iter + test_importhooks Modified: python/branches/p3yk/Lib/test/test_iter.py ============================================================================== --- python/branches/p3yk/Lib/test/test_iter.py (original) +++ python/branches/p3yk/Lib/test/test_iter.py Thu Feb 22 05:49:03 2007 @@ -225,7 +225,7 @@ dict = {} for i in range(10): dict[i] = None - self.check_for_loop(dict, dict.keys()) + self.check_for_loop(dict, list(dict.keys())) # Test a file def test_iter_file(self): @@ -254,7 +254,7 @@ self.assertEqual(list(range(10, -1, -1)), range(10, -1, -1)) d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(list(d), d.keys()) + self.assertEqual(list(d), list(d.keys())) self.assertRaises(TypeError, list, list) self.assertRaises(TypeError, list, 42) @@ -319,7 +319,7 @@ self.assertEqual(filter(None, "abc"), "abc") d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(filter(None, d), d.keys()) + self.assertEqual(filter(None, d), list(d.keys())) self.assertRaises(TypeError, filter, None, list) self.assertRaises(TypeError, filter, None, 42) @@ -393,9 +393,9 @@ self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6)) d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(map(None, d), d.keys()) - self.assertEqual(map(lambda k, d=d: (k, d[k]), d), d.items()) - dkeys = d.keys() + self.assertEqual(map(None, d), list(d.keys())) + self.assertEqual(map(lambda k, d=d: (k, d[k]), d), list(d.items())) + dkeys = list(d.keys()) expected = [(i < len(d) and dkeys[i] or None, i, i < len(d) and dkeys[i] or None) @@ -437,7 +437,7 @@ [(0,), (1,), (2,)]) d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(d.items(), list(zip(d, d.values()))) + self.assertEqual(list(d.items()), list(zip(d, d.values()))) # Generate all ints starting at constructor arg. class IntsFrom: From python-3000-checkins at python.org Thu Feb 22 05:50:24 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 05:50:24 +0100 (CET) Subject: [Python-3000-checkins] r53854 - in python/branches/p3yk: BROKEN Lib/test/test_importhooks.py Message-ID: <20070222045024.B8FE71E4003@bag.python.org> Author: brett.cannon Date: Thu Feb 22 05:50:21 2007 New Revision: 53854 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/test/test_importhooks.py Log: Fix test_importhooks for dict views. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Thu Feb 22 05:50:21 2007 @@ -1,2 +1 @@ test_bsddb test_bsddb3 test_compile test_dumbdbm - test_importhooks Modified: python/branches/p3yk/Lib/test/test_importhooks.py ============================================================================== --- python/branches/p3yk/Lib/test/test_importhooks.py (original) +++ python/branches/p3yk/Lib/test/test_importhooks.py Thu Feb 22 05:50:21 2007 @@ -254,7 +254,7 @@ mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc") for mname in mnames: parent = mname.split(".")[0] - for n in sys.modules.keys(): + for n in list(sys.modules.keys()): if n.startswith(parent): del sys.modules[n] for mname in mnames: From python-3000-checkins at python.org Thu Feb 22 06:04:35 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 06:04:35 +0100 (CET) Subject: [Python-3000-checkins] r53855 - in python/branches/p3yk/Lib: dumbdbm.py test/test_dumbdbm.py Message-ID: <20070222050435.747DB1E4002@bag.python.org> Author: brett.cannon Date: Thu Feb 22 06:04:32 2007 New Revision: 53855 Modified: python/branches/p3yk/Lib/dumbdbm.py python/branches/p3yk/Lib/test/test_dumbdbm.py Log: Fix dumbdbm and test_dumbdbm to work with dict views. Bug in dumbdbm was from dict views not being iterators but just iterables. Modified: python/branches/p3yk/Lib/dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/dumbdbm.py (original) +++ python/branches/p3yk/Lib/dumbdbm.py Thu Feb 22 06:04:32 2007 @@ -202,7 +202,7 @@ return key in self._index def iterkeys(self): - return self._index.keys() + return iter(self._index.keys()) __iter__ = iterkeys def __len__(self): Modified: python/branches/p3yk/Lib/test/test_dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dumbdbm.py (original) +++ python/branches/p3yk/Lib/test/test_dumbdbm.py Thu Feb 22 06:04:32 2007 @@ -32,7 +32,7 @@ def test_dumbdbm_creation(self): f = dumbdbm.open(_fname, 'c') - self.assertEqual(f.keys(), []) + self.assertEqual(list(f.keys()), []) for key in self._dict: f[key] = self._dict[key] self.read_helper(f) @@ -128,10 +128,8 @@ f.close() def keys_helper(self, f): - keys = f.keys() - keys.sort() - dkeys = self._dict.keys() - dkeys.sort() + keys = sorted(f.keys()) + dkeys = sorted(self._dict.keys()) self.assertEqual(keys, dkeys) return keys @@ -156,10 +154,8 @@ f.close() f = dumbdbm.open(_fname) - expected = d.items() - expected.sort() - got = f.items() - got.sort() + expected = sorted(d.items()) + got = sorted(f.items()) self.assertEqual(expected, got) f.close() From python-3000-checkins at python.org Thu Feb 22 06:05:22 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 06:05:22 +0100 (CET) Subject: [Python-3000-checkins] r53856 - python/branches/p3yk/BROKEN Message-ID: <20070222050522.C57051E4002@bag.python.org> Author: brett.cannon Date: Thu Feb 22 06:05:21 2007 New Revision: 53856 Modified: python/branches/p3yk/BROKEN Log: Remove test_dumbdbm as failing. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Thu Feb 22 06:05:21 2007 @@ -1 +1 @@ - test_bsddb test_bsddb3 test_compile test_dumbdbm + test_bsddb test_bsddb3 test_compile From python-3000-checkins at python.org Thu Feb 22 07:12:21 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 07:12:21 +0100 (CET) Subject: [Python-3000-checkins] r53857 - python/branches/p3yk/Lib/test/test_bsddb.py Message-ID: <20070222061221.A218A1E4002@bag.python.org> Author: brett.cannon Date: Thu Feb 22 07:12:19 2007 New Revision: 53857 Modified: python/branches/p3yk/Lib/test/test_bsddb.py Log: Fix obvious problems from switch to dict views. Some tests still fail over some reference count issue (I think). Modified: python/branches/p3yk/Lib/test/test_bsddb.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bsddb.py (original) +++ python/branches/p3yk/Lib/test/test_bsddb.py Thu Feb 22 07:12:19 2007 @@ -94,7 +94,7 @@ if not hasattr(self.f, 'iteritems'): return - di = self.d.items() + di = iter(self.d.items()) while 1: try: k, v = di.next() @@ -105,7 +105,7 @@ # it should behave the same as a dict. modifying values # of existing keys should not break iteration. (adding # or removing keys should) - fi = self.f.items() + fi = iter(self.f.items()) while 1: try: k, v = fi.next() @@ -159,7 +159,7 @@ # test the iterator interface (if present) if hasattr(self.f, 'iteritems'): if debug: print("D") - i = self.f.items() + i = iter(self.f.items()) k,v = i.next() if debug: print("E") self.f[k] = "please don't deadlock" @@ -198,7 +198,7 @@ # do the bsddb._DBWithCursor _iter_mixin internals leak cursors? nc1 = len(self.f._cursor_refs) # create iterator - i = self.f.items() + i = iter(self.f.items()) nc2 = len(self.f._cursor_refs) # use the iterator (should run to the first yeild, creating the cursor) k, v = i.next() @@ -246,8 +246,7 @@ def test_keyordering(self): if self.openmethod[0] is not bsddb.btopen: return - keys = self.d.keys() - keys.sort() + keys = sorted(self.d.keys()) self.assertEqual(self.f.first()[0], keys[0]) self.assertEqual(self.f.next()[0], keys[1]) self.assertEqual(self.f.last()[0], keys[-1]) From python-3000-checkins at python.org Thu Feb 22 07:41:03 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 22 Feb 2007 07:41:03 +0100 (CET) Subject: [Python-3000-checkins] r53858 - in python/branches/p3yk: BROKEN Lib/bsddb/dbtables.py Lib/bsddb/test/test_dbtables.py Message-ID: <20070222064103.320EC1E4008@bag.python.org> Author: brett.cannon Date: Thu Feb 22 07:40:59 2007 New Revision: 53858 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Lib/bsddb/dbtables.py python/branches/p3yk/Lib/bsddb/test/test_dbtables.py Log: Fix test_bsddb3 (along with something bsddb) to work with dict views. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Thu Feb 22 07:40:59 2007 @@ -1 +1 @@ - test_bsddb test_bsddb3 test_compile + test_bsddb test_compile Modified: python/branches/p3yk/Lib/bsddb/dbtables.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbtables.py (original) +++ python/branches/p3yk/Lib/bsddb/dbtables.py Thu Feb 22 07:40:59 2007 @@ -546,7 +546,7 @@ self.__load_column_info(table) if columns is None: columns = self.tablecolumns[table] - for column in (columns + conditions.keys()): + for column in (columns + list(conditions.keys())): if not self.__tablecolumns[table].count(column): raise TableDBError, "unknown column: %r" % (column,) @@ -580,7 +580,7 @@ # leave all unknown condition callables alone as equals return 0 - conditionlist = conditions.items() + conditionlist = list(conditions.items()) conditionlist.sort(cmp_conditions) # Apply conditions to column data to find what we want Modified: python/branches/p3yk/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 Thu Feb 22 07:40:59 2007 @@ -76,6 +76,7 @@ values = self.tdb.Select( tabname, [colname], conditions={colname: None}) + values = list(values) colval = pickle.loads(values[0][colname]) assert(colval > 3.141 and colval < 3.142) @@ -102,6 +103,7 @@ values = self.tdb.Select(tabname, [col2], conditions={col0: lambda x: pickle.loads(x) >= 8}) + values = list(values) assert len(values) == 2 if values[0]['Species'] == 'Penguin' : @@ -179,11 +181,13 @@ values = self.tdb.Select( tabname, ['a', 'd', 'b'], conditions={'e': dbtables.PrefixCond('Fuzzy')}) + values = list(values) assert len(values) == 1 assert values[0]['d'] == None values = self.tdb.Select(tabname, ['b'], conditions={'c': lambda c: c == 'meep'}) + values = list(values) assert len(values) == 1 assert values[0]['b'] == "bad" @@ -272,6 +276,7 @@ values = self.tdb.Select( tabname, ['p', 'e'], conditions={'e': dbtables.PrefixCond('the l')}) + values = list(values) assert len(values) == 2, values assert values[0]['e'] == values[1]['e'], values assert values[0]['p'] != values[1]['p'], values @@ -279,6 +284,7 @@ values = self.tdb.Select( tabname, ['d', 'a'], conditions={'a': dbtables.LikeCond('%aardvark%')}) + values = list(values) assert len(values) == 1, values assert values[0]['d'] == "is for dog", values assert values[0]['a'] == "is for aardvark", values @@ -290,6 +296,7 @@ 'd':dbtables.ExactCond('is for dog'), 'c':dbtables.PrefixCond('is for'), 'p':lambda s: not s}) + values = list(values) assert len(values) == 1, values assert values[0]['d'] == "is for dog", values assert values[0]['a'] == "is for aardvark", values @@ -354,6 +361,7 @@ values = self.tdb.Select( tabname, None, conditions={'Type': dbtables.ExactCond('Unknown')}) + values = list(values) assert len(values) == 1, values assert values[0]['Name'] == None, values assert values[0]['Access'] == None, values @@ -362,6 +370,7 @@ values = self.tdb.Select( tabname, None, conditions={'Name': dbtables.ExactCond('Nifty.MP3')}) + values = list(values) assert len(values) == 1, values assert values[0]['Type'] == "MP3", values assert values[0]['Access'] == "2", values @@ -369,6 +378,7 @@ # Make sure change applied only to select conditions values = self.tdb.Select( tabname, None, conditions={'Name': dbtables.LikeCond('%doc%')}) + values = list(values) assert len(values) == 1, values assert values[0]['Type'] == "Word", values assert values[0]['Access'] == "9", values From python-3000-checkins at python.org Fri Feb 23 00:55:30 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 23 Feb 2007 00:55:30 +0100 (CET) Subject: [Python-3000-checkins] r53859 - in python/branches/p3yk: BROKEN Lib/test/test_bsddb.py Lib/test/test_compile.py Message-ID: <20070222235530.ADDAB1E4003@bag.python.org> Author: guido.van.rossum Date: Fri Feb 23 00:55:25 2007 New Revision: 53859 Removed: python/branches/p3yk/BROKEN Modified: python/branches/p3yk/Lib/test/test_bsddb.py python/branches/p3yk/Lib/test/test_compile.py Log: Fix the last two tests. Thanks to Brett for fixing so many before! I see some tracebacks from threads when testing test_bsddbd3 (on OSX) but the test claims to pass, so I'm ignoring these. Deleted: /python/branches/p3yk/BROKEN ============================================================================== --- /python/branches/p3yk/BROKEN Fri Feb 23 00:55:25 2007 +++ (empty file) @@ -1 +0,0 @@ - test_bsddb test_compile Modified: python/branches/p3yk/Lib/test/test_bsddb.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bsddb.py (original) +++ python/branches/p3yk/Lib/test/test_bsddb.py Fri Feb 23 00:55:25 2007 @@ -198,9 +198,9 @@ # do the bsddb._DBWithCursor _iter_mixin internals leak cursors? nc1 = len(self.f._cursor_refs) # create iterator - i = iter(self.f.items()) + i = iter(self.f.iteritems()) nc2 = len(self.f._cursor_refs) - # use the iterator (should run to the first yeild, creating the cursor) + # use the iterator (should run to the first yield, creating the cursor) k, v = i.next() nc3 = len(self.f._cursor_refs) # destroy the iterator; this should cause the weakref callback @@ -210,7 +210,7 @@ self.assertEqual(nc1, nc2) self.assertEqual(nc1, nc4) - self.assert_(nc3 == nc1+1) + self.assertEqual(nc3, nc1+1) def test_popitem(self): k, v = self.f.popitem() 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 Fri Feb 23 00:55:25 2007 @@ -53,8 +53,8 @@ raise KeyError def __setitem__(self, key, value): self.results = (key, value) - def __iter__(self): - return iter('xyz') + def keys(self): + return list('xyz') m = M() g = globals() From python-3000-checkins at python.org Fri Feb 23 16:08:35 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Fri, 23 Feb 2007 16:08:35 +0100 (CET) Subject: [Python-3000-checkins] r53866 - in python/branches/p3yk: Doc/lib/emailgenerator.tex Doc/lib/libcollections.tex Doc/lib/libfunctools.tex Doc/lib/libheapq.tex Doc/lib/libitertools.tex Doc/lib/liblocale.tex Doc/lib/libos.tex Doc/lib/libshutil.tex Doc/lib/libstdtypes.tex Doc/lib/libstruct.tex Doc/lib/libtarfile.tex Doc/lib/libzipfile.tex Include/Python-ast.h Include/dictobject.h Lib/decimal.py Lib/distutils/command/build_ext.py Lib/encodings/__init__.py Lib/gzip.py Lib/heapq.py Lib/idlelib/AutoCompleteWindow.py Lib/idlelib/CallTips.py Lib/idlelib/CodeContext.py Lib/idlelib/IOBinding.py Lib/idlelib/NEWS.txt Lib/idlelib/PyShell.py Lib/idlelib/configHandler.py Lib/idlelib/help.txt Lib/imputil.py Lib/logging/__init__.py Lib/shutil.py Lib/stat.py Lib/subprocess.py Lib/tarfile.py Lib/test/test_datetime.py Lib/test/test_defaultdict.py Lib/test/test_descr.py Lib/test/test_dict.py Lib/test/test_gzip.py Lib/test/test_heapq.py Lib/test/test_itertools.py Lib/test/test_operator.py Lib/test/test_posix.py Lib/test/test_sax.py Lib/test/test_set.py Lib/test/test_tarfile.py Lib/test/test_zipfile.py Lib/trace.py Lib/xml/sax/saxutils.py Lib/zipfile.py Misc/ACKS Modules/collectionsmodule.c Modules/datetimemodule.c Modules/itertoolsmodule.c Modules/posixmodule.c Modules/socketmodule.c Modules/socketmodule.h Objects/abstract.c Objects/dictnotes.txt Objects/dictobject.c Objects/enumobject.c Objects/setobject.c Objects/typeobject.c Parser/Python.asdl Parser/asdl_c.py Python/Python-ast.c configure configure.in pyconfig.h.in setup.py Message-ID: <20070223150835.39D191E4008@bag.python.org> Author: thomas.wouters Date: Fri Feb 23 16:07:44 2007 New Revision: 53866 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/lib/emailgenerator.tex python/branches/p3yk/Doc/lib/libcollections.tex python/branches/p3yk/Doc/lib/libfunctools.tex python/branches/p3yk/Doc/lib/libheapq.tex python/branches/p3yk/Doc/lib/libitertools.tex python/branches/p3yk/Doc/lib/liblocale.tex python/branches/p3yk/Doc/lib/libos.tex python/branches/p3yk/Doc/lib/libshutil.tex python/branches/p3yk/Doc/lib/libstdtypes.tex python/branches/p3yk/Doc/lib/libstruct.tex python/branches/p3yk/Doc/lib/libtarfile.tex python/branches/p3yk/Doc/lib/libzipfile.tex python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Include/dictobject.h python/branches/p3yk/Lib/decimal.py python/branches/p3yk/Lib/distutils/command/build_ext.py python/branches/p3yk/Lib/encodings/__init__.py python/branches/p3yk/Lib/gzip.py python/branches/p3yk/Lib/heapq.py python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py python/branches/p3yk/Lib/idlelib/CallTips.py python/branches/p3yk/Lib/idlelib/CodeContext.py python/branches/p3yk/Lib/idlelib/IOBinding.py python/branches/p3yk/Lib/idlelib/NEWS.txt python/branches/p3yk/Lib/idlelib/PyShell.py python/branches/p3yk/Lib/idlelib/configHandler.py python/branches/p3yk/Lib/idlelib/help.txt python/branches/p3yk/Lib/imputil.py python/branches/p3yk/Lib/logging/__init__.py python/branches/p3yk/Lib/shutil.py python/branches/p3yk/Lib/stat.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/test/test_datetime.py python/branches/p3yk/Lib/test/test_defaultdict.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_dict.py python/branches/p3yk/Lib/test/test_gzip.py python/branches/p3yk/Lib/test/test_heapq.py python/branches/p3yk/Lib/test/test_itertools.py python/branches/p3yk/Lib/test/test_operator.py python/branches/p3yk/Lib/test/test_posix.py python/branches/p3yk/Lib/test/test_sax.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Lib/test/test_tarfile.py python/branches/p3yk/Lib/test/test_zipfile.py python/branches/p3yk/Lib/trace.py python/branches/p3yk/Lib/xml/sax/saxutils.py python/branches/p3yk/Lib/zipfile.py python/branches/p3yk/Misc/ACKS python/branches/p3yk/Modules/collectionsmodule.c python/branches/p3yk/Modules/datetimemodule.c python/branches/p3yk/Modules/itertoolsmodule.c python/branches/p3yk/Modules/posixmodule.c python/branches/p3yk/Modules/socketmodule.c python/branches/p3yk/Modules/socketmodule.h python/branches/p3yk/Objects/abstract.c python/branches/p3yk/Objects/dictnotes.txt python/branches/p3yk/Objects/dictobject.c python/branches/p3yk/Objects/enumobject.c python/branches/p3yk/Objects/setobject.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Parser/asdl_c.py python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/configure python/branches/p3yk/configure.in python/branches/p3yk/pyconfig.h.in python/branches/p3yk/setup.py Log: Merged revisions 53623-53858 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53624 | peter.astrand | 2007-02-02 20:06:36 +0100 (Fri, 02 Feb 2007) | 1 line We had several if statements checking the value of a fd. This is unsafe, since valid fds might be zero. We should check for not None instead. ........ r53635 | kurt.kaiser | 2007-02-05 07:03:18 +0100 (Mon, 05 Feb 2007) | 2 lines Add 'raw' support to configHandler. Patch 1650174 Tal Einat. ........ r53641 | kurt.kaiser | 2007-02-06 00:02:16 +0100 (Tue, 06 Feb 2007) | 5 lines 1. Calltips now 'handle' tuples in the argument list (display '' :) Suggested solution by Christos Georgiou, Bug 791968. 2. Clean up tests, were not failing when they should have been. 4. Remove some camelcase and an unneeded try/except block. ........ r53644 | kurt.kaiser | 2007-02-06 04:21:40 +0100 (Tue, 06 Feb 2007) | 2 lines Clean up ModifiedInterpreter.runcode() structure ........ r53646 | peter.astrand | 2007-02-06 16:37:50 +0100 (Tue, 06 Feb 2007) | 1 line Applied patch 1124861.3.patch to solve bug #1124861: Automatically create pipes on Windows, if GetStdHandle fails. Will backport. ........ r53648 | lars.gustaebel | 2007-02-06 19:38:13 +0100 (Tue, 06 Feb 2007) | 4 lines Patch #1652681: create nonexistent files in append mode and allow appending to empty files. ........ r53649 | kurt.kaiser | 2007-02-06 20:09:43 +0100 (Tue, 06 Feb 2007) | 4 lines Updated patch (CodeContext.061217.patch) to [ 1362975 ] CodeContext - Improved text indentation Tal Einat 16Dec06 ........ r53650 | kurt.kaiser | 2007-02-06 20:21:19 +0100 (Tue, 06 Feb 2007) | 2 lines narrow exception per [ 1540849 ] except too broad ........ r53653 | kurt.kaiser | 2007-02-07 04:39:41 +0100 (Wed, 07 Feb 2007) | 4 lines [ 1621265 ] Auto-completion list placement Move AC window below input line unless not enough space, then put it above. Patch: Tal Einat ........ r53654 | kurt.kaiser | 2007-02-07 09:07:13 +0100 (Wed, 07 Feb 2007) | 2 lines Handle AttributeError during calltip lookup ........ r53656 | raymond.hettinger | 2007-02-07 21:08:22 +0100 (Wed, 07 Feb 2007) | 3 lines SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses ........ r53658 | raymond.hettinger | 2007-02-07 22:04:20 +0100 (Wed, 07 Feb 2007) | 1 line SF: 1397711 Set docs conflated immutable and hashable ........ r53660 | raymond.hettinger | 2007-02-07 22:42:17 +0100 (Wed, 07 Feb 2007) | 1 line Check for a common user error with defaultdict(). ........ r53662 | raymond.hettinger | 2007-02-07 23:24:07 +0100 (Wed, 07 Feb 2007) | 1 line Bug #1575169: operator.isSequenceType() now returns False for subclasses of dict. ........ r53664 | raymond.hettinger | 2007-02-08 00:49:03 +0100 (Thu, 08 Feb 2007) | 1 line Silence compiler warning ........ r53666 | raymond.hettinger | 2007-02-08 01:07:32 +0100 (Thu, 08 Feb 2007) | 1 line Do not let overflows in enumerate() and count() pass silently. ........ r53668 | raymond.hettinger | 2007-02-08 01:50:39 +0100 (Thu, 08 Feb 2007) | 1 line Bypass set specific optimizations for set and frozenset subclasses. ........ r53670 | raymond.hettinger | 2007-02-08 02:42:35 +0100 (Thu, 08 Feb 2007) | 1 line Fix docstring bug ........ r53671 | martin.v.loewis | 2007-02-08 10:13:36 +0100 (Thu, 08 Feb 2007) | 3 lines Bug #1653736: Complain about keyword arguments to time.isoformat. Will backport to 2.5. ........ r53679 | kurt.kaiser | 2007-02-08 23:58:18 +0100 (Thu, 08 Feb 2007) | 6 lines Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented; mouse and cursor selection in ACWindow implemented; double Tab inserts current selection and closes ACW (similar to double-click and Return); scroll wheel now works in ACW. Added AutoComplete instructions to IDLE Help. ........ r53689 | martin.v.loewis | 2007-02-09 13:19:32 +0100 (Fri, 09 Feb 2007) | 3 lines Bug #1653736: Properly discard third argument to slot_nb_inplace_power. Will backport. ........ r53691 | martin.v.loewis | 2007-02-09 13:36:48 +0100 (Fri, 09 Feb 2007) | 4 lines Bug #1600860: Search for shared python library in LIBDIR, not lib/python/config, on "linux" and "gnu" systems. Will backport. ........ r53693 | martin.v.loewis | 2007-02-09 13:58:49 +0100 (Fri, 09 Feb 2007) | 2 lines Update broken link. Will backport to 2.5. ........ r53697 | georg.brandl | 2007-02-09 19:48:41 +0100 (Fri, 09 Feb 2007) | 2 lines Bug #1656078: typo in in profile docs. ........ r53731 | brett.cannon | 2007-02-11 06:36:00 +0100 (Sun, 11 Feb 2007) | 3 lines Change a very minor inconsistency (that is purely cosmetic) in the AST definition. ........ r53735 | skip.montanaro | 2007-02-11 19:24:37 +0100 (Sun, 11 Feb 2007) | 1 line fix trace.py --ignore-dir ........ r53741 | brett.cannon | 2007-02-11 20:44:41 +0100 (Sun, 11 Feb 2007) | 3 lines Check in changed Python-ast.c from a cosmetic change to Python.asdl (in r53731). ........ r53751 | brett.cannon | 2007-02-12 04:51:02 +0100 (Mon, 12 Feb 2007) | 5 lines Modify Parser/asdl_c.py so that the __version__ number for Python/Python-ast.c is specified at the top of the file. Also add a note that Python/Python-ast.c needs to be committed separately after a change to the AST grammar to capture the revision number of the change (which is what __version__ is set to). ........ r53752 | lars.gustaebel | 2007-02-12 10:25:53 +0100 (Mon, 12 Feb 2007) | 3 lines Bug #1656581: Point out that external file objects are supposed to be at position 0. ........ r53754 | martin.v.loewis | 2007-02-12 13:21:10 +0100 (Mon, 12 Feb 2007) | 3 lines Patch 1463026: Support default namespace in XMLGenerator. Fixes #847665. Will backport. ........ r53757 | armin.rigo | 2007-02-12 17:23:24 +0100 (Mon, 12 Feb 2007) | 4 lines Fix the line to what is my guess at the original author's meaning. (The line has no effect anyway, but is present because it's customary call the base class __init__). ........ r53763 | martin.v.loewis | 2007-02-13 09:34:45 +0100 (Tue, 13 Feb 2007) | 3 lines Patch #685268: Consider a package's __path__ in imputil. Will backport. ........ r53765 | martin.v.loewis | 2007-02-13 10:49:38 +0100 (Tue, 13 Feb 2007) | 2 lines Patch #698833: Support file decryption in zipfile. ........ r53766 | martin.v.loewis | 2007-02-13 11:10:39 +0100 (Tue, 13 Feb 2007) | 3 lines Patch #1517891: Make 'a' create the file if it doesn't exist. Fixes #1514451. ........ r53767 | martin.v.loewis | 2007-02-13 13:08:24 +0100 (Tue, 13 Feb 2007) | 3 lines Bug #1658794: Remove extraneous 'this'. Will backport to 2.5. ........ r53769 | martin.v.loewis | 2007-02-13 13:14:19 +0100 (Tue, 13 Feb 2007) | 3 lines Patch #1657276: Make NETLINK_DNRTMSG conditional. Will backport. ........ r53771 | lars.gustaebel | 2007-02-13 17:09:24 +0100 (Tue, 13 Feb 2007) | 4 lines Patch #1647484: Renamed GzipFile's filename attribute to name. The filename attribute is still accessible as a property that emits a DeprecationWarning. ........ r53772 | lars.gustaebel | 2007-02-13 17:24:00 +0100 (Tue, 13 Feb 2007) | 3 lines Strip the '.gz' extension from the filename that is written to the gzip header. ........ r53774 | martin.v.loewis | 2007-02-14 11:07:37 +0100 (Wed, 14 Feb 2007) | 2 lines Patch #1432399: Add HCI sockets. ........ r53775 | martin.v.loewis | 2007-02-14 12:30:07 +0100 (Wed, 14 Feb 2007) | 2 lines Update 1432399 to removal of _BT_SOCKADDR_MEMB. ........ r53776 | martin.v.loewis | 2007-02-14 12:30:56 +0100 (Wed, 14 Feb 2007) | 3 lines Ignore directory time stamps when considering whether to rerun libffi configure. ........ r53778 | lars.gustaebel | 2007-02-14 15:45:12 +0100 (Wed, 14 Feb 2007) | 4 lines A missing binary mode in AppendTest caused failures in Windows Buildbot. ........ r53782 | martin.v.loewis | 2007-02-15 10:51:35 +0100 (Thu, 15 Feb 2007) | 2 lines Patch #1397848: add the reasoning behind no-resize-on-shrinkage. ........ r53783 | georg.brandl | 2007-02-15 11:37:59 +0100 (Thu, 15 Feb 2007) | 2 lines Make functools.wraps() docs a bit clearer. ........ r53785 | georg.brandl | 2007-02-15 12:29:04 +0100 (Thu, 15 Feb 2007) | 2 lines Patch #1494140: Add documentation for the new struct.Struct object. ........ r53787 | georg.brandl | 2007-02-15 12:29:55 +0100 (Thu, 15 Feb 2007) | 2 lines Add missing \versionadded. ........ r53800 | brett.cannon | 2007-02-15 23:54:39 +0100 (Thu, 15 Feb 2007) | 11 lines Update the encoding package's search function to use absolute imports when calling __import__. This helps make the expected search locations for encoding modules be more explicit. One could use an explicit value for __path__ when making the call to __import__ to force the exact location searched for encodings. This would give the most strict search path possible if one is worried about malicious code being imported. The unfortunate side-effect of that is that if __path__ was modified on 'encodings' on purpose in a safe way it would not be picked up in future __import__ calls. ........ r53801 | brett.cannon | 2007-02-16 20:33:01 +0100 (Fri, 16 Feb 2007) | 2 lines Make the __import__ call in encodings.__init__ absolute with a level 0 call. ........ r53809 | vinay.sajip | 2007-02-16 23:36:24 +0100 (Fri, 16 Feb 2007) | 1 line Minor fix for currentframe (SF #1652788). ........ r53818 | raymond.hettinger | 2007-02-19 03:03:19 +0100 (Mon, 19 Feb 2007) | 3 lines Extend work on revision 52962: Eliminate redundant calls to PyObject_Hash(). ........ r53820 | raymond.hettinger | 2007-02-19 05:08:43 +0100 (Mon, 19 Feb 2007) | 1 line Add merge() function to heapq. ........ r53821 | raymond.hettinger | 2007-02-19 06:28:28 +0100 (Mon, 19 Feb 2007) | 1 line Add tie-breaker count to preserve sort stability. ........ r53822 | raymond.hettinger | 2007-02-19 07:59:32 +0100 (Mon, 19 Feb 2007) | 1 line Use C heapreplace() instead of slower _siftup() in pure python. ........ r53823 | raymond.hettinger | 2007-02-19 08:30:21 +0100 (Mon, 19 Feb 2007) | 1 line Add test for merge stability ........ r53824 | raymond.hettinger | 2007-02-19 10:14:10 +0100 (Mon, 19 Feb 2007) | 1 line Provide an example of defaultdict with non-zero constant factory function. ........ r53825 | lars.gustaebel | 2007-02-19 10:54:47 +0100 (Mon, 19 Feb 2007) | 2 lines Moved misplaced news item. ........ r53826 | martin.v.loewis | 2007-02-19 11:55:19 +0100 (Mon, 19 Feb 2007) | 3 lines Patch #1490190: posixmodule now includes os.chflags() and os.lchflags() functions on platforms where the underlying system calls are available. ........ r53827 | raymond.hettinger | 2007-02-19 19:15:04 +0100 (Mon, 19 Feb 2007) | 1 line Fixup docstrings for merge(). ........ r53829 | raymond.hettinger | 2007-02-19 21:44:04 +0100 (Mon, 19 Feb 2007) | 1 line Fixup set/dict interoperability. ........ r53837 | raymond.hettinger | 2007-02-21 06:20:38 +0100 (Wed, 21 Feb 2007) | 1 line Add itertools.izip_longest(). ........ r53838 | raymond.hettinger | 2007-02-21 18:22:05 +0100 (Wed, 21 Feb 2007) | 1 line Remove filler struct item and fix leak. ........ Modified: python/branches/p3yk/Doc/lib/emailgenerator.tex ============================================================================== --- python/branches/p3yk/Doc/lib/emailgenerator.tex (original) +++ python/branches/p3yk/Doc/lib/emailgenerator.tex Fri Feb 23 16:07:44 2007 @@ -33,7 +33,7 @@ line. This is the only guaranteed portable way to avoid having such lines be mistaken for a \UNIX{} mailbox format envelope header separator (see \ulink{WHY THE CONTENT-LENGTH FORMAT IS BAD} -{http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html} +{http://www.jwz.org/doc/content-length.html} for details). \var{mangle_from_} defaults to \code{True}, but you might want to set this to \code{False} if you are not writing \UNIX{} mailbox format files. Modified: python/branches/p3yk/Doc/lib/libcollections.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libcollections.tex (original) +++ python/branches/p3yk/Doc/lib/libcollections.tex Fri Feb 23 16:07:44 2007 @@ -311,16 +311,20 @@ When a letter is first encountered, it is missing from the mapping, so the \member{default_factory} function calls \function{int()} to supply a default count of zero. The increment operation then builds up the count for each -letter. This technique makes counting simpler and faster than an equivalent -technique using \method{dict.get()}: +letter. -\begin{verbatim} ->>> d = {} ->>> for k in s: - d[k] = d.get(k, 0) + 1 +The function \function{int()} which always returns zero is just a special +case of constant functions. A faster and more flexible way to create +constant functions is to use \function{itertools.repeat()} which can supply +any constant value (not just zero): ->>> d.items() -[('i', 4), ('p', 2), ('s', 4), ('m', 1)] +\begin{verbatim} +>>> def constant_factory(value): +... return itertools.repeat(value).next +>>> d = defaultdict(constant_factory('')) +>>> d.update(name='John', action='ran') +>>> '%(name)s %(action)s to %(object)s' % d +'John ran to ' \end{verbatim} Setting the \member{default_factory} to \class{set} makes the Modified: python/branches/p3yk/Doc/lib/libfunctools.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libfunctools.tex (original) +++ python/branches/p3yk/Doc/lib/libfunctools.tex Fri Feb 23 16:07:44 2007 @@ -66,15 +66,16 @@ \begin{funcdesc}{update_wrapper} {wrapper, wrapped\optional{, assigned}\optional{, updated}} -Update a wrapper function to look like the wrapped function. The optional -arguments are tuples to specify which attributes of the original +Update a \var{wrapper} function to look like the \var{wrapped} function. +The optional arguments are tuples to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function and which attributes of the wrapper function are updated with the corresponding attributes from the original function. The default values for these arguments are the module level constants -\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's name, -module and documentation string) and \var{WRAPPER_UPDATES} (which -updates the wrapper function's instance dictionary). +\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's +\var{__name__}, \var{__module__} and \var{__doc__}, the documentation string) +and \var{WRAPPER_UPDATES} (which updates the wrapper function's \var{__dict__}, +i.e. the instance dictionary). The main intended use for this function is in decorator functions which wrap the decorated function and return the wrapper. If the @@ -98,6 +99,7 @@ ... >>> @my_decorator ... def example(): + ... """Docstring""" ... print 'Called example function' ... >>> example() @@ -105,9 +107,12 @@ Called example function >>> example.__name__ 'example' + >>> example.__doc__ + 'Docstring' \end{verbatim} Without the use of this decorator factory, the name of the example -function would have been \code{'wrapper'}. +function would have been \code{'wrapper'}, and the docstring of the +original \function{example()} would have been lost. \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/libheapq.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libheapq.tex (original) +++ python/branches/p3yk/Doc/lib/libheapq.tex Fri Feb 23 16:07:44 2007 @@ -88,7 +88,18 @@ >>> \end{verbatim} -The module also offers two general purpose functions based on heaps. +The module also offers three general purpose functions based on heaps. + +\begin{funcdesc}{merge}{*iterables} +Merge multiple sorted inputs into a single sorted output (for example, merge +timestamped entries from multiple log files). Returns an iterator over +over the sorted values. + +Similar to \code{sorted(itertools.chain(*iterables))} but returns an iterable, +does not pull the data into memory all at once, and assumes that each of the +input streams is already sorted (smallest to largest). +\versionadded{2.6} +\end{funcdesc} \begin{funcdesc}{nlargest}{n, iterable\optional{, key}} Return a list with the \var{n} largest elements from the dataset defined @@ -110,7 +121,7 @@ \versionchanged[Added the optional \var{key} argument]{2.5} \end{funcdesc} -Both functions perform best for smaller values of \var{n}. For larger +The latter two functions perform best for smaller values of \var{n}. For larger values, it is more efficient to use the \function{sorted()} function. Also, when \code{n==1}, it is more efficient to use the builtin \function{min()} and \function{max()} functions. Modified: python/branches/p3yk/Doc/lib/libitertools.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libitertools.tex (original) +++ python/branches/p3yk/Doc/lib/libitertools.tex Fri Feb 23 16:07:44 2007 @@ -302,6 +302,33 @@ don't care about trailing, unmatched values from the longer iterables. \end{funcdesc} +\begin{funcdesc}{izip_longest}{*iterables\optional{, fillvalue}} + Make an iterator that aggregates elements from each of the iterables. + If the iterables are of uneven length, missing values are filled-in + with \var{fillvalue}. Iteration continues until the longest iterable + is exhausted. Equivalent to: + + \begin{verbatim} + def izip_longest(*args, **kwds): + fillvalue = kwds.get('fillvalue') + def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): + yield counter() # yields the fillvalue, or raises IndexError + fillers = repeat(fillvalue) + iters = [chain(it, sentinel(), fillers) for it in args] + try: + for tup in izip(*iters): + yield tup + except IndexError: + pass + \end{verbatim} + + If one of the iterables is potentially infinite, then the + \function{izip_longest()} function should be wrapped with something + that limits the number of calls (for example \function{islice()} or + \function{take()}). + \versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{repeat}{object\optional{, times}} Make an iterator that returns \var{object} over and over again. Runs indefinitely unless the \var{times} argument is specified. Modified: python/branches/p3yk/Doc/lib/liblocale.tex ============================================================================== --- python/branches/p3yk/Doc/lib/liblocale.tex (original) +++ python/branches/p3yk/Doc/lib/liblocale.tex Fri Feb 23 16:07:44 2007 @@ -481,7 +481,7 @@ locale settings. When a call to the \function{setlocale()} function changes the \constant{LC_CTYPE} settings, the variables \code{string.lowercase}, \code{string.uppercase} and -\code{string.letters} are recalculated. Note that this code that uses +\code{string.letters} are recalculated. Note that code that uses these variable through `\keyword{from} ... \keyword{import} ...', e.g.\ \code{from string import letters}, is not affected by subsequent \function{setlocale()} calls. Modified: python/branches/p3yk/Doc/lib/libos.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libos.tex (original) +++ python/branches/p3yk/Doc/lib/libos.tex Fri Feb 23 16:07:44 2007 @@ -758,6 +758,26 @@ \versionadded{2.3} \end{funcdesc} +\begin{funcdesc}{chflags}{path, flags} +Set the flags of \var{path} to the numeric \var{flags}. +\var{flags} may take a combination (bitwise OR) of the following values +(as defined in the \module{stat} module): +\begin{itemize} + \item \code{UF_NODUMP} + \item \code{UF_IMMUTABLE} + \item \code{UF_APPEND} + \item \code{UF_OPAQUE} + \item \code{UF_NOUNLINK} + \item \code{SF_ARCHIVED} + \item \code{SF_IMMUTABLE} + \item \code{SF_APPEND} + \item \code{SF_NOUNLINK} + \item \code{SF_SNAPSHOT} +\end{itemize} +Availability: Macintosh, \UNIX. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{chroot}{path} Change the root directory of the current process to \var{path}. Availability: Macintosh, \UNIX. @@ -804,6 +824,13 @@ Availability: Macintosh, \UNIX. \end{funcdesc} +\begin{funcdesc}{lchflags}{path, flags} +Set the flags of \var{path} to the numeric \var{flags}, like +\function{chflags()}, but do not follow symbolic links. +Availability: \UNIX. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{lchown}{path, uid, gid} Change the owner and group id of \var{path} to the numeric \var{uid} and gid. This function will not follow symbolic links. Modified: python/branches/p3yk/Doc/lib/libshutil.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libshutil.tex (original) +++ python/branches/p3yk/Doc/lib/libshutil.tex Fri Feb 23 16:07:44 2007 @@ -44,8 +44,8 @@ \end{funcdesc} \begin{funcdesc}{copystat}{src, dst} - Copy the permission bits, last access time, and last modification - time from \var{src} to \var{dst}. The file contents, owner, and + Copy the permission bits, last access time, last modification time, + and flags from \var{src} to \var{dst}. The file contents, owner, and group are unaffected. \var{src} and \var{dst} are path names given as strings. \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk/Doc/lib/libstdtypes.tex Fri Feb 23 16:07:44 2007 @@ -1212,7 +1212,7 @@ \label{types-set}} \obindex{set} -A \dfn{set} object is an unordered collection of immutable values. +A \dfn{set} object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. Modified: python/branches/p3yk/Doc/lib/libstruct.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstruct.tex (original) +++ python/branches/p3yk/Doc/lib/libstruct.tex Fri Feb 23 16:07:44 2007 @@ -29,6 +29,15 @@ exactly. \end{funcdesc} +\begin{funcdesc}{pack_into}{fmt, buffer, offset, v1, v2, \moreargs} + Pack the values \code{\var{v1}, \var{v2}, \textrm{\ldots}} according to the given + format, write the packed bytes into the writable \var{buffer} starting at + \var{offset}. + Note that the offset is not an optional argument. + + \versionadded{2.5} +\end{funcdesc} + \begin{funcdesc}{unpack}{fmt, string} Unpack the string (presumably packed by \code{pack(\var{fmt}, \textrm{\ldots})}) according to the given format. The result is a @@ -37,6 +46,16 @@ (\code{len(\var{string})} must equal \code{calcsize(\var{fmt})}). \end{funcdesc} +\begin{funcdesc}{unpack_from}{fmt, buffer\optional{,offset \code{= 0}}} + Unpack the \var{buffer} according to tthe given format. + The result is a tuple even if it contains exactly one item. The + \var{buffer} must contain at least the amount of data required by the + format (\code{len(buffer[offset:])} must be at least + \code{calcsize(\var{fmt})}). + + \versionadded{2.5} +\end{funcdesc} + \begin{funcdesc}{calcsize}{fmt} Return the size of the struct (and hence of the string) corresponding to the given format. @@ -208,3 +227,43 @@ \seemodule{array}{Packed binary storage of homogeneous data.} \seemodule{xdrlib}{Packing and unpacking of XDR data.} \end{seealso} + +\subsection{Struct Objects \label{struct-objects}} + +The \module{struct} module also defines the following type: + +\begin{classdesc}{Struct}{format} + Return a new Struct object which writes and reads binary data according to + the format string \var{format}. Creating a Struct object once and calling + its methods is more efficient than calling the \module{struct} functions + with the same format since the format string only needs to be compiled once. + + \versionadded{2.5} +\end{classdesc} + +Compiled Struct objects support the following methods and attributes: + +\begin{methoddesc}[Struct]{pack}{v1, v2, \moreargs} + Identical to the \function{pack()} function, using the compiled format. + (\code{len(result)} will equal \member{self.size}.) +\end{methoddesc} + +\begin{methoddesc}[Struct]{pack_into}{buffer, offset, v1, v2, \moreargs} + Identical to the \function{pack_into()} function, using the compiled format. +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack}{string} + Identical to the \function{unpack()} function, using the compiled format. + (\code{len(string)} must equal \member{self.size}). +\end{methoddesc} + +\begin{methoddesc}[Struct]{unpack_from}{buffer\optional{,offset + \code{= 0}}} + Identical to the \function{unpack_from()} function, using the compiled format. + (\code{len(buffer[offset:])} must be at least \member{self.size}). +\end{methoddesc} + +\begin{memberdesc}[Struct]{format} + The format string used to construct this Struct object. +\end{memberdesc} + Modified: python/branches/p3yk/Doc/lib/libtarfile.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtarfile.tex (original) +++ python/branches/p3yk/Doc/lib/libtarfile.tex Fri Feb 23 16:07:44 2007 @@ -36,7 +36,8 @@ \lineii{'r:'}{Open for reading exclusively without compression.} \lineii{'r:gz'}{Open for reading with gzip compression.} \lineii{'r:bz2'}{Open for reading with bzip2 compression.} - \lineii{'a' or 'a:'}{Open for appending with no compression.} + \lineii{'a' or 'a:'}{Open for appending with no compression. The file + is created if it does not exist.} \lineii{'w' or 'w:'}{Open for uncompressed writing.} \lineii{'w:gz'}{Open for gzip compressed writing.} \lineii{'w:bz2'}{Open for bzip2 compressed writing.} @@ -48,8 +49,8 @@ avoid this. If a compression method is not supported, \exception{CompressionError} is raised. - If \var{fileobj} is specified, it is used as an alternative to - a file object opened for \var{name}. + If \var{fileobj} is specified, it is used as an alternative to a file + object opened for \var{name}. It is supposed to be at position 0. For special purposes, there is a second format for \var{mode}: \code{'filemode|[compression]'}. \function{open()} will return a @@ -160,6 +161,7 @@ If \var{fileobj} is given, it is used for reading or writing data. If it can be determined, \var{mode} is overridden by \var{fileobj}'s mode. + \var{fileobj} will be used from position 0. \begin{notice} \var{fileobj} is not closed, when \class{TarFile} is closed. \end{notice} Modified: python/branches/p3yk/Doc/lib/libzipfile.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libzipfile.tex (original) +++ python/branches/p3yk/Doc/lib/libzipfile.tex Fri Feb 23 16:07:44 2007 @@ -17,8 +17,10 @@ {PKZIP Application Note}. This module does not currently handle ZIP files which have appended -comments, or multi-disk ZIP files. It can handle ZIP files that use the -ZIP64 extensions (that is ZIP files that are more than 4 GByte in size). +comments, or multi-disk ZIP files. It can handle ZIP files that use +the ZIP64 extensions (that is ZIP files that are more than 4 GByte in +size). It supports decryption of encrypted files in ZIP archives, but +it cannot currently create an encrypted file. The available attributes of this module are: @@ -99,6 +101,8 @@ \end{verbatim} also works, and at least \program{WinZip} can read such files. + If \var{mode} is \code{a} and the file does not exist at all, + it is created. \var{compression} is the ZIP compression method to use when writing the archive, and should be \constant{ZIP_STORED} or \constant{ZIP_DEFLATED}; unrecognized values will cause @@ -112,6 +116,9 @@ ZIP file would require ZIP64 extensions. ZIP64 extensions are disabled by default because the default \program{zip} and \program{unzip} commands on \UNIX{} (the InfoZIP utilities) don't support these extensions. + + \versionchanged[If the file does not exist, it is created if the + mode is 'a']{2.6} \end{classdesc} \begin{methoddesc}{close}{} @@ -138,9 +145,18 @@ Print a table of contents for the archive to \code{sys.stdout}. \end{methoddesc} -\begin{methoddesc}{read}{name} +\begin{methoddesc}{setpassword}{pwd} + Set \var{pwd} as default password to extract encrypted files. + \versionadded{2.6} +\end{methoddesc} + +\begin{methoddesc}{read}{name\optional{, pwd}} Return the bytes of the file in the archive. The archive must be - open for read or append. + open for read or append. \var{pwd} is the password used for encrypted + files and, if specified, it will override the default password set with + \method{setpassword()}. + + \versionchanged[\var{pwd} was added]{2.6} \end{methoddesc} \begin{methoddesc}{testzip}{} Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Fri Feb 23 16:07:44 2007 @@ -1,4 +1,4 @@ -/* File automatically generated by Parser/asdl_c.py */ +/* File automatically generated by Parser/asdl_c.py. */ #include "asdl.h" Modified: python/branches/p3yk/Include/dictobject.h ============================================================================== --- python/branches/p3yk/Include/dictobject.h (original) +++ python/branches/p3yk/Include/dictobject.h Fri Feb 23 16:07:44 2007 @@ -100,12 +100,15 @@ PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); PyAPI_FUNC(int) PyDict_Next( PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); +PyAPI_FUNC(int) _PyDict_Next( + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp); PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp); PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key); +PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, long hash); /* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */ PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other); Modified: python/branches/p3yk/Lib/decimal.py ============================================================================== --- python/branches/p3yk/Lib/decimal.py (original) +++ python/branches/p3yk/Lib/decimal.py Fri Feb 23 16:07:44 2007 @@ -487,7 +487,7 @@ 28 >>> with localcontext(): ... ctx = getcontext() - ... ctx.prec() += 2 + ... ctx.prec += 2 ... print(ctx.prec) ... 30 Modified: python/branches/p3yk/Lib/distutils/command/build_ext.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/build_ext.py (original) +++ python/branches/p3yk/Lib/distutils/command/build_ext.py Fri Feb 23 16:07:44 2007 @@ -185,9 +185,7 @@ # for extensions under Cygwin and AtheOS Python's library directory must be # appended to library_dirs - if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos' or \ - ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')) and - sysconfig.get_config_var('Py_ENABLE_SHARED')): + if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos': if string.find(sys.executable, sys.exec_prefix) != -1: # building third party extensions self.library_dirs.append(os.path.join(sys.prefix, "lib", @@ -197,6 +195,17 @@ # building python standard extensions self.library_dirs.append('.') + # for extensions under Linux with a shared Python library, + # Python's library directory must be appended to library_dirs + if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \ + and sysconfig.get_config_var('Py_ENABLE_SHARED'): + if string.find(sys.executable, sys.exec_prefix) != -1: + # building third party extensions + self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) + else: + # building python standard extensions + self.library_dirs.append('.') + # The argument parsing will result in self.define being a string, but # it has to be a list of 2-tuples. All the preprocessor symbols # specified by the 'define' option will be set to '1'. Multiple Modified: python/branches/p3yk/Lib/encodings/__init__.py ============================================================================== --- python/branches/p3yk/Lib/encodings/__init__.py (original) +++ python/branches/p3yk/Lib/encodings/__init__.py Fri Feb 23 16:07:44 2007 @@ -93,8 +93,10 @@ if not modname or '.' in modname: continue try: - mod = __import__('encodings.' + modname, - globals(), locals(), _import_tail) + # Import is absolute to prevent the possibly malicious import of a + # module with side-effects that is not in the 'encodings' package. + mod = __import__('encodings.' + modname, fromlist=_import_tail, + level=0) except ImportError: pass else: Modified: python/branches/p3yk/Lib/gzip.py ============================================================================== --- python/branches/p3yk/Lib/gzip.py (original) +++ python/branches/p3yk/Lib/gzip.py Fri Feb 23 16:07:44 2007 @@ -106,7 +106,7 @@ self._new_member = True self.extrabuf = "" self.extrasize = 0 - self.filename = filename + self.name = filename # Starts small, scales exponentially self.min_readsize = 100 @@ -127,14 +127,20 @@ if self.mode == WRITE: self._write_gzip_header() + @property + def filename(self): + import warnings + warnings.warn("use the name attribute", DeprecationWarning) + if self.mode == WRITE and self.name[-3:] != ".gz": + return self.name + ".gz" + return self.name + def __repr__(self): s = repr(self.fileobj) return '' def _init_write(self, filename): - if filename[-3:] != '.gz': - filename = filename + '.gz' - self.filename = filename + self.name = filename self.crc = zlib.crc32("") self.size = 0 self.writebuf = [] @@ -143,7 +149,9 @@ def _write_gzip_header(self): self.fileobj.write('\037\213') # magic header self.fileobj.write('\010') # compression method - fname = self.filename[:-3] + fname = self.name + if fname.endswith(".gz"): + fname = fname[:-3] flags = 0 if fname: flags = FNAME Modified: python/branches/p3yk/Lib/heapq.py ============================================================================== --- python/branches/p3yk/Lib/heapq.py (original) +++ python/branches/p3yk/Lib/heapq.py Fri Feb 23 16:07:44 2007 @@ -126,8 +126,8 @@ From all times, sorting has always been a Great Art! :-) """ -__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'nlargest', - 'nsmallest'] +__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', + 'nlargest', 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee from operator import itemgetter, neg @@ -308,6 +308,41 @@ except ImportError: pass +def merge(*iterables): + '''Merge multiple sorted inputs into a single sorted output. + + Similar to sorted(itertools.chain(*iterables)) but returns an iterable, + does not pull the data into memory all at once, and assumes that each of + the input streams is already sorted (smallest to largest). + + >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) + [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] + + ''' + _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration + + h = [] + h_append = h.append + for itnum, it in enumerate(map(iter, iterables)): + try: + next = it.next + h_append([next(), itnum, next]) + except _StopIteration: + pass + heapify(h) + + while 1: + try: + while 1: + v, itnum, next = s = h[0] # raises IndexError when h is empty + yield v + s[0] = next() # raises StopIteration when exhausted + _heapreplace(h, s) # restore heap condition + except _StopIteration: + _heappop(h) # remove empty iterator + except IndexError: + return + # Extend the implementations of nsmallest and nlargest to use a key= argument _nsmallest = nsmallest def nsmallest(n, iterable, key=None): @@ -341,3 +376,6 @@ while heap: sort.append(heappop(heap)) print(sort) + + import doctest + doctest.testmod() Modified: python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py Fri Feb 23 16:07:44 2007 @@ -10,13 +10,14 @@ KEYPRESS_VIRTUAL_EVENT_NAME = "<>" # We need to bind event beyond so that the function will be called # before the default specific IDLE function -KEYPRESS_SEQUENCES = ("", "", "", - "", "", "", "") +KEYPRESS_SEQUENCES = ("", "", "", "", + "", "", "", "", + "", "") KEYRELEASE_VIRTUAL_EVENT_NAME = "<>" KEYRELEASE_SEQUENCE = "" -LISTUPDATE_SEQUENCE = "" +LISTUPDATE_SEQUENCE = "" WINCONFIG_SEQUENCE = "" -DOUBLECLICK_SEQUENCE = "" +DOUBLECLICK_SEQUENCE = "" class AutoCompleteWindow: @@ -49,6 +50,8 @@ # event ids self.hideid = self.keypressid = self.listupdateid = self.winconfigid \ = self.keyreleaseid = self.doubleclickid = None + # Flag set if last keypress was a tab + self.lastkey_was_tab = False def _change_start(self, newstart): i = 0 @@ -118,11 +121,6 @@ i = 0 while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]: i += 1 - previous_completion = self.completions[cursel - 1] - while cursel > 0 and selstart[:i] <= previous_completion: - i += 1 - if selstart == previous_completion: - break # maybe we have a duplicate? newstart = selstart[:i] self._change_start(newstart) @@ -206,7 +204,7 @@ self.keyrelease_event) self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE) self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, - self.listupdate_event) + self.listselect_event) self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event) self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, self.doubleclick_event) @@ -215,24 +213,34 @@ if not self.is_active(): return # Position the completion list window + text = self.widget + text.see(self.startindex) + x, y, cx, cy = text.bbox(self.startindex) acw = self.autocompletewindow - self.widget.see(self.startindex) - x, y, cx, cy = self.widget.bbox(self.startindex) - acw.wm_geometry("+%d+%d" % (x + self.widget.winfo_rootx(), - y + self.widget.winfo_rooty() \ - -acw.winfo_height())) - + acw_width, acw_height = acw.winfo_width(), acw.winfo_height() + text_width, text_height = text.winfo_width(), text.winfo_height() + new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width)) + new_y = text.winfo_rooty() + y + if (text_height - (y + cy) >= acw_height # enough height below + or y < acw_height): # not enough height above + # place acw below current line + new_y += cy + else: + # place acw above current line + new_y -= acw_height + acw.wm_geometry("+%d+%d" % (new_x, new_y)) def hide_event(self, event): if not self.is_active(): return self.hide_window() - def listupdate_event(self, event): + def listselect_event(self, event): if not self.is_active(): return self.userwantswindow = True - self._selection_changed() + cursel = int(self.listbox.curselection()[0]) + self._change_start(self.completions[cursel]) def doubleclick_event(self, event): # Put the selected completion in the text, and close the list @@ -248,7 +256,8 @@ state = event.mc_state else: state = 0 - + if keysym != "Tab": + self.lastkey_was_tab = False if (len(keysym) == 1 or keysym in ("underscore", "BackSpace") or (self.mode==AutoComplete.COMPLETE_FILES and keysym in ("period", "minus"))) \ @@ -330,13 +339,21 @@ self.listbox.select_clear(cursel) self.listbox.select_set(newsel) self._selection_changed() + self._change_start(self.completions[newsel]) return "break" elif (keysym == "Tab" and not state): - # The user wants a completion, but it is handled by AutoComplete - # (not AutoCompleteWindow), so ignore. - self.userwantswindow = True - return + if self.lastkey_was_tab: + # two tabs in a row; insert current selection and close acw + cursel = int(self.listbox.curselection()[0]) + self._change_start(self.completions[cursel]) + self.hide_window() + return "break" + else: + # first tab; let AutoComplete handle the completion + self.userwantswindow = True + self.lastkey_was_tab = True + return elif any(s in keysym for s in ("Shift", "Control", "Alt", "Meta", "Command", "Option")): Modified: python/branches/p3yk/Lib/idlelib/CallTips.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/CallTips.py (original) +++ python/branches/p3yk/Lib/idlelib/CallTips.py Fri Feb 23 16:07:44 2007 @@ -3,7 +3,9 @@ Call Tips are floating windows which display function, class, and method parameter and docstring information when you type an opening parenthesis, and which disappear when you type a closing parenthesis. + """ +import re import sys import types @@ -89,6 +91,8 @@ two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. + To find methods, fetch_tip must be fed a fully qualified name. + """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt @@ -108,7 +112,7 @@ namespace.update(__main__.__dict__) try: return eval(name, namespace) - except: + except (NameError, AttributeError): return None def _find_constructor(class_ob): @@ -124,39 +128,37 @@ def get_arg_text(ob): """Get a string describing the arguments for the given object""" - argText = "" + arg_text = "" if ob is not None: - argOffset = 0 + arg_offset = 0 if type(ob) in (types.ClassType, types.TypeType): # Look for the highest __init__ in the class chain. fob = _find_constructor(ob) if fob is None: fob = lambda: None else: - argOffset = 1 + arg_offset = 1 elif type(ob)==types.MethodType: # bit of a hack for methods - turn it into a function # but we drop the "self" param. fob = ob.im_func - argOffset = 1 + arg_offset = 1 else: fob = ob - # Try and build one for Python defined functions + # Try to build one for Python defined functions if type(fob) in [types.FunctionType, types.LambdaType]: - try: - realArgs = fob.func_code.co_varnames[argOffset:fob.func_code.co_argcount] - defaults = fob.func_defaults or [] - defaults = list(map(lambda name: "=%s" % repr(name), defaults)) - defaults = [""] * (len(realArgs)-len(defaults)) + defaults - items = map(lambda arg, dflt: arg+dflt, realArgs, defaults) - if fob.func_code.co_flags & 0x4: - items.append("...") - if fob.func_code.co_flags & 0x8: - items.append("***") - argText = ", ".join(items) - argText = "(%s)" % argText - except: - pass + argcount = fob.func_code.co_argcount + real_args = fob.func_code.co_varnames[arg_offset:argcount] + defaults = fob.func_defaults or [] + defaults = list(map(lambda name: "=%s" % repr(name), defaults)) + defaults = [""] * (len(real_args) - len(defaults)) + defaults + items = map(lambda arg, dflt: arg + dflt, real_args, defaults) + if fob.func_code.co_flags & 0x4: + items.append("...") + if fob.func_code.co_flags & 0x8: + items.append("***") + arg_text = ", ".join(items) + arg_text = "(%s)" % re.sub("\.\d+", "", arg_text) # See if we can use the docstring doc = getattr(ob, "__doc__", "") if doc: @@ -164,10 +166,10 @@ pos = doc.find("\n") if pos < 0 or pos > 70: pos = 70 - if argText: - argText += "\n" - argText += doc[:pos] - return argText + if arg_text: + arg_text += "\n" + arg_text += doc[:pos] + return arg_text ################################################# # @@ -181,16 +183,18 @@ def t4(*args): "(...)" def t5(a, *args): "(a, ...)" def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)" + def t7((a, b), c, (d, e)): "(, c, )" - class TC: - "(a=None, ...)" - def __init__(self, a=None, *b): "(a=None, ...)" + class TC(object): + "(ai=None, ...)" + def __init__(self, ai=None, *b): "(ai=None, ...)" def t1(self): "()" - def t2(self, a, b=None): "(a, b=None)" - def t3(self, a, *args): "(a, ...)" + def t2(self, ai, b=None): "(ai, b=None)" + def t3(self, ai, *args): "(ai, ...)" def t4(self, *args): "(...)" - def t5(self, a, *args): "(a, ...)" - def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)" + def t5(self, ai, *args): "(ai, ...)" + def t6(self, ai, b=None, *args, **kw): "(ai, b=None, ..., ***)" + def t7(self, (ai, b), c, (d, e)): "(, c, )" def test(tests): ct = CallTips() @@ -198,15 +202,20 @@ for t in tests: expected = t.__doc__ + "\n" + t.__doc__ name = t.__name__ - arg_text = ct.fetch_tip(name) + # exercise fetch_tip(), not just get_arg_text() + try: + qualified_name = "%s.%s" % (t.im_class.__name__, name) + except AttributeError: + qualified_name = name + arg_text = ct.fetch_tip(qualified_name) if arg_text != expected: failed.append(t) - print("%s - expected %s, but got %s" % (t, expected, - get_arg_text(entity))) + fmt = "%s - expected %s, but got %s" + print(fmt % (t.__name__, expected, get_arg_text(t))) print("%d of %d tests failed" % (len(failed), len(tests))) tc = TC() - tests = (t1, t2, t3, t4, t5, t6, - TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6) + tests = (t1, t2, t3, t4, t5, t6, t7, + TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6, tc.t7) test(tests) Modified: python/branches/p3yk/Lib/idlelib/CodeContext.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/CodeContext.py (original) +++ python/branches/p3yk/Lib/idlelib/CodeContext.py Fri Feb 23 16:07:44 2007 @@ -10,6 +10,7 @@ """ import Tkinter +from Tkconstants import TOP, LEFT, X, W, SUNKEN from configHandler import idleConf import re from sys import maxint as INFINITY @@ -24,7 +25,6 @@ class CodeContext: menudefs = [('options', [('!Code Conte_xt', '<>')])] - context_depth = idleConf.GetOption("extensions", "CodeContext", "numlines", type="int", default=3) bgcolor = idleConf.GetOption("extensions", "CodeContext", @@ -54,66 +54,33 @@ def toggle_code_context_event(self, event=None): if not self.label: - # The following code attempts to figure out the required border - # width and vertical padding required for the CodeContext widget - # to be perfectly aligned with the text in the main Text widget. - # This is done by retrieving the appropriate attributes from the - # editwin.text and editwin.text_frame widgets. + # Calculate the border width and horizontal padding required to + # align the context with the text in the main Text widget. # # All values are passed through int(str()), since some - # values may be pixel objects, which can't simply be added added - # to ints. - # - # This code is considered somewhat unstable since it relies on - # some of Tk's inner workings. However its effect is merely - # cosmetic; failure will only cause the CodeContext text to be - # somewhat misaligned with the text in the main Text widget. - # - # To avoid possible errors, all references to the inner workings - # of Tk are executed inside try/except blocks. - - widgets_for_width_calc = self.editwin.text, self.editwin.text_frame - - # calculate the required vertical padding + # values may be pixel objects, which can't simply be added to ints. + widgets = self.editwin.text, self.editwin.text_frame + # Calculate the required vertical padding padx = 0 - for widget in widgets_for_width_calc: - try: - # retrieve the "padx" attribte from widget's pack info - padx += int(str( widget.pack_info()['padx'] )) - except: - pass - try: - # retrieve the widget's "padx" attribte - padx += int(str( widget.cget('padx') )) - except: - pass - - # calculate the required border width - border_width = 0 - for widget in widgets_for_width_calc: - try: - # retrieve the widget's "border" attribte - border_width += int(str( widget.cget('border') )) - except: - pass - + for widget in widgets: + padx += int(str( widget.pack_info()['padx'] )) + padx += int(str( widget.cget('padx') )) + # Calculate the required border width + border = 0 + for widget in widgets: + border += int(str( widget.cget('border') )) self.label = Tkinter.Label(self.editwin.top, text="\n" * (self.context_depth - 1), - anchor="w", justify="left", + anchor=W, justify=LEFT, font=self.textfont, bg=self.bgcolor, fg=self.fgcolor, width=1, #don't request more than we get - padx=padx, #line up with text widget - border=border_width, #match border width - relief="sunken", - ) - - # CodeContext's label widget is packed before and above the - # text_frame widget, thus ensuring that it will appear directly - # above it. - self.label.pack(side="top", fill="x", expand=False, + padx=padx, border=border, + relief=SUNKEN) + # Pack the label widget before and above the text_frame widget, + # thus ensuring that it will appear directly above text_frame + self.label.pack(side=TOP, fill=X, expand=False, before=self.editwin.text_frame) - else: self.label.destroy() self.label = None @@ -190,7 +157,6 @@ stopindent) self.info.extend(lines) self.topvisible = new_topvisible - # empty lines in context pane: context_strings = [""] * max(0, self.context_depth - len(self.info)) # followed by the context hint lines: Modified: python/branches/p3yk/Lib/idlelib/IOBinding.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/IOBinding.py (original) +++ python/branches/p3yk/Lib/idlelib/IOBinding.py Fri Feb 23 16:07:44 2007 @@ -209,7 +209,7 @@ # gets set to "not modified" at every new prompt. try: interp = self.editwin.interp - except: + except AttributeError: interp = None if not self.filename and self.get_saved() and not interp: self.editwin.flist.open(filename, self.loadfile) Modified: python/branches/p3yk/Lib/idlelib/NEWS.txt ============================================================================== --- python/branches/p3yk/Lib/idlelib/NEWS.txt (original) +++ python/branches/p3yk/Lib/idlelib/NEWS.txt Fri Feb 23 16:07:44 2007 @@ -3,6 +3,19 @@ *Release date: XX-XXX-200X* +- Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented; + mouse and cursor selection in ACWindow implemented; double Tab inserts + current selection and closes ACW (similar to double-click and Return); scroll + wheel now works in ACW. Added AutoComplete instructions to IDLE Help. + +- AutoCompleteWindow moved below input line, will move above if there + isn't enough space. Patch 1621265 Tal Einat + +- Calltips now 'handle' tuples in the argument list (display '' :) + Suggested solution by Christos Georgiou, Bug 791968. + +- Add 'raw' support to configHandler. Patch 1650174 Tal Einat. + - Avoid hang when encountering a duplicate in a completion list. Bug 1571112. - Patch #1362975: Rework CodeContext indentation algorithm to Modified: python/branches/p3yk/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/PyShell.py (original) +++ python/branches/p3yk/Lib/idlelib/PyShell.py Fri Feb 23 16:07:44 2007 @@ -706,34 +706,36 @@ debugger = self.debugger try: self.tkconsole.beginexecuting() - try: - if not debugger and self.rpcclt is not None: - self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", - (code,), {}) - elif debugger: - debugger.run(code, self.locals) - else: - exec(code, self.locals) - except SystemExit: - if not self.tkconsole.closing: - if tkMessageBox.askyesno( - "Exit?", - "Do you want to exit altogether?", - default="yes", - master=self.tkconsole.text): - raise - else: - self.showtraceback() - else: + if not debugger and self.rpcclt is not None: + self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", + (code,), {}) + elif debugger: + debugger.run(code, self.locals) + else: + exec(code, self.locals) + except SystemExit: + if not self.tkconsole.closing: + if tkMessageBox.askyesno( + "Exit?", + "Do you want to exit altogether?", + default="yes", + master=self.tkconsole.text): raise - except: - if use_subprocess: - # When run w/o subprocess, both user and IDLE errors - # are printed here; skip message in that case. - print("IDLE internal error in runcode()", file=self.tkconsole.stderr) + else: + else: + raise + except: + if use_subprocess: + print("IDLE internal error in runcode()", + file=self.tkconsole.stderr) self.showtraceback() - if use_subprocess: - self.tkconsole.endexecuting() + self.tkconsole.endexecuting() + else: + if self.tkconsole.canceled: + self.tkconsole.canceled = False + print("KeyboardInterrupt", file=self.tkconsole.stderr) + else: + self.showtraceback() finally: if not use_subprocess: try: Modified: python/branches/p3yk/Lib/idlelib/configHandler.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/configHandler.py (original) +++ python/branches/p3yk/Lib/idlelib/configHandler.py Fri Feb 23 16:07:44 2007 @@ -39,22 +39,19 @@ self.file=cfgFile ConfigParser.__init__(self,defaults=cfgDefaults) - def Get(self, section, option, type=None, default=None): + def Get(self, section, option, type=None, default=None, raw=False): """ Get an option value for given section/option or return default. If type is specified, return as type. """ + if not self.has_option(section, option): + return default if type=='bool': - getVal=self.getboolean + return self.getboolean(section, option) elif type=='int': - getVal=self.getint - else: - getVal=self.get - if self.has_option(section,option): - #return getVal(section, option, raw, vars, default) - return getVal(section, option) + return self.getint(section, option) else: - return default + return self.get(section, option, raw=raw) def GetOptionList(self,section): """ @@ -219,7 +216,7 @@ return userDir def GetOption(self, configType, section, option, default=None, type=None, - warn_on_default=True): + warn_on_default=True, raw=False): """ Get an option value for given config type and given general configuration section/option or return a default. If type is specified, @@ -233,9 +230,11 @@ """ if self.userCfg[configType].has_option(section,option): - return self.userCfg[configType].Get(section, option, type=type) + return self.userCfg[configType].Get(section, option, + type=type, raw=raw) elif self.defaultCfg[configType].has_option(section,option): - return self.defaultCfg[configType].Get(section, option, type=type) + return self.defaultCfg[configType].Get(section, option, + type=type, raw=raw) else: #returning default, print warning if warn_on_default: warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n' Modified: python/branches/p3yk/Lib/idlelib/help.txt ============================================================================== --- python/branches/p3yk/Lib/idlelib/help.txt (original) +++ python/branches/p3yk/Lib/idlelib/help.txt Fri Feb 23 16:07:44 2007 @@ -44,6 +44,10 @@ Find in Files... -- Open a search dialog box for searching files Replace... -- Open a search-and-replace dialog box Go to Line -- Ask for a line number and show that line + Show Calltip -- Open a small window with function param hints + Show Completions -- Open a scroll window allowing selection keywords + and attributes. (see '*TIPS*', below) + Show Parens -- Highlight the surrounding parenthesis Expand Word -- Expand the word you have typed to match another word in the same buffer; repeat to get a different expansion @@ -91,6 +95,7 @@ Code Context -- Open a pane at the top of the edit window which shows the block context of the section of code which is scrolling off the top or the window. + (Not present in Shell window.) Windows Menu: @@ -138,8 +143,11 @@ Control-left/right Arrow moves by words in a strange but useful way. Home/End go to begin/end of line. Control-Home/End go to begin/end of file. - Some useful Emacs bindings (Control-a, Control-e, Control-k, etc.) - are inherited from Tcl/Tk. + Some useful Emacs bindings are inherited from Tcl/Tk: + Control-a beginning of line + Control-e end of line + Control-k kill line (but doesn't put it in clipboard) + Control-l center window around the insertion point Standard Windows bindings may work on that platform. Keybindings are selected in the Settings Dialog, look there. @@ -155,6 +163,52 @@ See also the indent/dedent region commands in the edit menu. +Completions: + + Completions are supplied for functions, classes, and attributes of + classes, both built-in and user-defined. Completions are also provided + for filenames. + + The AutoCompleteWindow (ACW) will open after a predefined delay + (default is two seconds) after a '.' or (in a string) an os.sep is + typed. If after one of those characters (plus zero or more other + characters) you type a Tab the ACW will open immediately if a possible + continuation is found. + + If there is only one possible completion for the characters entered, a + Tab will supply that completion without opening the ACW. + + 'Show Completions' will force open a completions window. In an empty + string, this will contain the files in the current directory. On a + blank line, it will contain the built-in and user-defined functions and + classes in the current name spaces, plus any modules imported. If some + characters have been entered, the ACW will attempt to be more specific. + + If string of characters is typed, the ACW selection will jump to the + entry most closely matching those characters. Entering a Tab will cause + the longest non-ambiguous match to be entered in the Edit window or + Shell. Two Tabs in a row will supply the current ACW selection, as + will Return or a double click. Cursor keys, Page Up/Down, mouse + selection, and the scrollwheel all operate on the ACW. + + 'Hidden' attributes can be accessed by typing the beginning of hidden + name after a '.'. e.g. '_'. This allows access to modules with + '__all__' set, or to class-private attributes. + + Completions and the 'Expand Word' facility can save a lot of typing! + + Completions are currently limited to those in the namespaces. Names in + an Edit window which are not via __main__ or sys.modules will not be + found. Run the module once with your imports to correct this + situation. Note that IDLE itself places quite a few modules in + sys.modules, so much can be found by default, e.g. the re module. + + If you don't like the ACW popping up unbidden, simply make the delay + longer or disable the extension. OTOH, you could make the delay zero. + + You could also switch off the CallTips extension. (We will be adding + a delay to the call tip window.) + Python Shell window: Control-c interrupts executing command. @@ -165,7 +219,7 @@ Alt-p retrieves previous command matching what you have typed. Alt-n retrieves next. - (These are Control-p, Control-n on the Mac) + (These are Control-p, Control-n on the Mac) Return while cursor is on a previous command retrieves that command. Expand word is also useful to reduce typing. @@ -196,7 +250,7 @@ be changed using the Settings dialog. Command line usage: - + Enter idle -h at the command prompt to get a usage message. Running without a subprocess: @@ -211,3 +265,18 @@ re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. + +Extensions: + + IDLE contains an extension facility. See the beginning of + config-extensions.def in the idlelib directory for further information. + The default extensions are currently: + + FormatParagraph + AutoExpand + ZoomHeight + ScriptBinding + CallTips + ParenMatch + AutoComplete + CodeContext Modified: python/branches/p3yk/Lib/imputil.py ============================================================================== --- python/branches/p3yk/Lib/imputil.py (original) +++ python/branches/p3yk/Lib/imputil.py Fri Feb 23 16:07:44 2007 @@ -552,6 +552,10 @@ # This method is only used when we look for a module within a package. assert parent + for submodule_path in parent.__path__: + code = self._import_pathname(_os_path_join(submodule_path, modname), fqname) + if code is not None: + return code return self._import_pathname(_os_path_join(parent.__pkgdir__, modname), fqname) Modified: python/branches/p3yk/Lib/logging/__init__.py ============================================================================== --- python/branches/p3yk/Lib/logging/__init__.py (original) +++ python/branches/p3yk/Lib/logging/__init__.py Fri Feb 23 16:07:44 2007 @@ -1,4 +1,4 @@ -# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, @@ -21,7 +21,7 @@ Should work under Python versions >= 1.5.2, except that source line information is not available unless 'sys._getframe()' is. -Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. +Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.5.0.1" -__date__ = "09 January 2007" +__version__ = "0.5.0.2" +__date__ = "16 February 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -68,7 +68,7 @@ except: return sys.exc_traceback.tb_frame.f_back -if hasattr(sys, '_getframe'): currentframe = sys._getframe +if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) # done filching # _srcfile is only used in conjunction with sys._getframe(). Modified: python/branches/p3yk/Lib/shutil.py ============================================================================== --- python/branches/p3yk/Lib/shutil.py (original) +++ python/branches/p3yk/Lib/shutil.py Fri Feb 23 16:07:44 2007 @@ -60,13 +60,15 @@ os.chmod(dst, mode) def copystat(src, dst): - """Copy all stat info (mode bits, atime and mtime) from src to dst""" + """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) + if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): + os.chflags(dst, st.st_flags) def copy(src, dst): Modified: python/branches/p3yk/Lib/stat.py ============================================================================== --- python/branches/p3yk/Lib/stat.py (original) +++ python/branches/p3yk/Lib/stat.py Fri Feb 23 16:07:44 2007 @@ -84,3 +84,16 @@ S_IROTH = 00004 S_IWOTH = 00002 S_IXOTH = 00001 + +# Names for file flags + +UF_NODUMP = 0x00000001 +UF_IMMUTABLE = 0x00000002 +UF_APPEND = 0x00000004 +UF_OPAQUE = 0x00000008 +UF_NOUNLINK = 0x00000010 +SF_ARCHIVED = 0x00010000 +SF_IMMUTABLE = 0x00020000 +SF_APPEND = 0x00040000 +SF_NOUNLINK = 0x00100000 +SF_SNAPSHOT = 0x00200000 Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Fri Feb 23 16:07:44 2007 @@ -593,14 +593,30 @@ c2pread, c2pwrite, errread, errwrite) - if p2cwrite: + # On Windows, you cannot just redirect one or two handles: You + # either have to redirect all three or none. If the subprocess + # user has only redirected one or two handles, we are + # automatically creating PIPEs for the rest. We should close + # these after the process is started. See bug #1124861. + if mswindows: + if stdin is None and p2cwrite is not None: + os.close(p2cwrite) + p2cwrite = None + if stdout is None and c2pread is not None: + os.close(c2pread) + c2pread = None + if stderr is None and errread is not None: + os.close(errread) + errread = None + + if p2cwrite is not None: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) - if c2pread: + if c2pread is not None: if universal_newlines: self.stdout = os.fdopen(c2pread, 'rU', bufsize) else: self.stdout = os.fdopen(c2pread, 'rb', bufsize) - if errread: + if errread is not None: if universal_newlines: self.stderr = os.fdopen(errread, 'rU', bufsize) else: @@ -669,7 +685,9 @@ if stdin is None: p2cread = GetStdHandle(STD_INPUT_HANDLE) - elif stdin == PIPE: + if p2cread is not None: + pass + elif stdin is None or stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) # Detach and turn into fd p2cwrite = p2cwrite.Detach() @@ -683,7 +701,9 @@ if stdout is None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) - elif stdout == PIPE: + if c2pwrite is not None: + pass + elif stdout is None or stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) # Detach and turn into fd c2pread = c2pread.Detach() @@ -697,7 +717,9 @@ if stderr is None: errwrite = GetStdHandle(STD_ERROR_HANDLE) - elif stderr == PIPE: + if errwrite is not None: + pass + elif stderr is None or stderr == PIPE: errread, errwrite = CreatePipe(None, 0) # Detach and turn into fd errread = errread.Detach() @@ -987,29 +1009,29 @@ # Child try: # Close parent's pipe ends - if p2cwrite: + if p2cwrite is not None: os.close(p2cwrite) - if c2pread: + if c2pread is not None: os.close(c2pread) - if errread: + if errread is not None: os.close(errread) os.close(errpipe_read) # Dup fds for child - if p2cread: + if p2cread is not None: os.dup2(p2cread, 0) - if c2pwrite: + if c2pwrite is not None: os.dup2(c2pwrite, 1) - if errwrite: + if errwrite is not None: os.dup2(errwrite, 2) # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - if p2cread and p2cread not in (0,): + if p2cread is not None and p2cread not in (0,): os.close(p2cread) - if c2pwrite and c2pwrite not in (p2cread, 1): + if c2pwrite is not None and c2pwrite not in (p2cread, 1): os.close(c2pwrite) - if errwrite and errwrite not in (p2cread, c2pwrite, 2): + if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2): os.close(errwrite) # Close all other fds, if asked for @@ -1042,11 +1064,11 @@ # Parent os.close(errpipe_write) - if p2cread and p2cwrite: + if p2cread is not None and p2cwrite is not None: os.close(p2cread) - if c2pwrite and c2pread: + if c2pwrite is not None and c2pread is not None: os.close(c2pwrite) - if errwrite and errread: + if errwrite is not None and errread is not None: os.close(errwrite) # Wait for exec to fail or succeed; possibly raising exception Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Fri Feb 23 16:07:44 2007 @@ -1062,6 +1062,10 @@ self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode] if not fileobj: + if self._mode == "a" and not os.path.exists(self.name): + # Create nonexistent files in append mode. + self._mode = "w" + self.mode = "wb" fileobj = _open(self.name, self.mode) self._extfileobj = False else: @@ -1095,7 +1099,8 @@ self.fileobj.seek(0) break if tarinfo is None: - self.fileobj.seek(- BLOCKSIZE, 1) + if self.offset > 0: + self.fileobj.seek(- BLOCKSIZE, 1) break if self._mode in "aw": @@ -1122,7 +1127,7 @@ 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression - 'a' or 'a:' open for appending + 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression Modified: python/branches/p3yk/Lib/test/test_datetime.py ============================================================================== --- python/branches/p3yk/Lib/test/test_datetime.py (original) +++ python/branches/p3yk/Lib/test/test_datetime.py Fri Feb 23 16:07:44 2007 @@ -1767,6 +1767,11 @@ self.assertEqual(t.isoformat(), "00:00:00.100000") self.assertEqual(t.isoformat(), str(t)) + def test_1653736(self): + # verify it doesn't accept extra keyword arguments + t = self.theclass(second=1) + self.assertRaises(TypeError, t.isoformat, foo=3) + def test_strftime(self): t = self.theclass(1, 2, 3, 4) self.assertEqual(t.strftime('%H %M %S'), "01 02 03") Modified: python/branches/p3yk/Lib/test/test_defaultdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_defaultdict.py (original) +++ python/branches/p3yk/Lib/test/test_defaultdict.py Fri Feb 23 16:07:44 2007 @@ -47,6 +47,7 @@ self.assertEqual(err.args, (15,)) else: self.fail("d2[15] didn't raise KeyError") + self.assertRaises(TypeError, defaultdict, 1) def test_missing(self): d1 = defaultdict() @@ -60,10 +61,10 @@ self.assertEqual(repr(d1), "defaultdict(None, {})") d1[11] = 41 self.assertEqual(repr(d1), "defaultdict(None, {11: 41})") - d2 = defaultdict(0) - self.assertEqual(d2.default_factory, 0) + d2 = defaultdict(int) + self.assertEqual(d2.default_factory, int) d2[12] = 42 - self.assertEqual(repr(d2), "defaultdict(0, {12: 42})") + self.assertEqual(repr(d2), "defaultdict(, {12: 42})") def foo(): return 43 d3 = defaultdict(foo) self.assert_(d3.default_factory is foo) Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Fri Feb 23 16:07:44 2007 @@ -2093,7 +2093,7 @@ __slots__ = ['prec'] def __init__(self, value=0.0, prec=12): self.prec = int(prec) - float.__init__(value) + float.__init__(self, value) def __repr__(self): return "%.*g" % (self.prec, self) vereq(repr(precfloat(1.1)), "1.1") Modified: python/branches/p3yk/Lib/test/test_dict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dict.py (original) +++ python/branches/p3yk/Lib/test/test_dict.py Fri Feb 23 16:07:44 2007 @@ -182,6 +182,14 @@ self.assertRaises(ValueError, {}.update, [(1, 2, 3)]) + # SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses + class KeyUpperDict(dict): + def __getitem__(self, key): + return key.upper() + d.clear() + d.update(KeyUpperDict.fromkeys('abc')) + self.assertEqual(d, {'a':'A', 'b':'B', 'c':'C'}) + def test_fromkeys(self): self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) d = {} Modified: python/branches/p3yk/Lib/test/test_gzip.py ============================================================================== --- python/branches/p3yk/Lib/test/test_gzip.py (original) +++ python/branches/p3yk/Lib/test/test_gzip.py Fri Feb 23 16:07:44 2007 @@ -153,6 +153,13 @@ self.assertEqual(f.myfileobj.mode, 'rb') f.close() + def test_1647484(self): + for mode in ('wb', 'rb'): + f = gzip.GzipFile(self.filename, mode) + self.assert_(hasattr(f, "name")) + self.assertEqual(f.name, self.filename) + f.close() + def test_main(verbose=None): test_support.run_unittest(TestGzip) Modified: python/branches/p3yk/Lib/test/test_heapq.py ============================================================================== --- python/branches/p3yk/Lib/test/test_heapq.py (original) +++ python/branches/p3yk/Lib/test/test_heapq.py Fri Feb 23 16:07:44 2007 @@ -1,6 +1,6 @@ """Unittests for heapq.""" -from heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest +from heapq import heappush, heappop, heapify, heapreplace, merge, nlargest, nsmallest import random import unittest from test import test_support @@ -103,6 +103,29 @@ heap_sorted = [heappop(heap) for i in range(size)] self.assertEqual(heap_sorted, sorted(data)) + def test_merge(self): + inputs = [] + for i in xrange(random.randrange(5)): + row = sorted(random.randrange(1000) for j in range(random.randrange(10))) + inputs.append(row) + self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs))) + self.assertEqual(list(merge()), []) + + def test_merge_stability(self): + class Int(int): + pass + inputs = [[], [], [], []] + for i in range(20000): + stream = random.randrange(4) + x = random.randrange(500) + obj = Int(x) + obj.pair = (x, stream) + inputs[stream].append(obj) + for stream in inputs: + stream.sort() + result = [i.pair for i in merge(*inputs)] + self.assertEqual(result, sorted(result)) + def test_nsmallest(self): data = [(random.randrange(2000), i) for i in range(1000)] for f in (None, lambda x: x[0] * 547 % 2000): Modified: python/branches/p3yk/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_itertools.py (original) +++ python/branches/p3yk/Lib/test/test_itertools.py Fri Feb 23 16:07:44 2007 @@ -55,8 +55,7 @@ self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)]) self.assertRaises(TypeError, count, 2, 3) self.assertRaises(TypeError, count, 'a') - c = count(sys.maxint-2) # verify that rollover doesn't crash - c.next(); c.next(); c.next(); c.next(); c.next() + self.assertRaises(OverflowError, list, islice(count(sys.maxint-5), 10)) c = count(3) self.assertEqual(repr(c), 'count(3)') c.next() @@ -203,6 +202,51 @@ ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + def test_iziplongest(self): + for args in [ + ['abc', range(6)], + [range(6), 'abc'], + [range(1000), range(2000,2100), range(3000,3050)], + [range(1000), range(0), range(3000,3050), range(1200), range(1500)], + [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)], + ]: + target = map(None, *args) + self.assertEqual(list(izip_longest(*args)), target) + self.assertEqual(list(izip_longest(*args, **{})), target) + target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X' + self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target) + + self.assertEqual(take(3,izip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input + + self.assertEqual(list(izip_longest()), list(zip())) + self.assertEqual(list(izip_longest([])), list(zip([]))) + self.assertEqual(list(izip_longest('abcdef')), list(zip('abcdef'))) + + self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict + self.assertRaises(TypeError, izip_longest, 3) + self.assertRaises(TypeError, izip_longest, range(3), 3) + + for stmt in [ + "izip_longest('abc', fv=1)", + "izip_longest('abc', fillvalue=1, bogus_keyword=None)", + ]: + try: + eval(stmt, globals(), locals()) + except TypeError: + pass + else: + self.fail('Did not raise Type in: ' + stmt) + + # Check tuple re-use (implementation detail) + self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')], + list(zip('abc', 'def'))) + self.assertEqual([pair for pair in izip_longest('abc', 'def')], + list(zip('abc', 'def'))) + ids = map(id, izip_longest('abc', 'def')) + self.assertEqual(min(ids), max(ids)) + ids = map(id, list(izip_longest('abc', 'def'))) + self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + def test_repeat(self): self.assertEqual(lzip(xrange(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) @@ -616,6 +660,15 @@ self.assertRaises(TypeError, izip, N(s)) self.assertRaises(ZeroDivisionError, list, izip(E(s))) + def test_iziplongest(self): + for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): + for g in (G, I, Ig, S, L, R): + self.assertEqual(list(izip_longest(g(s))), list(zip(g(s)))) + self.assertEqual(list(izip_longest(g(s), g(s))), list(zip(g(s), g(s)))) + self.assertRaises(TypeError, izip_longest, X(s)) + self.assertRaises(TypeError, izip_longest, N(s)) + self.assertRaises(ZeroDivisionError, list, izip_longest(E(s))) + def test_imap(self): for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)): for g in (G, I, Ig, S, L, R): Modified: python/branches/p3yk/Lib/test/test_operator.py ============================================================================== --- python/branches/p3yk/Lib/test/test_operator.py (original) +++ python/branches/p3yk/Lib/test/test_operator.py Fri Feb 23 16:07:44 2007 @@ -210,6 +210,8 @@ self.failUnless(operator.isSequenceType(xrange(10))) self.failUnless(operator.isSequenceType('yeahbuddy')) self.failIf(operator.isSequenceType(3)) + class Dict(dict): pass + self.failIf(operator.isSequenceType(Dict())) def test_lshift(self): self.failUnlessRaises(TypeError, operator.lshift) Modified: python/branches/p3yk/Lib/test/test_posix.py ============================================================================== --- python/branches/p3yk/Lib/test/test_posix.py (original) +++ python/branches/p3yk/Lib/test/test_posix.py Fri Feb 23 16:07:44 2007 @@ -192,6 +192,18 @@ posix.utime(test_support.TESTFN, (int(now), int(now))) posix.utime(test_support.TESTFN, (now, now)) + def test_chflags(self): + if hasattr(posix, 'chflags'): + st = os.stat(test_support.TESTFN) + if hasattr(st, 'st_flags'): + posix.chflags(test_support.TESTFN, st.st_flags) + + def test_lchflags(self): + if hasattr(posix, 'lchflags'): + st = os.stat(test_support.TESTFN) + if hasattr(st, 'st_flags'): + posix.lchflags(test_support.TESTFN, st.st_flags) + def test_main(): test_support.run_unittest(PosixTester) Modified: python/branches/p3yk/Lib/test/test_sax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sax.py (original) +++ python/branches/p3yk/Lib/test/test_sax.py Fri Feb 23 16:07:44 2007 @@ -216,7 +216,44 @@ ('' % ns_uri) -# ===== XMLFilterBase +def test_1463026_1(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS((None, 'a'), 'a') + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_2(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping(None, 'qux') + gen.startElementNS(('qux', 'a'), 'a', {}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping(None) + gen.endDocument() + + return result.getvalue() == start+'' + +def test_1463026_3(): + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping('my', 'qux') + gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'}) + gen.endElementNS(('qux', 'a'), 'a') + gen.endPrefixMapping('my') + gen.endDocument() + + return result.getvalue() == start+'' + +# ===== Xmlfilterbase def test_filter_basic(): result = StringIO() Modified: python/branches/p3yk/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk/Lib/test/test_set.py (original) +++ python/branches/p3yk/Lib/test/test_set.py Fri Feb 23 16:07:44 2007 @@ -26,6 +26,14 @@ def __repr__(self): return repr(self.value) +class HashCountingInt(int): + 'int-like object that counts the number of times __hash__ is called' + def __init__(self, *args): + self.hash_count = 0 + def __hash__(self): + self.hash_count += 1 + return int.__hash__(self) + class TestJointOps(unittest.TestCase): # Tests common to both set and frozenset @@ -273,6 +281,18 @@ fo.close() os.remove(test_support.TESTFN) + def test_do_not_rehash_dict_keys(self): + n = 10 + d = dict.fromkeys(map(HashCountingInt, xrange(n))) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s = self.thetype(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + s.difference(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + if hasattr(s, 'symmetric_difference_update'): + s.symmetric_difference_update(d) + self.assertEqual(sum(elem.hash_count for elem in d), n) + class TestSet(TestJointOps): thetype = set Modified: python/branches/p3yk/Lib/test/test_tarfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tarfile.py (original) +++ python/branches/p3yk/Lib/test/test_tarfile.py Fri Feb 23 16:07:44 2007 @@ -305,6 +305,61 @@ self.assertEqual(self.dst.getnames(), [], "added the archive to itself") +class AppendTest(unittest.TestCase): + # Test append mode (cp. patch #1652681). + + def setUp(self): + self.tarname = tmpname() + if os.path.exists(self.tarname): + os.remove(self.tarname) + + def _add_testfile(self, fileobj=None): + tar = tarfile.open(self.tarname, "a", fileobj=fileobj) + tar.addfile(tarfile.TarInfo("bar")) + tar.close() + + def _create_testtar(self): + src = tarfile.open(tarname()) + t = src.getmember("0-REGTYPE") + t.name = "foo" + f = src.extractfile(t) + tar = tarfile.open(self.tarname, "w") + tar.addfile(t, f) + tar.close() + + def _test(self, names=["bar"], fileobj=None): + tar = tarfile.open(self.tarname, fileobj=fileobj) + self.assert_(tar.getnames() == names) + + def test_non_existing(self): + self._add_testfile() + self._test() + + def test_empty(self): + open(self.tarname, "wb").close() + self._add_testfile() + self._test() + + def test_empty_fileobj(self): + fobj = StringIO.StringIO() + self._add_testfile(fobj) + fobj.seek(0) + self._test(fileobj=fobj) + + def test_fileobj(self): + self._create_testtar() + data = open(self.tarname, "rb").read() + fobj = StringIO.StringIO(data) + self._add_testfile(fobj) + fobj.seek(0) + self._test(names=["foo", "bar"], fileobj=fobj) + + def test_existing(self): + self._create_testtar() + self._add_testfile() + self._test(names=["foo", "bar"]) + + class Write100Test(BaseTest): # The name field in a tar header stores strings of at most 100 chars. # If a string is shorter than 100 chars it has to be padded with '\0', @@ -711,6 +766,7 @@ ReadAsteriskTest, ReadStreamAsteriskTest, WriteTest, + AppendTest, Write100Test, WriteSize0Test, WriteStreamTest, Modified: python/branches/p3yk/Lib/test/test_zipfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_zipfile.py (original) +++ python/branches/p3yk/Lib/test/test_zipfile.py Fri Feb 23 16:07:44 2007 @@ -307,6 +307,28 @@ class OtherTests(unittest.TestCase): + def testCreateNonExistentFileForAppend(self): + if os.path.exists(TESTFN): + os.unlink(TESTFN) + + filename = 'testfile.txt' + content = 'hello, world. this is some content.' + + try: + zf = zipfile.ZipFile(TESTFN, 'a') + zf.writestr(filename, content) + zf.close() + except IOError: + self.fail('Could not append data to a non-existent zip file.') + + self.assert_(os.path.exists(TESTFN)) + + zf = zipfile.ZipFile(TESTFN, 'r') + self.assertEqual(zf.read(filename), content) + zf.close() + + os.unlink(TESTFN) + def testCloseErroneousFile(self): # This test checks that the ZipFile constructor closes the file object # it opens if there's an error in the file. If it doesn't, the traceback @@ -349,8 +371,49 @@ # and report that the first file in the archive was corrupt. self.assertRaises(RuntimeError, zipf.testzip) + +class DecryptionTests(unittest.TestCase): + # This test checks that ZIP decryption works. Since the library does not + # support encryption at the moment, we use a pre-generated encrypted + # ZIP file + + data = ( + 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00' + '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y' + '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl' + 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00' + '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81' + '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00' + '\x00\x00L\x00\x00\x00\x00\x00' ) + + plain = 'zipfile.py encryption test' + + def setUp(self): + fp = open(TESTFN, "wb") + fp.write(self.data) + fp.close() + self.zip = zipfile.ZipFile(TESTFN, "r") + + def tearDown(self): + self.zip.close() + os.unlink(TESTFN) + + def testNoPassword(self): + # Reading the encrypted file without password + # must generate a RunTime exception + self.assertRaises(RuntimeError, self.zip.read, "test.txt") + + def testBadPassword(self): + self.zip.setpassword("perl") + self.assertRaises(RuntimeError, self.zip.read, "test.txt") + + def testGoodPassword(self): + self.zip.setpassword("python") + self.assertEquals(self.zip.read("test.txt"), self.plain) + def test_main(): - run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, PyZipFileTests) + run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, + PyZipFileTests, DecryptionTests) #run_unittest(TestZip64InSmallFiles) if __name__ == "__main__": Modified: python/branches/p3yk/Lib/trace.py ============================================================================== --- python/branches/p3yk/Lib/trace.py (original) +++ python/branches/p3yk/Lib/trace.py Fri Feb 23 16:07:44 2007 @@ -587,7 +587,7 @@ """ if why == 'call': code = frame.f_code - filename = code.co_filename + filename = frame.f_globals.get('__file__', None) if filename: # XXX modname() doesn't work right for packages, so # the ignore support won't work right for packages Modified: python/branches/p3yk/Lib/xml/sax/saxutils.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/saxutils.py (original) +++ python/branches/p3yk/Lib/xml/sax/saxutils.py Fri Feb 23 16:07:44 2007 @@ -100,6 +100,17 @@ else: self._out.write(text.encode(self._encoding, _error_handling)) + def _qname(self, name): + """Builds a qualified name from a (ns_url, localname) pair""" + if name[0]: + # The name is in a non-empty namespace + prefix = self._current_context[name[0]] + if prefix: + # If it is not the default namespace, prepend the prefix + return prefix + ":" + name[1] + # Return the unqualified name + return name[1] + # ContentHandler methods def startDocument(self): @@ -125,29 +136,21 @@ self._write('' % name) def startElementNS(self, name, qname, attrs): - if name[0] is None: - # if the name was not namespace-scoped, use the unqualified part - name = name[1] - else: - # else try to restore the original prefix from the namespace - name = self._current_context[name[0]] + ":" + name[1] - self._write('<' + name) + self._write('<' + self._qname(name)) - for pair in self._undeclared_ns_maps: - self._write(' xmlns:%s="%s"' % pair) + for prefix, uri in self._undeclared_ns_maps: + if prefix: + self._out.write(' xmlns:%s="%s"' % (prefix, uri)) + else: + self._out.write(' xmlns="%s"' % uri) self._undeclared_ns_maps = [] for (name, value) in attrs.items(): - name = self._current_context[name[0]] + ":" + name[1] - self._write(' %s=%s' % (name, quoteattr(value))) + self._write(' %s=%s' % (self._qname(name), quoteattr(value))) self._write('>') def endElementNS(self, name, qname): - if name[0] is None: - name = name[1] - else: - name = self._current_context[name[0]] + ":" + name[1] - self._write('' % name) + self._write('' % self._qname(name)) def characters(self, content): self._write(escape(content)) Modified: python/branches/p3yk/Lib/zipfile.py ============================================================================== --- python/branches/p3yk/Lib/zipfile.py (original) +++ python/branches/p3yk/Lib/zipfile.py Fri Feb 23 16:07:44 2007 @@ -296,6 +296,65 @@ extra = extra[ln+4:] +class _ZipDecrypter: + """Class to handle decryption of files stored within a ZIP archive. + + ZIP supports a password-based form of encryption. Even though known + plaintext attacks have been found against it, it is still useful + for low-level securicy. + + Usage: + zd = _ZipDecrypter(mypwd) + plain_char = zd(cypher_char) + plain_text = map(zd, cypher_text) + """ + + def _GenerateCRCTable(): + """Generate a CRC-32 table. + + ZIP encryption uses the CRC32 one-byte primitive for scrambling some + internal keys. We noticed that a direct implementation is faster than + relying on binascii.crc32(). + """ + poly = 0xedb88320 + table = [0] * 256 + for i in range(256): + crc = i + for j in range(8): + if crc & 1: + crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly + else: + crc = ((crc >> 1) & 0x7FFFFFFF) + table[i] = crc + return table + crctable = _GenerateCRCTable() + + def _crc32(self, ch, crc): + """Compute the CRC32 primitive on one byte.""" + return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] + + def __init__(self, pwd): + self.key0 = 305419896 + self.key1 = 591751049 + self.key2 = 878082192 + for p in pwd: + self._UpdateKeys(p) + + def _UpdateKeys(self, c): + self.key0 = self._crc32(c, self.key0) + self.key1 = (self.key1 + (self.key0 & 255)) & 4294967295 + self.key1 = (self.key1 * 134775813 + 1) & 4294967295 + self.key2 = self._crc32(chr((self.key1 >> 24) & 255), self.key2) + + def __call__(self, c): + """Decrypt a single character.""" + c = ord(c) + k = self.key2 | 2 + c = c ^ (((k * (k^1)) >> 8) & 255) + c = chr(c) + self._UpdateKeys(c) + return c + class ZipFile: """ Class with methods to open, read, write, close, list zip files. @@ -330,13 +389,21 @@ self.filelist = [] # List of ZipInfo instances for archive self.compression = compression # Method of compression self.mode = key = mode.replace('b', '')[0] + self.pwd = None # Check if we were passed a file-like object if isinstance(file, basestring): self._filePassed = 0 self.filename = file modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'} - self.fp = open(file, modeDict[mode]) + try: + self.fp = open(file, modeDict[mode]) + except IOError: + if mode == 'a': + mode = key = 'w' + self.fp = open(file, modeDict[mode]) + else: + raise else: self._filePassed = 1 self.fp = file @@ -461,7 +528,11 @@ """Return the instance of ZipInfo given 'name'.""" return self.NameToInfo[name] - def read(self, name): + def setpassword(self, pwd): + """Set default password for encrypted files.""" + self.pwd = pwd + + def read(self, name, pwd=None): """Return file bytes (as a string) for name.""" if self.mode not in ("r", "a"): raise RuntimeError, 'read() requires mode "r" or "a"' @@ -469,6 +540,13 @@ raise RuntimeError, \ "Attempt to read ZIP archive that was already closed" zinfo = self.getinfo(name) + is_encrypted = zinfo.flag_bits & 0x1 + if is_encrypted: + if not pwd: + pwd = self.pwd + if not pwd: + raise RuntimeError, "File %s is encrypted, " \ + "password required for extraction" % name filepos = self.fp.tell() self.fp.seek(zinfo.header_offset, 0) @@ -489,6 +567,18 @@ zinfo.orig_filename, fname) bytes = self.fp.read(zinfo.compress_size) + # Go with decryption + if is_encrypted: + zd = _ZipDecrypter(pwd) + # The first 12 bytes in the cypher stream is an encryption header + # used to strengthen the algorithm. The first 11 bytes are + # completely random, while the 12th contains the MSB of the CRC, + # and is used to check the correctness of the password. + h = map(zd, bytes[0:12]) + if ord(h[11]) != ((zinfo.CRC>>24)&255): + raise RuntimeError, "Bad password for file %s" % name + bytes = "".join(map(zd, bytes[12:])) + # Go with decompression self.fp.seek(filepos, 0) if zinfo.compress_type == ZIP_STORED: pass Modified: python/branches/p3yk/Misc/ACKS ============================================================================== --- python/branches/p3yk/Misc/ACKS (original) +++ python/branches/p3yk/Misc/ACKS Fri Feb 23 16:07:44 2007 @@ -377,6 +377,7 @@ Kip Lehman Joerg Lehmann Marc-Andre Lemburg +Mark Levinson William Lewis Robert van Liere Martin Ligr Modified: python/branches/p3yk/Modules/collectionsmodule.c ============================================================================== --- python/branches/p3yk/Modules/collectionsmodule.c (original) +++ python/branches/p3yk/Modules/collectionsmodule.c Fri Feb 23 16:07:44 2007 @@ -1259,8 +1259,14 @@ newargs = PyTuple_New(0); else { Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n > 0) + if (n > 0) { newdefault = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(newdefault)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return -1; + } + } newargs = PySequence_GetSlice(args, 1, n); } if (newargs == NULL) Modified: python/branches/p3yk/Modules/datetimemodule.c ============================================================================== --- python/branches/p3yk/Modules/datetimemodule.c (original) +++ python/branches/p3yk/Modules/datetimemodule.c Fri Feb 23 16:07:44 2007 @@ -3138,7 +3138,7 @@ } static PyObject * -time_isoformat(PyDateTime_Time *self) +time_isoformat(PyDateTime_Time *self, PyObject *unused) { char buf[100]; PyObject *result; @@ -3374,7 +3374,7 @@ static PyMethodDef time_methods[] = { - {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, + {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" "[+HH:MM].")}, Modified: python/branches/p3yk/Modules/itertoolsmodule.c ============================================================================== --- python/branches/p3yk/Modules/itertoolsmodule.c (original) +++ python/branches/p3yk/Modules/itertoolsmodule.c Fri Feb 23 16:07:44 2007 @@ -2073,6 +2073,11 @@ static PyObject * count_next(countobject *lz) { + if (lz->cnt == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot count beyond LONG_MAX"); + return NULL; + } return PyInt_FromSsize_t(lz->cnt++); } @@ -2467,6 +2472,234 @@ PyObject_GC_Del, /* tp_free */ }; +/* iziplongest object ************************************************************/ + +#include "Python.h" + +typedef struct { + PyObject_HEAD + Py_ssize_t tuplesize; + Py_ssize_t numactive; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue; +} iziplongestobject; + +static PyTypeObject iziplongest_type; + +static PyObject * +izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + iziplongestobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue = Py_None; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { + fillvalue = PyDict_GetItemString(kwds, "fillvalue"); + if (fillvalue == NULL || PyDict_Size(kwds) > 1) { + PyErr_SetString(PyExc_TypeError, + "izip_longest() got an unexpected keyword argument"); + return NULL; + } + } + + /* args must be a tuple */ + assert(PyTuple_Check(args)); + + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "izip_longest argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } + + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create iziplongestobject structure */ + lz = (iziplongestobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->numactive = tuplesize; + lz->result = result; + Py_INCREF(fillvalue); + lz->fillvalue = fillvalue; + return (PyObject *)lz; +} + +static void +izip_longest_dealloc(iziplongestobject *lz) +{ + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_XDECREF(lz->fillvalue); + lz->ob_type->tp_free(lz); +} + +static int +izip_longest_traverse(iziplongestobject *lz, visitproc visit, void *arg) +{ + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + Py_VISIT(lz->fillvalue); + return 0; +} + +static PyObject * +izip_longest_next(iziplongestobject *lz) +{ + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (lz->numactive == 0) + return NULL; + if (result->ob_refcnt == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + assert(PyIter_Check(it)); + item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0) { + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } + PyTuple_SET_ITEM(result, i, item); + } + } + return result; +} + +PyDoc_STRVAR(izip_longest_doc, +"izip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> izip_longest object\n\ +\n\ +Return an izip_longest object whose .next() method returns a tuple where\n\ +the i-th element comes from the i-th iterable argument. The .next()\n\ +method continues until the longest iterable in the argument sequence\n\ +is exhausted and then it raises StopIteration. When the shorter iterables\n\ +are exhausted, the fillvalue is substituted in their place. The fillvalue\n\ +defaults to None or can be specified by a keyword argument.\n\ +"); + +static PyTypeObject iziplongest_type = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + "itertools.izip_longest", /* tp_name */ + sizeof(iziplongestobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)izip_longest_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + izip_longest_doc, /* tp_doc */ + (traverseproc)izip_longest_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)izip_longest_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + izip_longest_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ +}; /* module level code ********************************************************/ @@ -2480,6 +2713,7 @@ \n\ Iterators terminating on the shortest input sequence:\n\ izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ +izip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ ifilter(pred, seq) --> elements of seq where pred(elem) is True\n\ ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\ islice(seq, [start,] stop [, step]) --> elements from\n\ @@ -2517,6 +2751,7 @@ &ifilterfalse_type, &count_type, &izip_type, + &iziplongest_type, &repeat_type, &groupby_type, NULL Modified: python/branches/p3yk/Modules/posixmodule.c ============================================================================== --- python/branches/p3yk/Modules/posixmodule.c (original) +++ python/branches/p3yk/Modules/posixmodule.c Fri Feb 23 16:07:44 2007 @@ -1692,6 +1692,57 @@ } +#ifdef HAVE_CHFLAGS +PyDoc_STRVAR(posix_chflags__doc__, +"chflags(path, flags)\n\n\ +Set file flags."); + +static PyObject * +posix_chflags(PyObject *self, PyObject *args) +{ + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:chflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +} +#endif /* HAVE_CHFLAGS */ + +#ifdef HAVE_LCHFLAGS +PyDoc_STRVAR(posix_lchflags__doc__, +"lchflags(path, flags)\n\n\ +Set file flags.\n\ +This function will not follow symbolic links."); + +static PyObject * +posix_lchflags(PyObject *self, PyObject *args) +{ + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:lchflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +} +#endif /* HAVE_LCHFLAGS */ + #ifdef HAVE_CHROOT PyDoc_STRVAR(posix_chroot__doc__, "chroot(path)\n\n\ @@ -8070,10 +8121,16 @@ {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, #endif {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, +#ifdef HAVE_CHFLAGS + {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, +#endif /* HAVE_CHFLAGS */ {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, #ifdef HAVE_CHOWN {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, #endif /* HAVE_CHOWN */ +#ifdef HAVE_LCHFLAGS + {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, +#endif /* HAVE_LCHFLAGS */ #ifdef HAVE_LCHOWN {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, #endif /* HAVE_LCHOWN */ Modified: python/branches/p3yk/Modules/socketmodule.c ============================================================================== --- python/branches/p3yk/Modules/socketmodule.c (original) +++ python/branches/p3yk/Modules/socketmodule.c Fri Feb 23 16:07:44 2007 @@ -362,20 +362,25 @@ #if defined(__FreeBSD__) #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM +#define BTPROTO_HCI BLUETOOTH_PROTO_HCI #define sockaddr_l2 sockaddr_l2cap #define sockaddr_rc sockaddr_rfcomm #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb) #elif defined(__NetBSD__) #define sockaddr_l2 sockaddr_bt #define sockaddr_rc sockaddr_bt +#define sockaddr_hci sockaddr_bt #define sockaddr_sco sockaddr_bt #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb) #else #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb) #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb) +#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb) #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb) #endif #endif @@ -1119,6 +1124,14 @@ return ret; } + case BTPROTO_HCI: + { + struct sockaddr_hci *a = (struct sockaddr_hci *) addr; + PyObject *ret = NULL; + ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); + return ret; + } + #if !defined(__FreeBSD__) case BTPROTO_SCO: { @@ -1347,6 +1360,18 @@ *len_ret = sizeof *addr; return 1; } + case BTPROTO_HCI: + { + struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; + _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + *len_ret = sizeof *addr; + return 1; + } #if !defined(__FreeBSD__) case BTPROTO_SCO: { @@ -1485,6 +1510,9 @@ case BTPROTO_RFCOMM: *len_ret = sizeof (struct sockaddr_rc); return 1; + case BTPROTO_HCI: + *len_ret = sizeof (struct sockaddr_hci); + return 1; #if !defined(__FreeBSD__) case BTPROTO_SCO: *len_ret = sizeof (struct sockaddr_sco); @@ -4363,7 +4391,9 @@ PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); #endif PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); +#ifdef NETLINK_DNRTMSG PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); +#endif #ifdef NETLINK_TAPBASE PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); #endif @@ -4408,6 +4438,11 @@ #ifdef USE_BLUETOOTH PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); + PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); + PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); + PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); + PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); + PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); #if !defined(__FreeBSD__) PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); #endif Modified: python/branches/p3yk/Modules/socketmodule.h ============================================================================== --- python/branches/p3yk/Modules/socketmodule.h (original) +++ python/branches/p3yk/Modules/socketmodule.h Fri Feb 23 16:07:44 2007 @@ -46,6 +46,7 @@ #include #include #include +#include #endif #ifdef HAVE_BLUETOOTH_H @@ -98,6 +99,7 @@ struct sockaddr_l2 bt_l2; struct sockaddr_rc bt_rc; struct sockaddr_sco bt_sco; + struct sockaddr_hci bt_hci; #endif #ifdef HAVE_NETPACKET_PACKET_H struct sockaddr_ll ll; Modified: python/branches/p3yk/Objects/abstract.c ============================================================================== --- python/branches/p3yk/Objects/abstract.c (original) +++ python/branches/p3yk/Objects/abstract.c Fri Feb 23 16:07:44 2007 @@ -980,6 +980,8 @@ int PySequence_Check(PyObject *s) { + if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type)) + return 0; return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } Modified: python/branches/p3yk/Objects/dictnotes.txt ============================================================================== --- python/branches/p3yk/Objects/dictnotes.txt (original) +++ python/branches/p3yk/Objects/dictnotes.txt Fri Feb 23 16:07:44 2007 @@ -98,6 +98,17 @@ depending on the size of the dictionary. Setting to *4 eliminates every other resize step. +* Maximum sparseness (minimum dictionary load). What percentage + of entries can be unused before the dictionary shrinks to + free up memory and speed up iteration? (The current CPython + code does not represent this parameter directly.) + +* Shrinkage rate upon exceeding maximum sparseness. The current + CPython code never even checks sparseness when deleting a + key. When a new key is added, it resizes based on the number + of active keys, so that the addition may trigger shrinkage + rather than growth. + Tune-ups should be measured across a broad range of applications and use cases. A change to any parameter will help in some situations and hurt in others. The key is to find settings that help the most common @@ -115,6 +126,15 @@ Also, every dictionary iterates at least twice, once for the memset() when it is created and once by dealloc(). +Dictionary operations involving only a single key can be O(1) unless +resizing is possible. By checking for a resize only when the +dictionary can grow (and may *require* resizing), other operations +remain O(1), and the odds of resize thrashing or memory fragmentation +are reduced. In particular, an algorithm that empties a dictionary +by repeatedly invoking .pop will see no resizing, which might +not be necessary at all because the dictionary is eventually +discarded entirely. + Results of Cache Locality Experiments ------------------------------------- Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Fri Feb 23 16:07:44 2007 @@ -833,6 +833,34 @@ return 1; } +/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/ +int +_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash) +{ + register Py_ssize_t i; + register Py_ssize_t mask; + register dictentry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((dictobject *)op)->ma_table; + mask = ((dictobject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + *phash = (long)(ep[i].me_hash); + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; +} + /* Methods */ static void @@ -1336,7 +1364,7 @@ return -1; } mp = (dictobject*)a; - if (PyDict_Check(b)) { + if (PyDict_CheckExact(b)) { other = (dictobject*)b; if (other == mp || other->ma_used == 0) /* a.update(a) or a.update({}); nothing to do */ @@ -1909,6 +1937,17 @@ return ep == NULL ? -1 : (ep->me_value != NULL); } +/* Internal version of PyDict_Contains used when the hash value is already known */ +int +_PyDict_Contains(PyObject *op, PyObject *key, long hash) +{ + dictobject *mp = (dictobject *)op; + dictentry *ep; + + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); +} + /* Hack to implement "key in dict" */ static PySequenceMethods dict_as_sequence = { 0, /* sq_length */ Modified: python/branches/p3yk/Objects/enumobject.c ============================================================================== --- python/branches/p3yk/Objects/enumobject.c (original) +++ python/branches/p3yk/Objects/enumobject.c Fri Feb 23 16:07:44 2007 @@ -62,6 +62,12 @@ PyObject *result = en->en_result; PyObject *it = en->en_sit; + if (en->en_index == LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "enumerate() is limited to LONG_MAX items"); + return NULL; + } + next_item = (*it->ob_type->tp_iternext)(it); if (next_item == NULL) return NULL; Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Fri Feb 23 16:07:44 2007 @@ -932,14 +932,31 @@ { PyObject *key, *it; - if (PyAnySet_Check(other)) + if (PyAnySet_CheckExact(other)) return set_merge(so, other); if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; - while (PyDict_Next(other, &pos, &key, &value)) { - if (set_add_key(so, key) == -1) + long hash; + Py_ssize_t dictsize = PyDict_Size(other); + + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if (dictsize == -1) + return -1; + if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + dictsize)*2) != 0) + return -1; + } + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { + setentry an_entry; + + an_entry.hash = hash; + an_entry.key = key; + if (set_add_entry(so, &an_entry) == -1) return -1; } return 0; @@ -1210,7 +1227,7 @@ if (result == NULL) return NULL; - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_ssize_t pos = 0; setentry *entry; @@ -1334,7 +1351,7 @@ if ((PyObject *)so == other) return set_clear_internal(so); - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { setentry *entry; Py_ssize_t pos = 0; @@ -1383,7 +1400,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { + if (!PyAnySet_CheckExact(other) && !PyDict_CheckExact(other)) { result = set_copy(so); if (result == NULL) return NULL; @@ -1402,7 +1419,7 @@ setentry entrycopy; entrycopy.hash = entry->hash; entrycopy.key = entry->key; - if (!PyDict_Contains(other, entry->key)) { + if (!_PyDict_Contains(other, entry->key, entry->hash)) { if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { Py_DECREF(result); return NULL; @@ -1473,12 +1490,10 @@ if (PyDict_CheckExact(other)) { PyObject *value; int rv; - while (PyDict_Next(other, &pos, &key, &value)) { + long hash; + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { setentry an_entry; - long hash = PyObject_Hash(key); - if (hash == -1) - return NULL; an_entry.hash = hash; an_entry.key = key; rv = set_discard_entry(so, &an_entry); @@ -1492,7 +1507,7 @@ Py_RETURN_NONE; } - if (PyAnySet_Check(other)) { + if (PyAnySet_CheckExact(other)) { Py_INCREF(other); otherset = (PySetObject *)other; } else { @@ -1575,7 +1590,7 @@ setentry *entry; Py_ssize_t pos = 0; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { PyObject *tmp, *result; tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) @@ -1604,7 +1619,7 @@ { PyObject *tmp, *result; - if (!PyAnySet_Check(other)) { + if (!PyAnySet_CheckExact(other)) { tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) return NULL; Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Fri Feb 23 16:07:44 2007 @@ -4279,7 +4279,13 @@ SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O") SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O") SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O") -SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O") +/* Can't use SLOT1 here, because nb_inplace_power is ternary */ +static PyObject * +slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) +{ + static PyObject *cache_str; + return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); +} SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O") SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O") SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O") Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Fri Feb 23 16:07:44 2007 @@ -68,7 +68,7 @@ | Subscript(expr value, slice slice, expr_context ctx) | Name(identifier id, expr_context ctx) | List(expr* elts, expr_context ctx) - | Tuple(expr *elts, expr_context ctx) + | Tuple(expr* elts, expr_context ctx) -- col_offset is the byte offset in the utf8 string the parser uses attributes (int lineno, int col_offset) Modified: python/branches/p3yk/Parser/asdl_c.py ============================================================================== --- python/branches/p3yk/Parser/asdl_c.py (original) +++ python/branches/p3yk/Parser/asdl_c.py Fri Feb 23 16:07:44 2007 @@ -525,6 +525,9 @@ (cons.name, cons.name), 1) self.emit("if (!%s_singleton) return 0;" % cons.name, 1) +def parse_version(mod): + return mod.version.value[12:-3] + class ASTModuleVisitor(PickleVisitor): def visitModule(self, mod): @@ -540,7 +543,8 @@ self.emit('if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)', 1) self.emit("return;", 2) # Value of version: "$Revision$" - self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)' % mod.version.value[12:-3], 1) + self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)' + % parse_version(mod), 1) self.emit("return;", 2) for dfn in mod.dfns: self.visit(dfn) @@ -721,11 +725,23 @@ v.visit(object) v.emit("", 0) +common_msg = "/* File automatically generated by %s. */\n" + +c_file_msg = """ +/* + __version__ %s. + + This module must be committed separately after each AST grammar change; + The __version__ number is set to the revision number of the commit + containing the grammar change. +*/ +""" + def main(srcfile): argv0 = sys.argv[0] components = argv0.split(os.sep) argv0 = os.sep.join(components[-2:]) - auto_gen_msg = '/* File automatically generated by %s */\n' % argv0 + auto_gen_msg = common_msg % argv0 mod = asdl.parse(srcfile) if not asdl.check(mod): sys.exit(1) @@ -746,6 +762,7 @@ p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") f = open(p, "wb") print >> f, auto_gen_msg + print >> f, c_file_msg % parse_version(mod) print >> f, '#include "Python.h"' print >> f, '#include "%s-ast.h"' % mod.name print >> f Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Fri Feb 23 16:07:44 2007 @@ -1,4 +1,13 @@ -/* File automatically generated by Parser/asdl_c.py */ +/* File automatically generated by Parser/asdl_c.py. */ + + +/* + __version__ 53731. + + This module must be committed separately after each AST grammar change; + The __version__ number is set to the revision number of the commit + containing the grammar change. +*/ #include "Python.h" #include "Python-ast.h" @@ -3080,7 +3089,7 @@ if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) return; - if (PyModule_AddStringConstant(m, "__version__", "53704") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53731") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) Modified: python/branches/p3yk/configure ============================================================================== --- python/branches/p3yk/configure (original) +++ python/branches/p3yk/configure Fri Feb 23 16:07:44 2007 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 53017 . +# From configure.in Revision: 53610 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -15068,11 +15068,13 @@ -for ac_func in alarm bind_textdomain_codeset chown clock confstr ctermid \ - execv fork fpathconf ftime ftruncate \ + + +for ac_func in alarm bind_textdomain_codeset chflags chown clock confstr \ + ctermid execv fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ - kill killpg lchown lstat mkfifo mknod mktime \ + kill killpg lchflags lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink realpath \ select setegid seteuid setgid \ Modified: python/branches/p3yk/configure.in ============================================================================== --- python/branches/p3yk/configure.in (original) +++ python/branches/p3yk/configure.in Fri Feb 23 16:07:44 2007 @@ -2282,11 +2282,11 @@ AC_MSG_RESULT(MACHDEP_OBJS) # checks for library functions -AC_CHECK_FUNCS(alarm bind_textdomain_codeset chown clock confstr ctermid \ - execv fork fpathconf ftime ftruncate \ +AC_CHECK_FUNCS(alarm bind_textdomain_codeset chflags chown clock confstr \ + ctermid execv fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getspnam getspent getsid getwd \ - kill killpg lchown lstat mkfifo mknod mktime \ + kill killpg lchflags lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink realpath \ select setegid seteuid setgid \ Modified: python/branches/p3yk/pyconfig.h.in ============================================================================== --- python/branches/p3yk/pyconfig.h.in (original) +++ python/branches/p3yk/pyconfig.h.in Fri Feb 23 16:07:44 2007 @@ -67,6 +67,9 @@ /* Define this if you have the type _Bool. */ #undef HAVE_C99_BOOL +/* Define to 1 if you have the `chflags' function. */ +#undef HAVE_CHFLAGS + /* Define to 1 if you have the `chown' function. */ #undef HAVE_CHOWN @@ -290,6 +293,9 @@ Solaris and Linux, the necessary defines are already defined.) */ #undef HAVE_LARGEFILE_SUPPORT +/* Define to 1 if you have the `lchflags' function. */ +#undef HAVE_LCHFLAGS + /* Define to 1 if you have the `lchown' function. */ #undef HAVE_LCHOWN Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Fri Feb 23 16:07:44 2007 @@ -1318,7 +1318,8 @@ from distutils.dep_util import newer_group config_sources = [os.path.join(ffi_srcdir, fname) - for fname in os.listdir(ffi_srcdir)] + for fname in os.listdir(ffi_srcdir) + if os.path.isfile(os.path.join(ffi_srcdir, fname))] if self.force or newer_group(config_sources, ffi_configfile): from distutils.dir_util import mkpath From python-3000-checkins at python.org Fri Feb 23 20:57:09 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Fri, 23 Feb 2007 20:57:09 +0100 (CET) Subject: [Python-3000-checkins] r53872 - in python/branches/p3yk: Include/Python-ast.h Include/opcode.h Lib/compiler/ast.py Lib/compiler/pyassem.py Lib/compiler/pycodegen.py Lib/compiler/transformer.py Lib/opcode.py Lib/test/test_bytes.py Lib/test/test_compiler.py Parser/Python.asdl Parser/tokenizer.c Python/Python-ast.c Python/ast.c Python/ceval.c Python/compile.c Message-ID: <20070223195709.0A19C1E4008@bag.python.org> Author: thomas.wouters Date: Fri Feb 23 20:56:57 2007 New Revision: 53872 Modified: python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Include/opcode.h python/branches/p3yk/Lib/compiler/ast.py python/branches/p3yk/Lib/compiler/pyassem.py python/branches/p3yk/Lib/compiler/pycodegen.py python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/opcode.py python/branches/p3yk/Lib/test/test_bytes.py python/branches/p3yk/Lib/test/test_compiler.py python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Parser/tokenizer.c python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/ast.c python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/compile.c Log: Bytes literal. Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Fri Feb 23 20:56:57 2007 @@ -176,9 +176,9 @@ enum _expr_kind {BoolOp_kind=1, BinOp_kind=2, UnaryOp_kind=3, Lambda_kind=4, IfExp_kind=5, Dict_kind=6, Set_kind=7, ListComp_kind=8, GeneratorExp_kind=9, Yield_kind=10, Compare_kind=11, - Call_kind=12, Num_kind=13, Str_kind=14, Ellipsis_kind=15, - Attribute_kind=16, Subscript_kind=17, Name_kind=18, - List_kind=19, Tuple_kind=20}; + Call_kind=12, Num_kind=13, Str_kind=14, Bytes_kind=15, + Ellipsis_kind=16, Attribute_kind=17, Subscript_kind=18, + Name_kind=19, List_kind=20, Tuple_kind=21}; struct _expr { enum _expr_kind kind; union { @@ -255,6 +255,10 @@ } Str; struct { + string s; + } Bytes; + + struct { expr_ty value; identifier attr; expr_context_ty ctx; @@ -465,6 +469,8 @@ expr_ty _Py_Num(object n, int lineno, int col_offset, PyArena *arena); #define Str(a0, a1, a2, a3) _Py_Str(a0, a1, a2, a3) expr_ty _Py_Str(string s, int lineno, int col_offset, PyArena *arena); +#define Bytes(a0, a1, a2, a3) _Py_Bytes(a0, a1, a2, a3) +expr_ty _Py_Bytes(string s, int lineno, int col_offset, PyArena *arena); #define Ellipsis(a0, a1, a2) _Py_Ellipsis(a0, a1, a2) expr_ty _Py_Ellipsis(int lineno, int col_offset, PyArena *arena); #define Attribute(a0, a1, a2, a3, a4, a5) _Py_Attribute(a0, a1, a2, a3, a4, a5) Modified: python/branches/p3yk/Include/opcode.h ============================================================================== --- python/branches/p3yk/Include/opcode.h (original) +++ python/branches/p3yk/Include/opcode.h Fri Feb 23 20:56:57 2007 @@ -72,7 +72,7 @@ #define LOAD_LOCALS 82 #define RETURN_VALUE 83 #define IMPORT_STAR 84 - +#define MAKE_BYTES 85 #define YIELD_VALUE 86 #define POP_BLOCK 87 #define END_FINALLY 88 Modified: python/branches/p3yk/Lib/compiler/ast.py ============================================================================== --- python/branches/p3yk/Lib/compiler/ast.py (original) +++ python/branches/p3yk/Lib/compiler/ast.py Fri Feb 23 20:56:57 2007 @@ -267,6 +267,20 @@ def __repr__(self): return "Break()" +class Bytes(Node): + def __init__(self, value, lineno=None): + self.value = value + self.lineno = lineno + + def getChildren(self): + return self.value, + + def getChildNodes(self): + return () + + def __repr__(self): + return "Bytes(%s)" % (repr(self.value),) + class CallFunc(Node): def __init__(self, node, args, star_args = None, dstar_args = None, lineno=None): self.node = node Modified: python/branches/p3yk/Lib/compiler/pyassem.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pyassem.py (original) +++ python/branches/p3yk/Lib/compiler/pyassem.py Fri Feb 23 20:56:57 2007 @@ -792,6 +792,7 @@ 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, + 'MAKE_BYTES': 0, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, Modified: python/branches/p3yk/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk/Lib/compiler/pycodegen.py Fri Feb 23 20:56:57 2007 @@ -930,6 +930,10 @@ def visitConst(self, node): self.emit('LOAD_CONST', node.value) + + def visitBytes(self, node): + self.emit('LOAD_CONST', node.value) + self.emit('MAKE_BYTES') def visitKeyword(self, node): self.emit('LOAD_CONST', node.name) Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Fri Feb 23 20:56:57 2007 @@ -745,9 +745,11 @@ return eval(lit) def atom_string(self, nodelist): - k = '' - for node in nodelist: + k = self.decode_literal(nodelist[0][1]) + for node in nodelist[1:]: k += self.decode_literal(node[1]) + if isinstance(k, bytes): + return Bytes(str(k), lineno=nodelist[0][2]) return Const(k, lineno=nodelist[0][2]) def atom_ellipsis(self, nodelist): Modified: python/branches/p3yk/Lib/opcode.py ============================================================================== --- python/branches/p3yk/Lib/opcode.py (original) +++ python/branches/p3yk/Lib/opcode.py Fri Feb 23 20:56:57 2007 @@ -111,6 +111,7 @@ def_op('LOAD_LOCALS', 82) def_op('RETURN_VALUE', 83) def_op('IMPORT_STAR', 84) +def_op('MAKE_BYTES', 85) def_op('YIELD_VALUE', 86) def_op('POP_BLOCK', 87) def_op('END_FINALLY', 88) Modified: python/branches/p3yk/Lib/test/test_bytes.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bytes.py (original) +++ python/branches/p3yk/Lib/test/test_bytes.py Fri Feb 23 20:56:57 2007 @@ -403,7 +403,19 @@ self.assertEqual(bytes.join(tuple(lst)), bytes("abc")) self.assertEqual(bytes.join(iter(lst)), bytes("abc")) # XXX more... - + + def test_literal(self): + tests = [ + (b"Wonderful spam", u"Wonderful spam"), + (br"Wonderful spam too", u"Wonderful spam too"), + (b"\xaa\x00\000\200", u"\xaa\x00\000\200"), + (br"\xaa\x00\000\200", ur"\xaa\x00\000\200"), + ] + for b, s in tests: + self.assertEqual(b, bytes(s, 'latin-1')) + for c in range(128, 256): + self.assertRaises(SyntaxError, eval, + 'b"%s"' % chr(c)) # Optimizations: # __iter__? (optimization) Modified: python/branches/p3yk/Lib/test/test_compiler.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compiler.py (original) +++ python/branches/p3yk/Lib/test/test_compiler.py Fri Feb 23 20:56:57 2007 @@ -187,6 +187,30 @@ exec(c, dct) self.assertEquals(dct.get('result'), 1) + def testBytesLiteral(self): + c = compiler.compile("b'foo'", '', 'eval') + b = eval(c) + + c = compiler.compile('def f(b=b"foo"):\n' + ' b[0] += 1\n' + ' return b\n' + 'f(); f(); result = f()\n', + '', + 'exec') + dct = {} + exec(c, dct) + self.assertEquals(dct.get('result'), b"ioo") + + c = compiler.compile('def f():\n' + ' b = b"foo"\n' + ' b[0] += 1\n' + ' return b\n' + 'f(); f(); result = f()\n', + '', + 'exec') + dct = {} + exec(c, dct) + self.assertEquals(dct.get('result'), b"goo") NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard) Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Fri Feb 23 20:56:57 2007 @@ -60,6 +60,7 @@ expr? starargs, expr? kwargs) | Num(object n) -- a number as a PyObject. | Str(string s) -- need to specify raw, unicode, etc? + | Bytes(string s) | Ellipsis -- other literals? bools? Modified: python/branches/p3yk/Parser/tokenizer.c ============================================================================== --- python/branches/p3yk/Parser/tokenizer.c (original) +++ python/branches/p3yk/Parser/tokenizer.c Fri Feb 23 20:56:57 2007 @@ -1244,6 +1244,14 @@ if (c == '"' || c == '\'') goto letter_quote; break; + case 'b': + case 'B': + c = tok_nextc(tok); + if (c == 'r' || c == 'R') + c = tok_nextc(tok); + if (c == '"' || c == '\'') + goto letter_quote; + break; } while (isalnum(c) || c == '_') { c = tok_nextc(tok); Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Fri Feb 23 20:56:57 2007 @@ -2,7 +2,7 @@ /* - __version__ 53731. + __version__ 53866. This module must be committed separately after each AST grammar change; The __version__ number is set to the revision number of the commit @@ -216,6 +216,10 @@ static char *Str_fields[]={ "s", }; +static PyTypeObject *Bytes_type; +static char *Bytes_fields[]={ + "s", +}; static PyTypeObject *Ellipsis_type; static PyTypeObject *Attribute_type; static char *Attribute_fields[]={ @@ -547,6 +551,8 @@ if (!Num_type) return 0; Str_type = make_type("Str", expr_type, Str_fields, 1); if (!Str_type) return 0; + Bytes_type = make_type("Bytes", expr_type, Bytes_fields, 1); + if (!Bytes_type) return 0; Ellipsis_type = make_type("Ellipsis", expr_type, NULL, 0); if (!Ellipsis_type) return 0; Attribute_type = make_type("Attribute", expr_type, Attribute_fields, 3); @@ -1587,6 +1593,27 @@ } expr_ty +Bytes(string s, int lineno, int col_offset, PyArena *arena) +{ + expr_ty p; + if (!s) { + PyErr_SetString(PyExc_ValueError, + "field s is required for Bytes"); + return NULL; + } + p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); + if (!p) { + PyErr_NoMemory(); + return NULL; + } + p->kind = Bytes_kind; + p->v.Bytes.s = s; + p->lineno = lineno; + p->col_offset = col_offset; + return p; +} + +expr_ty Ellipsis(int lineno, int col_offset, PyArena *arena) { expr_ty p; @@ -2550,6 +2577,15 @@ goto failed; Py_DECREF(value); break; + case Bytes_kind: + result = PyType_GenericNew(Bytes_type, NULL, NULL); + if (!result) goto failed; + value = ast2obj_string(o->v.Bytes.s); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "s", value) == -1) + goto failed; + Py_DECREF(value); + break; case Ellipsis_kind: result = PyType_GenericNew(Ellipsis_type, NULL, NULL); if (!result) goto failed; @@ -3089,7 +3125,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__", "53731") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53866") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) @@ -3155,6 +3191,7 @@ if (PyDict_SetItemString(d, "Call", (PyObject*)Call_type) < 0) return; if (PyDict_SetItemString(d, "Num", (PyObject*)Num_type) < 0) return; if (PyDict_SetItemString(d, "Str", (PyObject*)Str_type) < 0) return; + if (PyDict_SetItemString(d, "Bytes", (PyObject*)Bytes_type) < 0) return; if (PyDict_SetItemString(d, "Ellipsis", (PyObject*)Ellipsis_type) < 0) return; if (PyDict_SetItemString(d, "Attribute", (PyObject*)Attribute_type) < Modified: python/branches/p3yk/Python/ast.c ============================================================================== --- python/branches/p3yk/Python/ast.c (original) +++ python/branches/p3yk/Python/ast.c Fri Feb 23 20:56:57 2007 @@ -33,8 +33,9 @@ static expr_ty ast_for_call(struct compiling *, const node *, expr_ty); static PyObject *parsenumber(const char *); -static PyObject *parsestr(const char *s, const char *encoding); -static PyObject *parsestrplus(struct compiling *, const node *n); +static PyObject *parsestr(const node *n, const char *encoding, int *bytesmode); +static PyObject *parsestrplus(struct compiling *, const node *n, + int *bytesmode); #ifndef LINENO #define LINENO(n) ((n)->n_lineno) @@ -1383,6 +1384,7 @@ | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING+ */ node *ch = CHILD(n, 0); + int bytesmode = 0; switch (TYPE(ch)) { case NAME: @@ -1390,12 +1392,15 @@ changed. */ return Name(NEW_IDENTIFIER(ch), Load, LINENO(n), n->n_col_offset, c->c_arena); case STRING: { - PyObject *str = parsestrplus(c, n); + PyObject *str = parsestrplus(c, n, &bytesmode); if (!str) return NULL; PyArena_AddPyObject(c->c_arena, str); - return Str(str, LINENO(n), n->n_col_offset, c->c_arena); + if (bytesmode) + return Bytes(str, LINENO(n), n->n_col_offset, c->c_arena); + else + return Str(str, LINENO(n), n->n_col_offset, c->c_arena); } case NUMBER: { PyObject *pynum = parsenumber(STR(ch)); @@ -3254,9 +3259,10 @@ * parsestr parses it, and returns the decoded Python string object. */ static PyObject * -parsestr(const char *s, const char *encoding) +parsestr(const node *n, const char *encoding, int *bytesmode) { size_t len; + const char *s = STR(n); int quote = Py_CHARMASK(*s); int rawmode = 0; int need_encoding; @@ -3267,6 +3273,10 @@ quote = *++s; unicode = 1; } + if (quote == 'b' || quote == 'B') { + quote = *++s; + *bytesmode = 1; + } if (quote == 'r' || quote == 'R') { quote = *++s; rawmode = 1; @@ -3276,6 +3286,10 @@ PyErr_BadInternalCall(); return NULL; } + if (unicode && *bytesmode) { + ast_error(n, "string cannot be both bytes and unicode"); + return NULL; + } s++; len = strlen(s); if (len > INT_MAX) { @@ -3300,7 +3314,18 @@ return decode_unicode(s, len, rawmode, encoding); } #endif - need_encoding = (encoding != NULL && + if (*bytesmode) { + /* Disallow non-ascii characters (but not escapes) */ + const char *c; + for (c = s; *c; c++) { + if (Py_CHARMASK(*c) >= 0x80) { + ast_error(n, "bytes can only contain ASCII " + "literal characters."); + return NULL; + } + } + } + need_encoding = (!*bytesmode && encoding != NULL && strcmp(encoding, "utf-8") != 0 && strcmp(encoding, "iso-8859-1") != 0); if (rawmode || strchr(s, '\\') == NULL) { @@ -3332,18 +3357,25 @@ * pasting the intermediate results together. */ static PyObject * -parsestrplus(struct compiling *c, const node *n) +parsestrplus(struct compiling *c, const node *n, int *bytesmode) { PyObject *v; int i; REQ(CHILD(n, 0), STRING); - if ((v = parsestr(STR(CHILD(n, 0)), c->c_encoding)) != NULL) { + v = parsestr(CHILD(n, 0), c->c_encoding, bytesmode); + if (v != NULL) { /* String literal concatenation */ for (i = 1; i < NCH(n); i++) { PyObject *s; - s = parsestr(STR(CHILD(n, i)), c->c_encoding); + int subbm = 0; + s = parsestr(CHILD(n, i), c->c_encoding, &subbm); if (s == NULL) goto onError; + if (*bytesmode != subbm) { + ast_error(n, "cannot mix bytes and nonbytes" + "literals"); + goto onError; + } if (PyString_Check(v) && PyString_Check(s)) { PyString_ConcatAndDel(&v, s); if (v == NULL) Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Fri Feb 23 20:56:57 2007 @@ -1885,6 +1885,19 @@ PUSH(x); if (x != NULL) continue; break; + + case MAKE_BYTES: + w = POP(); + if (PyString_Check(w)) + x = PyBytes_FromStringAndSize( + PyString_AS_STRING(w), + PyString_GET_SIZE(w)); + else + x = NULL; + Py_DECREF(w); + PUSH(x); + if (x != NULL) continue; + break; case LOAD_ATTR: w = GETITEM(names, oparg); Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Fri Feb 23 20:56:57 2007 @@ -789,6 +789,8 @@ return 1-oparg; case BUILD_MAP: return 1; + case MAKE_BYTES: + return 0; case LOAD_ATTR: return 0; case COMPARE_OP: @@ -3077,6 +3079,10 @@ case Str_kind: ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts); break; + case Bytes_kind: + ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts); + ADDOP(c, MAKE_BYTES); + break; case Ellipsis_kind: ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts); break; @@ -3426,7 +3432,6 @@ 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. From python-3000-checkins at python.org Fri Feb 23 21:00:13 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Fri, 23 Feb 2007 21:00:13 +0100 (CET) Subject: [Python-3000-checkins] r53873 - python/branches/p3yk/Parser/Python.asdl Message-ID: <20070223200013.A03AB1E4008@bag.python.org> Author: thomas.wouters Date: Fri Feb 23 21:00:10 2007 New Revision: 53873 Modified: python/branches/p3yk/Parser/Python.asdl Log: Touch file to regenerate Python-ast.[ch] Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Fri Feb 23 21:00:10 2007 @@ -111,3 +111,4 @@ -- import name with optional 'as' alias. alias = (identifier name, identifier? asname) } + From python-3000-checkins at python.org Fri Feb 23 21:11:31 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Fri, 23 Feb 2007 21:11:31 +0100 (CET) Subject: [Python-3000-checkins] r53874 - in python/branches/p3yk: Include/Python-ast.h Python/Python-ast.c Message-ID: <20070223201131.6B9491E4008@bag.python.org> Author: thomas.wouters Date: Fri Feb 23 21:11:29 2007 New Revision: 53874 Modified: python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Python/Python-ast.c Log: Prevent regeneration. Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Fri Feb 23 21:11:29 2007 @@ -516,3 +516,4 @@ alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); PyObject* PyAST_mod2obj(mod_ty t); + Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Fri Feb 23 21:11:29 2007 @@ -2,7 +2,7 @@ /* - __version__ 53866. + __version__ 53872. This module must be committed separately after each AST grammar change; The __version__ number is set to the revision number of the commit @@ -3125,7 +3125,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__", "53866") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53872") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) From python-3000-checkins at python.org Fri Feb 23 21:24:26 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Fri, 23 Feb 2007 21:24:26 +0100 (CET) Subject: [Python-3000-checkins] r53875 - in python/branches/p3yk: Lib/test/test_pep352.py Message-ID: <20070223202426.2FC841E400E@bag.python.org> Author: thomas.wouters Date: Fri Feb 23 21:24:22 2007 New Revision: 53875 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Lib/test/test_pep352.py Log: Merged revisions 53859-53874 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53861 | neal.norwitz | 2007-02-23 01:22:39 +0100 (Fri, 23 Feb 2007) | 1 line Fix typo in comment ........ r53864 | brett.cannon | 2007-02-23 15:28:25 +0100 (Fri, 23 Feb 2007) | 3 lines Refactor PEP 352 tests to make it easier in the future to make sure certain things cannot be raised or caught. ........ Modified: python/branches/p3yk/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep352.py (original) +++ python/branches/p3yk/Lib/test/test_pep352.py Fri Feb 23 21:24:22 2007 @@ -113,6 +113,37 @@ """Test usage of exceptions""" + def raise_fails(self, object_): + """Make sure that raising 'object_' triggers a TypeError.""" + try: + raise object_ + except TypeError: + return # What is expected. + self.fail("TypeError expected for raising %s" % type(object_)) + + def catch_fails(self, object_): + """Catching 'object_' should raise a TypeError.""" + try: + try: + raise StandardError + except object_: + pass + except TypeError: + pass + except StandardError: + self.fail("TypeError expected when catching %s" % type(object_)) + + try: + try: + raise StandardError + except (object_,): + pass + except TypeError: + return + except StandardError: + self.fail("TypeError expected when catching %s as specified in a " + "tuple" % type(object_)) + def test_raise_new_style_non_exception(self): # You cannot raise a new-style class that does not inherit from # BaseException; the ability was not possible until BaseException's @@ -120,27 +151,12 @@ # inherit from it. class NewStyleClass(object): pass - try: - raise NewStyleClass - except TypeError: - pass - except: - self.fail("able to raise new-style class") - try: - raise NewStyleClass() - except TypeError: - pass - except: - self.fail("able to raise new-style class instance") + self.raise_fails(NewStyleClass) + self.raise_fails(NewStyleClass()) def test_raise_string(self): # Raising a string raises TypeError. - try: - raise "spam" - except TypeError: - pass - except: - self.fail("was able to raise a string exception") + self.raise_fails("spam") def test_catch_string(self): # Catching a string should trigger a DeprecationWarning. From python-3000-checkins at python.org Sat Feb 24 20:41:39 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 24 Feb 2007 20:41:39 +0100 (CET) Subject: [Python-3000-checkins] r53892 - in python/branches/p3yk: Include/Python-ast.h Lib/test/test_bytes.py Objects/bytesobject.c Python/symtable.c Message-ID: <20070224194139.D10651E4007@bag.python.org> Author: georg.brandl Date: Sat Feb 24 20:41:35 2007 New Revision: 53892 Modified: python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Lib/test/test_bytes.py python/branches/p3yk/Objects/bytesobject.c python/branches/p3yk/Python/symtable.c Log: Make bytes_repr return a string containing a b"" literal. Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Sat Feb 24 20:41:35 2007 @@ -516,4 +516,3 @@ alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); PyObject* PyAST_mod2obj(mod_ty t); - Modified: python/branches/p3yk/Lib/test/test_bytes.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bytes.py (original) +++ python/branches/p3yk/Lib/test/test_bytes.py Sat Feb 24 20:41:35 2007 @@ -69,9 +69,11 @@ self.assertRaises(ValueError, bytes, [10**100]) def test_repr(self): - self.assertEqual(repr(bytes()), "bytes()") - self.assertEqual(repr(bytes([0])), "bytes([0x00])") - self.assertEqual(repr(bytes([0, 1, 254, 255])), "bytes([0x00, 0x01, 0xfe, 0xff])") + self.assertEqual(repr(bytes()), "b''") + self.assertEqual(repr(bytes([0])), "b'\\0'") + self.assertEqual(repr(bytes([0, 1, 254, 255])), "b'\\0\\x01\\xfe\\xff'") + self.assertEqual(repr(bytes('abc')), "b'abc'") + self.assertEqual(repr(bytes("'")), "b'\\''") def test_compare(self): b1 = bytes([1, 2, 3]) Modified: python/branches/p3yk/Objects/bytesobject.c ============================================================================== --- python/branches/p3yk/Objects/bytesobject.c (original) +++ python/branches/p3yk/Objects/bytesobject.c Sat Feb 24 20:41:35 2007 @@ -733,65 +733,63 @@ return -1; } +/* Mostly copied from string_repr, but without the + "smart quote" functionality. */ static PyObject * bytes_repr(PyBytesObject *self) { - PyObject *list; - PyObject *str; - PyObject *result; - int err; - int i; - - if (self->ob_size == 0) - return PyString_FromString("bytes()"); - - list = PyList_New(0); - if (list == NULL) + size_t newsize = 3 + 4 * self->ob_size; + PyObject *v; + if (newsize > PY_SSIZE_T_MAX || newsize / 4 != self->ob_size) { + PyErr_SetString(PyExc_OverflowError, + "bytes object is too large to make repr"); return NULL; - - str = PyString_FromString("bytes(["); - if (str == NULL) - goto error; - - err = PyList_Append(list, str); - Py_DECREF(str); - if (err < 0) - goto error; - - for (i = 0; i < self->ob_size; i++) { - char buffer[20]; - sprintf(buffer, ", 0x%02x", (unsigned char) (self->ob_bytes[i])); - str = PyString_FromString((i == 0) ? buffer+2 : buffer); - if (str == NULL) - goto error; - err = PyList_Append(list, str); - Py_DECREF(str); - if (err < 0) - goto error; } - - str = PyString_FromString("])"); - if (str == NULL) - goto error; - - err = PyList_Append(list, str); - Py_DECREF(str); - if (err < 0) - goto error; - - str = PyString_FromString(""); - if (str == NULL) - goto error; - - result = _PyString_Join(str, list); - Py_DECREF(str); - Py_DECREF(list); - return result; - - error: - /* Error handling when list != NULL */ - Py_DECREF(list); - return NULL; + v = PyString_FromStringAndSize((char *)NULL, newsize); + if (v == NULL) { + return NULL; + } + else { + register Py_ssize_t i; + register char c; + register char *p; + int quote = '\''; + + p = PyString_AS_STRING(v); + *p++ = 'b'; + *p++ = quote; + for (i = 0; i < self->ob_size; i++) { + /* There's at least enough room for a hex escape + and a closing quote. */ + assert(newsize - (p - PyString_AS_STRING(v)) >= 5); + c = self->ob_bytes[i]; + if (c == quote || c == '\\') + *p++ = '\\', *p++ = c; + else if (c == '\t') + *p++ = '\\', *p++ = 't'; + else if (c == '\n') + *p++ = '\\', *p++ = 'n'; + else if (c == '\r') + *p++ = '\\', *p++ = 'r'; + else if (c == 0) + *p++ = '\\', *p++ = '0'; + else if (c < ' ' || c >= 0x7f) { + /* For performance, we don't want to call + PyOS_snprintf here (extra layers of + function call). */ + sprintf(p, "\\x%02x", c & 0xff); + p += 4; + } + else + *p++ = c; + } + assert(newsize - (p - PyString_AS_STRING(v)) >= 1); + *p++ = quote; + *p = '\0'; + _PyString_Resize( + &v, (p - PyString_AS_STRING(v))); + return v; + } } static PyObject * Modified: python/branches/p3yk/Python/symtable.c ============================================================================== --- python/branches/p3yk/Python/symtable.c (original) +++ python/branches/p3yk/Python/symtable.c Sat Feb 24 20:41:35 2007 @@ -1177,7 +1177,8 @@ break; case Num_kind: case Str_kind: - case Ellipsis_kind: + case Bytes_kind: + case Ellipsis_kind: /* Nothing to do here. */ break; /* The following exprs can be assignment targets. */ From brett at python.org Sat Feb 24 22:32:47 2007 From: brett at python.org (Brett Cannon) Date: Sat, 24 Feb 2007 15:32:47 -0600 Subject: [Python-3000-checkins] r53892 - in python/branches/p3yk: Include/Python-ast.h Lib/test/test_bytes.py Objects/bytesobject.c Python/symtable.c In-Reply-To: <20070224194139.D10651E4007@bag.python.org> References: <20070224194139.D10651E4007@bag.python.org> Message-ID: Is this the type of repr we want for a mutable object? I know Guido has said he like repr representations to make it possible to tell inidividual objects apart and that the __str__ representation can mask that to make it easier to read. With the object being mutable it would be very easy to have two objects that look the same under repr. -Brett On 2/24/07, georg.brandl wrote: > Author: georg.brandl > Date: Sat Feb 24 20:41:35 2007 > New Revision: 53892 > > Modified: > python/branches/p3yk/Include/Python-ast.h > python/branches/p3yk/Lib/test/test_bytes.py > python/branches/p3yk/Objects/bytesobject.c > python/branches/p3yk/Python/symtable.c > Log: > Make bytes_repr return a string containing a b"" literal. > > > > Modified: python/branches/p3yk/Include/Python-ast.h > ============================================================================== > --- python/branches/p3yk/Include/Python-ast.h (original) > +++ python/branches/p3yk/Include/Python-ast.h Sat Feb 24 20:41:35 2007 > @@ -516,4 +516,3 @@ > alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); > > PyObject* PyAST_mod2obj(mod_ty t); > - > > Modified: python/branches/p3yk/Lib/test/test_bytes.py > ============================================================================== > --- python/branches/p3yk/Lib/test/test_bytes.py (original) > +++ python/branches/p3yk/Lib/test/test_bytes.py Sat Feb 24 20:41:35 2007 > @@ -69,9 +69,11 @@ > self.assertRaises(ValueError, bytes, [10**100]) > > def test_repr(self): > - self.assertEqual(repr(bytes()), "bytes()") > - self.assertEqual(repr(bytes([0])), "bytes([0x00])") > - self.assertEqual(repr(bytes([0, 1, 254, 255])), "bytes([0x00, 0x01, 0xfe, 0xff])") > + self.assertEqual(repr(bytes()), "b''") > + self.assertEqual(repr(bytes([0])), "b'\\0'") > + self.assertEqual(repr(bytes([0, 1, 254, 255])), "b'\\0\\x01\\xfe\\xff'") > + self.assertEqual(repr(bytes('abc')), "b'abc'") > + self.assertEqual(repr(bytes("'")), "b'\\''") > > def test_compare(self): > b1 = bytes([1, 2, 3]) > > Modified: python/branches/p3yk/Objects/bytesobject.c > ============================================================================== > --- python/branches/p3yk/Objects/bytesobject.c (original) > +++ python/branches/p3yk/Objects/bytesobject.c Sat Feb 24 20:41:35 2007 > @@ -733,65 +733,63 @@ > return -1; > } > > +/* Mostly copied from string_repr, but without the > + "smart quote" functionality. */ > static PyObject * > bytes_repr(PyBytesObject *self) > { > - PyObject *list; > - PyObject *str; > - PyObject *result; > - int err; > - int i; > - > - if (self->ob_size == 0) > - return PyString_FromString("bytes()"); > - > - list = PyList_New(0); > - if (list == NULL) > + size_t newsize = 3 + 4 * self->ob_size; > + PyObject *v; > + if (newsize > PY_SSIZE_T_MAX || newsize / 4 != self->ob_size) { > + PyErr_SetString(PyExc_OverflowError, > + "bytes object is too large to make repr"); > return NULL; > - > - str = PyString_FromString("bytes(["); > - if (str == NULL) > - goto error; > - > - err = PyList_Append(list, str); > - Py_DECREF(str); > - if (err < 0) > - goto error; > - > - for (i = 0; i < self->ob_size; i++) { > - char buffer[20]; > - sprintf(buffer, ", 0x%02x", (unsigned char) (self->ob_bytes[i])); > - str = PyString_FromString((i == 0) ? buffer+2 : buffer); > - if (str == NULL) > - goto error; > - err = PyList_Append(list, str); > - Py_DECREF(str); > - if (err < 0) > - goto error; > } > - > - str = PyString_FromString("])"); > - if (str == NULL) > - goto error; > - > - err = PyList_Append(list, str); > - Py_DECREF(str); > - if (err < 0) > - goto error; > - > - str = PyString_FromString(""); > - if (str == NULL) > - goto error; > - > - result = _PyString_Join(str, list); > - Py_DECREF(str); > - Py_DECREF(list); > - return result; > - > - error: > - /* Error handling when list != NULL */ > - Py_DECREF(list); > - return NULL; > + v = PyString_FromStringAndSize((char *)NULL, newsize); > + if (v == NULL) { > + return NULL; > + } > + else { > + register Py_ssize_t i; > + register char c; > + register char *p; > + int quote = '\''; > + > + p = PyString_AS_STRING(v); > + *p++ = 'b'; > + *p++ = quote; > + for (i = 0; i < self->ob_size; i++) { > + /* There's at least enough room for a hex escape > + and a closing quote. */ > + assert(newsize - (p - PyString_AS_STRING(v)) >= 5); > + c = self->ob_bytes[i]; > + if (c == quote || c == '\\') > + *p++ = '\\', *p++ = c; > + else if (c == '\t') > + *p++ = '\\', *p++ = 't'; > + else if (c == '\n') > + *p++ = '\\', *p++ = 'n'; > + else if (c == '\r') > + *p++ = '\\', *p++ = 'r'; > + else if (c == 0) > + *p++ = '\\', *p++ = '0'; > + else if (c < ' ' || c >= 0x7f) { > + /* For performance, we don't want to call > + PyOS_snprintf here (extra layers of > + function call). */ > + sprintf(p, "\\x%02x", c & 0xff); > + p += 4; > + } > + else > + *p++ = c; > + } > + assert(newsize - (p - PyString_AS_STRING(v)) >= 1); > + *p++ = quote; > + *p = '\0'; > + _PyString_Resize( > + &v, (p - PyString_AS_STRING(v))); > + return v; > + } > } > > static PyObject * > > Modified: python/branches/p3yk/Python/symtable.c > ============================================================================== > --- python/branches/p3yk/Python/symtable.c (original) > +++ python/branches/p3yk/Python/symtable.c Sat Feb 24 20:41:35 2007 > @@ -1177,7 +1177,8 @@ > break; > case Num_kind: > case Str_kind: > - case Ellipsis_kind: > + case Bytes_kind: > + case Ellipsis_kind: > /* Nothing to do here. */ > break; > /* The following exprs can be assignment targets. */ > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > From guido at python.org Sun Feb 25 05:55:07 2007 From: guido at python.org (Guido van Rossum) Date: Sat, 24 Feb 2007 22:55:07 -0600 Subject: [Python-3000-checkins] r53892 - in python/branches/p3yk: Include/Python-ast.h Lib/test/test_bytes.py Objects/bytesobject.c Python/symtable.c In-Reply-To: References: <20070224194139.D10651E4007@bag.python.org> Message-ID: I don't understand this. repr() isn't meant to let you tell individual objects apart, just disambiguate the type. repr(1) should != repr("1"). But repr([]) == repr([]) even if the two lists are not the same object. --Guido On 2/24/07, Brett Cannon wrote: > Is this the type of repr we want for a mutable object? I know Guido > has said he like repr representations to make it possible to tell > inidividual objects apart and that the __str__ representation can mask > that to make it easier to read. > > With the object being mutable it would be very easy to have two > objects that look the same under repr. > > -Brett > > On 2/24/07, georg.brandl wrote: > > Author: georg.brandl > > Date: Sat Feb 24 20:41:35 2007 > > New Revision: 53892 > > > > Modified: > > python/branches/p3yk/Include/Python-ast.h > > python/branches/p3yk/Lib/test/test_bytes.py > > python/branches/p3yk/Objects/bytesobject.c > > python/branches/p3yk/Python/symtable.c > > Log: > > Make bytes_repr return a string containing a b"" literal. > > > > > > > > Modified: python/branches/p3yk/Include/Python-ast.h > > ============================================================================== > > --- python/branches/p3yk/Include/Python-ast.h (original) > > +++ python/branches/p3yk/Include/Python-ast.h Sat Feb 24 20:41:35 2007 > > @@ -516,4 +516,3 @@ > > alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); > > > > PyObject* PyAST_mod2obj(mod_ty t); > > - > > > > Modified: python/branches/p3yk/Lib/test/test_bytes.py > > ============================================================================== > > --- python/branches/p3yk/Lib/test/test_bytes.py (original) > > +++ python/branches/p3yk/Lib/test/test_bytes.py Sat Feb 24 20:41:35 2007 > > @@ -69,9 +69,11 @@ > > self.assertRaises(ValueError, bytes, [10**100]) > > > > def test_repr(self): > > - self.assertEqual(repr(bytes()), "bytes()") > > - self.assertEqual(repr(bytes([0])), "bytes([0x00])") > > - self.assertEqual(repr(bytes([0, 1, 254, 255])), "bytes([0x00, 0x01, 0xfe, 0xff])") > > + self.assertEqual(repr(bytes()), "b''") > > + self.assertEqual(repr(bytes([0])), "b'\\0'") > > + self.assertEqual(repr(bytes([0, 1, 254, 255])), "b'\\0\\x01\\xfe\\xff'") > > + self.assertEqual(repr(bytes('abc')), "b'abc'") > > + self.assertEqual(repr(bytes("'")), "b'\\''") > > > > def test_compare(self): > > b1 = bytes([1, 2, 3]) > > > > Modified: python/branches/p3yk/Objects/bytesobject.c > > ============================================================================== > > --- python/branches/p3yk/Objects/bytesobject.c (original) > > +++ python/branches/p3yk/Objects/bytesobject.c Sat Feb 24 20:41:35 2007 > > @@ -733,65 +733,63 @@ > > return -1; > > } > > > > +/* Mostly copied from string_repr, but without the > > + "smart quote" functionality. */ > > static PyObject * > > bytes_repr(PyBytesObject *self) > > { > > - PyObject *list; > > - PyObject *str; > > - PyObject *result; > > - int err; > > - int i; > > - > > - if (self->ob_size == 0) > > - return PyString_FromString("bytes()"); > > - > > - list = PyList_New(0); > > - if (list == NULL) > > + size_t newsize = 3 + 4 * self->ob_size; > > + PyObject *v; > > + if (newsize > PY_SSIZE_T_MAX || newsize / 4 != self->ob_size) { > > + PyErr_SetString(PyExc_OverflowError, > > + "bytes object is too large to make repr"); > > return NULL; > > - > > - str = PyString_FromString("bytes(["); > > - if (str == NULL) > > - goto error; > > - > > - err = PyList_Append(list, str); > > - Py_DECREF(str); > > - if (err < 0) > > - goto error; > > - > > - for (i = 0; i < self->ob_size; i++) { > > - char buffer[20]; > > - sprintf(buffer, ", 0x%02x", (unsigned char) (self->ob_bytes[i])); > > - str = PyString_FromString((i == 0) ? buffer+2 : buffer); > > - if (str == NULL) > > - goto error; > > - err = PyList_Append(list, str); > > - Py_DECREF(str); > > - if (err < 0) > > - goto error; > > } > > - > > - str = PyString_FromString("])"); > > - if (str == NULL) > > - goto error; > > - > > - err = PyList_Append(list, str); > > - Py_DECREF(str); > > - if (err < 0) > > - goto error; > > - > > - str = PyString_FromString(""); > > - if (str == NULL) > > - goto error; > > - > > - result = _PyString_Join(str, list); > > - Py_DECREF(str); > > - Py_DECREF(list); > > - return result; > > - > > - error: > > - /* Error handling when list != NULL */ > > - Py_DECREF(list); > > - return NULL; > > + v = PyString_FromStringAndSize((char *)NULL, newsize); > > + if (v == NULL) { > > + return NULL; > > + } > > + else { > > + register Py_ssize_t i; > > + register char c; > > + register char *p; > > + int quote = '\''; > > + > > + p = PyString_AS_STRING(v); > > + *p++ = 'b'; > > + *p++ = quote; > > + for (i = 0; i < self->ob_size; i++) { > > + /* There's at least enough room for a hex escape > > + and a closing quote. */ > > + assert(newsize - (p - PyString_AS_STRING(v)) >= 5); > > + c = self->ob_bytes[i]; > > + if (c == quote || c == '\\') > > + *p++ = '\\', *p++ = c; > > + else if (c == '\t') > > + *p++ = '\\', *p++ = 't'; > > + else if (c == '\n') > > + *p++ = '\\', *p++ = 'n'; > > + else if (c == '\r') > > + *p++ = '\\', *p++ = 'r'; > > + else if (c == 0) > > + *p++ = '\\', *p++ = '0'; > > + else if (c < ' ' || c >= 0x7f) { > > + /* For performance, we don't want to call > > + PyOS_snprintf here (extra layers of > > + function call). */ > > + sprintf(p, "\\x%02x", c & 0xff); > > + p += 4; > > + } > > + else > > + *p++ = c; > > + } > > + assert(newsize - (p - PyString_AS_STRING(v)) >= 1); > > + *p++ = quote; > > + *p = '\0'; > > + _PyString_Resize( > > + &v, (p - PyString_AS_STRING(v))); > > + return v; > > + } > > } > > > > static PyObject * > > > > Modified: python/branches/p3yk/Python/symtable.c > > ============================================================================== > > --- python/branches/p3yk/Python/symtable.c (original) > > +++ python/branches/p3yk/Python/symtable.c Sat Feb 24 20:41:35 2007 > > @@ -1177,7 +1177,8 @@ > > break; > > case Num_kind: > > case Str_kind: > > - case Ellipsis_kind: > > + case Bytes_kind: > > + case Ellipsis_kind: > > /* Nothing to do here. */ > > break; > > /* The following exprs can be assignment targets. */ > > _______________________________________________ > > Python-3000-checkins mailing list > > Python-3000-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-3000-checkins > > > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From python-3000-checkins at python.org Sun Feb 25 06:08:29 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 25 Feb 2007 06:08:29 +0100 (CET) Subject: [Python-3000-checkins] r53897 - python/branches/p3yk/Lib/xreload.py Message-ID: <20070225050829.B41851E4006@bag.python.org> Author: guido.van.rossum Date: Sun Feb 25 06:08:26 2007 New Revision: 53897 Added: python/branches/p3yk/Lib/xreload.py (contents, props changed) Log: First draft of a different solution to the reload() problem. Added: python/branches/p3yk/Lib/xreload.py ============================================================================== --- (empty file) +++ python/branches/p3yk/Lib/xreload.py Sun Feb 25 06:08:26 2007 @@ -0,0 +1,136 @@ +"""Alternative to reload(). + +This works by executing the module in a scratch namespace, and then +patching classes, methods and functions. This avoids the need to +patch instances. New objects are copied into the target namespace. +""" + +import imp +import sys +import types + + +def xreload(mod): + """Reload a module in place, updating classes, methods and functions. + + Args: + mod: a module object + + Returns: + The (updated) input object itself. + """ + # Get the module name, e.g. 'foo.bar.whatever' + modname = mod.__name__ + # Get the module namespace (dict) early; this is part of the type check + modns = mod.__dict__ + # Parse it into package name and module name, e.g. 'foo.bar' and 'whatever' + i = modname.rfind(".") + if i >= 0: + pkgname, modname = modname[:i], modname[i+1:] + else: + pkgname = None + # Compute the search path + if pkgname: + # We're not reloading the package, only the module in it + pkg = sys.modules[pkgname] + path = pkg.__path__ # Search inside the package + else: + # Search the top-level module path + pkg = None + path = None # Make find_module() uses the default search path + # Find the module; may raise ImportError + (stream, filename, (suffix, mode, kind)) = imp.find_module(modname, path) + # Turn it into a code object + try: + # Is it Python source code or byte code read from a file? + # XXX Could handle frozen modules, zip-import modules + if kind not in (imp.PY_COMPILED, imp.PY_SOURCE): + # Fall back to built-in reload() + return reload(mod) + if kind == imp.PY_SOURCE: + source = stream.read() + code = compile(source, filename, "exec") + else: + code = marshal.load(stream) + finally: + if stream: + stream.close() + # Execute the code im a temporary namespace; if this fails, no changes + tmpns = {} + exec(code, tmpns) + # Now we get to the hard part + oldnames = set(modns) + newnames = set(tmpns) + # Add newly introduced names + for name in newnames - oldnames: + modns[name] = tmpns[name] + # Delete names that are no longer current + for name in oldnames - newnames - {"__name__"}: + del modns[name] + # Now update the rest in place + for name in oldnames & newnames: + modns[name] = _update(modns[name], tmpns[name]) + # Done! + return mod + + +def _update(oldobj, newobj): + """Update oldobj, if possible in place, with newobj. + + If oldobj is immutable, this simply returns newobj. + + Args: + oldobj: the object to be updated + newobj: the object used as the source for the update + + Returns: + either oldobj, updated in place, or newobj. + """ + if type(oldobj) is not type(newobj): + # Cop-out: if the type changed, give up + return newobj + if hasattr(newobj, "__reload_update__"): + # Provide a hook for updating + return newobj.__reload_update__(oldobj) + if isinstance(newobj, types.ClassType): + return _update_class(oldobj, newobj) + if isinstance(newobj, types.FunctionType): + return _update_function(oldobj, newobj) + if isinstance(newobj, types.MethodType): + return _update_method(oldobj, newobj) + # XXX Support class methods, static methods, other decorators + # Not something we recognize, just give up + return newobj + + +def _update_function(oldfunc, newfunc): + """Update a function object.""" + oldfunc.__doc__ = newfunc.__doc__ + oldfunc.__dict__.update(newfunc.__dict__) + oldfunc.func_code = newfunc.func_code + oldfunc.func_defaults = newfunc.func_defaults + # XXX What else? + return oldfunc + + +def _update_method(oldmeth, newmeth): + """Update a method object.""" + # XXX What if im_func is not a function? + _update_function(oldmeth.im_func, newmeth.im_func) + return oldmeth + + +def _update_class(oldclass, newclass): + """Update a class object.""" + # XXX What about __slots__? + olddict = oldclass.__dict__ + newdict = newclass.__dict__ + oldnames = set(olddict) + newnames = set(newdict) + for name in newnames - oldnames: + setattr(oldclass, name, newdict[name]) + for name in oldnames - newnames: + delattr(oldclass, name) + for name in oldnames & newnames - {"__dict__", "__doc__"}: + setattr(oldclass, name, newdict[name]) + return oldclass From python-3000-checkins at python.org Sun Feb 25 16:02:39 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Sun, 25 Feb 2007 16:02:39 +0100 (CET) Subject: [Python-3000-checkins] r53898 - python/branches/p3yk/Lib/xreload.py Message-ID: <20070225150239.47DEC1E4009@bag.python.org> Author: neal.norwitz Date: Sun Feb 25 16:02:38 2007 New Revision: 53898 Modified: python/branches/p3yk/Lib/xreload.py Log: Fix typo Modified: python/branches/p3yk/Lib/xreload.py ============================================================================== --- python/branches/p3yk/Lib/xreload.py (original) +++ python/branches/p3yk/Lib/xreload.py Sun Feb 25 16:02:38 2007 @@ -55,7 +55,7 @@ finally: if stream: stream.close() - # Execute the code im a temporary namespace; if this fails, no changes + # Execute the code in a temporary namespace; if this fails, no changes tmpns = {} exec(code, tmpns) # Now we get to the hard part From brett at python.org Sun Feb 25 16:07:19 2007 From: brett at python.org (Brett Cannon) Date: Sun, 25 Feb 2007 09:07:19 -0600 Subject: [Python-3000-checkins] r53892 - in python/branches/p3yk: Include/Python-ast.h Lib/test/test_bytes.py Objects/bytesobject.c Python/symtable.c In-Reply-To: References: <20070224194139.D10651E4007@bag.python.org> Message-ID: My misunderstanding. I thought I had heard you say that you really like repr of an object be able to disambiguate between instances. Sorry about the mix-up. -Brett On 2/24/07, Guido van Rossum wrote: > I don't understand this. repr() isn't meant to let you tell individual > objects apart, just disambiguate the type. repr(1) should != > repr("1"). But repr([]) == repr([]) even if the two lists are not the > same object. > > --Guido > > On 2/24/07, Brett Cannon wrote: > > Is this the type of repr we want for a mutable object? I know Guido > > has said he like repr representations to make it possible to tell > > inidividual objects apart and that the __str__ representation can mask > > that to make it easier to read. > > > > With the object being mutable it would be very easy to have two > > objects that look the same under repr. > > > > -Brett > > > > On 2/24/07, georg.brandl wrote: > > > Author: georg.brandl > > > Date: Sat Feb 24 20:41:35 2007 > > > New Revision: 53892 > > > > > > Modified: > > > python/branches/p3yk/Include/Python-ast.h > > > python/branches/p3yk/Lib/test/test_bytes.py > > > python/branches/p3yk/Objects/bytesobject.c > > > python/branches/p3yk/Python/symtable.c > > > Log: > > > Make bytes_repr return a string containing a b"" literal. > > > > > > > > > > > > Modified: python/branches/p3yk/Include/Python-ast.h > > > ============================================================================== > > > --- python/branches/p3yk/Include/Python-ast.h (original) > > > +++ python/branches/p3yk/Include/Python-ast.h Sat Feb 24 20:41:35 2007 > > > @@ -516,4 +516,3 @@ > > > alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); > > > > > > PyObject* PyAST_mod2obj(mod_ty t); > > > - > > > > > > Modified: python/branches/p3yk/Lib/test/test_bytes.py > > > ============================================================================== > > > --- python/branches/p3yk/Lib/test/test_bytes.py (original) > > > +++ python/branches/p3yk/Lib/test/test_bytes.py Sat Feb 24 20:41:35 2007 > > > @@ -69,9 +69,11 @@ > > > self.assertRaises(ValueError, bytes, [10**100]) > > > > > > def test_repr(self): > > > - self.assertEqual(repr(bytes()), "bytes()") > > > - self.assertEqual(repr(bytes([0])), "bytes([0x00])") > > > - self.assertEqual(repr(bytes([0, 1, 254, 255])), "bytes([0x00, 0x01, 0xfe, 0xff])") > > > + self.assertEqual(repr(bytes()), "b''") > > > + self.assertEqual(repr(bytes([0])), "b'\\0'") > > > + self.assertEqual(repr(bytes([0, 1, 254, 255])), "b'\\0\\x01\\xfe\\xff'") > > > + self.assertEqual(repr(bytes('abc')), "b'abc'") > > > + self.assertEqual(repr(bytes("'")), "b'\\''") > > > > > > def test_compare(self): > > > b1 = bytes([1, 2, 3]) > > > > > > Modified: python/branches/p3yk/Objects/bytesobject.c > > > ============================================================================== > > > --- python/branches/p3yk/Objects/bytesobject.c (original) > > > +++ python/branches/p3yk/Objects/bytesobject.c Sat Feb 24 20:41:35 2007 > > > @@ -733,65 +733,63 @@ > > > return -1; > > > } > > > > > > +/* Mostly copied from string_repr, but without the > > > + "smart quote" functionality. */ > > > static PyObject * > > > bytes_repr(PyBytesObject *self) > > > { > > > - PyObject *list; > > > - PyObject *str; > > > - PyObject *result; > > > - int err; > > > - int i; > > > - > > > - if (self->ob_size == 0) > > > - return PyString_FromString("bytes()"); > > > - > > > - list = PyList_New(0); > > > - if (list == NULL) > > > + size_t newsize = 3 + 4 * self->ob_size; > > > + PyObject *v; > > > + if (newsize > PY_SSIZE_T_MAX || newsize / 4 != self->ob_size) { > > > + PyErr_SetString(PyExc_OverflowError, > > > + "bytes object is too large to make repr"); > > > return NULL; > > > - > > > - str = PyString_FromString("bytes(["); > > > - if (str == NULL) > > > - goto error; > > > - > > > - err = PyList_Append(list, str); > > > - Py_DECREF(str); > > > - if (err < 0) > > > - goto error; > > > - > > > - for (i = 0; i < self->ob_size; i++) { > > > - char buffer[20]; > > > - sprintf(buffer, ", 0x%02x", (unsigned char) (self->ob_bytes[i])); > > > - str = PyString_FromString((i == 0) ? buffer+2 : buffer); > > > - if (str == NULL) > > > - goto error; > > > - err = PyList_Append(list, str); > > > - Py_DECREF(str); > > > - if (err < 0) > > > - goto error; > > > } > > > - > > > - str = PyString_FromString("])"); > > > - if (str == NULL) > > > - goto error; > > > - > > > - err = PyList_Append(list, str); > > > - Py_DECREF(str); > > > - if (err < 0) > > > - goto error; > > > - > > > - str = PyString_FromString(""); > > > - if (str == NULL) > > > - goto error; > > > - > > > - result = _PyString_Join(str, list); > > > - Py_DECREF(str); > > > - Py_DECREF(list); > > > - return result; > > > - > > > - error: > > > - /* Error handling when list != NULL */ > > > - Py_DECREF(list); > > > - return NULL; > > > + v = PyString_FromStringAndSize((char *)NULL, newsize); > > > + if (v == NULL) { > > > + return NULL; > > > + } > > > + else { > > > + register Py_ssize_t i; > > > + register char c; > > > + register char *p; > > > + int quote = '\''; > > > + > > > + p = PyString_AS_STRING(v); > > > + *p++ = 'b'; > > > + *p++ = quote; > > > + for (i = 0; i < self->ob_size; i++) { > > > + /* There's at least enough room for a hex escape > > > + and a closing quote. */ > > > + assert(newsize - (p - PyString_AS_STRING(v)) >= 5); > > > + c = self->ob_bytes[i]; > > > + if (c == quote || c == '\\') > > > + *p++ = '\\', *p++ = c; > > > + else if (c == '\t') > > > + *p++ = '\\', *p++ = 't'; > > > + else if (c == '\n') > > > + *p++ = '\\', *p++ = 'n'; > > > + else if (c == '\r') > > > + *p++ = '\\', *p++ = 'r'; > > > + else if (c == 0) > > > + *p++ = '\\', *p++ = '0'; > > > + else if (c < ' ' || c >= 0x7f) { > > > + /* For performance, we don't want to call > > > + PyOS_snprintf here (extra layers of > > > + function call). */ > > > + sprintf(p, "\\x%02x", c & 0xff); > > > + p += 4; > > > + } > > > + else > > > + *p++ = c; > > > + } > > > + assert(newsize - (p - PyString_AS_STRING(v)) >= 1); > > > + *p++ = quote; > > > + *p = '\0'; > > > + _PyString_Resize( > > > + &v, (p - PyString_AS_STRING(v))); > > > + return v; > > > + } > > > } > > > > > > static PyObject * > > > > > > Modified: python/branches/p3yk/Python/symtable.c > > > ============================================================================== > > > --- python/branches/p3yk/Python/symtable.c (original) > > > +++ python/branches/p3yk/Python/symtable.c Sat Feb 24 20:41:35 2007 > > > @@ -1177,7 +1177,8 @@ > > > break; > > > case Num_kind: > > > case Str_kind: > > > - case Ellipsis_kind: > > > + case Bytes_kind: > > > + case Ellipsis_kind: > > > /* Nothing to do here. */ > > > break; > > > /* The following exprs can be assignment targets. */ > > > _______________________________________________ > > > Python-3000-checkins mailing list > > > Python-3000-checkins at python.org > > > http://mail.python.org/mailman/listinfo/python-3000-checkins > > > > > _______________________________________________ > > Python-3000-checkins mailing list > > Python-3000-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-3000-checkins > > > > > -- > --Guido van Rossum (home page: http://www.python.org/~guido/) > From python-3000-checkins at python.org Sun Feb 25 17:19:23 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 25 Feb 2007 17:19:23 +0100 (CET) Subject: [Python-3000-checkins] r53906 - python/branches/p3yk/Lib/xreload.py Message-ID: <20070225161923.4933D1E4007@bag.python.org> Author: guido.van.rossum Date: Sun Feb 25 17:19:20 2007 New Revision: 53906 Modified: python/branches/p3yk/Lib/xreload.py Log: Add support for static and class methods. Modified: python/branches/p3yk/Lib/xreload.py ============================================================================== --- python/branches/p3yk/Lib/xreload.py (original) +++ python/branches/p3yk/Lib/xreload.py Sun Feb 25 17:19:20 2007 @@ -65,6 +65,7 @@ for name in newnames - oldnames: modns[name] = tmpns[name] # Delete names that are no longer current + # XXX What to do about renamed objects? for name in oldnames - newnames - {"__name__"}: del modns[name] # Now update the rest in place @@ -86,6 +87,9 @@ Returns: either oldobj, updated in place, or newobj. """ + if oldobj is newobj: + # Probably something imported + return newobj if type(oldobj) is not type(newobj): # Cop-out: if the type changed, give up return newobj @@ -98,11 +102,18 @@ return _update_function(oldobj, newobj) if isinstance(newobj, types.MethodType): return _update_method(oldobj, newobj) - # XXX Support class methods, static methods, other decorators + if isinstance(newobj, classmethod): + return _update_classmethod(oldobj, newobj) + if isinstance(newobj, staticmethod): + return _update_staticmethod(oldobj, newobj) + # XXX How to support decorators? # Not something we recognize, just give up return newobj +# All of the following functions have the same signature as _update() + + def _update_function(oldfunc, newfunc): """Update a function object.""" oldfunc.__doc__ = newfunc.__doc__ @@ -116,7 +127,7 @@ def _update_method(oldmeth, newmeth): """Update a method object.""" # XXX What if im_func is not a function? - _update_function(oldmeth.im_func, newmeth.im_func) + _update(oldmeth.im_func, newmeth.im_func) return oldmeth @@ -132,5 +143,27 @@ for name in oldnames - newnames: delattr(oldclass, name) for name in oldnames & newnames - {"__dict__", "__doc__"}: - setattr(oldclass, name, newdict[name]) + setattr(oldclass, name, _update(olddict[name], newdict[name])) return oldclass + + +def _update_classmethod(oldcm, newcm): + """Update a classmethod update.""" + # While we can't modify the classmethod object itself (it has no + # mutable attributes), we *can* extract the underlying function + # (by calling __get__(), which returns a method object) and update + # it in-place. We don't have the class available to pass to + # __get__() but any object except None will do. + _update(oldcm.__get__(0), newcm.__get__(0)) + return newcm + + +def _update_staticmethod(oldsm, newsm): + """Update a staticmethod update.""" + # While we can't modify the staticmethod object itself (it has no + # mutable attributes), we *can* extract the underlying function + # (by calling __get__(), which returns it) and update it in-place. + # We don't have the class available to pass to __get__() but any + # object except None will do. + _update(oldsm.__get__(0), newsm.__get__(0)) + return newsm From python-3000-checkins at python.org Sun Feb 25 21:39:16 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Sun, 25 Feb 2007 21:39:16 +0100 (CET) Subject: [Python-3000-checkins] r53912 - in python/branches/p3yk: Doc/lib/libetree.tex Include/dictobject.h Include/listobject.h Include/longobject.h Include/object.h Include/pyerrors.h Include/stringobject.h Include/tupleobject.h Include/unicodeobject.h Objects/dictobject.c Objects/exceptions.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/stringobject.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodeobject.c Message-ID: <20070225203916.516E01E4007@bag.python.org> Author: thomas.wouters Date: Sun Feb 25 21:39:11 2007 New Revision: 53912 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/lib/libetree.tex python/branches/p3yk/Include/dictobject.h python/branches/p3yk/Include/listobject.h python/branches/p3yk/Include/longobject.h python/branches/p3yk/Include/object.h python/branches/p3yk/Include/pyerrors.h python/branches/p3yk/Include/stringobject.h python/branches/p3yk/Include/tupleobject.h python/branches/p3yk/Include/unicodeobject.h python/branches/p3yk/Objects/dictobject.c python/branches/p3yk/Objects/exceptions.c python/branches/p3yk/Objects/intobject.c python/branches/p3yk/Objects/listobject.c python/branches/p3yk/Objects/longobject.c python/branches/p3yk/Objects/stringobject.c python/branches/p3yk/Objects/tupleobject.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/Objects/unicodeobject.c Log: Merged revisions 53875-53911 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53899 | neal.norwitz | 2007-02-25 16:52:27 +0100 (Sun, 25 Feb 2007) | 1 line Add more details when releasing interned strings ........ r53900 | neal.norwitz | 2007-02-25 16:53:36 +0100 (Sun, 25 Feb 2007) | 1 line Whitespace only changes ........ r53901 | jeremy.hylton | 2007-02-25 16:57:45 +0100 (Sun, 25 Feb 2007) | 8 lines Fix crash in exec when unicode filename can't be decoded. I can't think of an easy way to test this behavior. It only occurs when the file system default encoding and the interpreter default encoding are different, such that you can open the file but not decode its name. ........ r53902 | jeremy.hylton | 2007-02-25 17:01:58 +0100 (Sun, 25 Feb 2007) | 2 lines Put declarations before code. ........ r53910 | fred.drake | 2007-02-25 18:56:27 +0100 (Sun, 25 Feb 2007) | 3 lines - SF patch #1657613: add documentation for the Element interface - clean up bogus use of the {datadescni} environment everywhere ........ r53911 | neal.norwitz | 2007-02-25 20:44:48 +0100 (Sun, 25 Feb 2007) | 17 lines Variation of patch # 1624059 to speed up checking if an object is a subclass of some of the common builtin types. Use a bit in tp_flags for each common builtin type. Check the bit to determine if any instance is a subclass of these common types. The check avoids a function call and O(n) search of the base classes. The check is done in the various Py*_Check macros rather than calling PyType_IsSubtype(). All the bits are set in tp_flags when the type is declared in the Objects/*object.c files because PyType_Ready() is not called for all the types. Should PyType_Ready() be called for all types? If so and the change is made, the changes to the Objects/*object.c files can be reverted (remove setting the tp_flags). Objects/typeobject.c would also have to be modified to add conditions for Py*_CheckExact() in addition to each the PyType_IsSubtype check. ........ Modified: python/branches/p3yk/Doc/lib/libetree.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libetree.tex (original) +++ python/branches/p3yk/Doc/lib/libetree.tex Sun Feb 25 21:39:11 2007 @@ -38,10 +38,7 @@ The comment string can be either an 8-bit ASCII string or a Unicode string. \var{text} is a string containing the comment string. - -\begin{datadescni}{Returns:} -An element instance, representing a comment. -\end{datadescni} +Returns an element instance representing a comment. \end{funcdesc} \begin{funcdesc}{dump}{elem} @@ -65,28 +62,19 @@ \var{tag} is the element name. \var{attrib} is an optional dictionary, containing element attributes. \var{extra} contains additional attributes, given as keyword arguments. - -\begin{datadescni}{Returns:} -An element instance. -\end{datadescni} +Returns an element instance. \end{funcdesc} \begin{funcdesc}{fromstring}{text} Parses an XML section from a string constant. Same as XML. \var{text} is a string containing XML data. - -\begin{datadescni}{Returns:} -An Element instance. -\end{datadescni} +Returns an Element instance. \end{funcdesc} \begin{funcdesc}{iselement}{element} Checks if an object appears to be a valid element object. \var{element} is an element instance. - -\begin{datadescni}{Returns:} -A true value if this is an element object. -\end{datadescni} +Returns a true value if this is an element object. \end{funcdesc} \begin{funcdesc}{iterparse}{source\optional{, events}} @@ -95,10 +83,7 @@ \var{source} is a filename or file object containing XML data. \var{events} is a list of events to report back. If omitted, only ``end'' events are reported. - -\begin{datadescni}{Returns:} -A (event, elem) iterator. -\end{datadescni} +Returns an iterator providing \code{(\var{event}, \var{elem})} pairs. \end{funcdesc} \begin{funcdesc}{parse}{source\optional{, parser}} @@ -106,10 +91,7 @@ \var{source} is a filename or file object containing XML data. \var{parser} is an optional parser instance. If not given, the standard XMLTreeBuilder parser is used. - -\begin{datadescni}{Returns:} -An ElementTree instance -\end{datadescni} +Returns an ElementTree instance. \end{funcdesc} \begin{funcdesc}{ProcessingInstruction}{target\optional{, text}} @@ -117,13 +99,11 @@ that will be serialized as an XML processing instruction. \var{target} is a string containing the PI target. \var{text} is a string containing the PI contents, if given. - -\begin{datadescni}{Returns:} -An element instance, representing a PI. -\end{datadescni} +Returns an element instance, representing a processing instruction. \end{funcdesc} -\begin{funcdesc}{SubElement}{parent, tag\optional{, attrib} \optional{, **extra}} +\begin{funcdesc}{SubElement}{parent, tag\optional{, + attrib\optional{, **extra}}} Subelement factory. This function creates an element instance, and appends it to an existing element. @@ -133,10 +113,7 @@ \var{tag} is the subelement name. \var{attrib} is an optional dictionary, containing element attributes. \var{extra} contains additional attributes, given as keyword arguments. - -\begin{datadescni}{Returns:} -An element instance. -\end{datadescni} +Returns an element instance. \end{funcdesc} \begin{funcdesc}{tostring}{element\optional{, encoding}} @@ -144,33 +121,162 @@ subelements. \var{element} is an Element instance. \var{encoding} is the output encoding (default is US-ASCII). - -\begin{datadescni}{Returns:} -An encoded string containing the XML data. -\end{datadescni} +Returns an encoded string containing the XML data. \end{funcdesc} \begin{funcdesc}{XML}{text} Parses an XML section from a string constant. This function can be used to embed ``XML literals'' in Python code. \var{text} is a string containing XML data. - -\begin{datadescni}{Returns:} -An Element instance. -\end{datadescni} +Returns an Element instance. \end{funcdesc} \begin{funcdesc}{XMLID}{text} Parses an XML section from a string constant, and also returns a dictionary which maps from element id:s to elements. \var{text} is a string containing XML data. - -\begin{datadescni}{Returns:} -A tuple containing an Element instance and a dictionary. -\end{datadescni} +Returns a tuple containing an Element instance and a dictionary. \end{funcdesc} +\subsection{The Element Interface\label{elementtree-element-interface}} + +Element objects returned by Element or SubElement have the +following methods and attributes. + +\begin{memberdesc}{tag} +A string identifying what kind of data this element represents +(the element type, in other words). +\end{memberdesc} + +\begin{memberdesc}{text} +The \var{text} attribute can be used to hold additional data +associated with the element. +As the name implies this attribute is usually a string but may be any +application-specific object. +If the element is created from an XML file the attribute will contain +any text found between the element tags. +\end{memberdesc} + +\begin{memberdesc}{tail} +The \var{tail} attribute can be used to hold additional data +associated with the element. +This attribute is usually a string but may be any application-specific object. +If the element is created from an XML file the attribute will contain +any text found after the element's end tag and before the next tag. +\end{memberdesc} + +\begin{memberdesc}{attrib} +A dictionary containing the element's attributes. +Note that while the \var{attrib} value is always a real mutable Python +dictionary, an ElementTree implementation may choose to use another +internal representation, and create the dictionary only if someone +asks for it. To take advantage of such implementations, use the +dictionary methods below whenever possible. +\end{memberdesc} + +The following dictionary-like methods work on the element attributes. + +\begin{methoddesc}{clear}{} +Resets an element. This function removes all subelements, clears +all attributes, and sets the text and tail attributes to None. +\end{methoddesc} + +\begin{methoddesc}{get}{key\optional{, default=None}} +Gets the element attribute named \var{key}. + +Returns the attribute value, or \var{default} if the +attribute was not found. +\end{methoddesc} + +\begin{methoddesc}{items}{} +Returns the element attributes as a sequence of (name, value) pairs. +The attributes are returned in an arbitrary order. +\end{methoddesc} + +\begin{methoddesc}{keys}{} +Returns the elements attribute names as a list. +The names are returned in an arbitrary order. +\end{methoddesc} + +\begin{methoddesc}{set}{key, value} +Set the attribute \var{key} on the element to \var{value}. +\end{methoddesc} + +The following methods work on the element's children (subelements). + +\begin{methoddesc}{append}{subelement} +Adds the element \var{subelement} to the end of this elements internal list +of subelements. +\end{methoddesc} + +\begin{methoddesc}{find}{match} +Finds the first subelement matching \var{match}. +\var{match} may be a tag name or path. +Returns an element instance or \code{None}. +\end{methoddesc} + +\begin{methoddesc}{findall}{match} +Finds all subelements matching \var{match}. +\var{match} may be a tag name or path. +Returns an iterable yielding all matching elements in document order. +\end{methoddesc} + +\begin{methoddesc}{findtext}{condition\optional{, default=None}} +Finds text for the first subelement matching \var{condition}. +\var{condition} may be a tag name or path. +Returns the text content of the first matching element, or +\var{default} if no element was found. Note that if the +matching element has no text content an empty string is returned. +\end{methoddesc} + +\begin{methoddesc}{getchildren}{} +Returns all subelements. The elements are returned in document order. +\end{methoddesc} + +\begin{methoddesc}{getiterator}{\optional{tag=None}} +Creates a tree iterator with the current element as the root. +The iterator iterates over this element and all elements below it +that match the given tag. If tag +is \code{None} or \code{'*'} then all elements are iterated over. +Returns an iterable that provides element objects in document (depth first) +order. +\end{methoddesc} + +\begin{methoddesc}{insert}{index, element} +Inserts a subelement at the given position in this element. +\end{methoddesc} + +\begin{methoddesc}{makeelement}{tag, attrib} +Creates a new element object of the same type as this element. +Do not call this method, use the SubElement factory function instead. +\end{methoddesc} + +\begin{methoddesc}{remove}{subelement} +Removes \var{subelement} from the element. +Unlike the findXXX methods this method compares elements based on +the instance identity, not on tag value or contents. +\end{methoddesc} + +Element objects also support the following sequence type methods for +working with subelements: \method{__delitem__()}, +\method{__getitem__()}, \method{__setitem__()}, \method{__len__()}. + +Caution: Because Element objects do not define a +\method{__nonzero__()} method, elements with no subelements will test +as \code{False}. + +\begin{verbatim} +element = root.find('foo') + +if not element: # careful! + print "element not found, or element has no subelements" + +if element is None: + print "element not found" +\end{verbatim} + + \subsection{ElementTree Objects\label{elementtree-elementtree-objects}} \begin{classdesc}{ElementTree}{\optional{element,} \optional{file}} @@ -193,21 +299,15 @@ Finds the first toplevel element with given tag. Same as getroot().find(path). \var{path} is the element to look for. - -\begin{datadescni}{Returns:} -The first matching element, or None if no element was found. -\end{datadescni} +Returns the first matching element, or \code{None} if no element was found. \end{methoddesc} \begin{methoddesc}{findall}{path} Finds all toplevel elements with the given tag. Same as getroot().findall(path). \var{path} is the element to look for. - -\begin{datadescni}{Returns:} -A list or iterator containing all matching elements, -in section order. -\end{datadescni} +Returns a list or iterator containing all matching elements, +in document order. \end{methoddesc} \begin{methoddesc}{findtext}{path\optional{, default}} @@ -215,31 +315,20 @@ tag. Same as getroot().findtext(path). \var{path} is the toplevel element to look for. \var{default} is the value to return if the element was not found. - -\begin{datadescni}{Returns:} -The text content of the first matching element, or the +Returns the text content of the first matching element, or the default value no element was found. Note that if the element has is found, but has no text content, this method returns an empty string. -\end{datadescni} \end{methoddesc} \begin{methoddesc}{getiterator}{\optional{tag}} -Creates a tree iterator for the root element. The iterator loops +Creates and returns a tree iterator for the root element. The iterator loops over all elements in this tree, in section order. \var{tag} is the tag to look for (default is to return all elements) - -\begin{datadescni}{Returns:} -An iterator. -\end{datadescni} \end{methoddesc} \begin{methoddesc}{getroot}{} -Gets the root element for this tree. - -\begin{datadescni}{Returns:} -An element instance. -\end{datadescni} +Returns the root element for this tree. \end{methoddesc} \begin{methoddesc}{parse}{source\optional{, parser}} @@ -247,10 +336,7 @@ \var{source} is a file name or file object. \var{parser} is an optional parser instance. If not given, the standard XMLTreeBuilder parser is used. - -\begin{datadescni}{Returns:} -The section root element. -\end{datadescni} +Returns the section root element. \end{methoddesc} \begin{methoddesc}{write}{file\optional{, encoding}} @@ -270,10 +356,7 @@ the URI part of a QName. If \var{tag} is given, the first argument is interpreted as an URI, and this argument is interpreted as a local name. - -\begin{datadescni}{Returns:} -An opaque object, representing the QName. -\end{datadescni} +\class{QName} instances are opaque. \end{classdesc} @@ -291,10 +374,7 @@ \begin{methoddesc}{close}{} Flushes the parser buffers, and returns the toplevel documen element. - -\begin{datadescni}{Returns:} -An Element instance. -\end{datadescni} +Returns an Element instance. \end{methoddesc} \begin{methoddesc}{data}{data} @@ -306,20 +386,14 @@ \begin{methoddesc}{end}{tag} Closes the current element. \var{tag} is the element name. - -\begin{datadescni}{Returns:} -The closed element. -\end{datadescni} +Returns the closed element. \end{methoddesc} \begin{methoddesc}{start}{tag, attrs} Opens a new element. \var{tag} is the element name. \var{attrs} is a dictionary containing element attributes. - -\begin{datadescni}{Returns:} -The opened element. -\end{datadescni} +Returns the opened element. \end{methoddesc} @@ -336,10 +410,7 @@ \begin{methoddesc}{close}{} Finishes feeding data to the parser. - -\begin{datadescni}{Returns:} -An element structure. -\end{datadescni} +Returns an element structure. \end{methoddesc} \begin{methoddesc}{doctype}{name, pubid, system} @@ -351,6 +422,5 @@ \begin{methoddesc}{feed}{data} Feeds data to the parser. - \var{data} is encoded data. \end{methoddesc} Modified: python/branches/p3yk/Include/dictobject.h ============================================================================== --- python/branches/p3yk/Include/dictobject.h (original) +++ python/branches/p3yk/Include/dictobject.h Sun Feb 25 21:39:11 2007 @@ -90,7 +90,8 @@ PyAPI_DATA(PyTypeObject) PyDict_Type; -#define PyDict_Check(op) PyObject_TypeCheck(op, &PyDict_Type) +#define PyDict_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_DICT_SUBCLASS) #define PyDict_CheckExact(op) ((op)->ob_type == &PyDict_Type) PyAPI_FUNC(PyObject *) PyDict_New(void); Modified: python/branches/p3yk/Include/listobject.h ============================================================================== --- python/branches/p3yk/Include/listobject.h (original) +++ python/branches/p3yk/Include/listobject.h Sun Feb 25 21:39:11 2007 @@ -40,7 +40,8 @@ PyAPI_DATA(PyTypeObject) PyList_Type; -#define PyList_Check(op) PyObject_TypeCheck(op, &PyList_Type) +#define PyList_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_LIST_SUBCLASS) #define PyList_CheckExact(op) ((op)->ob_type == &PyList_Type) PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size); Modified: python/branches/p3yk/Include/longobject.h ============================================================================== --- python/branches/p3yk/Include/longobject.h (original) +++ python/branches/p3yk/Include/longobject.h Sun Feb 25 21:39:11 2007 @@ -11,7 +11,8 @@ PyAPI_DATA(PyTypeObject) PyLong_Type; -#define PyLong_Check(op) PyObject_TypeCheck(op, &PyLong_Type) +#define PyLong_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_LONG_SUBCLASS) #define PyLong_CheckExact(op) ((op)->ob_type == &PyLong_Type) PyAPI_FUNC(PyObject *) PyLong_FromLong(long); Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Sun Feb 25 21:39:11 2007 @@ -357,7 +357,8 @@ PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */ PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */ -#define PyType_Check(op) PyObject_TypeCheck(op, &PyType_Type) +#define PyType_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_TYPE_SUBCLASS) #define PyType_CheckExact(op) ((op)->ob_type == &PyType_Type) PyAPI_FUNC(int) PyType_Ready(PyTypeObject *); @@ -469,11 +470,23 @@ #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0 #endif +/* These flags are used to determine if a type is a subclass. */ +#define Py_TPFLAGS_INT_SUBCLASS (1L<<23) +#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) +#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25) +#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26) +#define Py_TPFLAGS_STRING_SUBCLASS (1L<<27) +#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28) +#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29) +#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30) +#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31) + #define Py_TPFLAGS_DEFAULT ( \ Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ 0) #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) +#define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) /* Modified: python/branches/p3yk/Include/pyerrors.h ============================================================================== --- python/branches/p3yk/Include/pyerrors.h (original) +++ python/branches/p3yk/Include/pyerrors.h Sun Feb 25 21:39:11 2007 @@ -94,13 +94,12 @@ /* */ -#define PyExceptionClass_Check(x) \ - (PyType_Check((x)) && PyType_IsSubtype( \ - (PyTypeObject*)(x), (PyTypeObject*)PyExc_BaseException)) +#define PyExceptionClass_Check(x) \ + (PyType_Check((x)) && \ + PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) - -#define PyExceptionInstance_Check(x) \ - (PyType_IsSubtype((x)->ob_type, (PyTypeObject*)PyExc_BaseException)) +#define PyExceptionInstance_Check(x) \ + PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) #define PyExceptionClass_Name(x) \ ((char *)(((PyTypeObject*)(x))->tp_name)) Modified: python/branches/p3yk/Include/stringobject.h ============================================================================== --- python/branches/p3yk/Include/stringobject.h (original) +++ python/branches/p3yk/Include/stringobject.h Sun Feb 25 21:39:11 2007 @@ -55,7 +55,8 @@ PyAPI_DATA(PyTypeObject) PyBaseString_Type; PyAPI_DATA(PyTypeObject) PyString_Type; -#define PyString_Check(op) PyObject_TypeCheck(op, &PyString_Type) +#define PyString_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_STRING_SUBCLASS) #define PyString_CheckExact(op) ((op)->ob_type == &PyString_Type) PyAPI_FUNC(PyObject *) PyString_FromStringAndSize(const char *, Py_ssize_t); Modified: python/branches/p3yk/Include/tupleobject.h ============================================================================== --- python/branches/p3yk/Include/tupleobject.h (original) +++ python/branches/p3yk/Include/tupleobject.h Sun Feb 25 21:39:11 2007 @@ -33,7 +33,8 @@ PyAPI_DATA(PyTypeObject) PyTuple_Type; -#define PyTuple_Check(op) PyObject_TypeCheck(op, &PyTuple_Type) +#define PyTuple_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_TUPLE_SUBCLASS) #define PyTuple_CheckExact(op) ((op)->ob_type == &PyTuple_Type) PyAPI_FUNC(PyObject *) PyTuple_New(Py_ssize_t size); Modified: python/branches/p3yk/Include/unicodeobject.h ============================================================================== --- python/branches/p3yk/Include/unicodeobject.h (original) +++ python/branches/p3yk/Include/unicodeobject.h Sun Feb 25 21:39:11 2007 @@ -392,7 +392,8 @@ PyAPI_DATA(PyTypeObject) PyUnicode_Type; -#define PyUnicode_Check(op) PyObject_TypeCheck(op, &PyUnicode_Type) +#define PyUnicode_Check(op) \ + PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_UNICODE_SUBCLASS) #define PyUnicode_CheckExact(op) ((op)->ob_type == &PyUnicode_Type) /* Fast access macros */ Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Sun Feb 25 21:39:11 2007 @@ -2027,7 +2027,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ dictionary_doc, /* tp_doc */ dict_traverse, /* tp_traverse */ dict_tp_clear, /* tp_clear */ Modified: python/branches/p3yk/Objects/exceptions.c ============================================================================== --- python/branches/p3yk/Objects/exceptions.c (original) +++ python/branches/p3yk/Objects/exceptions.c Sun Feb 25 21:39:11 2007 @@ -300,7 +300,8 @@ PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ PyDoc_STR("Common base class for all exceptions"), /* tp_doc */ (traverseproc)BaseException_traverse, /* tp_traverse */ (inquiry)BaseException_clear, /* tp_clear */ Modified: python/branches/p3yk/Objects/intobject.c ============================================================================== --- python/branches/p3yk/Objects/intobject.c (original) +++ python/branches/p3yk/Objects/intobject.c Sun Feb 25 21:39:11 2007 @@ -1115,7 +1115,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */ int_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ Modified: python/branches/p3yk/Objects/listobject.c ============================================================================== --- python/branches/p3yk/Objects/listobject.c (original) +++ python/branches/p3yk/Objects/listobject.c Sun Feb 25 21:39:11 2007 @@ -2683,7 +2683,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ list_doc, /* tp_doc */ (traverseproc)list_traverse, /* tp_traverse */ (inquiry)list_clear, /* tp_clear */ Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Sun Feb 25 21:39:11 2007 @@ -3643,7 +3643,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ long_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ Modified: python/branches/p3yk/Objects/stringobject.c ============================================================================== --- python/branches/p3yk/Objects/stringobject.c (original) +++ python/branches/p3yk/Objects/stringobject.c Sun Feb 25 21:39:11 2007 @@ -1131,8 +1131,7 @@ much time, since Py_NE is rarely used. */ if (a->ob_size == b->ob_size && (a->ob_sval[0] == b->ob_sval[0] - && memcmp(a->ob_sval, b->ob_sval, - a->ob_size) == 0)) { + && memcmp(a->ob_sval, b->ob_sval, a->ob_size) == 0)) { result = Py_True; } else { result = Py_False; @@ -1145,7 +1144,7 @@ c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval); if (c==0) c = memcmp(a->ob_sval, b->ob_sval, min_len); - }else + } else c = 0; if (c == 0) c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; @@ -4018,7 +4017,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &string_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_STRING_SUBCLASS, /* tp_flags */ string_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ @@ -4981,6 +4981,7 @@ PyObject *keys; PyStringObject *s; Py_ssize_t i, n; + Py_ssize_t immortal_size = 0, mortal_size = 0; if (interned == NULL || !PyDict_Check(interned)) return; @@ -4995,8 +4996,9 @@ give them their stolen references back, and then clear and DECREF the interned dict. */ - fprintf(stderr, "releasing interned strings\n"); n = PyList_GET_SIZE(keys); + fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n", + n); for (i = 0; i < n; i++) { s = (PyStringObject *) PyList_GET_ITEM(keys, i); switch (s->ob_sstate) { @@ -5005,15 +5007,20 @@ break; case SSTATE_INTERNED_IMMORTAL: s->ob_refcnt += 1; + immortal_size += s->ob_size; break; case SSTATE_INTERNED_MORTAL: s->ob_refcnt += 2; + mortal_size += s->ob_size; break; default: Py_FatalError("Inconsistent interned string state."); } s->ob_sstate = SSTATE_NOT_INTERNED; } + fprintf(stderr, "total size of all interned strings: " + "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d " + "mortal/immortal\n", mortal_size, immortal_size); Py_DECREF(keys); PyDict_Clear(interned); Py_DECREF(interned); Modified: python/branches/p3yk/Objects/tupleobject.c ============================================================================== --- python/branches/p3yk/Objects/tupleobject.c (original) +++ python/branches/p3yk/Objects/tupleobject.c Sun Feb 25 21:39:11 2007 @@ -669,7 +669,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ tuple_doc, /* tp_doc */ (traverseproc)tupletraverse, /* tp_traverse */ 0, /* tp_clear */ Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Sun Feb 25 21:39:11 2007 @@ -2205,7 +2205,7 @@ (setattrofunc)type_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ type_doc, /* tp_doc */ (traverseproc)type_traverse, /* tp_traverse */ (inquiry)type_clear, /* tp_clear */ @@ -2874,6 +2874,24 @@ COPYVAL(tp_itemsize); COPYVAL(tp_weaklistoffset); COPYVAL(tp_dictoffset); + + /* Setup fast subclass flags */ + if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) + type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; + else if (PyType_IsSubtype(base, &PyType_Type)) + type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyLong_Type)) + type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; + else if (PyType_IsSubtype(base, &PyString_Type)) + type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS; + else if (PyType_IsSubtype(base, &PyUnicode_Type)) + type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyTuple_Type)) + type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyList_Type)) + type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; + else if (PyType_IsSubtype(base, &PyDict_Type)) + type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; } /* Map rich comparison operators to their __xx__ namesakes */ Modified: python/branches/p3yk/Objects/unicodeobject.c ============================================================================== --- python/branches/p3yk/Objects/unicodeobject.c (original) +++ python/branches/p3yk/Objects/unicodeobject.c Sun Feb 25 21:39:11 2007 @@ -7971,7 +7971,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &unicode_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */ unicode_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ From python-3000-checkins at python.org Sun Feb 25 21:56:12 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Sun, 25 Feb 2007 21:56:12 +0100 (CET) Subject: [Python-3000-checkins] r53913 - in python/branches/p3yk: Doc/lib/libdis.tex Doc/lib/libinspect.tex Doc/lib/libstdtypes.tex Doc/ref/ref3.tex Lib/Bastion.py Lib/dis.py Lib/doctest.py Lib/idlelib/CallTips.py Lib/inspect.py Lib/pdb.py Lib/test/test_code.py Lib/test/test_compile.py Lib/test/test_compiler.py Lib/test/test_copy.py Lib/test/test_decorators.py Lib/test/test_dis.py Lib/test/test_extcall.py Lib/test/test_funcattrs.py Lib/test/test_grammar.py Lib/test/test_hotshot.py Lib/test/test_inspect.py Lib/test/test_keywordonlyarg.py Lib/test/test_marshal.py Lib/test/test_new.py Lib/test/test_profilehooks.py Lib/test/test_pyclbr.py Lib/test/test_scope.py Lib/test/test_struct.py Lib/test/test_support.py Lib/test/test_sys.py Lib/test/test_trace.py Lib/test/test_univnewlines.py Lib/test/test_urllib.py Lib/trace.py Lib/types.py Lib/xreload.py Objects/funcobject.c Message-ID: <20070225205612.88A5D1E4011@bag.python.org> Author: neal.norwitz Date: Sun Feb 25 21:55:47 2007 New Revision: 53913 Modified: python/branches/p3yk/Doc/lib/libdis.tex python/branches/p3yk/Doc/lib/libinspect.tex python/branches/p3yk/Doc/lib/libstdtypes.tex python/branches/p3yk/Doc/ref/ref3.tex python/branches/p3yk/Lib/Bastion.py python/branches/p3yk/Lib/dis.py python/branches/p3yk/Lib/doctest.py python/branches/p3yk/Lib/idlelib/CallTips.py python/branches/p3yk/Lib/inspect.py python/branches/p3yk/Lib/pdb.py python/branches/p3yk/Lib/test/test_code.py python/branches/p3yk/Lib/test/test_compile.py python/branches/p3yk/Lib/test/test_compiler.py python/branches/p3yk/Lib/test/test_copy.py python/branches/p3yk/Lib/test/test_decorators.py python/branches/p3yk/Lib/test/test_dis.py python/branches/p3yk/Lib/test/test_extcall.py python/branches/p3yk/Lib/test/test_funcattrs.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_hotshot.py python/branches/p3yk/Lib/test/test_inspect.py python/branches/p3yk/Lib/test/test_keywordonlyarg.py python/branches/p3yk/Lib/test/test_marshal.py python/branches/p3yk/Lib/test/test_new.py python/branches/p3yk/Lib/test/test_profilehooks.py python/branches/p3yk/Lib/test/test_pyclbr.py python/branches/p3yk/Lib/test/test_scope.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_support.py python/branches/p3yk/Lib/test/test_sys.py python/branches/p3yk/Lib/test/test_trace.py python/branches/p3yk/Lib/test/test_univnewlines.py python/branches/p3yk/Lib/test/test_urllib.py python/branches/p3yk/Lib/trace.py python/branches/p3yk/Lib/types.py python/branches/p3yk/Lib/xreload.py python/branches/p3yk/Objects/funcobject.c Log: Change all the function attributes from func_* -> __*__. This gets rid of func_name, func_dict and func_doc as they already exist as __name__, __dict__ and __doc__. Modified: python/branches/p3yk/Doc/lib/libdis.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libdis.tex (original) +++ python/branches/p3yk/Doc/lib/libdis.tex Sun Feb 25 21:55:47 2007 @@ -622,7 +622,7 @@ \end{opcodedesc} \begin{opcodedesc}{MAKE_CLOSURE}{argc} -Creates a new function object, sets its \var{func_closure} slot, and +Creates a new function object, sets its \var{__closure__} slot, and pushes it on the stack. TOS is the code associated with the function. If the code object has N free variables, the next N items on the stack are the cells for these variables. The function also has \var{argc} Modified: python/branches/p3yk/Doc/lib/libinspect.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libinspect.tex (original) +++ python/branches/p3yk/Doc/lib/libinspect.tex Sun Feb 25 21:55:47 2007 @@ -45,11 +45,9 @@ \hline \lineiv{function}{__doc__}{documentation string}{} \lineiv{}{__name__}{name with which this function was defined}{} - \lineiv{}{func_code}{code object containing compiled function bytecode}{} - \lineiv{}{func_defaults}{tuple of any default values for arguments}{} - \lineiv{}{func_doc}{(same as __doc__)}{} - \lineiv{}{func_globals}{global namespace in which this function was defined}{} - \lineiv{}{func_name}{(same as __name__)}{} + \lineiv{}{__code__}{code object containing compiled function bytecode}{} + \lineiv{}{__defaults__}{tuple of any default values for arguments}{} + \lineiv{}{__globals__}{global namespace in which this function was defined}{} \hline \lineiv{traceback}{tb_frame}{frame object at this level}{} \lineiv{}{tb_lasti}{index of last attempted instruction in bytecode}{} Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk/Doc/lib/libstdtypes.tex Sun Feb 25 21:55:47 2007 @@ -1964,10 +1964,10 @@ They differ from function objects because they don't contain a reference to their global execution environment. Code objects are returned by the built-in \function{compile()} function and can be -extracted from function objects through their \member{func_code} +extracted from function objects through their \member{__code__} attribute. \bifuncindex{compile} -\withsubitem{(function object attribute)}{\ttindex{func_code}} +\withsubitem{(function object attribute)}{\ttindex{__code__}} A code object can be executed or evaluated by passing it (instead of a source string) to the \function{exec()} or \function{eval()} Modified: python/branches/p3yk/Doc/ref/ref3.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref3.tex (original) +++ python/branches/p3yk/Doc/ref/ref3.tex Sun Feb 25 21:55:47 2007 @@ -473,42 +473,42 @@ Special attributes: \begin{tableiii}{lll}{member}{Attribute}{Meaning}{} - \lineiii{func_doc}{The function's documentation string, or + \lineiii{__doc__}{The function's documentation string, or \code{None} if unavailable}{Writable} - \lineiii{__doc__}{Another way of spelling - \member{func_doc}}{Writable} - - \lineiii{func_name}{The function's name}{Writable} - - \lineiii{__name__}{Another way of spelling - \member{func_name}}{Writable} + \lineiii{__name__}{The function's name}{Writable} \lineiii{__module__}{The name of the module the function was defined in, or \code{None} if unavailable.}{Writable} - \lineiii{func_defaults}{A tuple containing default argument values + \lineiii{__defaults__}{A tuple containing default argument values for those arguments that have defaults, or \code{None} if no arguments have a default value}{Writable} - \lineiii{func_code}{The code object representing the compiled + \lineiii{__code__}{The code object representing the compiled function body.}{Writable} - \lineiii{func_globals}{A reference to the dictionary that holds the + \lineiii{__globals__}{A reference to the dictionary that holds the function's global variables --- the global namespace of the module in which the function was defined.}{Read-only} - \lineiii{func_dict}{The namespace supporting arbitrary function + \lineiii{__dict__}{The namespace supporting arbitrary function attributes.}{Writable} - \lineiii{func_closure}{\code{None} or a tuple of cells that contain + \lineiii{__closure__}{\code{None} or a tuple of cells that contain bindings for the function's free variables.}{Read-only} + + \lineiii{__annotations__}{A dict containing annotations of parameters.} + {Writable} + + \lineiii{__kwdefaults__}{A dict containing defaults for keyword-only + parameters.}{Writable} \end{tableiii} Most of the attributes labelled ``Writable'' check the type of the assigned value. -\versionchanged[\code{func_name} is now writable]{2.4} +\versionchanged[\code{__name__} is now writable]{2.4} Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to @@ -521,16 +521,16 @@ from its code object; see the description of internal types below. \withsubitem{(function attribute)}{ - \ttindex{func_doc} \ttindex{__doc__} \ttindex{__name__} \ttindex{__module__} \ttindex{__dict__} - \ttindex{func_defaults} - \ttindex{func_closure} - \ttindex{func_code} - \ttindex{func_globals} - \ttindex{func_dict}} + \ttindex{__defaults__} + \ttindex{__closure__} + \ttindex{__code__} + \ttindex{__globals__} + \ttindex{__annotations__} + \ttindex{__kwdefaults__} \indexii{global}{namespace} \item[User-defined methods] @@ -700,7 +700,7 @@ section~\ref{import}, ``The \keyword{import} statement'').% \stindex{import}\obindex{module} A module object has a namespace implemented by a dictionary object -(this is the dictionary referenced by the func_globals attribute of +(this is the dictionary referenced by the __globals__ attribute of functions defined in the module). Attribute references are translated to lookups in this dictionary, e.g., \code{m.x} is equivalent to \code{m.__dict__["x"]}. Modified: python/branches/p3yk/Lib/Bastion.py ============================================================================== --- python/branches/p3yk/Lib/Bastion.py (original) +++ python/branches/p3yk/Lib/Bastion.py Sun Feb 25 21:55:47 2007 @@ -158,7 +158,7 @@ else: print "accessible" try: - print "b._get_.func_defaults =", map(type, b._get_.func_defaults), + print "b._get_.__defaults__ =", map(type, b._get_.__defaults__), except: print "inaccessible" else: Modified: python/branches/p3yk/Lib/dis.py ============================================================================== --- python/branches/p3yk/Lib/dis.py (original) +++ python/branches/p3yk/Lib/dis.py Sun Feb 25 21:55:47 2007 @@ -20,8 +20,8 @@ return if hasattr(x, 'im_func'): x = x.im_func - if hasattr(x, 'func_code'): - x = x.func_code + if hasattr(x, '__code__'): + x = x.__code__ if hasattr(x, '__dict__'): items = x.__dict__.items() items.sort() Modified: python/branches/p3yk/Lib/doctest.py ============================================================================== --- python/branches/p3yk/Lib/doctest.py (original) +++ python/branches/p3yk/Lib/doctest.py Sun Feb 25 21:55:47 2007 @@ -831,7 +831,7 @@ if module is None: return True elif inspect.isfunction(object): - return module.__dict__ is object.func_globals + return module.__dict__ is object.__globals__ elif inspect.isclass(object): return module.__name__ == object.__module__ elif inspect.getmodule(object) is not None: @@ -969,7 +969,7 @@ # Find the line number for functions & methods. if inspect.ismethod(obj): obj = obj.im_func - if inspect.isfunction(obj): obj = obj.func_code + if inspect.isfunction(obj): obj = obj.__code__ if inspect.istraceback(obj): obj = obj.tb_frame if inspect.isframe(obj): obj = obj.f_code if inspect.iscode(obj): Modified: python/branches/p3yk/Lib/idlelib/CallTips.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/CallTips.py (original) +++ python/branches/p3yk/Lib/idlelib/CallTips.py Sun Feb 25 21:55:47 2007 @@ -147,15 +147,15 @@ fob = ob # Try to build one for Python defined functions if type(fob) in [types.FunctionType, types.LambdaType]: - argcount = fob.func_code.co_argcount - real_args = fob.func_code.co_varnames[arg_offset:argcount] - defaults = fob.func_defaults or [] + argcount = fob.__code__.co_argcount + real_args = fob.__code__.co_varnames[arg_offset:argcount] + defaults = fob.__defaults__ or [] defaults = list(map(lambda name: "=%s" % repr(name), defaults)) defaults = [""] * (len(real_args) - len(defaults)) + defaults items = map(lambda arg, dflt: arg + dflt, real_args, defaults) - if fob.func_code.co_flags & 0x4: + if fob.__code__.co_flags & 0x4: items.append("...") - if fob.func_code.co_flags & 0x8: + if fob.__code__.co_flags & 0x8: items.append("***") arg_text = ", ".join(items) arg_text = "(%s)" % re.sub("\.\d+", "", arg_text) Modified: python/branches/p3yk/Lib/inspect.py ============================================================================== --- python/branches/p3yk/Lib/inspect.py (original) +++ python/branches/p3yk/Lib/inspect.py Sun Feb 25 21:55:47 2007 @@ -2,7 +2,7 @@ """Get useful information from live Python objects. This module encapsulates the interface provided by the internal special -attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion. +attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion. It also provides some help for examining source code and class layout. Here are some of the useful functions provided by this module: @@ -129,11 +129,11 @@ Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined - func_code code object containing compiled function bytecode - func_defaults tuple of any default values for arguments - func_doc (same as __doc__) - func_globals global namespace in which this function was defined - func_name (same as __name__)""" + __code__ code object containing compiled function bytecode + __defaults__ tuple of any default values for arguments + __globals__ global namespace in which this function was defined + __annotations__ dict of parameter annotations + __kwdefaults__ dict of keyword only parameters with defaults""" return isinstance(object, types.FunctionType) def istraceback(object): @@ -353,7 +353,7 @@ if ismethod(object): object = object.im_func if isfunction(object): - object = object.func_code + object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): @@ -496,7 +496,7 @@ if ismethod(object): object = object.im_func if isfunction(object): - object = object.func_code + object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): @@ -741,8 +741,8 @@ func = func.im_func if not isfunction(func): raise TypeError('arg is not a Python function') - args, varargs, varkw = getargs(func.func_code) - return args, varargs, varkw, func.func_defaults + args, varargs, varkw = getargs(func.__code__) + return args, varargs, varkw, func.__defaults__ def getargvalues(frame): """Get information about arguments passed into a particular frame. Modified: python/branches/p3yk/Lib/pdb.py ============================================================================== --- python/branches/p3yk/Lib/pdb.py (original) +++ python/branches/p3yk/Lib/pdb.py Sun Feb 25 21:55:47 2007 @@ -262,7 +262,7 @@ func = getattr(self, 'do_' + cmd) except AttributeError: func = self.default - if func.func_name in self.commands_resuming : # one of the resuming commands. + if func.__name__ in self.commands_resuming : # one of the resuming commands. self.commands_doprompt[self.commands_bnum] = False self.cmdqueue = [] return 1 @@ -347,7 +347,7 @@ try: if hasattr(func, 'im_func'): func = func.im_func - code = func.func_code + code = func.__code__ #use co_name to identify the bkpt (function names #could be aliased, but co_name is invariant) funcname = code.co_name @@ -759,13 +759,13 @@ return code = None # Is it a function? - try: code = value.func_code + try: code = value.__code__ except: pass if code: print('Function', code.co_name, file=self.stdout) return # Is it an instance method? - try: code = value.im_func.func_code + try: code = value.im_func.__code__ except: pass if code: print('Method', code.co_name, file=self.stdout) Modified: python/branches/p3yk/Lib/test/test_code.py ============================================================================== --- python/branches/p3yk/Lib/test/test_code.py (original) +++ python/branches/p3yk/Lib/test/test_code.py Sun Feb 25 21:55:47 2007 @@ -6,7 +6,7 @@ ... return g ... ->>> dump(f.func_code) +>>> dump(f.__code__) name: f argcount: 1 kwonlyargcount: 0 @@ -18,7 +18,7 @@ flags: 3 consts: ('None', '') ->>> dump(f(4).func_code) +>>> dump(f(4).__code__) name: g argcount: 1 kwonlyargcount: 0 @@ -37,7 +37,7 @@ ... return c ... ->>> dump(h.func_code) +>>> dump(h.__code__) name: h argcount: 2 kwonlyargcount: 0 @@ -54,7 +54,7 @@ ... print(obj.attr2) ... print(obj.attr3) ->>> dump(attrs.func_code) +>>> dump(attrs.__code__) name: attrs argcount: 1 kwonlyargcount: 0 @@ -72,7 +72,7 @@ ... 53 ... 0x53 ->>> dump(optimize_away.func_code) +>>> dump(optimize_away.__code__) name: optimize_away argcount: 0 kwonlyargcount: 0 @@ -88,7 +88,7 @@ ... return a,b,k1 ... ->>> dump(keywordonly_args.func_code) +>>> dump(keywordonly_args.__code__) name: keywordonly_args argcount: 2 kwonlyargcount: 1 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 Sun Feb 25 21:55:47 2007 @@ -235,7 +235,7 @@ g = +9223372036854775807 # 1 << 63 - 1 h = -9223372036854775807 # 1 << 63 - 1 - for variable in self.test_32_63_bit_values.func_code.co_consts: + for variable in self.test_32_63_bit_values.__code__.co_consts: if variable is not None: self.assertTrue(isinstance(variable, int)) @@ -315,7 +315,7 @@ f2 = lambda x=2: x return f1, f2 f1, f2 = f() - self.assertNotEqual(id(f1.func_code), id(f2.func_code)) + self.assertNotEqual(id(f1.__code__), id(f2.__code__)) def test_unicode_encoding(self): code = u"# -*- coding: utf-8 -*-\npass\n" Modified: python/branches/p3yk/Lib/test/test_compiler.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compiler.py (original) +++ python/branches/p3yk/Lib/test/test_compiler.py Sun Feb 25 21:55:47 2007 @@ -160,7 +160,7 @@ c = compiler.compile(sourcecode, '', 'exec') dct = {} exec(c, dct) - self.assertEquals(dct['f'].func_annotations, expected) + self.assertEquals(dct['f'].__annotations__, expected) def testWith(self): # SF bug 1638243 Modified: python/branches/p3yk/Lib/test/test_copy.py ============================================================================== --- python/branches/p3yk/Lib/test/test_copy.py (original) +++ python/branches/p3yk/Lib/test/test_copy.py Sun Feb 25 21:55:47 2007 @@ -83,7 +83,7 @@ def f(): pass tests = [None, 42, 2**100, 3.14, True, False, 1j, - "hello", u"hello\u1234", f.func_code, + "hello", u"hello\u1234", f.__code__, NewStyle, xrange(10), Classic, max] for x in tests: self.assert_(copy.copy(x) is x, repr(x)) @@ -256,7 +256,7 @@ def f(): pass tests = [None, 42, 2**100, 3.14, True, False, 1j, - "hello", u"hello\u1234", f.func_code, + "hello", u"hello\u1234", f.__code__, NewStyle, xrange(10), Classic, max] for x in tests: self.assert_(copy.deepcopy(x) is x, repr(x)) Modified: python/branches/p3yk/Lib/test/test_decorators.py ============================================================================== --- python/branches/p3yk/Lib/test/test_decorators.py (original) +++ python/branches/p3yk/Lib/test/test_decorators.py Sun Feb 25 21:55:47 2007 @@ -27,7 +27,7 @@ def dbcheck(exprstr, globals=None, locals=None): "Decorator to implement debugging assertions" def decorate(func): - expr = compile(exprstr, "dbcheck-%s" % func.func_name, "eval") + expr = compile(exprstr, "dbcheck-%s" % func.__name__, "eval") def check(*args, **kwds): if not eval(expr, globals, locals): raise DbcheckError(exprstr, func, args, kwds) @@ -40,12 +40,12 @@ def countcalls(counts): "Decorator to count calls to a function" def decorate(func): - func_name = func.func_name + func_name = func.__name__ counts[func_name] = 0 def call(*args, **kwds): counts[func_name] += 1 return func(*args, **kwds) - call.func_name = func_name + call.__name__ = func_name return call return decorate @@ -63,7 +63,7 @@ except TypeError: # Unhashable argument return func(*args) - call.func_name = func.func_name + call.__name__ = func.__name__ return call # ----------------------------------------------- @@ -131,7 +131,7 @@ @countcalls(counts) def double(x): return x * 2 - self.assertEqual(double.func_name, 'double') + self.assertEqual(double.__name__, 'double') self.assertEqual(counts, dict(double=0)) Modified: python/branches/p3yk/Lib/test/test_dis.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dis.py (original) +++ python/branches/p3yk/Lib/test/test_dis.py Sun Feb 25 21:55:47 2007 @@ -19,8 +19,8 @@ %-4d 10 LOAD_CONST 1 (1) 13 RETURN_VALUE -"""%(_f.func_code.co_firstlineno + 1, - _f.func_code.co_firstlineno + 2) +"""%(_f.__code__.co_firstlineno + 1, + _f.__code__.co_firstlineno + 2) def bug708901(): @@ -43,9 +43,9 @@ >> 25 POP_BLOCK >> 26 LOAD_CONST 0 (None) 29 RETURN_VALUE -"""%(bug708901.func_code.co_firstlineno + 1, - bug708901.func_code.co_firstlineno + 2, - bug708901.func_code.co_firstlineno + 3) +"""%(bug708901.__code__.co_firstlineno + 1, + bug708901.__code__.co_firstlineno + 2, + bug708901.__code__.co_firstlineno + 3) def bug1333982(x=[]): @@ -78,9 +78,9 @@ %-4d 48 LOAD_CONST 0 (None) 51 RETURN_VALUE -"""%(bug1333982.func_code.co_firstlineno + 1, - bug1333982.func_code.co_firstlineno + 2, - bug1333982.func_code.co_firstlineno + 3) +"""%(bug1333982.__code__.co_firstlineno + 1, + bug1333982.__code__.co_firstlineno + 2, + bug1333982.__code__.co_firstlineno + 3) _BIG_LINENO_FORMAT = """\ %3d 0 LOAD_GLOBAL 0 (spam) Modified: python/branches/p3yk/Lib/test/test_extcall.py ============================================================================== --- python/branches/p3yk/Lib/test/test_extcall.py (original) +++ python/branches/p3yk/Lib/test/test_extcall.py Sun Feb 25 21:55:47 2007 @@ -274,6 +274,6 @@ for kwargs in ['', 'a', 'd', 'ad', 'abde']: kwdict = {} for k in kwargs: kwdict[k] = k + k - print(func.func_name, args, sortdict(kwdict), '->', end=' ') + print(func.__name__, args, sortdict(kwdict), '->', end=' ') try: func(*args, **kwdict) except TypeError as err: print(err) Modified: python/branches/p3yk/Lib/test/test_funcattrs.py ============================================================================== --- python/branches/p3yk/Lib/test/test_funcattrs.py (original) +++ python/branches/p3yk/Lib/test/test_funcattrs.py Sun Feb 25 21:55:47 2007 @@ -47,7 +47,7 @@ d = {'hello': 'world'} b.__dict__ = d -if b.func_dict is not d: +if b.__dict__ is not d: raise TestFailed, 'func.__dict__ assignment to dictionary failed' if b.hello != 'world': raise TestFailed, 'attribute after func.__dict__ assignment failed' @@ -179,12 +179,12 @@ else: raise TestFailed try: - del another.func_dict + del another.__dict__ except TypeError: pass else: raise TestFailed try: - another.func_dict = None + another.__dict__ = None except TypeError: pass else: raise TestFailed @@ -195,7 +195,7 @@ # This isn't specifically related to function attributes, but it does test a # core dump regression in funcobject.c -del another.func_defaults +del another.__defaults__ def foo(): pass @@ -212,7 +212,7 @@ d={} d[foo] = 1 -foo.func_code = temp.func_code +foo.__code__ = temp.__code__ d[foo] @@ -236,45 +236,31 @@ def test_func_closure(): a = 12 def f(): print(a) - c = f.func_closure + c = f.__closure__ verify(isinstance(c, tuple)) verify(len(c) == 1) verify(c[0].__class__.__name__ == "cell") # don't have a type object handy - cantset(f, "func_closure", c) + cantset(f, "__closure__", c) def test_func_doc(): def f(): pass verify(f.__doc__ is None) - verify(f.func_doc is None) f.__doc__ = "hello" verify(f.__doc__ == "hello") - verify(f.func_doc == "hello") del f.__doc__ verify(f.__doc__ is None) - verify(f.func_doc is None) - f.func_doc = "world" - verify(f.__doc__ == "world") - verify(f.func_doc == "world") - del f.func_doc - verify(f.func_doc is None) - verify(f.__doc__ is None) def test_func_globals(): def f(): pass - verify(f.func_globals is globals()) - cantset(f, "func_globals", globals()) + verify(f.__globals__ is globals()) + cantset(f, "__globals__", globals()) def test_func_name(): def f(): pass verify(f.__name__ == "f") - verify(f.func_name == "f") f.__name__ = "g" verify(f.__name__ == "g") - verify(f.func_name == "g") - f.func_name = "h" - verify(f.__name__ == "h") - verify(f.func_name == "h") - cantset(f, "func_globals", 1) + cantset(f, "__globals__", 1) cantset(f, "__name__", 1) # test that you can access func.__name__ in restricted mode s = """def f(): pass\nf.__name__""" @@ -288,25 +274,25 @@ def f1(): print(a) def g1(): print(b) def f2(): print(a, b) - verify(type(f.func_code) is types.CodeType) - f.func_code = g.func_code - cantset(f, "func_code", None) + verify(type(f.__code__) is types.CodeType) + f.__code__ = g.__code__ + cantset(f, "__code__", None) # can't change the number of free vars - cantset(f, "func_code", f1.func_code, exception=ValueError) - cantset(f1, "func_code", f.func_code, exception=ValueError) - cantset(f1, "func_code", f2.func_code, exception=ValueError) - f1.func_code = g1.func_code + cantset(f, "__code__", f1.__code__, exception=ValueError) + cantset(f1, "__code__", f.__code__, exception=ValueError) + cantset(f1, "__code__", f2.__code__, exception=ValueError) + f1.__code__ = g1.__code__ def test_func_defaults(): def f(a, b): return (a, b) - verify(f.func_defaults is None) - f.func_defaults = (1, 2) - verify(f.func_defaults == (1, 2)) + verify(f.__defaults__ is None) + f.__defaults__ = (1, 2) + verify(f.__defaults__ == (1, 2)) verify(f(10) == (10, 2)) def g(a=1, b=2): return (a, b) - verify(g.func_defaults == (1, 2)) - del g.func_defaults - verify(g.func_defaults is None) + verify(g.__defaults__ == (1, 2)) + del g.__defaults__ + verify(g.__defaults__ is None) try: g() except TypeError: @@ -317,18 +303,13 @@ def test_func_dict(): def f(): pass a = f.__dict__ - b = f.func_dict verify(a == {}) - verify(a is b) f.hello = 'world' verify(a == {'hello': 'world'}) - verify(f.func_dict is a is f.__dict__) - f.func_dict = {} - verify(not hasattr(f, "hello")) + verify(a is f.__dict__) f.__dict__ = {'world': 'hello'} verify(f.world == "hello") - verify(f.__dict__ is f.func_dict == {'world': 'hello'}) - cantset(f, "func_dict", None) + verify(f.__dict__ == {'world': 'hello'}) cantset(f, "__dict__", None) def test_im_class(): Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Sun Feb 25 21:55:47 2007 @@ -162,18 +162,18 @@ 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')) + self.assertEquals(f2.__code__.co_varnames, ('one_argument',)) + self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments')) if sys.platform.startswith('java'): - self.assertEquals(f4.func_code.co_varnames, + self.assertEquals(f4.__code__.co_varnames, ('two', '(compound, (argument, list))', 'compound', 'argument', 'list',)) - self.assertEquals(f5.func_code.co_varnames, + self.assertEquals(f5.__code__.co_varnames, ('(compound, first)', 'two', 'compound', 'first')) else: - self.assertEquals(f4.func_code.co_varnames, + self.assertEquals(f4.__code__.co_varnames, ('two', '.1', 'compound', 'argument', 'list')) - self.assertEquals(f5.func_code.co_varnames, + self.assertEquals(f5.__code__.co_varnames, ('.0', 'two', 'compound', 'first')) def a1(one_arg,): pass def a2(two, args,): pass @@ -209,9 +209,9 @@ # 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')) + self.assertEquals(v3.__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.__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() @@ -302,23 +302,23 @@ # argument annotation tests def f(x) -> list: pass - self.assertEquals(f.func_annotations, {'return': list}) + self.assertEquals(f.__annotations__, {'return': list}) def f(x:int): pass - self.assertEquals(f.func_annotations, {'x': int}) + self.assertEquals(f.__annotations__, {'x': int}) def f(*x:str): pass - self.assertEquals(f.func_annotations, {'x': str}) + self.assertEquals(f.__annotations__, {'x': str}) def f(**x:float): pass - self.assertEquals(f.func_annotations, {'x': float}) + self.assertEquals(f.__annotations__, {'x': float}) def f(x, y:1+2): pass - self.assertEquals(f.func_annotations, {'y': 3}) + self.assertEquals(f.__annotations__, {'y': 3}) def f(a, (b:1, c:2, d)): pass - self.assertEquals(f.func_annotations, {'b': 1, 'c': 2}) + self.assertEquals(f.__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, + self.assertEquals(f.__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, + self.assertEquals(f.__annotations__, {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, 'k': 11, 'return': 12}) Modified: python/branches/p3yk/Lib/test/test_hotshot.py ============================================================================== --- python/branches/p3yk/Lib/test/test_hotshot.py (original) +++ python/branches/p3yk/Lib/test/test_hotshot.py Sun Feb 25 21:55:47 2007 @@ -85,8 +85,8 @@ x = 1 def g(): f() - f_lineno = f.func_code.co_firstlineno - g_lineno = g.func_code.co_firstlineno + f_lineno = f.__code__.co_firstlineno + g_lineno = g.__code__.co_firstlineno events = [(ENTER, ("test_hotshot", g_lineno, "g")), (LINE, ("test_hotshot", g_lineno+1, "g")), (ENTER, ("test_hotshot", f_lineno, "f")), Modified: python/branches/p3yk/Lib/test/test_inspect.py ============================================================================== --- python/branches/p3yk/Lib/test/test_inspect.py (original) +++ python/branches/p3yk/Lib/test/test_inspect.py Sun Feb 25 21:55:47 2007 @@ -53,7 +53,7 @@ self.istest(inspect.isbuiltin, 'sys.exit') self.istest(inspect.isbuiltin, '[].append') self.istest(inspect.isclass, 'mod.StupidGit') - self.istest(inspect.iscode, 'mod.spam.func_code') + self.istest(inspect.iscode, 'mod.spam.__code__') self.istest(inspect.isframe, 'tb.tb_frame') self.istest(inspect.isfunction, 'mod.spam') self.istest(inspect.ismethod, 'mod.StupidGit.abuse') @@ -210,7 +210,7 @@ m.__file__ = "" # hopefully not a real filename... m.__loader__ = "dummy" # pretend the filename is understood by a loader exec("def x(): pass", m.__dict__) - self.assertEqual(inspect.getsourcefile(m.x.func_code), '') + self.assertEqual(inspect.getsourcefile(m.x.__code__), '') del sys.modules[name] inspect.getmodule(compile('a=10','','single')) Modified: python/branches/p3yk/Lib/test/test_keywordonlyarg.py ============================================================================== --- python/branches/p3yk/Lib/test/test_keywordonlyarg.py (original) +++ python/branches/p3yk/Lib/test/test_keywordonlyarg.py Sun Feb 25 21:55:47 2007 @@ -135,12 +135,12 @@ def foo(p1,p2=0, *, k1, k2=0): return p1 + p2 + k1 + k2 - self.assertEquals(2, foo.func_code.co_kwonlyargcount) - self.assertEquals({"k2":0}, foo.func_kwdefaults) - foo.func_kwdefaults = {"k1":0} + self.assertEquals(2, foo.__code__.co_kwonlyargcount) + self.assertEquals({"k2":0}, foo.__kwdefaults__) + foo.__kwdefaults__ = {"k1":0} try: foo(1,k1=10) - self.fail("func_kwdefaults is not properly changed") + self.fail("__kwdefaults__ is not properly changed") except TypeError: pass Modified: python/branches/p3yk/Lib/test/test_marshal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_marshal.py (original) +++ python/branches/p3yk/Lib/test/test_marshal.py Sun Feb 25 21:55:47 2007 @@ -144,7 +144,7 @@ class CodeTestCase(unittest.TestCase): def test_code(self): - co = ExceptionTestCase.test_exceptions.func_code + co = ExceptionTestCase.test_exceptions.__code__ new = marshal.loads(marshal.dumps(co)) self.assertEqual(co, new) Modified: python/branches/p3yk/Lib/test/test_new.py ============================================================================== --- python/branches/p3yk/Lib/test/test_new.py (original) +++ python/branches/p3yk/Lib/test/test_new.py Sun Feb 25 21:55:47 2007 @@ -79,18 +79,18 @@ return x + y return g g = f(4) - new.function(f.func_code, {}, "blah") - g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure) + new.function(f.__code__, {}, "blah") + g2 = new.function(g.__code__, {}, "blah", (2,), g.__closure__) self.assertEqual(g2(), 6) - g3 = new.function(g.func_code, {}, "blah", None, g.func_closure) + g3 = new.function(g.__code__, {}, "blah", None, g.__closure__) self.assertEqual(g3(5), 9) def test_closure(func, closure, exc): - self.assertRaises(exc, new.function, func.func_code, {}, "", None, closure) + self.assertRaises(exc, new.function, func.__code__, {}, "", None, closure) test_closure(g, None, TypeError) # invalid closure test_closure(g, (1,), TypeError) # non-cell in closure test_closure(g, (1, 1), ValueError) # closure is wrong size - test_closure(f, g.func_closure, ValueError) # no closure needed + test_closure(f, g.__closure__, ValueError) # no closure needed # Note: Jython will never have new.code() if hasattr(new, 'code'): @@ -98,7 +98,7 @@ # bogus test of new.code() def f(a): pass - c = f.func_code + c = f.__code__ argcount = c.co_argcount kwonlyargcount = c.co_kwonlyargcount nlocals = c.co_nlocals Modified: python/branches/p3yk/Lib/test/test_profilehooks.py ============================================================================== --- python/branches/p3yk/Lib/test/test_profilehooks.py (original) +++ python/branches/p3yk/Lib/test/test_profilehooks.py Sun Feb 25 21:55:47 2007 @@ -324,7 +324,7 @@ if hasattr(function, "f_code"): code = function.f_code else: - code = function.func_code + code = function.__code__ return code.co_firstlineno, code.co_name Modified: python/branches/p3yk/Lib/test/test_pyclbr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pyclbr.py (original) +++ python/branches/p3yk/Lib/test/test_pyclbr.py Sun Feb 25 21:55:47 2007 @@ -140,7 +140,7 @@ if isinstance(item, ClassType): return item.__module__ == module.__name__ if isinstance(item, FunctionType): - return item.func_globals is module.__dict__ + return item.__globals__ is module.__dict__ return False for name in dir(module): item = getattr(module, name) Modified: python/branches/p3yk/Lib/test/test_scope.py ============================================================================== --- python/branches/p3yk/Lib/test/test_scope.py (original) +++ python/branches/p3yk/Lib/test/test_scope.py Sun Feb 25 21:55:47 2007 @@ -518,10 +518,10 @@ return lambda: x + 1 g = f(3) - self.assertRaises(TypeError, eval, g.func_code) + self.assertRaises(TypeError, eval, g.__code__) try: - exec(g.func_code, {}) + exec(g.__code__, {}) except TypeError: pass else: 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 Sun Feb 25 21:55:47 2007 @@ -54,7 +54,7 @@ # 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 + globals = func.__globals__ if '__warningregistry__' in globals: del globals['__warningregistry__'] warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) 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 Sun Feb 25 21:55:47 2007 @@ -341,7 +341,7 @@ finally: if locale and orig_locale: locale.setlocale(category, orig_locale) - inner.func_name = func.func_name + inner.__name__ = func.__name__ inner.__doc__ = func.__doc__ return inner return decorator Modified: python/branches/p3yk/Lib/test/test_sys.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sys.py (original) +++ python/branches/p3yk/Lib/test/test_sys.py Sun Feb 25 21:55:47 2007 @@ -230,7 +230,7 @@ self.assertRaises(TypeError, sys._getframe, 42, 42) self.assertRaises(ValueError, sys._getframe, 2000000000) self.assert_( - SysModuleTest.test_getframe.im_func.func_code \ + SysModuleTest.test_getframe.im_func.__code__ \ is sys._getframe().f_code ) Modified: python/branches/p3yk/Lib/test/test_trace.py ============================================================================== --- python/branches/p3yk/Lib/test/test_trace.py (original) +++ python/branches/p3yk/Lib/test/test_trace.py Sun Feb 25 21:55:47 2007 @@ -226,14 +226,14 @@ sys.settrace(tracer.trace) func() sys.settrace(None) - self.compare_events(func.func_code.co_firstlineno, + self.compare_events(func.__code__.co_firstlineno, tracer.events, func.events) def run_test2(self, func): tracer = Tracer() func(tracer.trace) sys.settrace(None) - self.compare_events(func.func_code.co_firstlineno, + self.compare_events(func.__code__.co_firstlineno, tracer.events, func.events) def test_01_basic(self): @@ -313,7 +313,7 @@ def g(frame, why, extra): if (why == 'line' and - frame.f_lineno == f.func_code.co_firstlineno + 2): + frame.f_lineno == f.__code__.co_firstlineno + 2): raise RuntimeError, "i am crashing" return g @@ -344,7 +344,7 @@ self.done = False def trace(self, frame, event, arg): - if not self.done and frame.f_code == self.function.func_code: + if not self.done and frame.f_code == self.function.__code__: firstLine = frame.f_code.co_firstlineno if frame.f_lineno == firstLine + self.jumpFrom: # Cope with non-integer self.jumpTo (because of Modified: python/branches/p3yk/Lib/test/test_univnewlines.py ============================================================================== --- python/branches/p3yk/Lib/test/test_univnewlines.py (original) +++ python/branches/p3yk/Lib/test/test_univnewlines.py Sun Feb 25 21:55:47 2007 @@ -83,7 +83,7 @@ namespace = {} execfile(test_support.TESTFN, namespace) func = namespace['line3'] - self.assertEqual(func.func_code.co_firstlineno, 3) + self.assertEqual(func.__code__.co_firstlineno, 3) self.assertEqual(namespace['line4'], FATX) Modified: python/branches/p3yk/Lib/test/test_urllib.py ============================================================================== --- python/branches/p3yk/Lib/test/test_urllib.py (original) +++ python/branches/p3yk/Lib/test/test_urllib.py Sun Feb 25 21:55:47 2007 @@ -295,7 +295,7 @@ def test_default_safe(self): # Test '/' is default value for 'safe' parameter - self.assertEqual(urllib.quote.func_defaults[0], '/') + self.assertEqual(urllib.quote.__defaults__[0], '/') def test_safe(self): # Test setting 'safe' parameter does what it should do Modified: python/branches/p3yk/Lib/trace.py ============================================================================== --- python/branches/p3yk/Lib/trace.py (original) +++ python/branches/p3yk/Lib/trace.py Sun Feb 25 21:55:47 2007 @@ -532,7 +532,7 @@ ## use of gc.get_referrers() was suggested by Michael Hudson # all functions which refer to this code object funcs = [f for f in gc.get_referrers(code) - if hasattr(f, "func_doc")] + if hasattr(f, "__doc__")] # require len(func) == 1 to avoid ambiguity caused by calls to # new.function(): "In the face of ambiguity, refuse the # temptation to guess." Modified: python/branches/p3yk/Lib/types.py ============================================================================== --- python/branches/p3yk/Lib/types.py (original) +++ python/branches/p3yk/Lib/types.py Sun Feb 25 21:55:47 2007 @@ -43,7 +43,7 @@ FunctionType = type(_f) LambdaType = type(lambda: None) # Same as FunctionType try: - CodeType = type(_f.func_code) + CodeType = type(_f.__code__) except RuntimeError: # Execution in restricted environment pass Modified: python/branches/p3yk/Lib/xreload.py ============================================================================== --- python/branches/p3yk/Lib/xreload.py (original) +++ python/branches/p3yk/Lib/xreload.py Sun Feb 25 21:55:47 2007 @@ -118,8 +118,8 @@ """Update a function object.""" oldfunc.__doc__ = newfunc.__doc__ oldfunc.__dict__.update(newfunc.__dict__) - oldfunc.func_code = newfunc.func_code - oldfunc.func_defaults = newfunc.func_defaults + oldfunc.__code__ = newfunc.__code__ + oldfunc.__defaults__ = newfunc.__defaults__ # XXX What else? return oldfunc Modified: python/branches/p3yk/Objects/funcobject.c ============================================================================== --- python/branches/p3yk/Objects/funcobject.c (original) +++ python/branches/p3yk/Objects/funcobject.c Sun Feb 25 21:55:47 2007 @@ -225,11 +225,10 @@ #define OFF(x) offsetof(PyFunctionObject, x) static PyMemberDef func_memberlist[] = { - {"func_closure", T_OBJECT, OFF(func_closure), + {"__closure__", T_OBJECT, OFF(func_closure), RESTRICTED|READONLY}, - {"func_doc", T_OBJECT, OFF(func_doc), WRITE_RESTRICTED}, {"__doc__", T_OBJECT, OFF(func_doc), WRITE_RESTRICTED}, - {"func_globals", T_OBJECT, OFF(func_globals), + {"__globals__", T_OBJECT, OFF(func_globals), RESTRICTED|READONLY}, {"__module__", T_OBJECT, OFF(func_module), WRITE_RESTRICTED}, {NULL} /* Sentinel */ @@ -306,7 +305,7 @@ * other than a code object. */ if (value == NULL || !PyCode_Check(value)) { PyErr_SetString(PyExc_TypeError, - "func_code must be set to a code object"); + "__code__ must be set to a code object"); return -1; } nfree = PyCode_GetNumFree((PyCodeObject *)value); @@ -345,7 +344,7 @@ * other than a string object. */ if (value == NULL || !PyString_Check(value)) { PyErr_SetString(PyExc_TypeError, - "func_name must be set to a string object"); + "__name__ must be set to a string object"); return -1; } tmp = op->func_name; @@ -381,7 +380,7 @@ value = NULL; if (value != NULL && !PyTuple_Check(value)) { PyErr_SetString(PyExc_TypeError, - "func_defaults must be set to a tuple object"); + "__defaults__ must be set to a tuple object"); return -1; } tmp = op->func_defaults; @@ -418,7 +417,7 @@ * Can only set func_kwdefaults to NULL or a dict. */ if (value != NULL && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, - "func_kwdefaults must be set to a dict object"); + "__kwdefaults__ must be set to a dict object"); return -1; } tmp = op->func_kwdefaults; @@ -452,7 +451,7 @@ * or a dict. */ if (value != NULL && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, - "func_annotations must be set to a dict object"); + "__annotations__ must be set to a dict object"); return -1; } tmp = op->func_annotations; @@ -463,16 +462,14 @@ } static PyGetSetDef func_getsetlist[] = { - {"func_code", (getter)func_get_code, (setter)func_set_code}, - {"func_defaults", (getter)func_get_defaults, + {"__code__", (getter)func_get_code, (setter)func_set_code}, + {"__defaults__", (getter)func_get_defaults, (setter)func_set_defaults}, - {"func_kwdefaults", (getter)func_get_kwdefaults, + {"__kwdefaults__", (getter)func_get_kwdefaults, (setter)func_set_kwdefaults}, - {"func_annotations", (getter)func_get_annotations, + {"__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}, {"__name__", (getter)func_get_name, (setter)func_set_name}, {NULL} /* Sentinel */ }; From python-3000-checkins at python.org Sun Feb 25 22:03:55 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 25 Feb 2007 22:03:55 +0100 (CET) Subject: [Python-3000-checkins] r53914 - python/branches/p3yk/Lib/test/test_xreload.py Message-ID: <20070225210355.4C14D1E4007@bag.python.org> Author: guido.van.rossum Date: Sun Feb 25 22:03:54 2007 New Revision: 53914 Added: python/branches/p3yk/Lib/test/test_xreload.py (contents, props changed) Log: Add a proper unit test for xreload.py. Added: python/branches/p3yk/Lib/test/test_xreload.py ============================================================================== --- (empty file) +++ python/branches/p3yk/Lib/test/test_xreload.py Sun Feb 25 22:03:54 2007 @@ -0,0 +1,103 @@ +"""Doctests for module reloading. + +>>> from xreload import xreload +>>> from test.test_xreload import make_mod +>>> make_mod() +>>> import x +>>> C = x.C +>>> Cfoo = C.foo +>>> Cbar = C.bar +>>> Cstomp = C.stomp +>>> b = C() +>>> bfoo = b.foo +>>> b.foo() +42 +>>> bfoo() +42 +>>> Cfoo(b) +42 +>>> Cbar() +42 42 +>>> Cstomp() +42 42 42 +>>> make_mod(repl="42", subst="24") +>>> xreload(x) + +>>> b.foo() +24 +>>> bfoo() +24 +>>> Cfoo(b) +24 +>>> Cbar() +24 24 +>>> Cstomp() +24 24 24 + +""" + +SAMPLE_CODE = """ +class C: + def foo(self): + print(42) + @classmethod + def bar(cls): + print(42, 42) + @staticmethod + def stomp(): + print (42, 42, 42) +""" + +import os +import sys +import shutil +import doctest +import xreload +import tempfile +from test.test_support import run_unittest + +tempdir = None +save_path = None + + +def setUp(unused=None): + global tempdir, save_path + tempdir = tempfile.mkdtemp() + save_path = list(sys.path) + sys.path.append(tempdir) + + +def tearDown(unused=None): + global tempdir, save_path + if save_path is not None: + sys.path = save_path + save_path = None + if tempdir is not None: + shutil.rmtree(tempdir) + tempdir = None + + +def make_mod(name="x", repl=None, subst=None): + if not tempdir: + setUp() + assert tempdir + fn = os.path.join(tempdir, name + ".py") + f = open(fn, "w") + sample = SAMPLE_CODE + if repl is not None and subst is not None: + sample = sample.replace(repl, subst) + try: + f.write(sample) + finally: + f.close() + + +def test_suite(): + return doctest.DocTestSuite(setUp=setUp, tearDown=tearDown) + + +def test_main(): + run_unittest(test_suite()) + +if __name__ == "__main__": + test_main() From python-3000-checkins at python.org Sun Feb 25 22:22:22 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 25 Feb 2007 22:22:22 +0100 (CET) Subject: [Python-3000-checkins] r53915 - python/branches/p3yk/Lib/xreload.py Message-ID: <20070225212222.34EEB1E4007@bag.python.org> Author: guido.van.rossum Date: Sun Feb 25 22:22:21 2007 New Revision: 53915 Modified: python/branches/p3yk/Lib/xreload.py Log: Use Glyph's trick to ensure that __globals__ is set properly. Modified: python/branches/p3yk/Lib/xreload.py ============================================================================== --- python/branches/p3yk/Lib/xreload.py (original) +++ python/branches/p3yk/Lib/xreload.py Sun Feb 25 22:22:21 2007 @@ -55,22 +55,22 @@ finally: if stream: stream.close() - # Execute the code in a temporary namespace; if this fails, no changes - tmpns = {} - exec(code, tmpns) + # Execute the code. We copy the module dict to a temporary; then + # clear the module dict; then execute the new code in the module + # dict; then swap things back and around. This trick (due to + # Glyph Lefkowitz) ensures that the (readonly) __globals__ + # attribute of methods and functions is set to the correct dict + # object. + tmpns = modns.copy() + modns.clear() + modns["__name__"] = tmpns["__name__"] + exec(code, modns) # Now we get to the hard part - oldnames = set(modns) - newnames = set(tmpns) - # Add newly introduced names - for name in newnames - oldnames: - modns[name] = tmpns[name] - # Delete names that are no longer current - # XXX What to do about renamed objects? - for name in oldnames - newnames - {"__name__"}: - del modns[name] - # Now update the rest in place + oldnames = set(tmpns) + newnames = set(modns) + # Update attributes in place for name in oldnames & newnames: - modns[name] = _update(modns[name], tmpns[name]) + modns[name] = _update(tmpns[name], modns[name]) # Done! return mod From python-3000-checkins at python.org Sun Feb 25 23:37:41 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 25 Feb 2007 23:37:41 +0100 (CET) Subject: [Python-3000-checkins] r53922 - python/branches/p3yk/Lib/idlelib/PyShell.py Message-ID: <20070225223741.55A381E4007@bag.python.org> Author: guido.van.rossum Date: Sun Feb 25 23:37:36 2007 New Revision: 53922 Modified: python/branches/p3yk/Lib/idlelib/PyShell.py Log: Fix merge bug (lost line causing syntax error). Modified: python/branches/p3yk/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/PyShell.py (original) +++ python/branches/p3yk/Lib/idlelib/PyShell.py Sun Feb 25 23:37:36 2007 @@ -722,6 +722,7 @@ master=self.tkconsole.text): raise else: + self.showtraceback() else: raise except: From python-3000-checkins at python.org Mon Feb 26 00:47:21 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Mon, 26 Feb 2007 00:47:21 +0100 (CET) Subject: [Python-3000-checkins] r53926 - python/branches/p3yk/Objects/abstract.c Message-ID: <20070225234721.BD12A1E400B@bag.python.org> Author: neal.norwitz Date: Mon Feb 26 00:47:19 2007 New Revision: 53926 Modified: python/branches/p3yk/Objects/abstract.c Log: These comments aren't relevant for 3k. They were to support modules compiled before the PyNumberMethods were added which was 2.0 I think. Modified: python/branches/p3yk/Objects/abstract.c ============================================================================== --- python/branches/p3yk/Objects/abstract.c (original) +++ python/branches/p3yk/Objects/abstract.c Mon Feb 26 00:47:19 2007 @@ -565,14 +565,12 @@ PyObject * PyNumber_FloorDivide(PyObject *v, PyObject *w) { - /* XXX tp_flags test */ return binary_op(v, w, NB_SLOT(nb_floor_divide), "//"); } PyObject * PyNumber_TrueDivide(PyObject *v, PyObject *w) { - /* XXX tp_flags test */ return binary_op(v, w, NB_SLOT(nb_true_divide), "/"); } @@ -649,7 +647,6 @@ PyObject * PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w) { - /* XXX tp_flags test */ return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide), NB_SLOT(nb_floor_divide), "//="); } @@ -657,7 +654,6 @@ PyObject * PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w) { - /* XXX tp_flags test */ return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide), NB_SLOT(nb_true_divide), "/="); } From python-3000-checkins at python.org Mon Feb 26 02:58:42 2007 From: python-3000-checkins at python.org (george.yoshida) Date: Mon, 26 Feb 2007 02:58:42 +0100 (CET) Subject: [Python-3000-checkins] r53928 - python/branches/p3yk/Doc/ref/ref3.tex Message-ID: <20070226015842.CA36F1E4006@bag.python.org> Author: george.yoshida Date: Mon Feb 26 02:58:37 2007 New Revision: 53928 Modified: python/branches/p3yk/Doc/ref/ref3.tex Log: put a missing curly brace Modified: python/branches/p3yk/Doc/ref/ref3.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref3.tex (original) +++ python/branches/p3yk/Doc/ref/ref3.tex Mon Feb 26 02:58:37 2007 @@ -530,7 +530,7 @@ \ttindex{__code__} \ttindex{__globals__} \ttindex{__annotations__} - \ttindex{__kwdefaults__} + \ttindex{__kwdefaults__}} \indexii{global}{namespace} \item[User-defined methods] From python-3000-checkins at python.org Mon Feb 26 06:44:29 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 06:44:29 +0100 (CET) Subject: [Python-3000-checkins] r53929 - python/branches/p3yk/Objects/abstract.c Message-ID: <20070226054429.538661E4006@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 06:44:27 2007 New Revision: 53929 Modified: python/branches/p3yk/Objects/abstract.c Log: Don't confound Neil S on b"a"[0] = b"b". Modified: python/branches/p3yk/Objects/abstract.c ============================================================================== --- python/branches/p3yk/Objects/abstract.c (original) +++ python/branches/p3yk/Objects/abstract.c Mon Feb 26 06:44:27 2007 @@ -805,7 +805,7 @@ if (result && !PyInt_Check(result) && !PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, - "__index__ returned non-int " \ + "__index__ returned non-int " "(type %.200s)", result->ob_type->tp_name); Py_DECREF(result); @@ -815,7 +815,7 @@ else { PyErr_Format(PyExc_TypeError, "'%.200s' object cannot be interpreted " - "as an index", item->ob_type->tp_name); + "as an integer", item->ob_type->tp_name); } return result; } From python-3000-checkins at python.org Mon Feb 26 08:07:09 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 08:07:09 +0100 (CET) Subject: [Python-3000-checkins] r53930 - python/branches/p3yk/Lib/pickle.py Message-ID: <20070226070709.8EAFF1E4006@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 08:07:02 2007 New Revision: 53930 Modified: python/branches/p3yk/Lib/pickle.py Log: Fix a bizarre error where test_pickletools fails if preceded by test_pyclbr. The fix is in neither, but in pickle.py where a loop over sys.modules.items() could modify sys.modules, occasionally. Modified: python/branches/p3yk/Lib/pickle.py ============================================================================== --- python/branches/p3yk/Lib/pickle.py (original) +++ python/branches/p3yk/Lib/pickle.py Mon Feb 26 08:07:02 2007 @@ -791,7 +791,7 @@ if func in classmap: return classmap[func] - for name, module in sys.modules.items(): + for name, module in list(sys.modules.items()): if module is None: continue # skip dummy package entries if name != '__main__' and getattr(module, funcname, None) is func: From python-3000-checkins at python.org Mon Feb 26 10:41:21 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 10:41:21 +0100 (CET) Subject: [Python-3000-checkins] r53931 - python/branches/p3yk/Lib/token.py Message-ID: <20070226094121.E17781E4006@bag.python.org> Author: georg.brandl Date: Mon Feb 26 10:41:19 2007 New Revision: 53931 Modified: python/branches/p3yk/Lib/token.py Log: Fix token.py main code vs. dict views. Modified: python/branches/p3yk/Lib/token.py ============================================================================== --- python/branches/p3yk/Lib/token.py (original) +++ python/branches/p3yk/Lib/token.py Mon Feb 26 10:41:19 2007 @@ -108,7 +108,7 @@ name, val = match.group(1, 2) val = int(val) tokens[val] = name # reverse so we can sort them... - keys = tokens.keys() + keys = list(tokens.keys()) keys.sort() # load the output skeleton from the target: try: From python-3000-checkins at python.org Mon Feb 26 11:35:13 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 11:35:13 +0100 (CET) Subject: [Python-3000-checkins] r53932 - python/branches/p3yk/Python/bltinmodule.c Message-ID: <20070226103513.84F941E4015@bag.python.org> Author: georg.brandl Date: Mon Feb 26 11:35:10 2007 New Revision: 53932 Modified: python/branches/p3yk/Python/bltinmodule.c Log: Fix leak in the print function. Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Mon Feb 26 11:35:10 2007 @@ -1392,12 +1392,14 @@ builtin_print(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"sep", "end", "file", 0}; - PyObject *dummy_args = PyTuple_New(0); + static PyObject *dummy_args; PyObject *sep = NULL, *end = NULL, *file = NULL; int i, err; - if (dummy_args == NULL) - return NULL; + if (dummy_args == NULL) { + if (!(dummy_args = PyTuple_New(0))) + return NULL; + } if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print", kwlist, &sep, &end, &file)) return NULL; From python-3000-checkins at python.org Mon Feb 26 13:29:00 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 13:29:00 +0100 (CET) Subject: [Python-3000-checkins] r53933 - python/branches/p3yk/Objects/funcobject.c Message-ID: <20070226122900.A06551E4006@bag.python.org> Author: georg.brandl Date: Mon Feb 26 13:28:57 2007 New Revision: 53933 Modified: python/branches/p3yk/Objects/funcobject.c Log: Fix refleaks in function objects caused by kwdefaults not being allocated. Should func_new be extended to support a "kwdefaults" arg? Modified: python/branches/p3yk/Objects/funcobject.c ============================================================================== --- python/branches/p3yk/Objects/funcobject.c (original) +++ python/branches/p3yk/Objects/funcobject.c Mon Feb 26 13:28:57 2007 @@ -413,7 +413,7 @@ if (value == Py_None) value = NULL; - /* Legal to del f.func_defaults. + /* Legal to del f.func_kwdefaults. * Can only set func_kwdefaults to NULL or a dict. */ if (value != NULL && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, @@ -587,6 +587,7 @@ Py_XDECREF(op->func_module); Py_DECREF(op->func_name); Py_XDECREF(op->func_defaults); + Py_XDECREF(op->func_kwdefaults); Py_XDECREF(op->func_doc); Py_XDECREF(op->func_dict); Py_XDECREF(op->func_closure); @@ -609,6 +610,7 @@ Py_VISIT(f->func_globals); Py_VISIT(f->func_module); Py_VISIT(f->func_defaults); + Py_VISIT(f->func_kwdefaults); Py_VISIT(f->func_doc); Py_VISIT(f->func_name); Py_VISIT(f->func_dict); From python-3000-checkins at python.org Mon Feb 26 14:48:31 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 14:48:31 +0100 (CET) Subject: [Python-3000-checkins] r53934 - python/branches/p3yk/Objects/stringobject.c Message-ID: <20070226134831.7A1A51E4006@bag.python.org> Author: georg.brandl Date: Mon Feb 26 14:48:28 2007 New Revision: 53934 Modified: python/branches/p3yk/Objects/stringobject.c Log: Fix a refleak in PyString_Format. Modified: python/branches/p3yk/Objects/stringobject.c ============================================================================== --- python/branches/p3yk/Objects/stringobject.c (original) +++ python/branches/p3yk/Objects/stringobject.c Mon Feb 26 14:48:28 2007 @@ -4780,10 +4780,13 @@ reslen += rescnt; if (reslen < 0) { Py_DECREF(result); + Py_XDECREF(temp); return PyErr_NoMemory(); } - if (_PyString_Resize(&result, reslen) < 0) + if (_PyString_Resize(&result, reslen) < 0) { + Py_XDECREF(temp); return NULL; + } res = PyString_AS_STRING(result) + reslen - rescnt; } @@ -4834,6 +4837,7 @@ if (dict && (argidx < arglen) && c != '%') { PyErr_SetString(PyExc_TypeError, "not all arguments converted during string formatting"); + Py_XDECREF(temp); goto error; } Py_XDECREF(temp); From python-3000-checkins at python.org Mon Feb 26 14:58:22 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 14:58:22 +0100 (CET) Subject: [Python-3000-checkins] r53937 - python/branches/p3yk/Python/ceval.c Message-ID: <20070226135822.B1FA11E4006@bag.python.org> Author: georg.brandl Date: Mon Feb 26 14:58:18 2007 New Revision: 53937 Modified: python/branches/p3yk/Python/ceval.c Log: Fix a refleak in the MAKE_FUNCTION opcode in ceval.c. Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Mon Feb 26 14:58:18 2007 @@ -2298,6 +2298,8 @@ u = POP(); /* kw only arg name */ /* XXX(nnorwitz): check for errors */ PyDict_SetItem(v, u, w); + Py_DECREF(w); + Py_DECREF(u); } err = PyFunction_SetKwDefaults(x, v); Py_DECREF(v); From python-3000-checkins at python.org Mon Feb 26 15:08:27 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 15:08:27 +0100 (CET) Subject: [Python-3000-checkins] r53938 - python/branches/p3yk/Lib/token.py Message-ID: <20070226140827.D37FC1E401A@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 15:08:27 2007 New Revision: 53938 Modified: python/branches/p3yk/Lib/token.py Log: Use better idiom to sort keys. Modified: python/branches/p3yk/Lib/token.py ============================================================================== --- python/branches/p3yk/Lib/token.py (original) +++ python/branches/p3yk/Lib/token.py Mon Feb 26 15:08:27 2007 @@ -108,8 +108,7 @@ name, val = match.group(1, 2) val = int(val) tokens[val] = name # reverse so we can sort them... - keys = list(tokens.keys()) - keys.sort() + keys = sorted(tokens.keys()) # load the output skeleton from the target: try: fp = open(outFileName) From python-3000-checkins at python.org Mon Feb 26 15:46:33 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 26 Feb 2007 15:46:33 +0100 (CET) Subject: [Python-3000-checkins] r53939 - python/branches/p3yk/Objects/longobject.c Message-ID: <20070226144633.E70411E4006@bag.python.org> Author: georg.brandl Date: Mon Feb 26 15:46:30 2007 New Revision: 53939 Modified: python/branches/p3yk/Objects/longobject.c Log: Another refleak, this time in PyLong_AsLong. Fixes leaks showing in test_getargs2 and test_email. Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Mon Feb 26 15:46:30 2007 @@ -298,6 +298,7 @@ /* This version by Tim Peters */ register PyLongObject *v; unsigned long x, prev; + long res; Py_ssize_t i; int sign; int do_decref = 0; /* if nb_int was called */ @@ -326,46 +327,55 @@ } } + res = -1; v = (PyLongObject *)vv; i = v->ob_size; + switch (i) { - case -1: return -v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << SHIFT) + v->ob_digit[i]; - if ((x >> SHIFT) != prev) - goto overflow; - } - if (do_decref) { - Py_DECREF(vv); - } - /* Haven't lost any bits, but casting to long requires extra care - * (see comment above). - */ - if (x <= (unsigned long)LONG_MAX) { - return (long)x * sign; - } - else if (sign < 0 && x == PY_ABS_LONG_MIN) { - return LONG_MIN; + case -1: + res = -v->ob_digit[0]; + break; + case 0: + res = 0; + break; + case 1: + res = v->ob_digit[0]; + break; + default: + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + while (--i >= 0) { + prev = x; + x = (x << SHIFT) + v->ob_digit[i]; + if ((x >> SHIFT) != prev) { + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C long"); + goto exit; + } + } + /* Haven't lost any bits, but casting to long requires extra care + * (see comment above). + */ + if (x <= (unsigned long)LONG_MAX) { + res = (long)x * sign; + } + else if (sign < 0 && x == PY_ABS_LONG_MIN) { + res = LONG_MIN; + } + else { + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C long"); + } } - /* else overflow */ - - overflow: + exit: if (do_decref) { Py_DECREF(vv); } - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C long"); - return -1; + return res; } int From python-3000-checkins at python.org Mon Feb 26 16:59:56 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 16:59:56 +0100 (CET) Subject: [Python-3000-checkins] r53942 - python/branches/p3yk/Lib/pickletools.py Message-ID: <20070226155956.82CA11E4006@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 16:59:50 2007 New Revision: 53942 Modified: python/branches/p3yk/Lib/pickletools.py Log: Change a test to be more predictable. The problem with using random.random is that several modules and tests do "from random in random" which confuses pickle.whichmodule(). Modified: python/branches/p3yk/Lib/pickletools.py ============================================================================== --- python/branches/p3yk/Lib/pickletools.py (original) +++ python/branches/p3yk/Lib/pickletools.py Mon Feb 26 16:59:50 2007 @@ -2050,10 +2050,10 @@ Exercise the INST/OBJ/BUILD family. >>> import random ->>> dis(pickle.dumps(random.random, 0)) - 0: c GLOBAL 'random random' - 15: p PUT 0 - 18: . STOP +>>> dis(pickle.dumps(random.getrandbits, 0)) + 0: c GLOBAL 'random getrandbits' + 20: p PUT 0 + 23: . STOP highest protocol among opcodes = 0 >>> from pickletools import _Example From python-3000-checkins at python.org Mon Feb 26 17:57:56 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 17:57:56 +0100 (CET) Subject: [Python-3000-checkins] r53945 - python/branches/p3yk/Lib/xreload.py Message-ID: <20070226165756.8B0A71E4014@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 17:57:52 2007 New Revision: 53945 Modified: python/branches/p3yk/Lib/xreload.py Log: Add a partial list of limitations, stripping out some corresponding XXX comments. Modified: python/branches/p3yk/Lib/xreload.py ============================================================================== --- python/branches/p3yk/Lib/xreload.py (original) +++ python/branches/p3yk/Lib/xreload.py Mon Feb 26 17:57:52 2007 @@ -1,8 +1,33 @@ """Alternative to reload(). This works by executing the module in a scratch namespace, and then -patching classes, methods and functions. This avoids the need to -patch instances. New objects are copied into the target namespace. +patching classes, methods and functions in place. This avoids the +need to patch instances. New objects are copied into the target +namespace. + +Some of the many limitiations include: + +- Global mutable objects other than classes are simply replaced, not patched + +- Code using metaclasses is not handled correctly + +- Code creating global singletons is not handled correctly + +- Functions and methods using decorators (other than classmethod and + staticmethod) is not handled correctly + +- Renamings are not handled correctly + +- Dependent modules are not reloaded + +- When a dependent module contains 'from foo import bar', and + reloading foo deletes foo.bar, the dependent module continues to use + the old foo.bar object rather than failing + +- Frozen modules and modules loaded from zip files aren't handled + correctly + +- Classes involving __slots__ are not handled correctly """ import imp @@ -43,7 +68,6 @@ # Turn it into a code object try: # Is it Python source code or byte code read from a file? - # XXX Could handle frozen modules, zip-import modules if kind not in (imp.PY_COMPILED, imp.PY_SOURCE): # Fall back to built-in reload() return reload(mod) @@ -106,7 +130,6 @@ return _update_classmethod(oldobj, newobj) if isinstance(newobj, staticmethod): return _update_staticmethod(oldobj, newobj) - # XXX How to support decorators? # Not something we recognize, just give up return newobj @@ -120,7 +143,6 @@ oldfunc.__dict__.update(newfunc.__dict__) oldfunc.__code__ = newfunc.__code__ oldfunc.__defaults__ = newfunc.__defaults__ - # XXX What else? return oldfunc @@ -133,7 +155,6 @@ def _update_class(oldclass, newclass): """Update a class object.""" - # XXX What about __slots__? olddict = oldclass.__dict__ newdict = newclass.__dict__ oldnames = set(olddict) From python-3000-checkins at python.org Mon Feb 26 17:59:58 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 17:59:58 +0100 (CET) Subject: [Python-3000-checkins] r53946 - in python/branches/p3yk: Lib/test/test_builtin.py Python/bltinmodule.c Message-ID: <20070226165958.797B81E4006@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 17:59:55 2007 New Revision: 53946 Modified: python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Python/bltinmodule.c Log: Add raw_input() back, named input(). Revive the old unittests too. Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Mon Feb 26 17:59:55 2007 @@ -664,6 +664,8 @@ id([0,1,2,3]) id({'spam': 1, 'eggs': 2, 'ham': 3}) + # Test input() later, alphabetized as if it were raw_input + def test_int(self): self.assertEqual(int(314), 314) self.assertEqual(int(3.14), 3) @@ -1256,6 +1258,7 @@ self.assertRaises(TypeError, oct, ()) def write_testfile(self): + # NB the first 4 lines are also used to test input, below fp = open(TESTFN, 'w') try: fp.write('1+1\n') @@ -1417,6 +1420,43 @@ self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint) self.assertRaises(OverflowError, range, 0, 2*sys.maxint) + def test_input(self): + self.write_testfile() + fp = open(TESTFN, 'r') + savestdin = sys.stdin + savestdout = sys.stdout # Eats the echo + try: + sys.stdin = fp + sys.stdout = BitBucket() + self.assertEqual(input(), "1+1") + self.assertEqual(input('testing\n'), "1+1") + self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.') + self.assertEqual(input('testing\n'), 'Dear John') + + # SF 1535165: don't segfault on closed stdin + # sys.stdout must be a regular file for triggering + sys.stdout = savestdout + sys.stdin.close() + self.assertRaises(ValueError, input) + + sys.stdout = BitBucket() + sys.stdin = cStringIO.StringIO("NULL\0") + self.assertRaises(TypeError, input, 42, 42) + sys.stdin = cStringIO.StringIO(" 'whitespace'") + self.assertEqual(input(), " 'whitespace'") + sys.stdin = cStringIO.StringIO() + self.assertRaises(EOFError, input) + + del sys.stdout + self.assertRaises(RuntimeError, input, 'prompt') + del sys.stdin + self.assertRaises(RuntimeError, input, 'prompt') + finally: + sys.stdin = savestdin + sys.stdout = savestdout + fp.close() + unlink(TESTFN) + def test_reload(self): import marshal reload(marshal) Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Mon Feb 26 17:59:55 2007 @@ -1753,6 +1753,83 @@ For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\ These are exactly the valid indices for a list of 4 elements."); +static PyObject * +builtin_input(PyObject *self, PyObject *args) +{ + PyObject *v = NULL; + PyObject *fin = PySys_GetObject("stdin"); + PyObject *fout = PySys_GetObject("stdout"); + + if (!PyArg_UnpackTuple(args, "input", 0, 1, &v)) + return NULL; + + if (fin == NULL) { + PyErr_SetString(PyExc_RuntimeError, "input: lost sys.stdin"); + return NULL; + } + if (fout == NULL) { + PyErr_SetString(PyExc_RuntimeError, "input: lost sys.stdout"); + return NULL; + } + if (PyFile_AsFile(fin) && PyFile_AsFile(fout) + && isatty(fileno(PyFile_AsFile(fin))) + && isatty(fileno(PyFile_AsFile(fout)))) { + PyObject *po; + char *prompt; + char *s; + PyObject *result; + if (v != NULL) { + po = PyObject_Str(v); + if (po == NULL) + return NULL; + prompt = PyString_AsString(po); + if (prompt == NULL) + return NULL; + } + else { + po = NULL; + prompt = ""; + } + s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout), + prompt); + Py_XDECREF(po); + if (s == NULL) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_KeyboardInterrupt); + return NULL; + } + if (*s == '\0') { + PyErr_SetNone(PyExc_EOFError); + result = NULL; + } + else { /* strip trailing '\n' */ + size_t len = strlen(s); + if (len > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "input: input too long"); + result = NULL; + } + else { + result = PyString_FromStringAndSize(s, len-1); + } + } + PyMem_FREE(s); + return result; + } + if (v != NULL) { + if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0) + return NULL; + } + return PyFile_GetLine(fin, -1); +} + +PyDoc_STRVAR(input_doc, +"input([prompt]) -> string\n\ +\n\ +Read a string from standard input. The trailing newline is stripped.\n\ +If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\ +On Unix, GNU readline is used if enabled. The prompt string, if given,\n\ +is printed without a trailing newline before reading."); static PyObject * builtin_reload(PyObject *self, PyObject *v) @@ -2046,6 +2123,7 @@ {"hash", builtin_hash, METH_O, hash_doc}, {"hex", builtin_hex, METH_O, hex_doc}, {"id", builtin_id, METH_O, id_doc}, + {"input", builtin_input, METH_VARARGS, input_doc}, {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, {"iter", builtin_iter, METH_VARARGS, iter_doc}, From python-3000-checkins at python.org Mon Feb 26 19:20:20 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Mon, 26 Feb 2007 19:20:20 +0100 (CET) Subject: [Python-3000-checkins] r53952 - in python/branches/p3yk: Misc/developers.txt Parser/asdl_c.py Python/Python-ast.c Python/ceval.c Message-ID: <20070226182020.9A32A1E4012@bag.python.org> Author: thomas.wouters Date: Mon Feb 26 19:20:15 2007 New Revision: 53952 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Misc/developers.txt python/branches/p3yk/Parser/asdl_c.py python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/ceval.c Log: Merged revisions 53912-53951 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53919 | thomas.wouters | 2007-02-25 23:12:31 +0100 (Sun, 25 Feb 2007) | 8 lines Backported r51621 from p3yk: Don't use a fixed temporary name (gdbm). Don't use our own temp name creation (dbm). Should be backported to 2.5. ........ r53935 | georg.brandl | 2007-02-26 14:51:29 +0100 (Mon, 26 Feb 2007) | 2 lines Backport from Py3k branch: fix refleak in PyString_Format. ........ r53943 | jeremy.hylton | 2007-02-26 17:14:51 +0100 (Mon, 26 Feb 2007) | 2 lines Reformat long lines. ........ r53947 | neal.norwitz | 2007-02-26 18:01:08 +0100 (Mon, 26 Feb 2007) | 1 line Add Steven Bethard to help out with patches. ........ r53949 | georg.brandl | 2007-02-26 18:09:03 +0100 (Mon, 26 Feb 2007) | 3 lines Fix typo. ........ r53951 | neal.norwitz | 2007-02-26 19:10:47 +0100 (Mon, 26 Feb 2007) | 5 lines Fix a couple of problems in generating the AST code: * use %r instead of backticks since backticks are going away in Py3k * PyArena_Malloc() already sets PyErr_NoMemory so we don't need to do it again * the signature for ast2obj_int incorrectly used a bool, rather than a long ........ Modified: python/branches/p3yk/Misc/developers.txt ============================================================================== --- python/branches/p3yk/Misc/developers.txt (original) +++ python/branches/p3yk/Misc/developers.txt Mon Feb 26 19:20:15 2007 @@ -17,6 +17,9 @@ Permissions History ------------------- +- Steven Bethard (SF name "bediviere") added to the SourceForge Python + project 26 Feb 2007, by NCN, as a tracker tech. + - Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python project 06 Jan 2007, by NCN, as a tracker tech. He will maintain asyncore. Modified: python/branches/p3yk/Parser/asdl_c.py ============================================================================== --- python/branches/p3yk/Parser/asdl_c.py (original) +++ python/branches/p3yk/Parser/asdl_c.py Mon Feb 26 19:20:15 2007 @@ -299,10 +299,8 @@ emit('}', 1) emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1); - emit("if (!p) {", 1) - emit("PyErr_NoMemory();", 2) + emit("if (!p)", 1) emit("return NULL;", 2) - emit("}", 1) if union: self.emit_body_union(name, args, attrs) else: @@ -474,7 +472,7 @@ return PyBool_FromLong(b); } -static PyObject* ast2obj_int(bool b) +static PyObject* ast2obj_int(long b) { return PyInt_FromLong(b); } Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Mon Feb 26 19:20:15 2007 @@ -2,7 +2,7 @@ /* - __version__ 53872. + __version__ 53873. This module must be committed separately after each AST grammar change; The __version__ number is set to the revision number of the commit @@ -448,7 +448,7 @@ return PyBool_FromLong(b); } -static PyObject* ast2obj_int(bool b) +static PyObject* ast2obj_int(long b) { return PyInt_FromLong(b); } @@ -754,10 +754,8 @@ { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Module_kind; p->v.Module.body = body; return p; @@ -768,10 +766,8 @@ { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Interactive_kind; p->v.Interactive.body = body; return p; @@ -787,10 +783,8 @@ return NULL; } p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Expression_kind; p->v.Expression.body = body; return p; @@ -801,10 +795,8 @@ { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Suite_kind; p->v.Suite.body = body; return p; @@ -827,10 +819,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = FunctionDef_kind; p->v.FunctionDef.name = name; p->v.FunctionDef.args = args; @@ -853,10 +843,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ClassDef_kind; p->v.ClassDef.name = name; p->v.ClassDef.bases = bases; @@ -871,10 +859,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Return_kind; p->v.Return.value = value; p->lineno = lineno; @@ -887,10 +873,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Delete_kind; p->v.Delete.targets = targets; p->lineno = lineno; @@ -909,10 +893,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Assign_kind; p->v.Assign.targets = targets; p->v.Assign.value = value; @@ -942,10 +924,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = AugAssign_kind; p->v.AugAssign.target = target; p->v.AugAssign.op = op; @@ -971,10 +951,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = For_kind; p->v.For.target = target; p->v.For.iter = iter; @@ -996,10 +974,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = While_kind; p->v.While.test = test; p->v.While.body = body; @@ -1020,10 +996,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = If_kind; p->v.If.test = test; p->v.If.body = body; @@ -1044,10 +1018,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = With_kind; p->v.With.context_expr = context_expr; p->v.With.optional_vars = optional_vars; @@ -1063,10 +1035,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Raise_kind; p->v.Raise.type = type; p->v.Raise.inst = inst; @@ -1082,10 +1052,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = TryExcept_kind; p->v.TryExcept.body = body; p->v.TryExcept.handlers = handlers; @@ -1101,10 +1069,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = TryFinally_kind; p->v.TryFinally.body = body; p->v.TryFinally.finalbody = finalbody; @@ -1123,10 +1089,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Assert_kind; p->v.Assert.test = test; p->v.Assert.msg = msg; @@ -1140,10 +1104,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Import_kind; p->v.Import.names = names; p->lineno = lineno; @@ -1162,10 +1124,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ImportFrom_kind; p->v.ImportFrom.module = module; p->v.ImportFrom.names = names; @@ -1180,10 +1140,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Global_kind; p->v.Global.names = names; p->lineno = lineno; @@ -1201,10 +1159,8 @@ return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Expr_kind; p->v.Expr.value = value; p->lineno = lineno; @@ -1217,10 +1173,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Pass_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1232,10 +1186,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Break_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1247,10 +1199,8 @@ { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Continue_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1268,10 +1218,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = BoolOp_kind; p->v.BoolOp.op = op; p->v.BoolOp.values = values; @@ -1301,10 +1249,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = BinOp_kind; p->v.BinOp.left = left; p->v.BinOp.op = op; @@ -1330,10 +1276,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = UnaryOp_kind; p->v.UnaryOp.op = op; p->v.UnaryOp.operand = operand; @@ -1358,10 +1302,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Lambda_kind; p->v.Lambda.args = args; p->v.Lambda.body = body; @@ -1391,10 +1333,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = IfExp_kind; p->v.IfExp.test = test; p->v.IfExp.body = body; @@ -1410,10 +1350,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Dict_kind; p->v.Dict.keys = keys; p->v.Dict.values = values; @@ -1427,10 +1365,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Set_kind; p->v.Set.elts = elts; p->lineno = lineno; @@ -1449,10 +1385,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ListComp_kind; p->v.ListComp.elt = elt; p->v.ListComp.generators = generators; @@ -1472,10 +1406,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = GeneratorExp_kind; p->v.GeneratorExp.elt = elt; p->v.GeneratorExp.generators = generators; @@ -1489,10 +1421,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Yield_kind; p->v.Yield.value = value; p->lineno = lineno; @@ -1511,10 +1441,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Compare_kind; p->v.Compare.left = left; p->v.Compare.ops = ops; @@ -1535,10 +1463,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Call_kind; p->v.Call.func = func; p->v.Call.args = args; @@ -1560,10 +1486,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Num_kind; p->v.Num.n = n; p->lineno = lineno; @@ -1581,10 +1505,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Str_kind; p->v.Str.s = s; p->lineno = lineno; @@ -1602,10 +1524,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Bytes_kind; p->v.Bytes.s = s; p->lineno = lineno; @@ -1618,10 +1538,8 @@ { expr_ty p; p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Ellipsis_kind; p->lineno = lineno; p->col_offset = col_offset; @@ -1649,10 +1567,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Attribute_kind; p->v.Attribute.value = value; p->v.Attribute.attr = attr; @@ -1683,10 +1599,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Subscript_kind; p->v.Subscript.value = value; p->v.Subscript.slice = slice; @@ -1712,10 +1626,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Name_kind; p->v.Name.id = id; p->v.Name.ctx = ctx; @@ -1735,10 +1647,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = List_kind; p->v.List.elts = elts; p->v.List.ctx = ctx; @@ -1758,10 +1668,8 @@ return NULL; } p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Tuple_kind; p->v.Tuple.elts = elts; p->v.Tuple.ctx = ctx; @@ -1775,10 +1683,8 @@ { slice_ty p; p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Slice_kind; p->v.Slice.lower = lower; p->v.Slice.upper = upper; @@ -1791,10 +1697,8 @@ { slice_ty p; p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = ExtSlice_kind; p->v.ExtSlice.dims = dims; return p; @@ -1810,10 +1714,8 @@ return NULL; } p = (slice_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = Index_kind; p->v.Index.value = value; return p; @@ -1834,10 +1736,8 @@ return NULL; } p = (comprehension_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->target = target; p->iter = iter; p->ifs = ifs; @@ -1850,10 +1750,8 @@ { excepthandler_ty p; p = (excepthandler_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->type = type; p->name = name; p->body = body; @@ -1869,10 +1767,8 @@ { arguments_ty p; p = (arguments_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->args = args; p->vararg = vararg; p->varargannotation = varargannotation; @@ -1894,10 +1790,8 @@ return NULL; } p = (arg_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = SimpleArg_kind; p->v.SimpleArg.arg = arg; p->v.SimpleArg.annotation = annotation; @@ -1909,10 +1803,8 @@ { arg_ty p; p = (arg_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->kind = NestedArgs_kind; p->v.NestedArgs.args = args; return p; @@ -1933,10 +1825,8 @@ return NULL; } p = (keyword_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->arg = arg; p->value = value; return p; @@ -1952,10 +1842,8 @@ return NULL; } p = (alias_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); + if (!p) return NULL; - } p->name = name; p->asname = asname; return p; @@ -3125,7 +3013,7 @@ if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) return; - if (PyModule_AddStringConstant(m, "__version__", "53872") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53873") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Mon Feb 26 19:20:15 2007 @@ -4077,7 +4077,8 @@ metaclass = (PyObject *) &PyType_Type; Py_INCREF(metaclass); } - result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, NULL); + result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, + NULL); Py_DECREF(metaclass); if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { /* A type error here likely means that the user passed @@ -4091,7 +4092,8 @@ if (PyString_Check(pvalue)) { PyObject *newmsg; newmsg = PyString_FromFormat( - "Error when calling the metaclass bases\n %s", + "Error when calling the metaclass bases\n" + " %s", PyString_AS_STRING(pvalue)); if (newmsg != NULL) { Py_DECREF(pvalue); From python-3000-checkins at python.org Mon Feb 26 20:04:53 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Mon, 26 Feb 2007 20:04:53 +0100 (CET) Subject: [Python-3000-checkins] r53956 - python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Parser/asdl_c.py Message-ID: <20070226190453.230C91E4006@bag.python.org> Author: neal.norwitz Date: Mon Feb 26 20:04:49 2007 New Revision: 53956 Modified: python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Parser/asdl_c.py Log: bool is no longer required, it was only used for the print statement Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Mon Feb 26 20:04:49 2007 @@ -1,4 +1,4 @@ --- ASDL's five builtin types are identifier, int, string, object, bool +-- ASDL's five builtin types are identifier, int, string, object module Python version "$Revision$" { Modified: python/branches/p3yk/Parser/asdl_c.py ============================================================================== --- python/branches/p3yk/Parser/asdl_c.py (original) +++ python/branches/p3yk/Parser/asdl_c.py Mon Feb 26 20:04:49 2007 @@ -15,7 +15,7 @@ """Return a string for the C name of the type. This function special cases the default types provided by asdl: - identifier, string, int, bool. + identifier, string, int. """ # XXX ack! need to figure out where Id is useful and where string if isinstance(name, asdl.Id): @@ -288,8 +288,7 @@ emit("{") emit("%s p;" % ctype, 1) for argtype, argname, opt in args: - # XXX hack alert: false is allowed for a bool - if not opt and not (argtype == "bool" or argtype == "int"): + if not opt and argtype != "int": emit("if (!%s) {" % argname, 1) emit("PyErr_SetString(PyExc_ValueError,", 2) msg = "field %s is required for %s" % (argname, name) @@ -467,10 +466,6 @@ } #define ast2obj_identifier ast2obj_object #define ast2obj_string ast2obj_object -static PyObject* ast2obj_bool(bool b) -{ - return PyBool_FromLong(b); -} static PyObject* ast2obj_int(long b) { From python-3000-checkins at python.org Mon Feb 26 20:14:16 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Mon, 26 Feb 2007 20:14:16 +0100 (CET) Subject: [Python-3000-checkins] r53957 - in python/branches/p3yk: Include/asdl.h Python/Python-ast.c Python/ast.c Python/compile.c Message-ID: <20070226191416.38D031E4006@bag.python.org> Author: neal.norwitz Date: Mon Feb 26 20:14:12 2007 New Revision: 53957 Modified: python/branches/p3yk/Include/asdl.h python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/ast.c python/branches/p3yk/Python/compile.c Log: Whoops, fix build breakage. There were still a few uses of the bool type. Remove the last few uses of bool/true/false. Modified: python/branches/p3yk/Include/asdl.h ============================================================================== --- python/branches/p3yk/Include/asdl.h (original) +++ python/branches/p3yk/Include/asdl.h Mon Feb 26 20:14:12 2007 @@ -5,10 +5,6 @@ typedef PyObject * string; typedef PyObject * object; -#ifndef __cplusplus -typedef enum {false, true} bool; -#endif - /* It would be nice if the code generated by asdl_c.py was completely independent of Python, but it is a goal the requires too much work at this stage. So, for example, I'll represent identifiers as Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Mon Feb 26 20:14:12 2007 @@ -2,7 +2,7 @@ /* - __version__ 53873. + __version__ 53956. This module must be committed separately after each AST grammar change; The __version__ number is set to the revision number of the commit @@ -443,10 +443,6 @@ } #define ast2obj_identifier ast2obj_object #define ast2obj_string ast2obj_object -static PyObject* ast2obj_bool(bool b) -{ - return PyBool_FromLong(b); -} static PyObject* ast2obj_int(long b) { @@ -3013,7 +3009,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__", "53873") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53956") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) Modified: python/branches/p3yk/Python/ast.c ============================================================================== --- python/branches/p3yk/Python/ast.c (original) +++ python/branches/p3yk/Python/ast.c Mon Feb 26 20:14:12 2007 @@ -1660,7 +1660,7 @@ int j; slice_ty slc; expr_ty e; - bool simple = true; + int simple = 1; asdl_seq *slices, *elts; slices = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!slices) @@ -1670,7 +1670,7 @@ if (!slc) return NULL; if (slc->kind != Index_kind) - simple = false; + simple = 0; asdl_seq_SET(slices, j / 2, slc); } if (!simple) { Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Mon Feb 26 20:14:12 2007 @@ -119,7 +119,7 @@ int u_firstlineno; /* the first lineno of the block */ int u_lineno; /* the lineno for the current stmt */ - bool u_lineno_set; /* boolean to indicate whether instr + int u_lineno_set; /* boolean to indicate whether instr has been generated with current lineno */ }; @@ -464,7 +464,7 @@ u->u_nfblocks = 0; u->u_firstlineno = lineno; u->u_lineno = 0; - u->u_lineno_set = false; + u->u_lineno_set = 0; u->u_consts = PyDict_New(); if (!u->u_consts) { compiler_unit_free(u); @@ -643,7 +643,7 @@ basicblock *b; if (c->u->u_lineno_set) return; - c->u->u_lineno_set = true; + c->u->u_lineno_set = 1; b = c->u->u_curblock; b->b_instr[off].i_lineno = c->u->u_lineno; } @@ -1675,7 +1675,7 @@ /* XXX(nnorwitz): is there a better way to handle this? for loops are special, we want to be able to trace them each time around, so we need to set an extra line number. */ - c->u->u_lineno_set = false; + c->u->u_lineno_set = 0; ADDOP_JREL(c, FOR_ITER, cleanup); VISIT(c, expr, s->v.For.target); VISIT_SEQ(c, stmt, s->v.For.body); @@ -1898,7 +1898,7 @@ s->v.TryExcept.handlers, i); if (!handler->type && i < n-1) return compiler_error(c, "default 'except:' must be last"); - c->u->u_lineno_set = false; + c->u->u_lineno_set = 0; c->u->u_lineno = handler->lineno; except = compiler_new_block(c); if (except == NULL) @@ -2161,7 +2161,7 @@ /* Always assign a lineno to the next instruction for a stmt. */ c->u->u_lineno = s->lineno; - c->u->u_lineno_set = false; + c->u->u_lineno_set = 0; switch (s->kind) { case FunctionDef_kind: @@ -3015,7 +3015,7 @@ */ if (e->lineno > c->u->u_lineno) { c->u->u_lineno = e->lineno; - c->u->u_lineno_set = false; + c->u->u_lineno_set = 0; } switch (e->kind) { case BoolOp_kind: From python-3000-checkins at python.org Mon Feb 26 22:10:21 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Mon, 26 Feb 2007 22:10:21 +0100 (CET) Subject: [Python-3000-checkins] r53960 - in python/branches/p3yk: Lib/test/test_pep352.py Misc/NEWS Python/ceval.c Message-ID: <20070226211021.CC6841E4006@bag.python.org> Author: brett.cannon Date: Mon Feb 26 22:10:16 2007 New Revision: 53960 Modified: python/branches/p3yk/Lib/test/test_pep352.py python/branches/p3yk/Misc/NEWS python/branches/p3yk/Python/ceval.c Log: You can no longer catch non-BaseException objects; TypeError is raised if such an object is listed in an 'except' clause. Modified: python/branches/p3yk/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep352.py (original) +++ python/branches/p3yk/Lib/test/test_pep352.py Mon Feb 26 22:10:16 2007 @@ -158,34 +158,17 @@ # Raising a string raises TypeError. self.raise_fails("spam") + def test_catch_non_BaseException(self): + # Tryinng to catch an object that does not inherit from BaseException + # is not allowed. + class NonBaseException(object): + pass + self.catch_fails(NonBaseException) + self.catch_fails(NonBaseException()) + def test_catch_string(self): - # Catching a string should trigger a DeprecationWarning. - with guard_warnings_filter(): - warnings.resetwarnings() - warnings.filterwarnings("error") - str_exc = "spam" - try: - try: - raise StandardError - except str_exc: - pass - except DeprecationWarning: - pass - except StandardError: - self.fail("catching a string exception did not raise " - "DeprecationWarning") - # Make sure that even if the string exception is listed in a tuple - # that a warning is raised. - try: - try: - raise StandardError - except (AssertionError, str_exc): - pass - except DeprecationWarning: - pass - except StandardError: - self.fail("catching a string exception specified in a tuple did " - "not raise DeprecationWarning") + # Catching a string is bad. + self.catch_fails("spam") def test_main(): run_unittest(ExceptionClassTests, UsageTests) Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Mon Feb 26 22:10:16 2007 @@ -28,6 +28,8 @@ Core and Builtins ----------------- +- Objects listed in an 'except' clause must inherit from BaseException. + - PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone; and .keys(), .items(), .values() return dict views. Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Mon Feb 26 22:10:16 2007 @@ -1571,7 +1571,7 @@ why == WHY_CONTINUE) retval = POP(); } - else if (PyExceptionClass_Check(v) || PyString_Check(v)) { + else if (PyExceptionClass_Check(v)) { w = POP(); u = POP(); PyErr_Restore(v, w, u); @@ -3916,6 +3916,24 @@ } } +/* + Return a true value if the exception is allowed to be in an 'except' clause, + otherwise return a false value. +*/ +static int +can_catch_exc(PyObject *exc) +{ + if (!(PyExceptionClass_Check(exc) || PyExceptionInstance_Check(exc))) { + PyErr_SetString(PyExc_TypeError, + "catching an object must be a class or " + "instance of BaseException"); + return 0; + } + else { + return 1; + } +} + static PyObject * cmp_outcome(int op, register PyObject *v, register PyObject *w) { @@ -3944,28 +3962,14 @@ length = PyTuple_Size(w); for (i = 0; i < length; i += 1) { PyObject *exc = PyTuple_GET_ITEM(w, i); - if (PyString_Check(exc)) { - int ret_val; - ret_val = PyErr_WarnEx( - PyExc_DeprecationWarning, - "catching of string " - "exceptions is " - "deprecated", 1); - if (ret_val == -1) - return NULL; + if (!can_catch_exc(exc)) { + return NULL; } } } else { - if (PyString_Check(w)) { - int ret_val; - ret_val = PyErr_WarnEx( - PyExc_DeprecationWarning, - "catching of string " - "exceptions is deprecated", - 1); - if (ret_val == -1) - return NULL; + if (!can_catch_exc(w)) { + return NULL; } } res = PyErr_GivenExceptionMatches(v, w); From python-3000-checkins at python.org Mon Feb 26 22:23:58 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 22:23:58 +0100 (CET) Subject: [Python-3000-checkins] r53961 - in python/branches/p3yk: Lib/test/test_compile.py Lib/test/test_grammar.py Lib/test/test_peepholer.py Misc/NEWS Python/ceval.c Python/compile.c Python/peephole.c Message-ID: <20070226212358.2D5D91E4011@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 22:23:50 2007 New Revision: 53961 Modified: python/branches/p3yk/Lib/test/test_compile.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_peepholer.py python/branches/p3yk/Misc/NEWS python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/compile.c python/branches/p3yk/Python/peephole.c Log: Two more patches by Tony Lownds (SF# 1607548). (1) Combines the code paths for MAKE_FUNCTION and MAKE_CLOSURE. Fixes a crash where functions with closures and either annotations or keyword-only arguments result in MAKE_CLOSURE, but only MAKE_FUNCTION has the code to handle annotations or keyword-only arguments. Includes enough tests to trigger the bug. (2) Change peepholer to not bail in the presence of EXTENDED_ARG + MAKE_FUNCTION. Enforce the natural 16-bit limit of annotations in compile.c. Also update Misc/NEWS with the "input = raw_input" change. Modified: python/branches/p3yk/Lib/test/test_compile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compile.py (original) +++ python/branches/p3yk/Lib/test/test_compile.py Mon Feb 26 22:23:50 2007 @@ -393,6 +393,19 @@ del d[..., ...] self.assertEqual((Ellipsis, Ellipsis) in d, False) + def test_annotation_limit(self): + # 16 bits are available for # of annotations, and the + # tuple of annotations names is counted, hence 65534 + # is the max. Ensure the result of too many annotations is a + # SyntaxError. + s = "def f((%s)): pass" + s %= ', '.join('a%d:%d' % (i,i) for i in xrange(65535)) + self.assertRaises(SyntaxError, compile, s, '?', 'exec') + # Test that the max # of annotations compiles. + s = "def f((%s)): pass" + s %= ', '.join('a%d:%d' % (i,i) for i in xrange(65534)) + compile(s, '?', 'exec') + def test_main(): test_support.run_unittest(TestSpecifics) Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Mon Feb 26 22:23:50 2007 @@ -321,6 +321,13 @@ self.assertEquals(f.__annotations__, {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, 'k': 11, 'return': 12}) + + # test MAKE_CLOSURE with a variety of oparg's + closure = 1 + def f(): return closure + def f(x=1): return closure + def f(*, k=1): return closure + def f() -> int: return closure def testLambdef(self): ### lambdef: 'lambda' [varargslist] ':' test Modified: python/branches/p3yk/Lib/test/test_peepholer.py ============================================================================== --- python/branches/p3yk/Lib/test/test_peepholer.py (original) +++ python/branches/p3yk/Lib/test/test_peepholer.py Mon Feb 26 22:23:50 2007 @@ -195,6 +195,14 @@ # 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_make_function_doesnt_bail(self): + def f(): + def g()->1+1: + pass + return g + asm = disassemble(f) + self.assert_('BINARY_ADD' not in asm) def test_main(verbose=None): Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Mon Feb 26 22:23:50 2007 @@ -28,6 +28,10 @@ Core and Builtins ----------------- +- input() becomes raw_input(): the name input() now implements the + functionality formerly known as raw_input(); the name raw_input() + is no longer defined. + - Objects listed in an 'except' clause must inherit from BaseException. - PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone; @@ -82,7 +86,7 @@ backticks (`x`), <> - Removed these Python builtins: - apply(), coerce(), input(), raw_input() + apply(), coerce() - Removed these Python methods: {}.has_key Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Mon Feb 26 22:23:50 2007 @@ -2236,6 +2236,7 @@ break; } + case MAKE_CLOSURE: case MAKE_FUNCTION: { int posdefaults = oparg & 0xff; @@ -2245,6 +2246,12 @@ v = POP(); /* code object */ x = PyFunction_New(v, f->f_globals); Py_DECREF(v); + + if (x != NULL && opcode == MAKE_CLOSURE) { + v = POP(); + err = PyFunction_SetClosure(x, v); + Py_DECREF(v); + } if (x != NULL && num_annotations > 0) { Py_ssize_t name_ix; @@ -2308,34 +2315,6 @@ break; } - case MAKE_CLOSURE: - { - v = POP(); /* code object */ - x = PyFunction_New(v, f->f_globals); - Py_DECREF(v); - if (x != NULL) { - v = POP(); - err = PyFunction_SetClosure(x, v); - Py_DECREF(v); - } - if (x != NULL && oparg > 0) { - v = PyTuple_New(oparg); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - while (--oparg >= 0) { - w = POP(); - PyTuple_SET_ITEM(v, oparg, w); - } - err = PyFunction_SetDefaults(x, v); - Py_DECREF(v); - } - PUSH(x); - break; - } - case BUILD_SLICE: if (oparg == 3) w = POP(); Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Mon Feb 26 22:23:50 2007 @@ -836,6 +836,8 @@ return -NARGS(oparg)-2; case MAKE_FUNCTION: return -NARGS(oparg) - ((oparg >> 16) & 0xffff); + case MAKE_CLOSURE: + return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff); #undef NARGS case BUILD_SLICE: if (oparg == 3) @@ -843,8 +845,6 @@ else return -1; - case MAKE_CLOSURE: - return -oparg; case LOAD_CLOSURE: return 1; case LOAD_DEREF: @@ -1367,8 +1367,12 @@ 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. */ + /* Push arg annotations and a list of the argument names. Return the # + of items pushed. The expressions are evaluated out-of-order wrt the + source code. + + More than 2^16-1 annotations is a SyntaxError. Returns -1 on error. + */ static identifier return_str; PyObject *names; int len; @@ -1399,6 +1403,12 @@ } len = PyList_GET_SIZE(names); + if (len > 65534) { + /* len must fit in 16 bits, and len is incremented below */ + PyErr_SetString(PyExc_SyntaxError, + "too many annotations"); + goto error; + } if (len) { /* convert names to a tuple and place on stack */ PyObject *elt; @@ -1449,6 +1459,9 @@ if (args->defaults) VISIT_SEQ(c, expr, args->defaults); num_annotations = compiler_visit_annotations(c, args, returns); + if (num_annotations < 0) + return 0; + assert((num_annotations & 0xFFFF) == num_annotations); if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s, s->lineno)) Modified: python/branches/p3yk/Python/peephole.c ============================================================================== --- python/branches/p3yk/Python/peephole.c (original) +++ python/branches/p3yk/Python/peephole.c Mon Feb 26 22:23:50 2007 @@ -261,10 +261,12 @@ The consts object should still be in list form to allow new constants to be appended. - To keep the optimizer simple, it bails out (does nothing) for code - containing extended arguments or that has a length over 32,700. That - allows us to avoid overflow and sign issues. Likewise, it bails when - the lineno table has complex encoding for gaps >= 255. + To keep the optimizer simple, it bails out (does nothing) for code that + has a length over 32,700, and does not calculate extended arguments. + That allows us to avoid overflow and sign issues. Likewise, it bails when + the lineno table has complex encoding for gaps >= 255. EXTENDED_ARG can + appear before MAKE_FUNCTION; in this case both opcodes are skipped. + EXTENDED_ARG preceding any other opcode causes the optimizer to bail. Optimizations are restricted to simple transformations occuring within a single basic block. All transformations keep the code size the same or @@ -535,7 +537,11 @@ break; case EXTENDED_ARG: - goto exitUnchanged; + if (codestr[i+3] != MAKE_FUNCTION) + goto exitUnchanged; + /* don't visit MAKE_FUNCTION as GETARG will be wrong */ + i += 3; + break; /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ /* Remove unreachable JUMPs after RETURN */ From python-3000-checkins at python.org Mon Feb 26 22:36:03 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Mon, 26 Feb 2007 22:36:03 +0100 (CET) Subject: [Python-3000-checkins] r53962 - python/branches/p3yk/Misc/NEWS Message-ID: <20070226213603.C02391E4014@bag.python.org> Author: neal.norwitz Date: Mon Feb 26 22:35:59 2007 New Revision: 53962 Modified: python/branches/p3yk/Misc/NEWS Log: raw_input() really was removed, only input() was resurrected. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Mon Feb 26 22:35:59 2007 @@ -86,7 +86,7 @@ backticks (`x`), <> - Removed these Python builtins: - apply(), coerce() + apply(), coerce(), raw_input() - Removed these Python methods: {}.has_key From python-3000-checkins at python.org Mon Feb 26 22:42:59 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Mon, 26 Feb 2007 22:42:59 +0100 (CET) Subject: [Python-3000-checkins] r53963 - python/branches/p3yk/Misc/NEWS Message-ID: <20070226214259.AA95B1E4018@bag.python.org> Author: neal.norwitz Date: Mon Feb 26 22:42:55 2007 New Revision: 53963 Modified: python/branches/p3yk/Misc/NEWS Log: The raw_input name was removed, but the implementation was moved to input. So don't declare that it was removed, just leave the original description. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Mon Feb 26 22:42:55 2007 @@ -86,7 +86,7 @@ backticks (`x`), <> - Removed these Python builtins: - apply(), coerce(), raw_input() + apply(), coerce() - Removed these Python methods: {}.has_key From python-3000-checkins at python.org Mon Feb 26 23:01:20 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Mon, 26 Feb 2007 23:01:20 +0100 (CET) Subject: [Python-3000-checkins] r53964 - in python/branches/p3yk: Misc/NEWS Python/ceval.c Message-ID: <20070226220120.B74731E400C@bag.python.org> Author: brett.cannon Date: Mon Feb 26 23:01:14 2007 New Revision: 53964 Modified: python/branches/p3yk/Misc/NEWS python/branches/p3yk/Python/ceval.c Log: Make it so TypeError is raised if an instance of an object is put in an 'except' clause. Also refactor some code to help keep Neal Norwitz happy. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Mon Feb 26 23:01:14 2007 @@ -32,7 +32,7 @@ functionality formerly known as raw_input(); the name raw_input() is no longer defined. -- Objects listed in an 'except' clause must inherit from BaseException. +- Classes listed in an 'except' clause must inherit from BaseException. - PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone; and .keys(), .items(), .values() return dict views. Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Mon Feb 26 23:01:14 2007 @@ -3895,23 +3895,8 @@ } } -/* - Return a true value if the exception is allowed to be in an 'except' clause, - otherwise return a false value. -*/ -static int -can_catch_exc(PyObject *exc) -{ - if (!(PyExceptionClass_Check(exc) || PyExceptionInstance_Check(exc))) { - PyErr_SetString(PyExc_TypeError, - "catching an object must be a class or " - "instance of BaseException"); - return 0; - } - else { - return 1; - } -} +#define CANNOT_CATCH_MSG "catching classes that do not inherit from"\ + "BaseException is not allowed" static PyObject * cmp_outcome(int op, register PyObject *v, register PyObject *w) @@ -3941,13 +3926,17 @@ length = PyTuple_Size(w); for (i = 0; i < length; i += 1) { PyObject *exc = PyTuple_GET_ITEM(w, i); - if (!can_catch_exc(exc)) { + if (!PyExceptionClass_Check(exc)) { + PyErr_SetString(PyExc_TypeError, + CANNOT_CATCH_MSG); return NULL; } } } else { - if (!can_catch_exc(w)) { + if (!PyExceptionClass_Check(w)) { + PyErr_SetString(PyExc_TypeError, + CANNOT_CATCH_MSG); return NULL; } } From python-3000-checkins at python.org Mon Feb 26 23:01:30 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 23:01:30 +0100 (CET) Subject: [Python-3000-checkins] r53965 - python/branches/p3yk/Lib/test/regrtest.py Message-ID: <20070226220130.B192A1E4007@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 23:01:28 2007 New Revision: 53965 Modified: python/branches/p3yk/Lib/test/regrtest.py Log: Add -d/--debug option to print traceback without -v/--verbose. Modified: python/branches/p3yk/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk/Lib/test/regrtest.py (original) +++ python/branches/p3yk/Lib/test/regrtest.py Mon Feb 26 23:01:28 2007 @@ -10,6 +10,7 @@ -v: verbose -- run tests in verbose mode with output to stdout -w: verbose2 -- re-run failed tests in verbose mode +-d: debug -- print traceback for failed tests -q: quiet -- don't print anything except if a test fails -g: generate -- write the output file for a test instead of comparing it -x: exclude -- arguments are tests to *exclude* @@ -179,7 +180,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False, exclude=False, single=False, randomize=False, fromfile=None, findleaks=False, use_resources=None, trace=False, coverdir='coverage', - runleaks=False, huntrleaks=False, verbose2=False): + runleaks=False, huntrleaks=False, verbose2=False, debug=False): """Execute a test suite. This also parses command-line options and modifies its behavior @@ -204,12 +205,13 @@ test_support.record_original_stdout(sys.stdout) try: - opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:TD:NLR:wM:', + opts, args = getopt.getopt(sys.argv[1:], 'dhvgqxsrf:lu:t:TD:NLR:wM:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir', 'runleaks', 'huntrleaks=', 'verbose2', 'memlimit=', + 'debug', ]) except getopt.error as msg: usage(2, msg) @@ -224,6 +226,8 @@ verbose += 1 elif o in ('-w', '--verbose2'): verbose2 = True + elif o in ('-d', '--debug'): + debug = True elif o in ('-q', '--quiet'): quiet = True; verbose = 0 @@ -435,7 +439,7 @@ try: test_support.verbose = 1 ok = runtest(test, generate, 1, quiet, testdir, - huntrleaks) + huntrleaks, debug) except KeyboardInterrupt: # print a newline separate from the ^C print() @@ -496,7 +500,8 @@ tests.sort() return stdtests + tests -def runtest(test, generate, verbose, quiet, testdir=None, huntrleaks=False): +def runtest(test, generate, verbose, quiet, testdir=None, + huntrleaks=False, debug=False): """Run a single test. test -- the name of the test @@ -507,6 +512,8 @@ testdir -- test directory huntrleaks -- run multiple times to test for leaks; requires a debug build; a triple corresponding to -R's three arguments + debug -- if true, print tracebacks for failed tests regardless of + verbose setting Return: -2 test skipped because resource denied -1 test skipped for some other reason @@ -516,12 +523,12 @@ try: return runtest_inner(test, generate, verbose, quiet, testdir, - huntrleaks) + huntrleaks, debug) finally: cleanup_test_droppings(test, verbose) def runtest_inner(test, generate, verbose, quiet, - testdir=None, huntrleaks=False): + testdir=None, huntrleaks=False, debug=False): test_support.unload(test) if not testdir: testdir = findtestdir() @@ -576,7 +583,7 @@ type, value = sys.exc_info()[:2] print("test", test, "crashed --", str(type) + ":", value) sys.stdout.flush() - if verbose: + if verbose or debug: traceback.print_exc(file=sys.stdout) sys.stdout.flush() return 0 From python-3000-checkins at python.org Mon Feb 26 23:21:29 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 26 Feb 2007 23:21:29 +0100 (CET) Subject: [Python-3000-checkins] r53966 - python/branches/p3yk/Lib/linecache.py Message-ID: <20070226222129.229341E4006@bag.python.org> Author: guido.van.rossum Date: Mon Feb 26 23:21:25 2007 New Revision: 53966 Modified: python/branches/p3yk/Lib/linecache.py Log: Fix another loop over a dict that may change... :-( Modified: python/branches/p3yk/Lib/linecache.py ============================================================================== --- python/branches/p3yk/Lib/linecache.py (original) +++ python/branches/p3yk/Lib/linecache.py Mon Feb 26 23:21:25 2007 @@ -45,7 +45,7 @@ (This is not checked upon each call!)""" if filename is None: - filenames = cache.keys() + filenames = list(cache.keys()) else: if filename in cache: filenames = [filename] From python-3000-checkins at python.org Mon Feb 26 23:23:36 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Mon, 26 Feb 2007 23:23:36 +0100 (CET) Subject: [Python-3000-checkins] r53967 - in python/branches/p3yk: Lib/ctypes/test/test_structures.py Lib/test/output/test_logging Lib/test/test_exceptions.py Lib/test/test_generators.py Lib/test/test_modulefinder.py Lib/test/test_weakref.py Lib/traceback.py Lib/weakref.py Misc/NEWS Objects/exceptions.c PC/config.c PC/os2emx/config.c Python/errors.c Python/pythonrun.c RISCOS/Modules/config.c Message-ID: <20070226222336.156691E4006@bag.python.org> Author: neal.norwitz Date: Mon Feb 26 23:22:47 2007 New Revision: 53967 Modified: python/branches/p3yk/Lib/ctypes/test/test_structures.py python/branches/p3yk/Lib/test/output/test_logging python/branches/p3yk/Lib/test/test_exceptions.py python/branches/p3yk/Lib/test/test_generators.py python/branches/p3yk/Lib/test/test_modulefinder.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/traceback.py python/branches/p3yk/Lib/weakref.py python/branches/p3yk/Misc/NEWS python/branches/p3yk/Objects/exceptions.c python/branches/p3yk/PC/config.c python/branches/p3yk/PC/os2emx/config.c python/branches/p3yk/Python/errors.c python/branches/p3yk/Python/pythonrun.c python/branches/p3yk/RISCOS/Modules/config.c Log: Remove the exceptions builtin module, all the exceptions are already builtin. Modified: python/branches/p3yk/Lib/ctypes/test/test_structures.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_structures.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_structures.py Mon Feb 26 23:22:47 2007 @@ -294,20 +294,20 @@ # In Python 2.5, Exception is a new-style class, and the repr changed if issubclass(Exception, object): self.failUnlessEqual(msg, - "(Phone) : " + "(Phone) : " "expected string or Unicode object, int found") else: self.failUnlessEqual(msg, - "(Phone) exceptions.TypeError: " + "(Phone) TypeError: " "expected string or Unicode object, int found") cls, msg = self.get_except(Person, "Someone", ("a", "b", "c")) self.failUnlessEqual(cls, RuntimeError) if issubclass(Exception, object): self.failUnlessEqual(msg, - "(Phone) : too many initializers") + "(Phone) : too many initializers") else: - self.failUnlessEqual(msg, "(Phone) exceptions.ValueError: too many initializers") + self.failUnlessEqual(msg, "(Phone) ValueError: too many initializers") def get_except(self, func, *args): Modified: python/branches/p3yk/Lib/test/output/test_logging ============================================================================== --- python/branches/p3yk/Lib/test/output/test_logging (original) +++ python/branches/p3yk/Lib/test/output/test_logging Mon Feb 26 23:22:47 2007 @@ -488,12 +488,12 @@ -- log_test4 begin --------------------------------------------------- config0: ok. config1: ok. -config2: -config3: +config2: +config3: -- log_test4 end --------------------------------------------------- -- log_test5 begin --------------------------------------------------- ERROR:root:just testing -... Don't panic! +... Don't panic! -- log_test5 end --------------------------------------------------- -- logrecv output begin --------------------------------------------------- ERR -> CRITICAL: Message 0 (via logrecv.tcp.ERR) Modified: python/branches/p3yk/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk/Lib/test/test_exceptions.py Mon Feb 26 23:22:47 2007 @@ -15,15 +15,6 @@ class ExceptionTests(unittest.TestCase): - def testReload(self): - # Reloading the built-in exceptions module failed prior to Py2.2, while it - # should act the same as reloading built-in sys. - try: - import exceptions - reload(exceptions) - except ImportError as e: - self.fail("reloading exceptions: %s" % e) - def raise_catch(self, exc, excname): try: raise exc, "spam" @@ -289,7 +280,7 @@ if type(e) is not exc: raise # Verify module name - self.assertEquals(type(e).__module__, 'exceptions') + self.assertEquals(type(e).__module__, '__builtin__') # Verify no ref leaks in Exc_str() s = str(e) for checkArgName in expected: Modified: python/branches/p3yk/Lib/test/test_generators.py ============================================================================== --- python/branches/p3yk/Lib/test/test_generators.py (original) +++ python/branches/p3yk/Lib/test/test_generators.py Mon Feb 26 23:22:47 2007 @@ -1691,7 +1691,7 @@ >>> g.next() >>> del g >>> sys.stderr.getvalue().startswith( -... "Exception exceptions.RuntimeError: 'generator ignored GeneratorExit' in " +... "Exception RuntimeError: 'generator ignored GeneratorExit' in " ... ) True >>> sys.stderr = old @@ -1808,7 +1808,7 @@ ... del l ... err = sys.stderr.getvalue().strip() ... err.startswith( -... "Exception exceptions.RuntimeError: RuntimeError() in <" +... "Exception RuntimeError: RuntimeError() in <" ... ) ... err.endswith("> ignored") ... len(err.splitlines()) Modified: python/branches/p3yk/Lib/test/test_modulefinder.py ============================================================================== --- python/branches/p3yk/Lib/test/test_modulefinder.py (original) +++ python/branches/p3yk/Lib/test/test_modulefinder.py Mon Feb 26 23:22:47 2007 @@ -87,7 +87,7 @@ "a.module", ["a", "a.module", "b", "b.x", "b.y", "b.z", - "__future__", "sys", "exceptions"], + "__future__", "sys", "gc"], ["blahblah", "z"], [], """\ mymodule.py @@ -96,11 +96,11 @@ from __future__ import absolute_import import sys # sys import blahblah # fails - import exceptions # exceptions + import gc # gc import b.x # b.x from b import y # b.y from b.z import * # b.z.* -a/exceptions.py +a/gc.py a/sys.py import mymodule a/b/__init__.py @@ -123,7 +123,7 @@ "a.b.c", "a.b.c.moduleC", "a.b.c.d", "a.b.c.e", "a.b.x", - "exceptions"], + "gc"], [], [], """\ mymodule.py @@ -131,8 +131,8 @@ from .b import y, z # a.b.y, a.b.z a/module.py from __future__ import absolute_import # __future__ - import exceptions # exceptions -a/exceptions.py + import gc # gc +a/gc.py a/sys.py a/b/__init__.py from ..b import x # a.b.x @@ -170,7 +170,7 @@ a/another.py a/module.py from .b import y, z # a.b.y, a.b.z -a/exceptions.py +a/gc.py a/sys.py a/b/__init__.py from .c import moduleC # a.b.c.moduleC 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 Mon Feb 26 23:22:47 2007 @@ -104,9 +104,9 @@ def check(proxy): proxy.bar - self.assertRaises(weakref.ReferenceError, check, ref1) - self.assertRaises(weakref.ReferenceError, check, ref2) - self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C())) + self.assertRaises(ReferenceError, check, ref1) + self.assertRaises(ReferenceError, check, ref2) + self.assertRaises(ReferenceError, bool, weakref.proxy(C())) self.assert_(self.cbcalled == 2) def check_basic_ref(self, factory): Modified: python/branches/p3yk/Lib/traceback.py ============================================================================== --- python/branches/p3yk/Lib/traceback.py (original) +++ python/branches/p3yk/Lib/traceback.py Mon Feb 26 23:22:47 2007 @@ -169,7 +169,7 @@ stype = etype.__name__ smod = etype.__module__ - if smod not in ("exceptions", "__main__", "__builtin__"): + if smod not in ("__main__", "__builtin__"): stype = smod + '.' + stype if not issubclass(etype, SyntaxError): Modified: python/branches/p3yk/Lib/weakref.py ============================================================================== --- python/branches/p3yk/Lib/weakref.py (original) +++ python/branches/p3yk/Lib/weakref.py Mon Feb 26 23:22:47 2007 @@ -20,8 +20,6 @@ ProxyType, ReferenceType) -from exceptions import ReferenceError - ProxyTypes = (ProxyType, CallableProxyType) Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Mon Feb 26 23:22:47 2007 @@ -28,6 +28,8 @@ Core and Builtins ----------------- +- Remove the exceptions module, all the exceptions are already builtin. + - input() becomes raw_input(): the name input() now implements the functionality formerly known as raw_input(); the name raw_input() is no longer defined. Modified: python/branches/p3yk/Objects/exceptions.c ============================================================================== --- python/branches/p3yk/Objects/exceptions.c (original) +++ python/branches/p3yk/Objects/exceptions.c Mon Feb 26 23:22:47 2007 @@ -10,20 +10,11 @@ #include "osdefs.h" #define MAKE_IT_NONE(x) (x) = Py_None; Py_INCREF(Py_None); -#define EXC_MODULE_NAME "exceptions." /* NOTE: If the exception class hierarchy changes, don't forget to update * Lib/test/exception_hierarchy.txt */ -PyDoc_STRVAR(exceptions_doc, "Python's standard exception class hierarchy.\n\ -\n\ -Exceptions found here are defined both in the exceptions module and the\n\ -built-in namespace. It is recommended that user-defined exceptions\n\ -inherit from Exception. See the documentation for the exception\n\ -inheritance hierarchy.\n\ -"); - /* * BaseException */ @@ -282,7 +273,7 @@ static PyTypeObject _PyExc_BaseException = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - EXC_MODULE_NAME "BaseException", /*tp_name*/ + "BaseException", /*tp_name*/ sizeof(PyBaseExceptionObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)BaseException_dealloc, /*tp_dealloc*/ @@ -333,7 +324,7 @@ static PyTypeObject _PyExc_ ## EXCNAME = { \ PyObject_HEAD_INIT(NULL) \ 0, \ - EXC_MODULE_NAME # EXCNAME, \ + # EXCNAME, \ sizeof(PyBaseExceptionObject), \ 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, 0, 0, \ @@ -349,7 +340,7 @@ static PyTypeObject _PyExc_ ## EXCNAME = { \ PyObject_HEAD_INIT(NULL) \ 0, \ - EXC_MODULE_NAME # EXCNAME, \ + # EXCNAME, \ sizeof(Py ## EXCSTORE ## Object), \ 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, \ @@ -365,7 +356,7 @@ static PyTypeObject _PyExc_ ## EXCNAME = { \ PyObject_HEAD_INIT(NULL) \ 0, \ - EXC_MODULE_NAME # EXCNAME, \ + # EXCNAME, \ sizeof(Py ## EXCSTORE ## Object), 0, \ (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \ (reprfunc)EXCSTR, 0, 0, 0, \ @@ -1632,7 +1623,7 @@ static PyTypeObject _PyExc_UnicodeEncodeError = { PyObject_HEAD_INIT(NULL) 0, - EXC_MODULE_NAME "UnicodeEncodeError", + "UnicodeEncodeError", sizeof(PyUnicodeErrorObject), 0, (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (reprfunc)UnicodeEncodeError_str, 0, 0, 0, @@ -1704,7 +1695,7 @@ static PyTypeObject _PyExc_UnicodeDecodeError = { PyObject_HEAD_INIT(NULL) 0, - EXC_MODULE_NAME "UnicodeDecodeError", + "UnicodeDecodeError", sizeof(PyUnicodeErrorObject), 0, (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (reprfunc)UnicodeDecodeError_str, 0, 0, 0, @@ -1802,7 +1793,7 @@ static PyTypeObject _PyExc_UnicodeTranslateError = { PyObject_HEAD_INIT(NULL) 0, - EXC_MODULE_NAME "UnicodeTranslateError", + "UnicodeTranslateError", sizeof(PyUnicodeErrorObject), 0, (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (reprfunc)UnicodeTranslateError_str, 0, 0, 0, @@ -1956,17 +1947,10 @@ */ PyObject *PyExc_MemoryErrorInst=NULL; -/* module global functions */ -static PyMethodDef functions[] = { - /* Sentinel */ - {NULL, NULL} -}; - #define PRE_INIT(TYPE) if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \ Py_FatalError("exceptions bootstrapping error."); #define POST_INIT(TYPE) Py_INCREF(PyExc_ ## TYPE); \ - PyModule_AddObject(m, # TYPE, PyExc_ ## TYPE); \ if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \ Py_FatalError("Module dictionary insertion problem."); @@ -1996,7 +1980,7 @@ PyMODINIT_FUNC _PyExc_Init(void) { - PyObject *m, *bltinmod, *bdict; + PyObject *bltinmod, *bdict; PRE_INIT(BaseException) PRE_INIT(Exception) @@ -2053,10 +2037,6 @@ PRE_INIT(ImportWarning) PRE_INIT(UnicodeWarning) - m = Py_InitModule4("exceptions", functions, exceptions_doc, - (PyObject *)NULL, PYTHON_API_VERSION); - if (m == NULL) return; - bltinmod = PyImport_ImportModule("__builtin__"); if (bltinmod == NULL) Py_FatalError("exceptions bootstrapping error."); Modified: python/branches/p3yk/PC/config.c ============================================================================== --- python/branches/p3yk/PC/config.c (original) +++ python/branches/p3yk/PC/config.c Mon Feb 26 23:22:47 2007 @@ -161,7 +161,6 @@ {"__main__", NULL}, {"__builtin__", NULL}, {"sys", NULL}, - {"exceptions", NULL}, {"_types", init_types}, Modified: python/branches/p3yk/PC/os2emx/config.c ============================================================================== --- python/branches/p3yk/PC/os2emx/config.c (original) +++ python/branches/p3yk/PC/os2emx/config.c Mon Feb 26 23:22:47 2007 @@ -172,7 +172,6 @@ {"__main__", NULL}, {"__builtin__", NULL}, {"sys", NULL}, - {"exceptions", NULL}, /* This lives in gcmodule.c */ {"gc", initgc}, Modified: python/branches/p3yk/Python/errors.c ============================================================================== --- python/branches/p3yk/Python/errors.c (original) +++ python/branches/p3yk/Python/errors.c Mon Feb 26 23:22:47 2007 @@ -612,7 +612,8 @@ PyFile_WriteString("", f); else { char* modstr = PyString_AsString(moduleName); - if (modstr) + if (modstr && + strcmp(modstr, "__builtin__") != 0) { PyFile_WriteString(modstr, f); PyFile_WriteString(".", f); Modified: python/branches/p3yk/Python/pythonrun.c ============================================================================== --- python/branches/p3yk/Python/pythonrun.c (original) +++ python/branches/p3yk/Python/pythonrun.c Mon Feb 26 23:22:47 2007 @@ -221,7 +221,6 @@ /* initialize builtin exceptions */ _PyExc_Init(); - _PyImport_FixupExtension("exceptions", "exceptions"); /* phase 2 of builtins */ _PyImport_FixupExtension("__builtin__", "__builtin__"); @@ -1168,7 +1167,7 @@ err = PyFile_WriteString("", f); else { char* modstr = PyString_AsString(moduleName); - if (modstr && strcmp(modstr, "exceptions")) + if (modstr && strcmp(modstr, "__builtin__")) { err = PyFile_WriteString(modstr, f); err += PyFile_WriteString(".", f); Modified: python/branches/p3yk/RISCOS/Modules/config.c ============================================================================== --- python/branches/p3yk/RISCOS/Modules/config.c (original) +++ python/branches/p3yk/RISCOS/Modules/config.c Mon Feb 26 23:22:47 2007 @@ -63,7 +63,6 @@ {"__main__", NULL}, {"__builtin__", NULL}, {"sys", NULL}, - {"exceptions", NULL}, /* This lives in gcmodule.c */ {"gc", initgc}, From python-3000-checkins at python.org Tue Feb 27 00:12:32 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 27 Feb 2007 00:12:32 +0100 (CET) Subject: [Python-3000-checkins] r53972 - python/branches/p3yk/Objects/dictobject.c Message-ID: <20070226231232.2E5D01E4006@bag.python.org> Author: neal.norwitz Date: Tue Feb 27 00:12:28 2007 New Revision: 53972 Modified: python/branches/p3yk/Objects/dictobject.c Log: Add TODO Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Tue Feb 27 00:12:28 2007 @@ -2438,6 +2438,14 @@ return (PyObject *)dv; } +/* TODO(guido): The views objects are not complete: + + * support more set operations + * support arbitrary mappings? + - either these should be static or exported in dictobject.h + - if public then they should probably be in builtins +*/ + /* Forward */ PyTypeObject PyDictKeys_Type; PyTypeObject PyDictItems_Type; From python-3000-checkins at python.org Tue Feb 27 00:33:29 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 27 Feb 2007 00:33:29 +0100 (CET) Subject: [Python-3000-checkins] r53973 - python/branches/p3yk/Lib/test/test_traceback.py Message-ID: <20070226233329.858F31E4007@bag.python.org> Author: brett.cannon Date: Tue Feb 27 00:33:27 2007 New Revision: 53973 Modified: python/branches/p3yk/Lib/test/test_traceback.py Log: Fix a broken test in test_traceback where the module name was being tacked on needlessly. Modified: python/branches/p3yk/Lib/test/test_traceback.py ============================================================================== --- python/branches/p3yk/Lib/test/test_traceback.py (original) +++ python/branches/p3yk/Lib/test/test_traceback.py Tue Feb 27 00:33:27 2007 @@ -118,9 +118,7 @@ err = traceback.format_exception_only(X, X()) self.assertEqual(len(err), 1) str_value = '' % X.__name__ - self.assertEqual(err[0], "%s.%s: %s\n" % (X.__module__, - X.__name__, - str_value)) + self.assertEqual(err[0], "%s: %s\n" % ( X.__name__, str_value)) def test_without_exception(self): err = traceback.format_exception_only(None, None) From python-3000-checkins at python.org Tue Feb 27 01:12:45 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 27 Feb 2007 01:12:45 +0100 (CET) Subject: [Python-3000-checkins] r53978 - python/branches/p3yk/Lib/test/test_traceback.py Message-ID: <20070227001245.ECD821E4006@bag.python.org> Author: brett.cannon Date: Tue Feb 27 01:12:43 2007 New Revision: 53978 Modified: python/branches/p3yk/Lib/test/test_traceback.py Log: Tweak the fix for test_traceback since the fix for it to run on its own broke it under regrtest. 'traceback' likes to strip out the module name if it is __main__ or __builtin__ but not in other cases. Modified: python/branches/p3yk/Lib/test/test_traceback.py ============================================================================== --- python/branches/p3yk/Lib/test/test_traceback.py (original) +++ python/branches/p3yk/Lib/test/test_traceback.py Tue Feb 27 01:12:43 2007 @@ -118,7 +118,11 @@ err = traceback.format_exception_only(X, X()) self.assertEqual(len(err), 1) str_value = '' % X.__name__ - self.assertEqual(err[0], "%s: %s\n" % ( X.__name__, str_value)) + if X.__module__ in ('__main__', '__builtin__'): + str_name = X.__name__ + else: + str_name = '.'.join([X.__module__, X.__name__]) + self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value)) def test_without_exception(self): err = traceback.format_exception_only(None, None) From python-3000-checkins at python.org Tue Feb 27 01:16:13 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 27 Feb 2007 01:16:13 +0100 (CET) Subject: [Python-3000-checkins] r53979 - in python/branches/p3yk: Lib/ConfigParser.py Lib/test/test_dbm.py Lib/test/test_exceptions.py Lib/test/test_file.py Lib/test/test_pep352.py Lib/traceback.py Misc/NEWS Objects/exceptions.c Message-ID: <20070227001613.B2D441E4006@bag.python.org> Author: brett.cannon Date: Tue Feb 27 01:15:55 2007 New Revision: 53979 Modified: python/branches/p3yk/Lib/ConfigParser.py python/branches/p3yk/Lib/test/test_dbm.py python/branches/p3yk/Lib/test/test_exceptions.py python/branches/p3yk/Lib/test/test_file.py python/branches/p3yk/Lib/test/test_pep352.py python/branches/p3yk/Lib/traceback.py python/branches/p3yk/Misc/NEWS python/branches/p3yk/Objects/exceptions.c Log: Remove the ability to slice/index on exceptions per PEP 352. Modified: python/branches/p3yk/Lib/ConfigParser.py ============================================================================== --- python/branches/p3yk/Lib/ConfigParser.py (original) +++ python/branches/p3yk/Lib/ConfigParser.py Tue Feb 27 01:15:55 2007 @@ -569,7 +569,7 @@ value = value % vars except KeyError as e: raise InterpolationMissingOptionError( - option, section, rawval, e[0]) + option, section, rawval, e.message) else: break if "%(" in value: Modified: python/branches/p3yk/Lib/test/test_dbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dbm.py (original) +++ python/branches/p3yk/Lib/test/test_dbm.py Tue Feb 27 01:15:55 2007 @@ -17,7 +17,7 @@ try: os.unlink(filename + suffix) except OSError as e: - (errno, strerror) = e + (errno, strerror) = e.errno, e.strerror # if we can't delete the file because of permissions, # nothing will work, so skip the test if errno == 1: Modified: python/branches/p3yk/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk/Lib/test/test_exceptions.py Tue Feb 27 01:15:55 2007 @@ -302,13 +302,6 @@ 'pickled "%r", attribute "%s' % (e, checkArgName)) - def testSlicing(self): - # Test that you can slice an exception directly instead of requiring - # going through the 'args' attribute. - args = (1, 2, 3) - exc = BaseException(*args) - self.failUnlessEqual(exc[:], args) - def testKeywordArgs(self): # test that builtin exception don't take keyword args, # but user-defined subclasses can if they want Modified: python/branches/p3yk/Lib/test/test_file.py ============================================================================== --- python/branches/p3yk/Lib/test/test_file.py (original) +++ python/branches/p3yk/Lib/test/test_file.py Tue Feb 27 01:15:55 2007 @@ -156,7 +156,7 @@ try: f = open(TESTFN, bad_mode) except ValueError as msg: - if msg[0] != 0: + if msg.message != 0: s = str(msg) if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: self.fail("bad error message for invalid mode: %s" % s) Modified: python/branches/p3yk/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep352.py (original) +++ python/branches/p3yk/Lib/test/test_pep352.py Tue Feb 27 01:15:55 2007 @@ -15,7 +15,7 @@ self.failUnless(issubclass(Exception, object)) def verify_instance_interface(self, ins): - for attr in ("args", "message", "__str__", "__repr__", "__getitem__"): + for attr in ("args", "message", "__str__", "__repr__"): self.failUnless(hasattr(ins, attr), "%s missing %s attribute" % (ins.__class__.__name__, attr)) @@ -72,8 +72,7 @@ inheritance_tree.close() self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set) - interface_tests = ("length", "args", "message", "str", "unicode", "repr", - "indexing") + interface_tests = ("length", "args", "message", "str", "unicode", "repr") def interface_test_driver(self, results): for test_name, (given, expected) in zip(self.interface_tests, results): @@ -86,7 +85,7 @@ exc = Exception(arg) results = ([len(exc.args), 1], [exc.args[0], arg], [exc.message, arg], [str(exc), str(arg)], [unicode(exc), unicode(arg)], - [repr(exc), exc.__class__.__name__ + repr(exc.args)], [exc[0], arg]) + [repr(exc), exc.__class__.__name__ + repr(exc.args)]) self.interface_test_driver(results) def test_interface_multi_arg(self): @@ -97,8 +96,7 @@ results = ([len(exc.args), arg_count], [exc.args, args], [exc.message, ''], [str(exc), str(args)], [unicode(exc), unicode(args)], - [repr(exc), exc.__class__.__name__ + repr(exc.args)], - [exc[-1], args[-1]]) + [repr(exc), exc.__class__.__name__ + repr(exc.args)]) self.interface_test_driver(results) def test_interface_no_arg(self): @@ -106,7 +104,7 @@ exc = Exception() results = ([len(exc.args), 0], [exc.args, tuple()], [exc.message, ''], [str(exc), ''], [unicode(exc), u''], - [repr(exc), exc.__class__.__name__ + '()'], [True, True]) + [repr(exc), exc.__class__.__name__ + '()']) self.interface_test_driver(results) class UsageTests(unittest.TestCase): @@ -166,6 +164,10 @@ self.catch_fails(NonBaseException) self.catch_fails(NonBaseException()) + def test_catch_BaseException_instance(self): + # Catching an instance of a BaseException subclass won't work. + self.catch_fails(BaseException()) + def test_catch_string(self): # Catching a string is bad. self.catch_fails("spam") Modified: python/branches/p3yk/Lib/traceback.py ============================================================================== --- python/branches/p3yk/Lib/traceback.py (original) +++ python/branches/p3yk/Lib/traceback.py Tue Feb 27 01:15:55 2007 @@ -178,7 +178,7 @@ # It was a syntax error; show exactly where the problem was found. lines = [] try: - msg, (filename, lineno, offset, badline) = value + msg, (filename, lineno, offset, badline) = value.args except Exception: pass else: Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Tue Feb 27 01:15:55 2007 @@ -28,6 +28,8 @@ Core and Builtins ----------------- +- Removing indexing/slicing on BaseException. + - Remove the exceptions module, all the exceptions are already builtin. - input() becomes raw_input(): the name input() now implements the Modified: python/branches/p3yk/Objects/exceptions.c ============================================================================== --- python/branches/p3yk/Objects/exceptions.c (original) +++ python/branches/p3yk/Objects/exceptions.c Tue Feb 27 01:15:55 2007 @@ -174,33 +174,6 @@ }; - -static PyObject * -BaseException_getitem(PyBaseExceptionObject *self, Py_ssize_t index) -{ - return PySequence_GetItem(self->args, index); -} - -static PyObject * -BaseException_getslice(PyBaseExceptionObject *self, - Py_ssize_t start, Py_ssize_t stop) -{ - return PySequence_GetSlice(self->args, start, stop); -} - -static PySequenceMethods BaseException_as_sequence = { - 0, /* sq_length; */ - 0, /* sq_concat; */ - 0, /* sq_repeat; */ - (ssizeargfunc)BaseException_getitem, /* sq_item; */ - (ssizessizeargfunc)BaseException_getslice, /* sq_slice; */ - 0, /* sq_ass_item; */ - 0, /* sq_ass_slice; */ - 0, /* sq_contains; */ - 0, /* sq_inplace_concat; */ - 0 /* sq_inplace_repeat; */ -}; - static PyMemberDef BaseException_members[] = { {"message", T_OBJECT, offsetof(PyBaseExceptionObject, message), 0, PyDoc_STR("exception message")}, @@ -283,7 +256,7 @@ 0, /* tp_compare; */ (reprfunc)BaseException_repr, /*tp_repr*/ 0, /*tp_as_number*/ - &BaseException_as_sequence, /*tp_as_sequence*/ + 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ From python-3000-checkins at python.org Tue Feb 27 04:41:10 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 27 Feb 2007 04:41:10 +0100 (CET) Subject: [Python-3000-checkins] r53982 - python/branches/p3yk/Lib/copy.py Message-ID: <20070227034110.00D361E4007@bag.python.org> Author: neal.norwitz Date: Tue Feb 27 04:41:04 2007 New Revision: 53982 Modified: python/branches/p3yk/Lib/copy.py Log: Remove duplicate refs to int from int/long unification presumably. (There might be more refs like these.) Modified: python/branches/p3yk/Lib/copy.py ============================================================================== --- python/branches/p3yk/Lib/copy.py (original) +++ python/branches/p3yk/Lib/copy.py Tue Feb 27 04:41:04 2007 @@ -99,7 +99,7 @@ def _copy_immutable(x): return x -for t in (type(None), int, int, float, bool, str, tuple, +for t in (type(None), int, float, bool, str, tuple, frozenset, type, xrange, types.ClassType, types.BuiltinFunctionType, types.FunctionType): @@ -178,7 +178,6 @@ return x d[type(None)] = _deepcopy_atomic d[int] = _deepcopy_atomic -d[int] = _deepcopy_atomic d[float] = _deepcopy_atomic d[bool] = _deepcopy_atomic try: From python-3000-checkins at python.org Tue Feb 27 06:47:23 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 27 Feb 2007 06:47:23 +0100 (CET) Subject: [Python-3000-checkins] r53983 - python/branches/p3yk/Objects/dictobject.c Message-ID: <20070227054723.EA91D1E4007@bag.python.org> Author: guido.van.rossum Date: Tue Feb 27 06:47:18 2007 New Revision: 53983 Modified: python/branches/p3yk/Objects/dictobject.c Log: Fix some silly uses of KEYS, ITEMS, VALUES. Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Tue Feb 27 06:47:18 2007 @@ -1869,9 +1869,9 @@ static PyObject *dictitems_new(PyObject *); static PyObject *dictvalues_new(PyObject *); -PyDoc_STRVAR(KEYS__doc__, "D.KEYS() -> a set-like object for D's keys"); -PyDoc_STRVAR(ITEMS__doc__, "D.ITEMS() -> a set-like object for D's items"); -PyDoc_STRVAR(VALUES__doc__, "D.VALUES() -> a set-like object for D's values"); +PyDoc_STRVAR(keys__doc__, "D.keys() -> a set-like object for D's keys"); +PyDoc_STRVAR(items__doc__, "D.items() -> a set-like object for D's items"); +PyDoc_STRVAR(values__doc__, "D.values() -> a set-like object for D's values"); static PyMethodDef mapp_methods[] = { {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, @@ -1895,11 +1895,11 @@ values__doc__}, #endif {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, - KEYS__doc__}, + keys__doc__}, {"items", (PyCFunction)dictitems_new, METH_NOARGS, - ITEMS__doc__}, + items__doc__}, {"values", (PyCFunction)dictvalues_new, METH_NOARGS, - VALUES__doc__}, + values__doc__}, {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, update__doc__}, {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, @@ -2389,8 +2389,6 @@ /* View objects for keys(), items(), values(). */ /***********************************************/ -/* While this is incomplete, we use KEYS(), ITEMS(), VALUES(). */ - /* The instance lay-out is the same for all three; but the type differs. */ typedef struct { From python-3000-checkins at python.org Tue Feb 27 06:47:47 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 27 Feb 2007 06:47:47 +0100 (CET) Subject: [Python-3000-checkins] r53984 - in python/branches/p3yk/Lib: io.py test/test_io.py Message-ID: <20070227054747.847301E4007@bag.python.org> Author: guido.van.rossum Date: Tue Feb 27 06:47:44 2007 New Revision: 53984 Added: python/branches/p3yk/Lib/io.py (contents, props changed) python/branches/p3yk/Lib/test/test_io.py (contents, props changed) Log: Checkpoint for new I/O library. Added: python/branches/p3yk/Lib/io.py ============================================================================== --- (empty file) +++ python/branches/p3yk/Lib/io.py Tue Feb 27 06:47:44 2007 @@ -0,0 +1,264 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""New I/O library. + +See PEP XXX; for now: http://docs.google.com/Doc?id=dfksfvqd_1cn5g5m +""" + +__author__ = "Guido van Rossum " + +__all__ = ["open", "RawIOBase", "FileIO", "SocketIO", "BytesIO"] + +import os + +def open(filename, mode="r", buffering=None, *, encoding=None): + """Replacement for the built-in open function, with encoding parameter.""" + assert isinstance(filename, str) + assert isinstance(mode, str) + assert buffering is None or isinstance(buffering, int) + assert encoding is None or isinstance(encoding, str) + modes = set(mode) + if modes - set("arwb+t") or len(mode) > len(modes): + raise ValueError("invalid mode: %r" % mode) + reading = "r" in modes + writing = "w" in modes or "a" in modes + binary = "b" in modes + appending = "a" in modes + updating = "+" in modes + text = "t" in modes or not binary + if text and binary: + raise ValueError("can't have text and binary mode at once") + if reading + writing + appending > 1: + raise ValueError("can't have read/write/append mode at once") + if not (reading or writing or appending): + raise ValueError("must have exactly one of read/write/append mode") + if binary and encoding is not None: + raise ValueError("binary mode doesn't take an encoding") + raw = FileIO(filename, + (reading and "r" or "") + + (writing and "w" or "") + + (appending and "a" or "") + + (updating and "+" or "")) + if buffering is None: + buffering = 8*1024 # International standard buffer size + if buffering < 0: + raise ValueError("invalid buffering size") + if buffering == 0: + if binary: + return raw + raise ValueError("can't have unbuffered text I/O") + if updating: + buffer = BufferedRandom(raw, buffering) + elif writing: + buffer = BufferedWriter(raw, buffering) + else: + assert reading + buffer = BufferedReader(raw, buffering) + if binary: + return buffer + assert text + textio = TextIOWrapper(buffer) # Universal newlines default to on + return textio + + +class RawIOBase: + + """Base class for raw binary I/O.""" + + def read(self, n): + b = bytes(n.__index__()) + self.readinto(b) + return b + + def readinto(self, b): + raise IOError(".readinto() not supported") + + def write(self, b): + raise IOError(".write() not supported") + + def seek(self, pos, whence=0): + raise IOError(".seek() not supported") + + def tell(self): + raise IOError(".tell() not supported") + + def truncate(self, pos=None): + raise IOError(".truncate() not supported") + + def close(self): + pass + + def seekable(self): + return False + + def readable(self): + return False + + def writable(self): + return False + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def fileno(self): + raise IOError(".fileno() not supported") + + +class FileIO(RawIOBase): + + """Raw I/O implementation for OS files.""" + + def __init__(self, filename, mode): + self._seekable = None + self._mode = mode + if mode == "r": + flags = os.O_RDONLY + elif mode == "w": + flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC + self._writable = True + elif mode == "r+": + flags = os.O_RDWR + else: + assert 0, "unsupported mode %r (for now)" % mode + if hasattr(os, "O_BINARY"): + flags |= os.O_BINARY + self._fd = os.open(filename, flags) + + def readinto(self, b): + # XXX We really should have os.readinto() + b[:] = os.read(self._fd, len(b)) + return len(b) + + def write(self, b): + return os.write(self._fd, b) + + def seek(self, pos, whence=0): + os.lseek(self._fd, pos, whence) + + def tell(self): + return os.lseek(self._fd, 0, 1) + + def truncate(self, pos=None): + if pos is None: + pos = self.tell() + os.ftruncate(self._fd, pos) + + def close(self): + os.close(self._fd) + + def readable(self): + return "r" in self._mode or "+" in self._mode + + def writable(self): + return "w" in self._mode or "+" in self._mode or "a" in self._mode + + def seekable(self): + if self._seekable is None: + try: + os.lseek(self._fd, 0, 1) + except os.error: + self._seekable = False + else: + self._seekable = True + return self._seekable + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def fileno(self): + return self._fd + + +class SocketIO(RawIOBase): + + """Raw I/O implementation for stream sockets.""" + + def __init__(self, sock, mode): + assert mode in ("r", "w", "rw") + self._sock = sock + self._mode = mode + self._readable = "r" in mode + self._writable = "w" in mode + self._seekable = False + + def readinto(self, b): + return self._sock.recv_into(b) + + def write(self, b): + return self._sock.send(b) + + def close(self): + self._sock.close() + + def readable(self): + return "r" in self._mode + + def writable(self): + return "w" in self._mode + + +class BytesIO(RawIOBase): + + """Raw I/O implementation for bytes, like StringIO.""" + + def __init__(self, inital_bytes=None): + self._buffer = b"" + self._pos = 0 + if inital_bytes is not None: + self._buffer += inital_bytes + + def getvalue(self): + return self._buffer + + def read(self, n): + assert n >= 0 + newpos = min(len(self._buffer), self._pos + n) + b = self._buffer[self._pos : newpos] + self._pos = newpos + return b + + def readinto(self, b): + b[:] = self.read(len(b)) + + def write(self, b): + n = len(b) + newpos = self._pos + n + self._buffer[self._pos:newpos] = b + self._pos = newpos + return n + + def seek(self, pos, whence=0): + if whence == 0: + self._pos = max(0, pos) + elif whence == 1: + self._pos = max(0, self._pos + pos) + elif whence == 2: + self._pos = max(0, len(self._buffer) + pos) + else: + raise IOError("invalid whence value") + + def tell(self): + return self._pos + + def truncate(self, pos=None): + if pos is None: + pos = self._pos + else: + self._pos = max(0, pos) + del self._buffer[pos:] + + def readable(self): + return True + + def writable(self): + return True + + def seekable(self): + return True Added: python/branches/p3yk/Lib/test/test_io.py ============================================================================== --- (empty file) +++ python/branches/p3yk/Lib/test/test_io.py Tue Feb 27 06:47:44 2007 @@ -0,0 +1,62 @@ +import unittest +from test import test_support + +import io + +class IOTest(unittest.TestCase): + + def write_ops(self, f): + f.write(b"blah.") + f.seek(0) + f.write(b"Hello.") + self.assertEqual(f.tell(), 6) + f.seek(-1, 1) + self.assertEqual(f.tell(), 5) + f.write(" world\n\n\n") + f.seek(0) + f.write("h") + f.seek(-2, 2) + f.truncate() + + def read_ops(self, f): + data = f.read(5) + self.assertEqual(data, b"hello") + f.readinto(data) + self.assertEqual(data, b" worl") + f.readinto(data) + self.assertEqual(data, b"d\n") + f.seek(0) + self.assertEqual(f.read(20), b"hello world\n") + f.seek(-6, 2) + self.assertEqual(f.read(5), b"world") + f.seek(-6, 1) + self.assertEqual(f.read(5), b" worl") + self.assertEqual(f.tell(), 10) + + def test_raw_file_io(self): + f = io.open(test_support.TESTFN, "wb", buffering=0) + self.assertEqual(f.readable(), False) + self.assertEqual(f.writable(), True) + self.assertEqual(f.seekable(), True) + self.write_ops(f) + f.close() + f = io.open(test_support.TESTFN, "rb", buffering=0) + self.assertEqual(f.readable(), True) + self.assertEqual(f.writable(), False) + self.assertEqual(f.seekable(), True) + self.read_ops(f) + f.close() + + def test_raw_bytes_io(self): + f = io.BytesIO() + self.write_ops(f) + data = f.getvalue() + self.assertEqual(data, b"hello world\n") + f = io.BytesIO(data) + self.read_ops(f) + +def test_main(): + test_support.run_unittest(IOTest) + +if __name__ == "__main__": + test_main() From python-3000-checkins at python.org Tue Feb 27 07:26:16 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 27 Feb 2007 07:26:16 +0100 (CET) Subject: [Python-3000-checkins] r53985 - python/branches/p3yk/Lib/io.py Message-ID: <20070227062616.4525B1E4014@bag.python.org> Author: neal.norwitz Date: Tue Feb 27 07:26:14 2007 New Revision: 53985 Modified: python/branches/p3yk/Lib/io.py Log: Add some XXX comments for Guido to look at. Modified: python/branches/p3yk/Lib/io.py ============================================================================== --- python/branches/p3yk/Lib/io.py (original) +++ python/branches/p3yk/Lib/io.py Tue Feb 27 07:26:14 2007 @@ -166,6 +166,8 @@ self._seekable = True return self._seekable + # XXX(nnorwitz): is there any reason to redefine __enter__ & __exit__? + # Both already have the same impl in the base class. def __enter__(self): return self @@ -203,6 +205,8 @@ def writable(self): return "w" in self._mode + # XXX(nnorwitz)??? def fileno(self): return self._sock.fileno() + class BytesIO(RawIOBase): From python-3000-checkins at python.org Tue Feb 27 07:51:05 2007 From: python-3000-checkins at python.org (jeremy.hylton) Date: Tue, 27 Feb 2007 07:51:05 +0100 (CET) Subject: [Python-3000-checkins] r53986 - in python/branches/p3yk: Grammar/Grammar Include/Python-ast.h Include/graminit.h Include/symtable.h Lib/test/test_scope.py Lib/test/test_syntax.py Parser/Python.asdl Python/Python-ast.c Python/ast.c Python/compile.c Python/graminit.c Python/symtable.c Message-ID: <20070227065105.AFB391E4015@bag.python.org> Author: jeremy.hylton Date: Tue Feb 27 07:50:52 2007 New Revision: 53986 Modified: python/branches/p3yk/Grammar/Grammar python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Include/graminit.h python/branches/p3yk/Include/symtable.h python/branches/p3yk/Lib/test/test_scope.py python/branches/p3yk/Lib/test/test_syntax.py python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/ast.c python/branches/p3yk/Python/compile.c python/branches/p3yk/Python/graminit.c python/branches/p3yk/Python/symtable.c Log: Provisional implementation of PEP 3104. Add nonlocal_stmt to Grammar and Nonlocal node to AST. They both parallel the definitions for globals. The symbol table treats variables declared as nonlocal just like variables that are free implicitly. This change is missing the language spec changes, but makes some decisions about what the spec should say via the unittests. The PEP is silent on a number of decisions, so we should review those before claiming that nonlocal is complete. Thomas Wouters made the grammer and ast changes. Jeremy Hylton added the symbol table changes and the tests. Pete Shinners and Neal Norwitz helped review the code. Modified: python/branches/p3yk/Grammar/Grammar ============================================================================== --- python/branches/p3yk/Grammar/Grammar (original) +++ python/branches/p3yk/Grammar/Grammar Tue Feb 27 07:50:52 2007 @@ -39,7 +39,7 @@ stmt: simple_stmt | compound_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | - import_stmt | global_stmt | assert_stmt) + import_stmt | global_stmt | nonlocal_stmt | assert_stmt) expr_stmt: testlist (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | @@ -63,6 +63,7 @@ dotted_as_names: dotted_as_name (',' dotted_as_name)* dotted_name: NAME ('.' NAME)* global_stmt: 'global' NAME (',' NAME)* +nonlocal_stmt: 'nonlocal' NAME (',' NAME)* assert_stmt: 'assert' test [',' test] compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Tue Feb 27 07:50:52 2007 @@ -66,7 +66,8 @@ While_kind=8, If_kind=9, With_kind=10, Raise_kind=11, TryExcept_kind=12, TryFinally_kind=13, Assert_kind=14, Import_kind=15, ImportFrom_kind=16, Global_kind=17, - Expr_kind=18, Pass_kind=19, Break_kind=20, Continue_kind=21}; + Nonlocal_kind=18, Expr_kind=19, Pass_kind=20, Break_kind=21, + Continue_kind=22}; struct _stmt { enum _stmt_kind kind; union { @@ -165,6 +166,10 @@ } Global; struct { + asdl_seq *names; + } Nonlocal; + + struct { expr_ty value; } Expr; @@ -422,6 +427,9 @@ #define Global(a0, a1, a2, a3) _Py_Global(a0, a1, a2, a3) stmt_ty _Py_Global(asdl_seq * names, int lineno, int col_offset, PyArena *arena); +#define Nonlocal(a0, a1, a2, a3) _Py_Nonlocal(a0, a1, a2, a3) +stmt_ty _Py_Nonlocal(asdl_seq * names, int lineno, int col_offset, PyArena + *arena); #define Expr(a0, a1, a2, a3) _Py_Expr(a0, a1, a2, a3) stmt_ty _Py_Expr(expr_ty value, int lineno, int col_offset, PyArena *arena); #define Pass(a0, a1, a2) _Py_Pass(a0, a1, a2) Modified: python/branches/p3yk/Include/graminit.h ============================================================================== --- python/branches/p3yk/Include/graminit.h (original) +++ python/branches/p3yk/Include/graminit.h Tue Feb 27 07:50:52 2007 @@ -35,53 +35,54 @@ #define dotted_as_names 290 #define dotted_name 291 #define global_stmt 292 -#define assert_stmt 293 -#define compound_stmt 294 -#define if_stmt 295 -#define while_stmt 296 -#define for_stmt 297 -#define try_stmt 298 -#define with_stmt 299 -#define with_var 300 -#define except_clause 301 -#define suite 302 -#define testlist_safe 303 -#define old_test 304 -#define old_lambdef 305 -#define test 306 -#define or_test 307 -#define and_test 308 -#define not_test 309 -#define comparison 310 -#define comp_op 311 -#define expr 312 -#define xor_expr 313 -#define and_expr 314 -#define shift_expr 315 -#define arith_expr 316 -#define term 317 -#define factor 318 -#define power 319 -#define atom 320 -#define listmaker 321 -#define testlist_gexp 322 -#define lambdef 323 -#define trailer 324 -#define subscriptlist 325 -#define subscript 326 -#define sliceop 327 -#define exprlist 328 -#define testlist 329 -#define dictsetmaker 330 -#define classdef 331 -#define arglist 332 -#define argument 333 -#define list_iter 334 -#define list_for 335 -#define list_if 336 -#define gen_iter 337 -#define gen_for 338 -#define gen_if 339 -#define testlist1 340 -#define encoding_decl 341 -#define yield_expr 342 +#define nonlocal_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/Include/symtable.h ============================================================================== --- python/branches/p3yk/Include/symtable.h (original) +++ python/branches/p3yk/Include/symtable.h Tue Feb 27 07:50:52 2007 @@ -64,23 +64,24 @@ #define DEF_GLOBAL 1 /* global stmt */ #define DEF_LOCAL 2 /* assignment in code block */ #define DEF_PARAM 2<<1 /* formal parameter */ -#define USE 2<<2 /* name is used */ -#define DEF_STAR 2<<3 /* parameter is star arg */ -#define DEF_DOUBLESTAR 2<<4 /* parameter is star-star arg */ -#define DEF_INTUPLE 2<<5 /* name defined in tuple in parameters */ -#define DEF_FREE 2<<6 /* name used but not defined in nested block */ -#define DEF_FREE_GLOBAL 2<<7 /* free variable is actually implicit global */ -#define DEF_FREE_CLASS 2<<8 /* free variable from class's method */ -#define DEF_IMPORT 2<<9 /* assignment occurred via import */ +#define DEF_NONLOCAL 2<<2 /* nonlocal stmt */ +#define USE 2<<3 /* name is used */ +#define DEF_STAR 2<<4 /* parameter is star arg */ +#define DEF_DOUBLESTAR 2<<5 /* parameter is star-star arg */ +#define DEF_INTUPLE 2<<6 /* name defined in tuple in parameters */ +#define DEF_FREE 2<<7 /* name used but not defined in nested block */ +#define DEF_FREE_GLOBAL 2<<8 /* free variable is actually implicit global */ +#define DEF_FREE_CLASS 2<<9 /* free variable from class's method */ +#define DEF_IMPORT 2<<10 /* assignment occurred via import */ #define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT) /* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol table. GLOBAL is returned from PyST_GetScope() for either of them. - It is stored in ste_symbols at bits 12-14. + It is stored in ste_symbols at bits 12-15. */ #define SCOPE_OFF 11 -#define SCOPE_MASK 7 +#define SCOPE_MASK (DEF_GLOBAL | DEF_LOCAL | DEF_PARAM | DEF_NONLOCAL) #define LOCAL 1 #define GLOBAL_EXPLICIT 2 Modified: python/branches/p3yk/Lib/test/test_scope.py ============================================================================== --- python/branches/p3yk/Lib/test/test_scope.py (original) +++ python/branches/p3yk/Lib/test/test_scope.py Tue Feb 27 07:50:52 2007 @@ -555,6 +555,90 @@ f(4)() + def testNonLocalFunction(self): + + def f(x): + def inc(): + nonlocal x + x += 1 + return x + def dec(): + nonlocal x + x -= 1 + return x + return inc, dec + + inc, dec = f(0) + self.assertEqual(inc(), 1) + self.assertEqual(inc(), 2) + self.assertEqual(dec(), 1) + self.assertEqual(dec(), 0) + + def testNonLocalMethod(self): + + def f(x): + class c: + def inc(self): + nonlocal x + x += 1 + return x + def dec(self): + nonlocal x + x -= 1 + return x + return c() + + c = f(0) + self.assertEqual(c.inc(), 1) + self.assertEqual(c.inc(), 2) + self.assertEqual(c.dec(), 1) + self.assertEqual(c.dec(), 0) + + def testNonLocalClass(self): + + def f(x): + class c: + nonlocal x + x += 1 + def get(self): + return x + return c() + + c = f(0) + self.assertEqual(c.get(), 1) + self.assert_("x" not in c.__class__.__dict__) + + + def testNonLocalGenerator(self): + + def f(x): + def g(y): + nonlocal x + for i in range(y): + x += 1 + yield x + return g + + g = f(0) + self.assertEqual(list(g(5)), [1, 2, 3, 4, 5]) + + def testNestedNonLocal(self): + + def f(x): + def g(): + nonlocal x + x -= 2 + def h(): + nonlocal x + x += 4 + return x + return h + return g + + g = f(1) + h = g() + self.assertEqual(h(), 3) + def test_main(): run_unittest(ScopeTests) Modified: python/branches/p3yk/Lib/test/test_syntax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_syntax.py (original) +++ python/branches/p3yk/Lib/test/test_syntax.py Tue Feb 27 07:50:52 2007 @@ -367,6 +367,46 @@ ... SystemError: too many statically nested blocks +Misuse of the nonlocal statement can lead to a few unique syntax errors. + + >>> def f(x): + ... nonlocal x + Traceback (most recent call last): + ... + SyntaxError: name 'x' is local and nonlocal + + >>> def f(): + ... global x + ... nonlocal x + Traceback (most recent call last): + ... + SyntaxError: name 'x' is nonlocal and global + + >>> def f(): + ... nonlocal x + Traceback (most recent call last): + ... + SyntaxError: no binding for nonlocal 'x' found + +TODO(jhylton): Figure out how to test SyntaxWarning with doctest. + +## >>> def f(x): +## ... def f(): +## ... print(x) +## ... nonlocal x +## Traceback (most recent call last): +## ... +## SyntaxWarning: name 'x' is assigned to before nonlocal declaration + +## >>> def f(): +## ... x = 1 +## ... nonlocal x +## Traceback (most recent call last): +## ... +## SyntaxWarning: name 'x' is assigned to before nonlocal declaration + + + """ import re Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Tue Feb 27 07:50:52 2007 @@ -34,6 +34,7 @@ | ImportFrom(identifier module, alias* names, int? level) | Global(identifier* names) + | Nonlocal(identifier* names) | Expr(expr value) | Pass | Break | Continue Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Tue Feb 27 07:50:52 2007 @@ -131,6 +131,10 @@ static char *Global_fields[]={ "names", }; +static PyTypeObject *Nonlocal_type; +static char *Nonlocal_fields[]={ + "names", +}; static PyTypeObject *Expr_type; static char *Expr_fields[]={ "value", @@ -507,6 +511,8 @@ if (!ImportFrom_type) return 0; Global_type = make_type("Global", stmt_type, Global_fields, 1); if (!Global_type) return 0; + Nonlocal_type = make_type("Nonlocal", stmt_type, Nonlocal_fields, 1); + if (!Nonlocal_type) return 0; Expr_type = make_type("Expr", stmt_type, Expr_fields, 1); if (!Expr_type) return 0; Pass_type = make_type("Pass", stmt_type, NULL, 0); @@ -1146,6 +1152,20 @@ } stmt_ty +Nonlocal(asdl_seq * names, int lineno, int col_offset, PyArena *arena) +{ + stmt_ty p; + p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); + if (!p) + return NULL; + p->kind = Nonlocal_kind; + p->v.Nonlocal.names = names; + p->lineno = lineno; + p->col_offset = col_offset; + return p; +} + +stmt_ty Expr(expr_ty value, int lineno, int col_offset, PyArena *arena) { stmt_ty p; @@ -2197,6 +2217,15 @@ goto failed; Py_DECREF(value); break; + case Nonlocal_kind: + result = PyType_GenericNew(Nonlocal_type, NULL, NULL); + if (!result) goto failed; + value = ast2obj_list(o->v.Nonlocal.names, ast2obj_identifier); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "names", value) == -1) + goto failed; + Py_DECREF(value); + break; case Expr_kind: result = PyType_GenericNew(Expr_type, NULL, NULL); if (!result) goto failed; @@ -3049,6 +3078,8 @@ 0) return; if (PyDict_SetItemString(d, "Global", (PyObject*)Global_type) < 0) return; + if (PyDict_SetItemString(d, "Nonlocal", (PyObject*)Nonlocal_type) < 0) + return; if (PyDict_SetItemString(d, "Expr", (PyObject*)Expr_type) < 0) return; if (PyDict_SetItemString(d, "Pass", (PyObject*)Pass_type) < 0) return; if (PyDict_SetItemString(d, "Break", (PyObject*)Break_type) < 0) return; Modified: python/branches/p3yk/Python/ast.c ============================================================================== --- python/branches/p3yk/Python/ast.c (original) +++ python/branches/p3yk/Python/ast.c Tue Feb 27 07:50:52 2007 @@ -2557,6 +2557,27 @@ } static stmt_ty +ast_for_nonlocal_stmt(struct compiling *c, const node *n) +{ + /* nonlocal_stmt: 'nonlocal' NAME (',' NAME)* */ + identifier name; + asdl_seq *s; + int i; + + REQ(n, nonlocal_stmt); + s = asdl_seq_new(NCH(n) / 2, c->c_arena); + if (!s) + return NULL; + for (i = 1; i < NCH(n); i += 2) { + name = NEW_IDENTIFIER(CHILD(n, i)); + if (!name) + return NULL; + asdl_seq_SET(s, i / 2, name); + } + return Nonlocal(s, LINENO(n), n->n_col_offset, c->c_arena); +} + +static stmt_ty ast_for_assert_stmt(struct compiling *c, const node *n) { /* assert_stmt: 'assert' test [',' test] */ @@ -3063,8 +3084,8 @@ if (TYPE(n) == small_stmt) { REQ(n, small_stmt); n = CHILD(n, 0); - /* small_stmt: expr_stmt | del_stmt | pass_stmt - | flow_stmt | import_stmt | global_stmt | assert_stmt + /* small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt + | import_stmt | global_stmt | nonlocal_stmt | assert_stmt */ switch (TYPE(n)) { case expr_stmt: @@ -3079,6 +3100,8 @@ return ast_for_import_stmt(c, n); case global_stmt: return ast_for_global_stmt(c, n); + case nonlocal_stmt: + return ast_for_nonlocal_stmt(c, n); case assert_stmt: return ast_for_assert_stmt(c, n); default: Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Tue Feb 27 07:50:52 2007 @@ -2239,6 +2239,7 @@ case ImportFrom_kind: return compiler_from_import(c, s); case Global_kind: + case Nonlocal_kind: break; case Expr_kind: if (c->c_interactive && c->c_nestlevel <= 1) { Modified: python/branches/p3yk/Python/graminit.c ============================================================================== --- python/branches/p3yk/Python/graminit.c (original) +++ python/branches/p3yk/Python/graminit.c Tue Feb 27 07:50:52 2007 @@ -403,7 +403,7 @@ {2, arcs_16_2}, {1, arcs_16_3}, }; -static arc arcs_17_0[7] = { +static arc arcs_17_0[8] = { {39, 1}, {40, 1}, {41, 1}, @@ -411,28 +411,29 @@ {43, 1}, {44, 1}, {45, 1}, + {46, 1}, }; static arc arcs_17_1[1] = { {0, 1}, }; static state states_17[2] = { - {7, arcs_17_0}, + {8, arcs_17_0}, {1, arcs_17_1}, }; static arc arcs_18_0[1] = { {9, 1}, }; static arc arcs_18_1[3] = { - {46, 2}, + {47, 2}, {27, 3}, {0, 1}, }; static arc arcs_18_2[2] = { - {47, 4}, + {48, 4}, {9, 4}, }; static arc arcs_18_3[2] = { - {47, 5}, + {48, 5}, {9, 5}, }; static arc arcs_18_4[1] = { @@ -451,7 +452,6 @@ {2, arcs_18_5}, }; static arc arcs_19_0[12] = { - {48, 1}, {49, 1}, {50, 1}, {51, 1}, @@ -463,6 +463,7 @@ {57, 1}, {58, 1}, {59, 1}, + {60, 1}, }; static arc arcs_19_1[1] = { {0, 1}, @@ -472,10 +473,10 @@ {1, arcs_19_1}, }; static arc arcs_20_0[1] = { - {60, 1}, + {61, 1}, }; static arc arcs_20_1[1] = { - {61, 2}, + {62, 2}, }; static arc arcs_20_2[1] = { {0, 2}, @@ -486,7 +487,7 @@ {1, arcs_20_2}, }; static arc arcs_21_0[1] = { - {62, 1}, + {63, 1}, }; static arc arcs_21_1[1] = { {0, 1}, @@ -496,11 +497,11 @@ {1, arcs_21_1}, }; static arc arcs_22_0[5] = { - {63, 1}, {64, 1}, {65, 1}, {66, 1}, {67, 1}, + {68, 1}, }; static arc arcs_22_1[1] = { {0, 1}, @@ -510,7 +511,7 @@ {1, arcs_22_1}, }; static arc arcs_23_0[1] = { - {68, 1}, + {69, 1}, }; static arc arcs_23_1[1] = { {0, 1}, @@ -520,7 +521,7 @@ {1, arcs_23_1}, }; static arc arcs_24_0[1] = { - {69, 1}, + {70, 1}, }; static arc arcs_24_1[1] = { {0, 1}, @@ -530,7 +531,7 @@ {1, arcs_24_1}, }; static arc arcs_25_0[1] = { - {70, 1}, + {71, 1}, }; static arc arcs_25_1[2] = { {9, 2}, @@ -545,7 +546,7 @@ {1, arcs_25_2}, }; static arc arcs_26_0[1] = { - {47, 1}, + {48, 1}, }; static arc arcs_26_1[1] = { {0, 1}, @@ -555,7 +556,7 @@ {1, arcs_26_1}, }; static arc arcs_27_0[1] = { - {71, 1}, + {72, 1}, }; static arc arcs_27_1[2] = { {22, 2}, @@ -588,8 +589,8 @@ {1, arcs_27_6}, }; static arc arcs_28_0[2] = { - {72, 1}, {73, 1}, + {74, 1}, }; static arc arcs_28_1[1] = { {0, 1}, @@ -599,10 +600,10 @@ {1, arcs_28_1}, }; static arc arcs_29_0[1] = { - {74, 1}, + {75, 1}, }; static arc arcs_29_1[1] = { - {75, 2}, + {76, 2}, }; static arc arcs_29_2[1] = { {0, 2}, @@ -613,30 +614,30 @@ {1, arcs_29_2}, }; static arc arcs_30_0[1] = { - {76, 1}, + {77, 1}, }; static arc arcs_30_1[2] = { - {77, 2}, + {78, 2}, {12, 3}, }; static arc arcs_30_2[3] = { - {77, 2}, + {78, 2}, {12, 3}, - {74, 4}, + {75, 4}, }; static arc arcs_30_3[1] = { - {74, 4}, + {75, 4}, }; static arc arcs_30_4[3] = { {29, 5}, {13, 6}, - {78, 5}, + {79, 5}, }; static arc arcs_30_5[1] = { {0, 5}, }; static arc arcs_30_6[1] = { - {78, 7}, + {79, 7}, }; static arc arcs_30_7[1] = { {15, 5}, @@ -655,7 +656,7 @@ {19, 1}, }; static arc arcs_31_1[2] = { - {80, 2}, + {81, 2}, {0, 1}, }; static arc arcs_31_2[1] = { @@ -674,7 +675,7 @@ {12, 1}, }; static arc arcs_32_1[2] = { - {80, 2}, + {81, 2}, {0, 1}, }; static arc arcs_32_2[1] = { @@ -690,14 +691,14 @@ {1, arcs_32_3}, }; static arc arcs_33_0[1] = { - {79, 1}, + {80, 1}, }; static arc arcs_33_1[2] = { {28, 2}, {0, 1}, }; static arc arcs_33_2[2] = { - {79, 1}, + {80, 1}, {0, 2}, }; static state states_33[3] = { @@ -706,7 +707,7 @@ {2, arcs_33_2}, }; static arc arcs_34_0[1] = { - {81, 1}, + {82, 1}, }; static arc arcs_34_1[2] = { {28, 0}, @@ -720,7 +721,7 @@ {19, 1}, }; static arc arcs_35_1[2] = { - {77, 0}, + {78, 0}, {0, 1}, }; static state states_35[2] = { @@ -728,7 +729,7 @@ {2, arcs_35_1}, }; static arc arcs_36_0[1] = { - {82, 1}, + {83, 1}, }; static arc arcs_36_1[1] = { {19, 2}, @@ -743,82 +744,61 @@ {2, arcs_36_2}, }; static arc arcs_37_0[1] = { - {83, 1}, + {84, 1}, }; static arc arcs_37_1[1] = { - {22, 2}, + {19, 2}, }; static arc arcs_37_2[2] = { - {28, 3}, + {28, 1}, {0, 2}, }; -static arc arcs_37_3[1] = { - {22, 4}, -}; -static arc arcs_37_4[1] = { - {0, 4}, -}; -static state states_37[5] = { +static state states_37[3] = { {1, arcs_37_0}, {1, arcs_37_1}, {2, arcs_37_2}, - {1, arcs_37_3}, - {1, arcs_37_4}, }; -static arc arcs_38_0[7] = { - {84, 1}, +static arc arcs_38_0[1] = { {85, 1}, - {86, 1}, - {87, 1}, - {88, 1}, - {17, 1}, - {89, 1}, }; static arc arcs_38_1[1] = { - {0, 1}, -}; -static state states_38[2] = { - {7, arcs_38_0}, - {1, arcs_38_1}, -}; -static arc arcs_39_0[1] = { - {90, 1}, -}; -static arc arcs_39_1[1] = { {22, 2}, }; -static arc arcs_39_2[1] = { - {23, 3}, +static arc arcs_38_2[2] = { + {28, 3}, + {0, 2}, }; -static arc arcs_39_3[1] = { - {24, 4}, +static arc arcs_38_3[1] = { + {22, 4}, }; -static arc arcs_39_4[3] = { - {91, 1}, - {92, 5}, +static arc arcs_38_4[1] = { {0, 4}, }; -static arc arcs_39_5[1] = { - {23, 6}, +static state states_38[5] = { + {1, arcs_38_0}, + {1, arcs_38_1}, + {2, arcs_38_2}, + {1, arcs_38_3}, + {1, arcs_38_4}, }; -static arc arcs_39_6[1] = { - {24, 7}, +static arc arcs_39_0[7] = { + {86, 1}, + {87, 1}, + {88, 1}, + {89, 1}, + {90, 1}, + {17, 1}, + {91, 1}, }; -static arc arcs_39_7[1] = { - {0, 7}, +static arc arcs_39_1[1] = { + {0, 1}, }; -static state states_39[8] = { - {1, arcs_39_0}, +static state states_39[2] = { + {7, arcs_39_0}, {1, arcs_39_1}, - {1, arcs_39_2}, - {1, arcs_39_3}, - {3, arcs_39_4}, - {1, arcs_39_5}, - {1, arcs_39_6}, - {1, arcs_39_7}, }; static arc arcs_40_0[1] = { - {93, 1}, + {92, 1}, }; static arc arcs_40_1[1] = { {22, 2}, @@ -829,8 +809,9 @@ static arc arcs_40_3[1] = { {24, 4}, }; -static arc arcs_40_4[2] = { - {92, 5}, +static arc arcs_40_4[3] = { + {93, 1}, + {94, 5}, {0, 4}, }; static arc arcs_40_5[1] = { @@ -847,299 +828,323 @@ {1, arcs_40_1}, {1, arcs_40_2}, {1, arcs_40_3}, - {2, arcs_40_4}, + {3, arcs_40_4}, {1, arcs_40_5}, {1, arcs_40_6}, {1, arcs_40_7}, }; static arc arcs_41_0[1] = { - {94, 1}, + {95, 1}, }; static arc arcs_41_1[1] = { - {61, 2}, + {22, 2}, }; static arc arcs_41_2[1] = { - {95, 3}, + {23, 3}, }; static arc arcs_41_3[1] = { - {9, 4}, + {24, 4}, }; -static arc arcs_41_4[1] = { - {23, 5}, +static arc arcs_41_4[2] = { + {94, 5}, + {0, 4}, }; static arc arcs_41_5[1] = { - {24, 6}, + {23, 6}, }; -static arc arcs_41_6[2] = { - {92, 7}, - {0, 6}, +static arc arcs_41_6[1] = { + {24, 7}, }; static arc arcs_41_7[1] = { - {23, 8}, -}; -static arc arcs_41_8[1] = { - {24, 9}, -}; -static arc arcs_41_9[1] = { - {0, 9}, + {0, 7}, }; -static state states_41[10] = { +static state states_41[8] = { {1, arcs_41_0}, {1, arcs_41_1}, {1, arcs_41_2}, {1, arcs_41_3}, - {1, arcs_41_4}, + {2, arcs_41_4}, {1, arcs_41_5}, - {2, arcs_41_6}, + {1, arcs_41_6}, {1, arcs_41_7}, - {1, arcs_41_8}, - {1, arcs_41_9}, }; static arc arcs_42_0[1] = { {96, 1}, }; static arc arcs_42_1[1] = { - {23, 2}, + {62, 2}, }; static arc arcs_42_2[1] = { - {24, 3}, + {97, 3}, }; -static arc arcs_42_3[2] = { - {97, 4}, - {98, 5}, +static arc arcs_42_3[1] = { + {9, 4}, }; static arc arcs_42_4[1] = { - {23, 6}, + {23, 5}, }; static arc arcs_42_5[1] = { - {23, 7}, + {24, 6}, }; -static arc arcs_42_6[1] = { - {24, 8}, +static arc arcs_42_6[2] = { + {94, 7}, + {0, 6}, }; static arc arcs_42_7[1] = { - {24, 9}, + {23, 8}, }; -static arc arcs_42_8[4] = { - {97, 4}, - {92, 10}, - {98, 5}, - {0, 8}, +static arc arcs_42_8[1] = { + {24, 9}, }; static arc arcs_42_9[1] = { {0, 9}, }; -static arc arcs_42_10[1] = { - {23, 11}, -}; -static arc arcs_42_11[1] = { - {24, 12}, -}; -static arc arcs_42_12[2] = { - {98, 5}, - {0, 12}, -}; -static state states_42[13] = { +static state states_42[10] = { {1, arcs_42_0}, {1, arcs_42_1}, {1, arcs_42_2}, - {2, arcs_42_3}, + {1, arcs_42_3}, {1, arcs_42_4}, {1, arcs_42_5}, - {1, arcs_42_6}, + {2, arcs_42_6}, {1, arcs_42_7}, - {4, arcs_42_8}, + {1, arcs_42_8}, {1, arcs_42_9}, - {1, arcs_42_10}, - {1, arcs_42_11}, - {2, arcs_42_12}, }; static arc arcs_43_0[1] = { - {99, 1}, + {98, 1}, }; static arc arcs_43_1[1] = { - {22, 2}, + {23, 2}, }; -static arc arcs_43_2[2] = { - {100, 3}, - {23, 4}, +static arc arcs_43_2[1] = { + {24, 3}, }; -static arc arcs_43_3[1] = { - {23, 4}, +static arc arcs_43_3[2] = { + {99, 4}, + {100, 5}, }; static arc arcs_43_4[1] = { - {24, 5}, + {23, 6}, }; static arc arcs_43_5[1] = { - {0, 5}, + {23, 7}, +}; +static arc arcs_43_6[1] = { + {24, 8}, +}; +static arc arcs_43_7[1] = { + {24, 9}, +}; +static arc arcs_43_8[4] = { + {99, 4}, + {94, 10}, + {100, 5}, + {0, 8}, +}; +static arc arcs_43_9[1] = { + {0, 9}, +}; +static arc arcs_43_10[1] = { + {23, 11}, +}; +static arc arcs_43_11[1] = { + {24, 12}, }; -static state states_43[6] = { +static arc arcs_43_12[2] = { + {100, 5}, + {0, 12}, +}; +static state states_43[13] = { {1, arcs_43_0}, {1, arcs_43_1}, - {2, arcs_43_2}, - {1, arcs_43_3}, + {1, arcs_43_2}, + {2, arcs_43_3}, {1, arcs_43_4}, {1, arcs_43_5}, + {1, arcs_43_6}, + {1, arcs_43_7}, + {4, arcs_43_8}, + {1, arcs_43_9}, + {1, arcs_43_10}, + {1, arcs_43_11}, + {2, arcs_43_12}, }; static arc arcs_44_0[1] = { - {80, 1}, + {101, 1}, }; static arc arcs_44_1[1] = { - {101, 2}, + {22, 2}, }; -static arc arcs_44_2[1] = { - {0, 2}, +static arc arcs_44_2[2] = { + {102, 3}, + {23, 4}, +}; +static arc arcs_44_3[1] = { + {23, 4}, +}; +static arc arcs_44_4[1] = { + {24, 5}, +}; +static arc arcs_44_5[1] = { + {0, 5}, }; -static state states_44[3] = { +static state states_44[6] = { {1, arcs_44_0}, {1, arcs_44_1}, - {1, arcs_44_2}, + {2, arcs_44_2}, + {1, arcs_44_3}, + {1, arcs_44_4}, + {1, arcs_44_5}, }; static arc arcs_45_0[1] = { - {102, 1}, + {81, 1}, }; -static arc arcs_45_1[2] = { - {22, 2}, - {0, 1}, +static arc arcs_45_1[1] = { + {103, 2}, }; -static arc arcs_45_2[2] = { - {80, 3}, +static arc arcs_45_2[1] = { {0, 2}, }; -static arc arcs_45_3[1] = { - {19, 4}, -}; -static arc arcs_45_4[1] = { - {0, 4}, -}; -static state states_45[5] = { +static state states_45[3] = { {1, arcs_45_0}, - {2, arcs_45_1}, - {2, arcs_45_2}, - {1, arcs_45_3}, - {1, arcs_45_4}, + {1, arcs_45_1}, + {1, arcs_45_2}, }; -static arc arcs_46_0[2] = { - {3, 1}, - {2, 2}, +static arc arcs_46_0[1] = { + {104, 1}, }; -static arc arcs_46_1[1] = { +static arc arcs_46_1[2] = { + {22, 2}, {0, 1}, }; -static arc arcs_46_2[1] = { - {103, 3}, +static arc arcs_46_2[2] = { + {81, 3}, + {0, 2}, }; static arc arcs_46_3[1] = { - {6, 4}, + {19, 4}, }; -static arc arcs_46_4[2] = { - {6, 4}, - {104, 1}, +static arc arcs_46_4[1] = { + {0, 4}, }; static state states_46[5] = { - {2, arcs_46_0}, - {1, arcs_46_1}, - {1, arcs_46_2}, + {1, arcs_46_0}, + {2, arcs_46_1}, + {2, arcs_46_2}, {1, arcs_46_3}, - {2, arcs_46_4}, + {1, arcs_46_4}, }; -static arc arcs_47_0[1] = { - {106, 1}, +static arc arcs_47_0[2] = { + {3, 1}, + {2, 2}, }; -static arc arcs_47_1[2] = { - {28, 2}, +static arc arcs_47_1[1] = { {0, 1}, }; static arc arcs_47_2[1] = { - {106, 3}, + {105, 3}, }; -static arc arcs_47_3[2] = { - {28, 4}, - {0, 3}, +static arc arcs_47_3[1] = { + {6, 4}, }; static arc arcs_47_4[2] = { - {106, 3}, - {0, 4}, + {6, 4}, + {106, 1}, }; static state states_47[5] = { - {1, arcs_47_0}, - {2, arcs_47_1}, + {2, arcs_47_0}, + {1, arcs_47_1}, {1, arcs_47_2}, - {2, arcs_47_3}, + {1, arcs_47_3}, {2, arcs_47_4}, }; -static arc arcs_48_0[2] = { - {107, 1}, +static arc arcs_48_0[1] = { {108, 1}, }; -static arc arcs_48_1[1] = { +static arc arcs_48_1[2] = { + {28, 2}, {0, 1}, }; -static state states_48[2] = { - {2, arcs_48_0}, - {1, arcs_48_1}, +static arc arcs_48_2[1] = { + {108, 3}, }; -static arc arcs_49_0[1] = { - {109, 1}, +static arc arcs_48_3[2] = { + {28, 4}, + {0, 3}, }; -static arc arcs_49_1[2] = { - {33, 2}, - {23, 3}, +static arc arcs_48_4[2] = { + {108, 3}, + {0, 4}, }; -static arc arcs_49_2[1] = { - {23, 3}, +static state states_48[5] = { + {1, arcs_48_0}, + {2, arcs_48_1}, + {1, arcs_48_2}, + {2, arcs_48_3}, + {2, arcs_48_4}, }; -static arc arcs_49_3[1] = { - {106, 4}, +static arc arcs_49_0[2] = { + {109, 1}, + {110, 1}, }; -static arc arcs_49_4[1] = { - {0, 4}, +static arc arcs_49_1[1] = { + {0, 1}, }; -static state states_49[5] = { - {1, arcs_49_0}, - {2, arcs_49_1}, - {1, arcs_49_2}, - {1, arcs_49_3}, - {1, arcs_49_4}, -}; -static arc arcs_50_0[2] = { - {107, 1}, - {110, 2}, +static state states_49[2] = { + {2, arcs_49_0}, + {1, arcs_49_1}, +}; +static arc arcs_50_0[1] = { + {111, 1}, }; static arc arcs_50_1[2] = { - {90, 3}, - {0, 1}, + {33, 2}, + {23, 3}, }; static arc arcs_50_2[1] = { - {0, 2}, + {23, 3}, }; static arc arcs_50_3[1] = { - {107, 4}, + {108, 4}, }; static arc arcs_50_4[1] = { - {92, 5}, -}; -static arc arcs_50_5[1] = { - {22, 2}, + {0, 4}, }; -static state states_50[6] = { - {2, arcs_50_0}, +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}, - {1, arcs_50_5}, }; -static arc arcs_51_0[1] = { - {111, 1}, +static arc arcs_51_0[2] = { + {109, 1}, + {112, 2}, }; static arc arcs_51_1[2] = { - {112, 0}, + {92, 3}, {0, 1}, }; -static state states_51[2] = { - {1, arcs_51_0}, +static arc arcs_51_2[1] = { + {0, 2}, +}; +static arc arcs_51_3[1] = { + {109, 4}, +}; +static arc arcs_51_4[1] = { + {94, 5}, +}; +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}, + {1, arcs_51_3}, + {1, arcs_51_4}, + {1, arcs_51_5}, }; static arc arcs_52_0[1] = { {113, 1}, @@ -1152,69 +1157,69 @@ {1, arcs_52_0}, {2, arcs_52_1}, }; -static arc arcs_53_0[2] = { +static arc arcs_53_0[1] = { {115, 1}, - {116, 2}, }; -static arc arcs_53_1[1] = { - {113, 2}, +static arc arcs_53_1[2] = { + {116, 0}, + {0, 1}, +}; +static state states_53[2] = { + {1, arcs_53_0}, + {2, arcs_53_1}, +}; +static arc arcs_54_0[2] = { + {117, 1}, + {118, 2}, +}; +static arc arcs_54_1[1] = { + {115, 2}, }; -static arc arcs_53_2[1] = { +static arc arcs_54_2[1] = { {0, 2}, }; -static state states_53[3] = { - {2, arcs_53_0}, - {1, arcs_53_1}, - {1, arcs_53_2}, +static state states_54[3] = { + {2, arcs_54_0}, + {1, arcs_54_1}, + {1, arcs_54_2}, }; -static arc arcs_54_0[1] = { - {101, 1}, +static arc arcs_55_0[1] = { + {103, 1}, }; -static arc arcs_54_1[2] = { - {117, 0}, +static arc arcs_55_1[2] = { + {119, 0}, {0, 1}, }; -static state states_54[2] = { - {1, arcs_54_0}, - {2, arcs_54_1}, +static state states_55[2] = { + {1, arcs_55_0}, + {2, arcs_55_1}, }; -static arc arcs_55_0[9] = { - {118, 1}, - {119, 1}, +static arc arcs_56_0[9] = { {120, 1}, {121, 1}, {122, 1}, {123, 1}, - {95, 1}, - {115, 2}, - {124, 3}, + {124, 1}, + {125, 1}, + {97, 1}, + {117, 2}, + {126, 3}, }; -static arc arcs_55_1[1] = { +static arc arcs_56_1[1] = { {0, 1}, }; -static arc arcs_55_2[1] = { - {95, 1}, +static arc arcs_56_2[1] = { + {97, 1}, }; -static arc arcs_55_3[2] = { - {115, 1}, +static arc arcs_56_3[2] = { + {117, 1}, {0, 3}, }; -static state states_55[4] = { - {9, arcs_55_0}, - {1, arcs_55_1}, - {1, arcs_55_2}, - {2, arcs_55_3}, -}; -static arc arcs_56_0[1] = { - {125, 1}, -}; -static arc arcs_56_1[2] = { - {126, 0}, - {0, 1}, -}; -static state states_56[2] = { - {1, arcs_56_0}, - {2, arcs_56_1}, +static 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] = { {127, 1}, @@ -1241,21 +1246,20 @@ static arc arcs_59_0[1] = { {131, 1}, }; -static arc arcs_59_1[3] = { +static arc arcs_59_1[2] = { {132, 0}, - {133, 0}, {0, 1}, }; static state states_59[2] = { {1, arcs_59_0}, - {3, arcs_59_1}, + {2, arcs_59_1}, }; static arc arcs_60_0[1] = { - {134, 1}, + {133, 1}, }; static arc arcs_60_1[3] = { + {134, 0}, {135, 0}, - {136, 0}, {0, 1}, }; static state states_60[2] = { @@ -1263,144 +1267,130 @@ {3, arcs_60_1}, }; static arc arcs_61_0[1] = { - {137, 1}, + {136, 1}, }; -static arc arcs_61_1[5] = { - {29, 0}, +static arc arcs_61_1[3] = { + {137, 0}, {138, 0}, - {139, 0}, - {140, 0}, {0, 1}, }; static state states_61[2] = { {1, arcs_61_0}, - {5, arcs_61_1}, + {3, arcs_61_1}, }; -static arc arcs_62_0[4] = { - {135, 1}, - {136, 1}, - {141, 1}, - {142, 2}, +static arc arcs_62_0[1] = { + {139, 1}, +}; +static arc arcs_62_1[5] = { + {29, 0}, + {140, 0}, + {141, 0}, + {142, 0}, + {0, 1}, +}; +static state states_62[2] = { + {1, arcs_62_0}, + {5, arcs_62_1}, +}; +static arc arcs_63_0[4] = { + {137, 1}, + {138, 1}, + {143, 1}, + {144, 2}, }; -static arc arcs_62_1[1] = { - {137, 2}, +static arc arcs_63_1[1] = { + {139, 2}, }; -static arc arcs_62_2[1] = { +static arc arcs_63_2[1] = { {0, 2}, }; -static state states_62[3] = { - {4, arcs_62_0}, - {1, arcs_62_1}, - {1, arcs_62_2}, +static state states_63[3] = { + {4, arcs_63_0}, + {1, arcs_63_1}, + {1, arcs_63_2}, }; -static arc arcs_63_0[1] = { - {143, 1}, +static arc arcs_64_0[1] = { + {145, 1}, }; -static arc arcs_63_1[3] = { - {144, 1}, +static arc arcs_64_1[3] = { + {146, 1}, {31, 2}, {0, 1}, }; -static arc arcs_63_2[1] = { - {137, 3}, +static arc arcs_64_2[1] = { + {139, 3}, }; -static arc arcs_63_3[1] = { +static arc arcs_64_3[1] = { {0, 3}, }; -static state states_63[4] = { - {1, arcs_63_0}, - {3, arcs_63_1}, - {1, arcs_63_2}, - {1, arcs_63_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_64_0[7] = { +static arc arcs_65_0[7] = { {13, 1}, - {146, 2}, - {149, 3}, + {148, 2}, + {151, 3}, {19, 4}, - {152, 4}, - {153, 5}, - {77, 6}, + {154, 4}, + {155, 5}, + {78, 6}, }; -static arc arcs_64_1[3] = { - {47, 7}, - {145, 7}, +static arc arcs_65_1[3] = { + {48, 7}, + {147, 7}, {15, 4}, }; -static arc arcs_64_2[2] = { - {147, 8}, - {148, 4}, -}; -static arc arcs_64_3[2] = { - {150, 9}, - {151, 4}, +static arc arcs_65_2[2] = { + {149, 8}, + {150, 4}, }; -static arc arcs_64_4[1] = { +static arc arcs_65_3[2] = { + {152, 9}, + {153, 4}, +}; +static arc arcs_65_4[1] = { {0, 4}, }; -static arc arcs_64_5[2] = { - {153, 5}, +static arc arcs_65_5[2] = { + {155, 5}, {0, 5}, }; -static arc arcs_64_6[1] = { - {77, 10}, +static arc arcs_65_6[1] = { + {78, 10}, }; -static arc arcs_64_7[1] = { +static arc arcs_65_7[1] = { {15, 4}, }; -static arc arcs_64_8[1] = { - {148, 4}, -}; -static arc arcs_64_9[1] = { - {151, 4}, -}; -static arc arcs_64_10[1] = { - {77, 4}, -}; -static state states_64[11] = { - {7, arcs_64_0}, - {3, arcs_64_1}, - {2, arcs_64_2}, - {2, arcs_64_3}, - {1, arcs_64_4}, - {2, arcs_64_5}, - {1, arcs_64_6}, - {1, arcs_64_7}, - {1, arcs_64_8}, - {1, arcs_64_9}, - {1, arcs_64_10}, +static arc arcs_65_8[1] = { + {150, 4}, }; -static arc arcs_65_0[1] = { - {22, 1}, +static arc arcs_65_9[1] = { + {153, 4}, }; -static arc arcs_65_1[3] = { - {154, 2}, - {28, 3}, - {0, 1}, -}; -static arc arcs_65_2[1] = { - {0, 2}, -}; -static arc arcs_65_3[2] = { - {22, 4}, - {0, 3}, +static arc arcs_65_10[1] = { + {78, 4}, }; -static arc arcs_65_4[2] = { - {28, 3}, - {0, 4}, -}; -static state states_65[5] = { - {1, arcs_65_0}, +static state states_65[11] = { + {7, arcs_65_0}, {3, arcs_65_1}, - {1, arcs_65_2}, + {2, arcs_65_2}, {2, arcs_65_3}, - {2, arcs_65_4}, + {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] = { - {155, 2}, + {156, 2}, {28, 3}, {0, 1}, }; @@ -1423,144 +1413,154 @@ {2, arcs_66_4}, }; static arc arcs_67_0[1] = { - {109, 1}, + {22, 1}, }; -static arc arcs_67_1[2] = { - {33, 2}, - {23, 3}, +static arc arcs_67_1[3] = { + {157, 2}, + {28, 3}, + {0, 1}, }; static arc arcs_67_2[1] = { - {23, 3}, + {0, 2}, }; -static arc arcs_67_3[1] = { +static arc arcs_67_3[2] = { {22, 4}, + {0, 3}, }; -static arc arcs_67_4[1] = { +static arc arcs_67_4[2] = { + {28, 3}, {0, 4}, }; static state states_67[5] = { {1, arcs_67_0}, - {2, arcs_67_1}, + {3, arcs_67_1}, {1, arcs_67_2}, - {1, arcs_67_3}, - {1, arcs_67_4}, + {2, arcs_67_3}, + {2, arcs_67_4}, }; -static arc arcs_68_0[3] = { - {13, 1}, - {146, 2}, - {77, 3}, +static arc arcs_68_0[1] = { + {111, 1}, }; static arc arcs_68_1[2] = { - {14, 4}, - {15, 5}, + {33, 2}, + {23, 3}, }; static arc arcs_68_2[1] = { - {156, 6}, + {23, 3}, }; static arc arcs_68_3[1] = { - {19, 5}, + {22, 4}, }; static arc arcs_68_4[1] = { - {15, 5}, -}; -static arc arcs_68_5[1] = { - {0, 5}, -}; -static arc arcs_68_6[1] = { - {148, 5}, + {0, 4}, }; -static state states_68[7] = { - {3, arcs_68_0}, +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}, - {1, arcs_68_5}, - {1, arcs_68_6}, }; -static arc arcs_69_0[1] = { - {157, 1}, +static arc arcs_69_0[3] = { + {13, 1}, + {148, 2}, + {78, 3}, }; static arc arcs_69_1[2] = { + {14, 4}, + {15, 5}, +}; +static arc arcs_69_2[1] = { + {158, 6}, +}; +static arc arcs_69_3[1] = { + {19, 5}, +}; +static arc arcs_69_4[1] = { + {15, 5}, +}; +static arc arcs_69_5[1] = { + {0, 5}, +}; +static arc arcs_69_6[1] = { + {150, 5}, +}; +static state states_69[7] = { + {3, arcs_69_0}, + {2, arcs_69_1}, + {1, arcs_69_2}, + {1, arcs_69_3}, + {1, arcs_69_4}, + {1, arcs_69_5}, + {1, arcs_69_6}, +}; +static arc arcs_70_0[1] = { + {159, 1}, +}; +static arc arcs_70_1[2] = { {28, 2}, {0, 1}, }; -static arc arcs_69_2[2] = { - {157, 1}, +static arc arcs_70_2[2] = { + {159, 1}, {0, 2}, }; -static state states_69[3] = { - {1, arcs_69_0}, - {2, arcs_69_1}, - {2, arcs_69_2}, +static state states_70[3] = { + {1, arcs_70_0}, + {2, arcs_70_1}, + {2, arcs_70_2}, }; -static arc arcs_70_0[2] = { +static arc arcs_71_0[2] = { {22, 1}, {23, 2}, }; -static arc arcs_70_1[2] = { +static arc arcs_71_1[2] = { {23, 2}, {0, 1}, }; -static arc arcs_70_2[3] = { +static arc arcs_71_2[3] = { {22, 3}, - {158, 4}, + {160, 4}, {0, 2}, }; -static arc arcs_70_3[2] = { - {158, 4}, +static arc arcs_71_3[2] = { + {160, 4}, {0, 3}, }; -static arc arcs_70_4[1] = { +static arc arcs_71_4[1] = { {0, 4}, }; -static state states_70[5] = { - {2, arcs_70_0}, - {2, arcs_70_1}, - {3, arcs_70_2}, - {2, arcs_70_3}, - {1, arcs_70_4}, -}; -static arc arcs_71_0[1] = { - {23, 1}, -}; -static arc arcs_71_1[2] = { - {22, 2}, - {0, 1}, -}; -static arc arcs_71_2[1] = { - {0, 2}, -}; -static state states_71[3] = { - {1, arcs_71_0}, +static state states_71[5] = { + {2, arcs_71_0}, {2, arcs_71_1}, - {1, arcs_71_2}, + {3, arcs_71_2}, + {2, arcs_71_3}, + {1, arcs_71_4}, }; static arc arcs_72_0[1] = { - {101, 1}, + {23, 1}, }; static arc arcs_72_1[2] = { - {28, 2}, + {22, 2}, {0, 1}, }; -static arc arcs_72_2[2] = { - {101, 1}, +static arc arcs_72_2[1] = { {0, 2}, }; static state states_72[3] = { {1, arcs_72_0}, {2, arcs_72_1}, - {2, arcs_72_2}, + {1, arcs_72_2}, }; static arc arcs_73_0[1] = { - {22, 1}, + {103, 1}, }; static arc arcs_73_1[2] = { {28, 2}, {0, 1}, }; static arc arcs_73_2[2] = { - {22, 1}, + {103, 1}, {0, 2}, }; static state states_73[3] = { @@ -1571,482 +1571,500 @@ static arc arcs_74_0[1] = { {22, 1}, }; -static arc arcs_74_1[3] = { +static arc arcs_74_1[2] = { + {28, 2}, + {0, 1}, +}; +static arc arcs_74_2[2] = { + {22, 1}, + {0, 2}, +}; +static state states_74[3] = { + {1, arcs_74_0}, + {2, arcs_74_1}, + {2, arcs_74_2}, +}; +static arc arcs_75_0[1] = { + {22, 1}, +}; +static arc arcs_75_1[3] = { {23, 2}, {28, 3}, {0, 1}, }; -static arc arcs_74_2[1] = { +static arc arcs_75_2[1] = { {22, 4}, }; -static arc arcs_74_3[2] = { +static arc arcs_75_3[2] = { {22, 5}, {0, 3}, }; -static arc arcs_74_4[2] = { +static arc arcs_75_4[2] = { {28, 6}, {0, 4}, }; -static arc arcs_74_5[2] = { +static arc arcs_75_5[2] = { {28, 3}, {0, 5}, }; -static arc arcs_74_6[2] = { +static arc arcs_75_6[2] = { {22, 7}, {0, 6}, }; -static arc arcs_74_7[1] = { +static arc arcs_75_7[1] = { {23, 2}, }; -static state states_74[8] = { - {1, arcs_74_0}, - {3, arcs_74_1}, - {1, arcs_74_2}, - {2, arcs_74_3}, - {2, arcs_74_4}, - {2, arcs_74_5}, - {2, arcs_74_6}, - {1, arcs_74_7}, +static 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_75_0[1] = { - {159, 1}, +static arc arcs_76_0[1] = { + {161, 1}, }; -static arc arcs_75_1[1] = { +static arc arcs_76_1[1] = { {19, 2}, }; -static arc arcs_75_2[2] = { +static arc arcs_76_2[2] = { {13, 3}, {23, 4}, }; -static arc arcs_75_3[2] = { +static arc arcs_76_3[2] = { {9, 5}, {15, 6}, }; -static arc arcs_75_4[1] = { +static arc arcs_76_4[1] = { {24, 7}, }; -static arc arcs_75_5[1] = { +static arc arcs_76_5[1] = { {15, 6}, }; -static arc arcs_75_6[1] = { +static arc arcs_76_6[1] = { {23, 4}, }; -static arc arcs_75_7[1] = { +static arc arcs_76_7[1] = { {0, 7}, }; -static state states_75[8] = { - {1, arcs_75_0}, - {1, arcs_75_1}, - {2, arcs_75_2}, - {2, arcs_75_3}, - {1, arcs_75_4}, - {1, arcs_75_5}, - {1, arcs_75_6}, - {1, arcs_75_7}, +static 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_76_0[3] = { - {160, 1}, +static arc arcs_77_0[3] = { + {162, 1}, {29, 2}, {31, 3}, }; -static arc arcs_76_1[2] = { +static arc arcs_77_1[2] = { {28, 4}, {0, 1}, }; -static arc arcs_76_2[1] = { +static arc arcs_77_2[1] = { {22, 5}, }; -static arc arcs_76_3[1] = { +static arc arcs_77_3[1] = { {22, 6}, }; -static arc arcs_76_4[4] = { - {160, 1}, +static arc arcs_77_4[4] = { + {162, 1}, {29, 2}, {31, 3}, {0, 4}, }; -static arc arcs_76_5[2] = { +static arc arcs_77_5[2] = { {28, 7}, {0, 5}, }; -static arc arcs_76_6[1] = { +static arc arcs_77_6[1] = { {0, 6}, }; -static arc arcs_76_7[1] = { +static arc arcs_77_7[1] = { {31, 3}, }; -static state states_76[8] = { - {3, arcs_76_0}, - {2, arcs_76_1}, - {1, arcs_76_2}, - {1, arcs_76_3}, - {4, arcs_76_4}, - {2, arcs_76_5}, - {1, arcs_76_6}, - {1, arcs_76_7}, +static 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_77_0[1] = { +static arc arcs_78_0[1] = { {22, 1}, }; -static arc arcs_77_1[3] = { - {155, 2}, +static arc arcs_78_1[3] = { + {157, 2}, {27, 3}, {0, 1}, }; -static arc arcs_77_2[1] = { +static arc arcs_78_2[1] = { {0, 2}, }; -static arc arcs_77_3[1] = { +static arc arcs_78_3[1] = { {22, 2}, }; -static state states_77[4] = { - {1, arcs_77_0}, - {3, arcs_77_1}, - {1, arcs_77_2}, - {1, arcs_77_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_78_0[2] = { - {154, 1}, - {162, 1}, +static arc arcs_79_0[2] = { + {156, 1}, + {164, 1}, }; -static arc arcs_78_1[1] = { +static arc arcs_79_1[1] = { {0, 1}, }; -static state states_78[2] = { - {2, arcs_78_0}, - {1, arcs_78_1}, +static state states_79[2] = { + {2, arcs_79_0}, + {1, arcs_79_1}, }; -static arc arcs_79_0[1] = { - {94, 1}, +static arc arcs_80_0[1] = { + {96, 1}, }; -static arc arcs_79_1[1] = { - {61, 2}, +static arc arcs_80_1[1] = { + {62, 2}, }; -static arc arcs_79_2[1] = { - {95, 3}, +static arc arcs_80_2[1] = { + {97, 3}, }; -static arc arcs_79_3[1] = { - {105, 4}, +static arc arcs_80_3[1] = { + {107, 4}, }; -static arc arcs_79_4[2] = { - {161, 5}, +static arc arcs_80_4[2] = { + {163, 5}, {0, 4}, }; -static arc arcs_79_5[1] = { +static arc arcs_80_5[1] = { {0, 5}, }; -static state states_79[6] = { - {1, arcs_79_0}, - {1, arcs_79_1}, - {1, arcs_79_2}, - {1, arcs_79_3}, - {2, arcs_79_4}, - {1, arcs_79_5}, +static 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_80_0[1] = { - {90, 1}, +static arc arcs_81_0[1] = { + {92, 1}, }; -static arc arcs_80_1[1] = { - {106, 2}, +static arc arcs_81_1[1] = { + {108, 2}, }; -static arc arcs_80_2[2] = { - {161, 3}, +static arc arcs_81_2[2] = { + {163, 3}, {0, 2}, }; -static arc arcs_80_3[1] = { +static arc arcs_81_3[1] = { {0, 3}, }; -static state states_80[4] = { - {1, arcs_80_0}, - {1, arcs_80_1}, - {2, arcs_80_2}, - {1, arcs_80_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_81_0[2] = { - {155, 1}, - {164, 1}, +static arc arcs_82_0[2] = { + {157, 1}, + {166, 1}, }; -static arc arcs_81_1[1] = { +static arc arcs_82_1[1] = { {0, 1}, }; -static state states_81[2] = { - {2, arcs_81_0}, - {1, arcs_81_1}, +static state states_82[2] = { + {2, arcs_82_0}, + {1, arcs_82_1}, }; -static arc arcs_82_0[1] = { - {94, 1}, +static arc arcs_83_0[1] = { + {96, 1}, }; -static arc arcs_82_1[1] = { - {61, 2}, +static arc arcs_83_1[1] = { + {62, 2}, }; -static arc arcs_82_2[1] = { - {95, 3}, +static arc arcs_83_2[1] = { + {97, 3}, }; -static arc arcs_82_3[1] = { - {107, 4}, +static arc arcs_83_3[1] = { + {109, 4}, }; -static arc arcs_82_4[2] = { - {163, 5}, +static arc arcs_83_4[2] = { + {165, 5}, {0, 4}, }; -static arc arcs_82_5[1] = { +static arc arcs_83_5[1] = { {0, 5}, }; -static state states_82[6] = { - {1, arcs_82_0}, - {1, arcs_82_1}, - {1, arcs_82_2}, - {1, arcs_82_3}, - {2, arcs_82_4}, - {1, arcs_82_5}, +static 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_83_0[1] = { - {90, 1}, +static arc arcs_84_0[1] = { + {92, 1}, }; -static arc arcs_83_1[1] = { - {106, 2}, +static arc arcs_84_1[1] = { + {108, 2}, }; -static arc arcs_83_2[2] = { - {163, 3}, +static arc arcs_84_2[2] = { + {165, 3}, {0, 2}, }; -static arc arcs_83_3[1] = { +static arc arcs_84_3[1] = { {0, 3}, }; -static state states_83[4] = { - {1, arcs_83_0}, - {1, arcs_83_1}, - {2, arcs_83_2}, - {1, arcs_83_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_84_0[1] = { +static arc arcs_85_0[1] = { {22, 1}, }; -static arc arcs_84_1[2] = { +static arc arcs_85_1[2] = { {28, 0}, {0, 1}, }; -static state states_84[2] = { - {1, arcs_84_0}, - {2, arcs_84_1}, +static state states_85[2] = { + {1, arcs_85_0}, + {2, arcs_85_1}, }; -static arc arcs_85_0[1] = { +static arc arcs_86_0[1] = { {19, 1}, }; -static arc arcs_85_1[1] = { +static arc arcs_86_1[1] = { {0, 1}, }; -static state states_85[2] = { - {1, arcs_85_0}, - {1, arcs_85_1}, +static state states_86[2] = { + {1, arcs_86_0}, + {1, arcs_86_1}, }; -static arc arcs_86_0[1] = { - {167, 1}, +static arc arcs_87_0[1] = { + {169, 1}, }; -static arc arcs_86_1[2] = { +static arc arcs_87_1[2] = { {9, 2}, {0, 1}, }; -static arc arcs_86_2[1] = { +static arc arcs_87_2[1] = { {0, 2}, }; -static state states_86[3] = { - {1, arcs_86_0}, - {2, arcs_86_1}, - {1, arcs_86_2}, +static state states_87[3] = { + {1, arcs_87_0}, + {2, arcs_87_1}, + {1, arcs_87_2}, }; -static dfa dfas[87] = { +static dfa dfas[88] = { {256, "single_input", 0, 3, states_0, - "\004\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"}, + "\004\050\014\000\000\000\000\240\340\151\070\220\045\200\040\000\000\206\220\014\002\002"}, {257, "file_input", 0, 2, states_1, - "\204\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"}, + "\204\050\014\000\000\000\000\240\340\151\070\220\045\200\040\000\000\206\220\014\002\002"}, {258, "eval_input", 0, 3, states_2, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\200\040\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"}, + "\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\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"}, + "\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\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\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\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\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\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\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\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\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\120\360\064\014\144\011\040\010\000\200\041\044\203\200"}, + "\000\050\014\000\000\000\000\240\340\151\070\220\045\200\040\000\000\206\220\014\002\002"}, {272, "simple_stmt", 0, 4, states_16, - "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"}, + "\000\040\010\000\000\000\000\240\340\151\070\000\000\200\040\000\000\206\220\014\000\002"}, {273, "small_stmt", 0, 2, states_17, - "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"}, + "\000\040\010\000\000\000\000\240\340\151\070\000\000\200\040\000\000\206\220\014\000\002"}, {274, "expr_stmt", 0, 6, states_18, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\200\040\000\000\206\220\014\000\000"}, {275, "augassign", 0, 2, states_19, - "\000\000\000\000\000\000\377\017\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {276, "del_stmt", 0, 3, states_20, - "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {277, "pass_stmt", 0, 2, states_21, - "\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {278, "flow_stmt", 0, 2, states_22, - "\000\000\000\000\000\000\000\000\360\000\000\000\000\000\000\000\000\000\000\000\200"}, + "\000\000\000\000\000\000\000\000\340\001\000\000\000\000\000\000\000\000\000\000\000\002"}, {279, "break_stmt", 0, 2, states_23, - "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {280, "continue_stmt", 0, 2, states_24, - "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {281, "return_stmt", 0, 3, states_25, - "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {282, "yield_stmt", 0, 2, states_26, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, {283, "raise_stmt", 0, 7, states_27, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000\000"}, {284, "import_stmt", 0, 2, states_28, - "\000\000\000\000\000\000\000\000\000\024\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\000\000\050\000\000\000\000\000\000\000\000\000\000\000\000"}, {285, "import_name", 0, 3, states_29, - "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000"}, {286, "import_from", 0, 8, states_30, - "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, {287, "import_as_name", 0, 4, states_31, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {288, "dotted_as_name", 0, 4, states_32, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {289, "import_as_names", 0, 3, states_33, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {290, "dotted_as_names", 0, 2, states_34, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {291, "dotted_name", 0, 2, states_35, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {292, "global_stmt", 0, 3, states_36, - "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000"}, - {293, "assert_stmt", 0, 5, states_37, - "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000"}, - {294, "compound_stmt", 0, 2, states_38, - "\000\010\004\000\000\000\000\000\000\000\000\144\011\000\000\000\000\000\000\200\000"}, - {295, "if_stmt", 0, 8, states_39, - "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, - {296, "while_stmt", 0, 8, states_40, - "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"}, - {297, "for_stmt", 0, 10, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {298, "try_stmt", 0, 13, states_42, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {299, "with_stmt", 0, 6, states_43, - "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000"}, - {300, "with_var", 0, 3, states_44, - "\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000"}, - {301, "except_clause", 0, 5, states_45, - "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000"}, - {302, "suite", 0, 5, states_46, - "\004\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"}, - {303, "testlist_safe", 0, 5, states_47, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {304, "old_test", 0, 2, states_48, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {305, "old_lambdef", 0, 5, states_49, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, - {306, "test", 0, 6, states_50, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {307, "or_test", 0, 2, states_51, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"}, - {308, "and_test", 0, 2, states_52, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"}, - {309, "not_test", 0, 3, states_53, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"}, - {310, "comparison", 0, 2, states_54, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, - {311, "comp_op", 0, 4, states_55, - "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\310\037\000\000\000\000\000"}, - {312, "expr", 0, 2, states_56, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, - {313, "xor_expr", 0, 2, states_57, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, - {314, "and_expr", 0, 2, states_58, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, - {315, "shift_expr", 0, 2, states_59, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, - {316, "arith_expr", 0, 2, states_60, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, - {317, "term", 0, 2, states_61, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, - {318, "factor", 0, 3, states_62, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, - {319, "power", 0, 4, states_63, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"}, - {320, "atom", 0, 11, states_64, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"}, - {321, "listmaker", 0, 5, states_65, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {322, "testlist_gexp", 0, 5, states_66, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {323, "lambdef", 0, 5, states_67, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, - {324, "trailer", 0, 7, states_68, - "\000\040\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\004\000\000"}, - {325, "subscriptlist", 0, 3, states_69, - "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {326, "subscript", 0, 5, states_70, - "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {327, "sliceop", 0, 3, states_71, - "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {328, "exprlist", 0, 3, states_72, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"}, - {329, "testlist", 0, 3, states_73, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {330, "dictsetmaker", 0, 8, states_74, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {331, "classdef", 0, 8, states_75, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000"}, - {332, "arglist", 0, 8, states_76, - "\000\040\010\240\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {333, "argument", 0, 4, states_77, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {334, "list_iter", 0, 2, states_78, - "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"}, - {335, "list_for", 0, 6, states_79, - "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {336, "list_if", 0, 4, states_80, - "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, - {337, "gen_iter", 0, 2, states_81, - "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"}, - {338, "gen_for", 0, 6, states_82, - "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {339, "gen_if", 0, 4, states_83, - "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, - {340, "testlist1", 0, 2, states_84, - "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"}, - {341, "encoding_decl", 0, 2, states_85, - "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {342, "yield_expr", 0, 3, states_86, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000"}, + {293, "nonlocal_stmt", 0, 3, states_37, + "\000\000\000\000\000\000\000\000\000\000\020\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\040\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\220\045\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\020\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\200\000\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\001\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\004\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\040\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\002\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\001\000\000\000\000\000\000\000\000"}, + {303, "suite", 0, 5, states_47, + "\004\040\010\000\000\000\000\240\340\151\070\000\000\200\040\000\000\206\220\014\000\002"}, + {304, "testlist_safe", 0, 5, states_48, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\200\040\000\000\206\220\014\000\000"}, + {305, "old_test", 0, 2, states_49, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\200\040\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\200\000\000\000\000\000\000\000\000"}, + {307, "test", 0, 6, states_51, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\200\040\000\000\206\220\014\000\000"}, + {308, "or_test", 0, 2, states_52, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\000\040\000\000\206\220\014\000\000"}, + {309, "and_test", 0, 2, states_53, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\000\040\000\000\206\220\014\000\000"}, + {310, "not_test", 0, 3, states_54, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\000\040\000\000\206\220\014\000\000"}, + {311, "comparison", 0, 2, states_55, + "\000\040\010\000\000\000\000\000\000\100\000\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\002\000\040\177\000\000\000\000\000\000"}, + {313, "expr", 0, 2, states_57, + "\000\040\010\000\000\000\000\000\000\100\000\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\100\000\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\100\000\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\100\000\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\100\000\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\100\000\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\100\000\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\100\000\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\100\000\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\100\000\000\000\200\040\000\000\206\220\014\000\000"}, + {323, "testlist_gexp", 0, 5, states_67, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\200\040\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\200\000\000\000\000\000\000\000\000"}, + {325, "trailer", 0, 7, states_69, + "\000\040\000\000\000\000\000\000\000\100\000\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\100\000\000\000\200\040\000\000\206\220\014\000\000"}, + {327, "subscript", 0, 5, states_71, + "\000\040\210\000\000\000\000\000\000\100\000\000\000\200\040\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\100\000\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\100\000\000\000\200\040\000\000\206\220\014\000\000"}, + {331, "dictsetmaker", 0, 8, states_75, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\200\040\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\100\000\000\000\200\040\000\000\206\220\014\000\000"}, + {334, "argument", 0, 4, states_78, + "\000\040\010\000\000\000\000\000\000\100\000\000\000\200\040\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\020\001\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\001\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\020\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\020\001\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\001\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\020\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\100\000\000\000\200\040\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[168] = { +static label labels[170] = { {0, "EMPTY"}, {256, 0}, {4, 0}, {272, 0}, - {294, 0}, + {295, 0}, {257, 0}, {271, 0}, {0, 0}, {258, 0}, - {329, 0}, + {330, 0}, {259, 0}, {50, 0}, {291, 0}, {7, 0}, - {332, 0}, + {333, 0}, {8, 0}, {260, 0}, {261, 0}, @@ -2054,9 +2072,9 @@ {1, 0}, {262, 0}, {51, 0}, - {306, 0}, + {307, 0}, {11, 0}, - {302, 0}, + {303, 0}, {263, 0}, {265, 0}, {22, 0}, @@ -2078,8 +2096,9 @@ {284, 0}, {292, 0}, {293, 0}, + {294, 0}, {275, 0}, - {342, 0}, + {343, 0}, {37, 0}, {38, 0}, {39, 0}, @@ -2093,7 +2112,7 @@ {47, 0}, {49, 0}, {1, "del"}, - {328, 0}, + {329, 0}, {1, "pass"}, {279, 0}, {280, 0}, @@ -2115,13 +2134,14 @@ {1, "as"}, {288, 0}, {1, "global"}, + {1, "nonlocal"}, {1, "assert"}, - {295, 0}, {296, 0}, {297, 0}, {298, 0}, {299, 0}, - {331, 0}, + {300, 0}, + {332, 0}, {1, "if"}, {1, "elif"}, {1, "else"}, @@ -2129,27 +2149,27 @@ {1, "for"}, {1, "in"}, {1, "try"}, - {301, 0}, + {302, 0}, {1, "finally"}, {1, "with"}, - {300, 0}, - {312, 0}, + {301, 0}, + {313, 0}, {1, "except"}, {5, 0}, {6, 0}, - {303, 0}, {304, 0}, - {307, 0}, {305, 0}, - {1, "lambda"}, - {323, 0}, {308, 0}, - {1, "or"}, + {306, 0}, + {1, "lambda"}, + {324, 0}, {309, 0}, + {1, "or"}, + {310, 0}, {1, "and"}, {1, "not"}, - {310, 0}, {311, 0}, + {312, 0}, {20, 0}, {21, 0}, {28, 0}, @@ -2157,53 +2177,53 @@ {30, 0}, {29, 0}, {1, "is"}, - {313, 0}, - {18, 0}, {314, 0}, - {33, 0}, + {18, 0}, {315, 0}, - {19, 0}, + {33, 0}, {316, 0}, + {19, 0}, + {317, 0}, {34, 0}, {35, 0}, - {317, 0}, + {318, 0}, {14, 0}, {15, 0}, - {318, 0}, + {319, 0}, {17, 0}, {24, 0}, {48, 0}, {32, 0}, - {319, 0}, {320, 0}, - {324, 0}, - {322, 0}, - {9, 0}, {321, 0}, + {325, 0}, + {323, 0}, + {9, 0}, + {322, 0}, {10, 0}, {26, 0}, - {330, 0}, + {331, 0}, {27, 0}, {2, 0}, {3, 0}, - {335, 0}, - {338, 0}, - {325, 0}, + {336, 0}, + {339, 0}, {326, 0}, {327, 0}, + {328, 0}, {1, "class"}, - {333, 0}, {334, 0}, - {336, 0}, + {335, 0}, {337, 0}, - {339, 0}, + {338, 0}, {340, 0}, {341, 0}, + {342, 0}, {1, "yield"}, }; grammar _PyParser_Grammar = { - 87, + 88, dfas, - {168, labels}, + {170, labels}, 256 }; Modified: python/branches/p3yk/Python/symtable.c ============================================================================== --- python/branches/p3yk/Python/symtable.c (original) +++ python/branches/p3yk/Python/symtable.c Tue Feb 27 07:50:52 2007 @@ -8,9 +8,15 @@ #define GLOBAL_AFTER_ASSIGN \ "name '%.400s' is assigned to before global declaration" +#define NONLOCAL_AFTER_ASSIGN \ +"name '%.400s' is assigned to before nonlocal declaration" + #define GLOBAL_AFTER_USE \ "name '%.400s' is used prior to global declaration" +#define NONLOCAL_AFTER_USE \ +"name '%.400s' is used prior to nonlocal declaration" + #define IMPORT_STAR_WARNING "import * only allowed at module level" #define RETURN_VAL_IN_GENERATOR \ @@ -328,6 +334,8 @@ block, the name is treated as global until it is assigned to; then it is treated as a local. + TODO(jhylton): Discuss nonlocal + The symbol table requires two passes to determine the scope of each name. The first pass collects raw facts from the AST: the name is a parameter here, the name is used by not defined here, etc. The second pass analyzes @@ -378,6 +386,12 @@ PyString_AS_STRING(name)); return 0; } + if (flags & DEF_NONLOCAL) { + PyErr_Format(PyExc_SyntaxError, + "name '%s' is nonlocal and global", + PyString_AS_STRING(name)); + return 0; + } SET_SCOPE(dict, name, GLOBAL_EXPLICIT); if (PyDict_SetItem(global, name, Py_None) < 0) return 0; @@ -387,6 +401,24 @@ } return 1; } + if (flags & DEF_NONLOCAL) { + if (flags & DEF_PARAM) { + PyErr_Format(PyExc_SyntaxError, + "name '%s' is local and nonlocal", + PyString_AS_STRING(name)); + return 0; + } + if (!PyDict_GetItem(bound, name)) { + PyErr_Format(PyExc_SyntaxError, + "no binding for nonlocal '%s' found", + PyString_AS_STRING(name)); + + return 0; + } + SET_SCOPE(dict, name, FREE); + ste->ste_free = 1; + return PyDict_SetItem(free, name, Py_None) >= 0; + } if (flags & DEF_BOUND) { SET_SCOPE(dict, name, LOCAL); if (PyDict_SetItem(local, name, Py_None) < 0) @@ -405,24 +437,19 @@ if (bound && PyDict_GetItem(bound, name)) { SET_SCOPE(dict, name, FREE); ste->ste_free = 1; - if (PyDict_SetItem(free, name, Py_None) < 0) - return 0; - return 1; + return PyDict_SetItem(free, name, Py_None) >= 0; } /* If a parent has a global statement, then call it global explicit? It could also be global implicit. */ - else if (global && PyDict_GetItem(global, name)) { + if (global && PyDict_GetItem(global, name)) { SET_SCOPE(dict, name, GLOBAL_EXPLICIT); return 1; } - else { - if (ste->ste_nested) - ste->ste_free = 1; - SET_SCOPE(dict, name, GLOBAL_IMPLICIT); - return 1; - } - return 0; /* Can't get here */ + if (ste->ste_nested) + ste->ste_free = 1; + SET_SCOPE(dict, name, GLOBAL_IMPLICIT); + return 1; } #undef SET_SCOPE @@ -782,6 +809,7 @@ long val; PyObject *mangled = _Py_Mangle(st->st_private, name); + if (!mangled) return 0; dict = st->st_cur->ste_symbols; @@ -1075,6 +1103,33 @@ } break; } + case Nonlocal_kind: { + int i; + asdl_seq *seq = s->v.Nonlocal.names; + for (i = 0; i < asdl_seq_LEN(seq); i++) { + identifier name = (identifier)asdl_seq_GET(seq, i); + char *c_name = PyString_AS_STRING(name); + long cur = symtable_lookup(st, name); + if (cur < 0) + return 0; + if (cur & (DEF_LOCAL | USE)) { + char buf[256]; + if (cur & DEF_LOCAL) + PyOS_snprintf(buf, sizeof(buf), + NONLOCAL_AFTER_ASSIGN, + c_name); + else + PyOS_snprintf(buf, sizeof(buf), + NONLOCAL_AFTER_USE, + c_name); + if (!symtable_warn(st, buf, s->lineno)) + return 0; + } + if (!symtable_add_def(st, name, DEF_NONLOCAL)) + return 0; + } + break; + } case Expr_kind: VISIT(st, expr, s->v.Expr.value); break; From python-3000-checkins at python.org Tue Feb 27 07:57:36 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 27 Feb 2007 07:57:36 +0100 (CET) Subject: [Python-3000-checkins] r53987 - python/branches/p3yk/Include/longobject.h Message-ID: <20070227065736.1A6AF1E400B@bag.python.org> Author: neal.norwitz Date: Tue Feb 27 07:57:32 2007 New Revision: 53987 Modified: python/branches/p3yk/Include/longobject.h Log: I assume this was supposed to be Py_ssize_t since there are no uses of plain ssize_t. Modified: python/branches/p3yk/Include/longobject.h ============================================================================== --- python/branches/p3yk/Include/longobject.h (original) +++ python/branches/p3yk/Include/longobject.h Tue Feb 27 07:57:32 2007 @@ -21,7 +21,7 @@ PyAPI_FUNC(PyObject *) PyLong_FromSsize_t(Py_ssize_t); PyAPI_FUNC(PyObject *) PyLong_FromDouble(double); PyAPI_FUNC(long) PyLong_AsLong(PyObject *); -PyAPI_FUNC(ssize_t) PyLong_AsSsize_t(PyObject *); +PyAPI_FUNC(Py_ssize_t) PyLong_AsSsize_t(PyObject *); PyAPI_FUNC(size_t) PyLong_AsSize_t(PyObject *); PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLong(PyObject *); PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLongMask(PyObject *); From python-3000-checkins at python.org Tue Feb 27 09:40:55 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 27 Feb 2007 09:40:55 +0100 (CET) Subject: [Python-3000-checkins] r53989 - in python/branches/p3yk: Lib/test/test_bytes.py Objects/bytesobject.c Message-ID: <20070227084055.9FE961E4043@bag.python.org> Author: georg.brandl Date: Tue Feb 27 09:40:54 2007 New Revision: 53989 Modified: python/branches/p3yk/Lib/test/test_bytes.py python/branches/p3yk/Objects/bytesobject.c Log: Implement bytes.fromhex(), with tests. Modified: python/branches/p3yk/Lib/test/test_bytes.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bytes.py (original) +++ python/branches/p3yk/Lib/test/test_bytes.py Tue Feb 27 09:40:54 2007 @@ -396,6 +396,21 @@ seq.append(alloc) #print seq + def test_fromhex(self): + self.assertRaises(TypeError, bytes.fromhex) + self.assertRaises(TypeError, bytes.fromhex, 1) + self.assertEquals(bytes.fromhex(''), bytes()) + b = bytes([0x1a, 0x2b, 0x30]) + self.assertEquals(bytes.fromhex('1a2B30'), b) + self.assertEquals(bytes.fromhex(' 1A 2B 30 '), b) + self.assertEquals(bytes.fromhex(buffer('')), bytes()) + self.assertEquals(bytes.fromhex(buffer('0000')), bytes([0, 0])) + self.assertRaises(ValueError, bytes.fromhex, 'a') + self.assertRaises(ValueError, bytes.fromhex, 'rt') + self.assertRaises(ValueError, bytes.fromhex, '1a b cd') + self.assertRaises(ValueError, bytes.fromhex, '\x00') + self.assertRaises(ValueError, bytes.fromhex, '12 \x00 34') + def test_join(self): self.assertEqual(bytes.join([]), bytes()) self.assertEqual(bytes.join([bytes()]), bytes()) Modified: python/branches/p3yk/Objects/bytesobject.c ============================================================================== --- python/branches/p3yk/Objects/bytesobject.c (original) +++ python/branches/p3yk/Objects/bytesobject.c Tue Feb 27 09:40:54 2007 @@ -970,17 +970,82 @@ return NULL; } +PyDoc_STRVAR(fromhex_doc, +"bytes.fromhex(string) -> bytes\n\ +\n\ +Create a bytes object from a string of hexadecimal numbers.\n\ +Spaces between two numbers are accepted. Example:\n\ +bytes.fromhex('10 2030') -> bytes([0x10, 0x20, 0x30])."); + +static int +hex_digit_to_int(int c) +{ + if (isdigit(c)) + return c - '0'; + else { + if (isupper(c)) + c = tolower(c); + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + } + return -1; +} + +static PyObject * +bytes_fromhex(PyObject *cls, PyObject *args) +{ + PyObject *newbytes; + char *hex, *buf; + Py_ssize_t len, byteslen, i, j; + int top, bot; + + if (!PyArg_ParseTuple(args, "s#:fromhex", &hex, &len)) + return NULL; + + byteslen = len / 2; /* max length if there are no spaces */ + + newbytes = PyBytes_FromStringAndSize(NULL, byteslen); + if (!newbytes) + return NULL; + buf = PyBytes_AS_STRING(newbytes); + + for (i = j = 0; ; i += 2) { + /* skip over spaces in the input */ + while (Py_CHARMASK(hex[i]) == ' ') + i++; + if (i >= len) + break; + top = hex_digit_to_int(Py_CHARMASK(hex[i])); + bot = hex_digit_to_int(Py_CHARMASK(hex[i+1])); + if (top == -1 || bot == -1) { + PyErr_Format(PyExc_ValueError, + "non-hexadecimal number string '%c%c' found in " + "fromhex() arg at position %zd", + hex[i], hex[i+1], i); + goto error; + } + buf[j++] = (top << 4) + bot; + } + if (PyBytes_Resize(newbytes, j) < 0) + goto error; + return newbytes; + + error: + Py_DECREF(newbytes); + return NULL; +} + static PySequenceMethods bytes_as_sequence = { - (lenfunc)bytes_length, /*sq_length*/ - (binaryfunc)bytes_concat, /*sq_concat*/ - (ssizeargfunc)bytes_repeat, /*sq_repeat*/ - (ssizeargfunc)bytes_getitem, /*sq_item*/ - 0, /*sq_slice*/ - (ssizeobjargproc)bytes_setitem, /*sq_ass_item*/ - 0, /* sq_ass_slice */ + (lenfunc)bytes_length, /* sq_length */ + (binaryfunc)bytes_concat, /* sq_concat */ + (ssizeargfunc)bytes_repeat, /* sq_repeat */ + (ssizeargfunc)bytes_getitem, /* sq_item */ + 0, /* sq_slice */ + (ssizeobjargproc)bytes_setitem, /* sq_ass_item */ + 0, /* sq_ass_slice */ (objobjproc)bytes_contains, /* sq_contains */ - (binaryfunc)bytes_iconcat, /* sq_inplace_concat */ - (ssizeargfunc)bytes_irepeat, /* sq_inplace_repeat */ + (binaryfunc)bytes_iconcat, /* sq_inplace_concat */ + (ssizeargfunc)bytes_irepeat, /* sq_inplace_repeat */ }; static PyMappingMethods bytes_as_mapping = { @@ -1002,6 +1067,7 @@ bytes_methods[] = { {"decode", (PyCFunction)bytes_decode, METH_VARARGS, decode_doc}, {"__alloc__", (PyCFunction)bytes_alloc, METH_NOARGS, alloc_doc}, + {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, fromhex_doc}, {"join", (PyCFunction)bytes_join, METH_O|METH_CLASS, join_doc}, {NULL} }; @@ -1032,7 +1098,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 */ From python-3000-checkins at python.org Tue Feb 27 09:49:19 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 27 Feb 2007 09:49:19 +0100 (CET) Subject: [Python-3000-checkins] r53990 - python/branches/p3yk/Objects/bytesobject.c Message-ID: <20070227084919.030991E4007@bag.python.org> Author: georg.brandl Date: Tue Feb 27 09:49:18 2007 New Revision: 53990 Modified: python/branches/p3yk/Objects/bytesobject.c Log: Remove a few stray tabs from bytesobject.c. Modified: python/branches/p3yk/Objects/bytesobject.c ============================================================================== --- python/branches/p3yk/Objects/bytesobject.c (original) +++ python/branches/p3yk/Objects/bytesobject.c Tue Feb 27 09:49:18 2007 @@ -926,38 +926,38 @@ seq = PySequence_Fast(it, "can only join an iterable"); if (seq == NULL) - return NULL; + return NULL; n = PySequence_Fast_GET_SIZE(seq); items = PySequence_Fast_ITEMS(seq); /* Compute the total size, and check that they are all bytes */ for (i = 0; i < n; i++) { - PyObject *obj = items[i]; - if (!PyBytes_Check(obj)) { - PyErr_Format(PyExc_TypeError, - "can only join an iterable of bytes " - "(item %ld has type '%.100s')", + PyObject *obj = items[i]; + if (!PyBytes_Check(obj)) { + PyErr_Format(PyExc_TypeError, + "can only join an iterable of bytes " + "(item %ld has type '%.100s')", /* XXX %ld isn't right on Win64 */ - (long)i, obj->ob_type->tp_name); - goto error; - } - totalsize += PyBytes_GET_SIZE(obj); - if (totalsize < 0) { - PyErr_NoMemory(); - goto error; - } + (long)i, obj->ob_type->tp_name); + goto error; + } + totalsize += PyBytes_GET_SIZE(obj); + if (totalsize < 0) { + PyErr_NoMemory(); + goto error; + } } /* Allocate the result, and copy the bytes */ result = PyBytes_FromStringAndSize(NULL, totalsize); if (result == NULL) - goto error; + goto error; dest = PyBytes_AS_STRING(result); for (i = 0; i < n; i++) { - PyObject *obj = items[i]; - Py_ssize_t size = PyBytes_GET_SIZE(obj); - memcpy(dest, PyBytes_AS_STRING(obj), size); - dest += size; + PyObject *obj = items[i]; + Py_ssize_t size = PyBytes_GET_SIZE(obj); + memcpy(dest, PyBytes_AS_STRING(obj), size); + dest += size; } /* Done */ @@ -980,15 +980,15 @@ static int hex_digit_to_int(int c) { - if (isdigit(c)) - return c - '0'; - else { - if (isupper(c)) - c = tolower(c); - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - } - return -1; + if (isdigit(c)) + return c - '0'; + else { + if (isupper(c)) + c = tolower(c); + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + } + return -1; } static PyObject * @@ -1092,14 +1092,14 @@ 0, /* tp_as_number */ &bytes_as_sequence, /* tp_as_sequence */ &bytes_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ + 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)bytes_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &bytes_as_buffer, /* tp_as_buffer */ + /* bytes is 'final' or 'sealed' */ Py_TPFLAGS_DEFAULT, /* tp_flags */ - /* bytes is 'final' or 'sealed' */ bytes_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ From python-3000-checkins at python.org Tue Feb 27 16:45:14 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 27 Feb 2007 16:45:14 +0100 (CET) Subject: [Python-3000-checkins] r53991 - python/branches/p3yk/Lib/io.py Message-ID: <20070227154514.7A26F1E4002@bag.python.org> Author: guido.van.rossum Date: Tue Feb 27 16:45:13 2007 New Revision: 53991 Modified: python/branches/p3yk/Lib/io.py Log: Added some comments and docstrings. More is needed. Modified: python/branches/p3yk/Lib/io.py ============================================================================== --- python/branches/p3yk/Lib/io.py (original) +++ python/branches/p3yk/Lib/io.py Tue Feb 27 16:45:13 2007 @@ -3,6 +3,9 @@ """New I/O library. +This is an early prototype; eventually some of this will be +reimplemented in C and the rest may be turned into a package. + See PEP XXX; for now: http://docs.google.com/Doc?id=dfksfvqd_1cn5g5m """ @@ -13,7 +16,34 @@ import os def open(filename, mode="r", buffering=None, *, encoding=None): - """Replacement for the built-in open function, with encoding parameter.""" + """Replacement for the built-in open function. + + Args: + filename: string giving the name of the file to be opened + mode: optional mode string; see below + buffering: optional int >= 0 giving the buffer size; values + can be: 0 = unbuffered, 1 = line buffered, + larger = fully buffered + encoding: optional string giving the text encoding (*must* be given + as a keyword argument) + + Mode strings characters: + 'r': open for reading (default) + 'w': open for writing, truncating the file first + 'a': open for writing, appending to the end if the file exists + 'b': binary mode + 't': text mode (default) + '+': open a disk file for updating (implies reading and writing) + + Constraints: + - encoding must not be given when a binary mode is given + - buffering must not be zero when a text mode is given + + Returns: + Depending on the mode and buffering arguments, either a raw + binary stream, a buffered binary stream, or a buffered text + stream, open for reading and/or writing. + """ assert isinstance(filename, str) assert isinstance(mode, str) assert buffering is None or isinstance(buffering, int) @@ -22,11 +52,11 @@ if modes - set("arwb+t") or len(mode) > len(modes): raise ValueError("invalid mode: %r" % mode) reading = "r" in modes - writing = "w" in modes or "a" in modes - binary = "b" in modes + writing = "w" in modes appending = "a" in modes updating = "+" in modes - text = "t" in modes or not binary + text = "t" in modes + binary = "b" in modes if text and binary: raise ValueError("can't have text and binary mode at once") if reading + writing + appending > 1: @@ -42,6 +72,12 @@ (updating and "+" or "")) if buffering is None: buffering = 8*1024 # International standard buffer size + # Should default to line buffering if os.isatty(raw.fileno()) + try: + bs = os.fstat(raw.fileno()).st_blksize + except (os.error, AttributeError): + if bs > 1: + buffering = bs if buffering < 0: raise ValueError("invalid buffering size") if buffering == 0: @@ -50,21 +86,33 @@ raise ValueError("can't have unbuffered text I/O") if updating: buffer = BufferedRandom(raw, buffering) - elif writing: + elif writing or appending: buffer = BufferedWriter(raw, buffering) else: assert reading buffer = BufferedReader(raw, buffering) if binary: return buffer - assert text - textio = TextIOWrapper(buffer) # Universal newlines default to on + # XXX What about newline conventions? + textio = TextIOWrapper(buffer, encoding) return textio class RawIOBase: - """Base class for raw binary I/O.""" + """Base class for raw binary I/O. + + This class provides dummy implementations for all methods that + derived classes can override selectively; the default + implementations represent a file that cannot be read, written or + seeked. + + The read() method is implemented by calling readinto(); derived + classes that want to support readon only need to implement + readinto() as a primitive operation. + """ + + # XXX Add individual method docstrings def read(self, n): b = bytes(n.__index__()) @@ -112,6 +160,8 @@ """Raw I/O implementation for OS files.""" + # XXX More docs + def __init__(self, filename, mode): self._seekable = None self._mode = mode @@ -166,14 +216,6 @@ self._seekable = True return self._seekable - # XXX(nnorwitz): is there any reason to redefine __enter__ & __exit__? - # Both already have the same impl in the base class. - def __enter__(self): - return self - - def __exit__(self, *args): - self.close() - def fileno(self): return self._fd @@ -182,6 +224,8 @@ """Raw I/O implementation for stream sockets.""" + # XXX More docs + def __init__(self, sock, mode): assert mode in ("r", "w", "rw") self._sock = sock @@ -212,6 +256,8 @@ """Raw I/O implementation for bytes, like StringIO.""" + # XXX More docs + def __init__(self, inital_bytes=None): self._buffer = b"" self._pos = 0 From python-3000-checkins at python.org Tue Feb 27 16:53:32 2007 From: python-3000-checkins at python.org (jeremy.hylton) Date: Tue, 27 Feb 2007 16:53:32 +0100 (CET) Subject: [Python-3000-checkins] r53992 - python/branches/p3yk/Misc/NEWS Message-ID: <20070227155332.2DC2B1E4002@bag.python.org> Author: jeremy.hylton Date: Tue Feb 27 16:53:28 2007 New Revision: 53992 Modified: python/branches/p3yk/Misc/NEWS Log: Add news about nonlocal statement Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Tue Feb 27 16:53:28 2007 @@ -62,6 +62,21 @@ - Added function annotations per PEP 3107. +- Added nonlocal declaration from PEP 3104 + + >>> def f(x): + ... def inc(): + ... nonlocal x + ... x += 1 + ... return x + ... return inc + ... + >>> inc = f(0) + >>> inc() + 1 + >>> inc() + 2 + - Moved intern() to sys.intern(). - exec is now a function. From python-3000-checkins at python.org Tue Feb 27 18:19:33 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 27 Feb 2007 18:19:33 +0100 (CET) Subject: [Python-3000-checkins] r53995 - in python/branches/p3yk/Lib: io.py test/test_io.py Message-ID: <20070227171933.E48D31E4002@bag.python.org> Author: guido.van.rossum Date: Tue Feb 27 18:19:33 2007 New Revision: 53995 Modified: python/branches/p3yk/Lib/io.py python/branches/p3yk/Lib/test/test_io.py Log: Mike Verdone's checkpoint, cleaned up. Also implemented Neal's suggestion (add fileno() to SocketIO) and some unrelated changes, e.g. remove Google copyright and make BytesIO a subclass of BufferedIOBase. Modified: python/branches/p3yk/Lib/io.py ============================================================================== --- python/branches/p3yk/Lib/io.py (original) +++ python/branches/p3yk/Lib/io.py Tue Feb 27 18:19:33 2007 @@ -1,6 +1,3 @@ -# Copyright 2006 Google, Inc. All Rights Reserved. -# Licensed to PSF under a Contributor Agreement. - """New I/O library. This is an early prototype; eventually some of this will be @@ -9,12 +6,17 @@ See PEP XXX; for now: http://docs.google.com/Doc?id=dfksfvqd_1cn5g5m """ -__author__ = "Guido van Rossum " +__author__ = ("Guido van Rossum , " + "Mike Verdone ") -__all__ = ["open", "RawIOBase", "FileIO", "SocketIO", "BytesIO"] +__all__ = ["open", "RawIOBase", "FileIO", "SocketIO", "BytesIO", + "BufferedReader", "BufferedWriter", "BufferedRWPair", "EOF"] import os +DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes +EOF = b"" + def open(filename, mode="r", buffering=None, *, encoding=None): """Replacement for the built-in open function. @@ -71,8 +73,8 @@ (appending and "a" or "") + (updating and "+" or "")) if buffering is None: - buffering = 8*1024 # International standard buffer size - # Should default to line buffering if os.isatty(raw.fileno()) + buffering = DEFAULT_BUFFER_SIZE + # XXX Should default to line buffering if os.isatty(raw.fileno()) try: bs = os.fstat(raw.fileno()).st_blksize except (os.error, AttributeError): @@ -219,7 +221,7 @@ def fileno(self): return self._fd - + class SocketIO(RawIOBase): """Raw I/O implementation for stream sockets.""" @@ -249,12 +251,18 @@ def writable(self): return "w" in self._mode - # XXX(nnorwitz)??? def fileno(self): return self._sock.fileno() + def fileno(self): + return self._sock.fileno() + + +class BufferedIOBase(RawIOBase): + """XXX Docstring.""" -class BytesIO(RawIOBase): - """Raw I/O implementation for bytes, like StringIO.""" +class BytesIO(BufferedIOBase): + + """Buffered I/O implementation using a bytes buffer, like StringIO.""" # XXX More docs @@ -267,7 +275,9 @@ def getvalue(self): return self._buffer - def read(self, n): + def read(self, n=None): + if n is None: + n = len(self._buffer) assert n >= 0 newpos = min(len(self._buffer), self._pos + n) b = self._buffer[self._pos : newpos] @@ -312,3 +322,113 @@ def seekable(self): return True + + +class BufferedReader(BufferedIOBase): + + """Buffered reader. + + Buffer for a readable sequential RawIO object. Does not allow + random access (seek, tell). + """ + + def __init__(self, raw): + """ + Create a new buffered reader using the given readable raw IO object. + """ + assert raw.readable() + self.raw = raw + self._read_buf = b'' + if hasattr(raw, 'fileno'): + self.fileno = raw.fileno + + def read(self, n=None): + """ + Read n bytes. Returns exactly n bytes of data unless the underlying + raw IO stream reaches EOF of if the call would block in non-blocking + mode. If n is None, read until EOF or until read() would block. + """ + nodata_val = EOF + while (len(self._read_buf) < n) if (n is not None) else True: + current = self.raw.read(n) + if current in (EOF, None): + nodata_val = current + break + self._read_buf += current # XXX using += is bad + read = self._read_buf[:n] + if (not self._read_buf): + return nodata_val + self._read_buf = self._read_buf[n if n else 0:] + return read + + def write(self, b): + raise IOError(".write() unsupported") + + def readable(self): + return True + + def flush(self): + # Flush is a no-op + pass + + +class BufferedWriter(BufferedIOBase): + + """Buffered writer. + + XXX More docs. + """ + + def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): + assert raw.writeable() + self.raw = raw + self.buffer_size = buffer_size + self._write_buf_stack = [] + self._write_buf_size = 0 + if hasattr(raw, 'fileno'): + self.fileno = raw.fileno + + def read(self, n=None): + raise IOError(".read() not supported") + + def write(self, b): + assert issubclass(type(b), bytes) + self._write_buf_stack.append(b) + self._write_buf_size += len(b) + if (self._write_buf_size > self.buffer_size): + self.flush() + + def writeable(self): + return True + + def flush(self): + buf = b''.join(self._write_buf_stack) + while len(buf): + buf = buf[self.raw.write(buf):] + self._write_buf_stack = [] + self._write_buf_size = 0 + + # XXX support flushing buffer on close, del + + +class BufferedRWPair(BufferedReader, BufferedWriter): + + """Buffered Read/Write Pair. + + A buffered reader object and buffered writer object put together to + form a sequential IO object that can read and write. + """ + + def __init__(self, bufferedReader, bufferedWriter): + assert bufferedReader.readable() + assert bufferedWriter.writeable() + self.bufferedReader = bufferedReader + self.bufferedWriter = bufferedWriter + self.read = bufferedReader.read + self.write = bufferedWriter.write + self.flush = bufferedWriter.flush + self.readable = bufferedReader.readable + self.writeable = bufferedWriter.writeable + + def seekable(self): + return False Modified: python/branches/p3yk/Lib/test/test_io.py ============================================================================== --- python/branches/p3yk/Lib/test/test_io.py (original) +++ python/branches/p3yk/Lib/test/test_io.py Tue Feb 27 18:19:33 2007 @@ -1,8 +1,43 @@ +"""Unit tests for io.py.""" + import unittest from test import test_support import io + +class MockReadIO(io.RawIOBase): + def __init__(self, readStack): + self._readStack = list(readStack) + + def read(self, n=None): + try: + return self._readStack.pop(0) + except: + return io.EOF + + def fileno(self): + return 42 + + def readable(self): + return True + + +class MockWriteIO(io.RawIOBase): + def __init__(self): + self._writeStack = [] + + def write(self, b): + self._writeStack.append(b) + return len(b) + + def writeable(self): + return True + + def fileno(self): + return 42 + + class IOTest(unittest.TestCase): def write_ops(self, f): @@ -55,8 +90,117 @@ f = io.BytesIO(data) self.read_ops(f) + +class BytesIOTest(unittest.TestCase): + + def testInit(self): + buf = b"1234567890" + bytesIo = io.BytesIO(buf) + + def testRead(self): + buf = b"1234567890" + bytesIo = io.BytesIO(buf) + + self.assertEquals(buf[:1], bytesIo.read(1)) + self.assertEquals(buf[1:5], bytesIo.read(4)) + self.assertEquals(buf[5:], bytesIo.read(900)) + self.assertEquals(io.EOF, bytesIo.read()) + + def testReadNoArgs(self): + buf = b"1234567890" + bytesIo = io.BytesIO(buf) + + self.assertEquals(buf, bytesIo.read()) + self.assertEquals(io.EOF, bytesIo.read()) + + def testSeek(self): + buf = b"1234567890" + bytesIo = io.BytesIO(buf) + + bytesIo.read(5) + bytesIo.seek(0) + self.assertEquals(buf, bytesIo.read()) + + bytesIo.seek(3) + self.assertEquals(buf[3:], bytesIo.read()) + + def testTell(self): + buf = b"1234567890" + bytesIo = io.BytesIO(buf) + + self.assertEquals(0, bytesIo.tell()) + bytesIo.seek(5) + self.assertEquals(5, bytesIo.tell()) + bytesIo.seek(10000) + self.assertEquals(10000, bytesIo.tell()) + + +class BufferedReaderTest(unittest.TestCase): + + def testRead(self): + rawIo = MockReadIO((b"abc", b"d", b"efg")) + bufIo = io.BufferedReader(rawIo) + + self.assertEquals(b"abcdef", bufIo.read(6)) + + def testReadToEof(self): + rawIo = MockReadIO((b"abc", b"d", b"efg")) + bufIo = io.BufferedReader(rawIo) + + self.assertEquals(b"abcdefg", bufIo.read(9000)) + + def testReadNoArgs(self): + rawIo = MockReadIO((b"abc", b"d", b"efg")) + bufIo = io.BufferedReader(rawIo) + + self.assertEquals(b"abcdefg", bufIo.read()) + + def testFileno(self): + rawIo = MockReadIO((b"abc", b"d", b"efg")) + bufIo = io.BufferedReader(rawIo) + + self.assertEquals(42, bufIo.fileno()) + + def testFilenoNoFileno(self): + # TODO will we always have fileno() function? If so, kill + # this test. Else, write it. + pass + + +class BufferedWriterTest(unittest.TestCase): + + def testWrite(self): + # Write to the buffered IO but don't overflow the buffer. + writer = MockWriteIO() + bufIo = io.BufferedWriter(writer, 8) + + bufIo.write(b"abc") + + self.assertFalse(writer._writeStack) + + def testWriteOverflow(self): + writer = MockWriteIO() + bufIo = io.BufferedWriter(writer, 8) + + bufIo.write(b"abc") + bufIo.write(b"defghijkl") + + self.assertEquals(b"abcdefghijkl", writer._writeStack[0]) + + def testFlush(self): + writer = MockWriteIO() + bufIo = io.BufferedWriter(writer, 8) + + bufIo.write(b"abc") + bufIo.flush() + + self.assertEquals(b"abc", writer._writeStack[0]) + +# TODO. Tests for open() + def test_main(): - test_support.run_unittest(IOTest) + test_support.run_unittest(IOTest, BytesIOTest, BufferedReaderTest, + BufferedWriterTest) if __name__ == "__main__": test_main() From python-3000-checkins at python.org Tue Feb 27 19:58:57 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 27 Feb 2007 19:58:57 +0100 (CET) Subject: [Python-3000-checkins] r53999 - python/branches/p3yk/Lib/test/test_structmembers.py Message-ID: <20070227185857.5CA921E4017@bag.python.org> Author: neal.norwitz Date: Tue Feb 27 19:58:52 2007 New Revision: 53999 Modified: python/branches/p3yk/Lib/test/test_structmembers.py Log: Fix breakage from removing exceptions module Modified: python/branches/p3yk/Lib/test/test_structmembers.py ============================================================================== --- python/branches/p3yk/Lib/test/test_structmembers.py (original) +++ python/branches/p3yk/Lib/test/test_structmembers.py Tue Feb 27 19:58:52 2007 @@ -4,7 +4,7 @@ INT_MAX, INT_MIN, UINT_MAX, \ LONG_MAX, LONG_MIN, ULONG_MAX -import warnings, exceptions, unittest, test.test_warnings +import warnings, unittest, test.test_warnings from test import test_support ts=test_structmembersType(1,2,3,4,5,6,7,8,9.99999,10.1010101010) @@ -42,7 +42,7 @@ class TestWarnings(test.test_warnings.TestModule): def has_warned(self): self.assertEqual(test.test_warnings.msg.category, - exceptions.RuntimeWarning.__name__) + RuntimeWarning.__name__) def test_byte_max(self): ts.T_BYTE=CHAR_MAX+1 From python-3000-checkins at python.org Tue Feb 27 20:02:21 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 27 Feb 2007 20:02:21 +0100 (CET) Subject: [Python-3000-checkins] r54000 - in python/branches/p3yk: Include/pythonrun.h Lib/test/test_bytes.py Objects/bytesobject.c Python/pythonrun.c Message-ID: <20070227190221.5845C1E4011@bag.python.org> Author: neal.norwitz Date: Tue Feb 27 20:02:19 2007 New Revision: 54000 Modified: python/branches/p3yk/Include/pythonrun.h python/branches/p3yk/Lib/test/test_bytes.py python/branches/p3yk/Objects/bytesobject.c python/branches/p3yk/Python/pythonrun.c Log: SF patch #1669633, add methods for bytes from Pete Shinners. Modified: python/branches/p3yk/Include/pythonrun.h ============================================================================== --- python/branches/p3yk/Include/pythonrun.h (original) +++ python/branches/p3yk/Include/pythonrun.h Tue Feb 27 20:02:19 2007 @@ -122,6 +122,7 @@ PyAPI_FUNC(int) _PyFrame_Init(void); PyAPI_FUNC(int) _PyInt_Init(void); PyAPI_FUNC(void) _PyFloat_Init(void); +PyAPI_FUNC(int) PyBytes_Init(void); /* Various internal finalizers */ PyAPI_FUNC(void) _PyExc_Fini(void); @@ -133,6 +134,7 @@ PyAPI_FUNC(void) PyList_Fini(void); PyAPI_FUNC(void) PySet_Fini(void); PyAPI_FUNC(void) PyString_Fini(void); +PyAPI_FUNC(void) PyBytes_Fini(void); PyAPI_FUNC(void) PyInt_Fini(void); PyAPI_FUNC(void) PyFloat_Fini(void); PyAPI_FUNC(void) PyOS_FiniInterrupts(void); Modified: python/branches/p3yk/Lib/test/test_bytes.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bytes.py (original) +++ python/branches/p3yk/Lib/test/test_bytes.py Tue Feb 27 20:02:19 2007 @@ -145,6 +145,17 @@ input.reverse() self.assertEqual(output, input) + def test_reverse(self): + b = b'hello' + self.assertEqual(b.reverse(), None) + self.assertEqual(b, b'olleh') + b = b'hello1' # test even number of items + b.reverse() + self.assertEqual(b, b'1olleh') + b = bytes() + b.reverse() + self.assertFalse(b) + def test_getslice(self): def by(s): return bytes(map(ord, s)) @@ -434,36 +445,171 @@ self.assertRaises(SyntaxError, eval, 'b"%s"' % chr(c)) + def test_extend(self): + orig = b'hello' + a = bytes(orig) + a.extend(a) + self.assertEqual(a, orig + orig) + self.assertEqual(a[5:], orig) + + def test_remove(self): + b = b'hello' + b.remove(ord('l')) + self.assertEqual(b, b'helo') + b.remove(ord('l')) + self.assertEqual(b, b'heo') + self.assertRaises(ValueError, lambda: b.remove(ord('l'))) + self.assertRaises(ValueError, lambda: b.remove(400)) + self.assertRaises(ValueError, lambda: b.remove('e')) + # remove first and last + b.remove(ord('o')) + b.remove(ord('h')) + self.assertEqual(b, b'e') + + def test_pop(self): + b = b'world' + self.assertEqual(b.pop(), ord('d')) + self.assertEqual(b.pop(0), ord('w')) + self.assertEqual(b.pop(-2), ord('r')) + self.assertRaises(IndexError, lambda: b.pop(10)) + self.assertRaises(OverflowError, lambda: bytes().pop()) + + def test_nosort(self): + self.assertRaises(AttributeError, lambda: bytes().sort()) + + def test_index(self): + b = b'parrot' + self.assertEqual(b.index('p'), 0) + self.assertEqual(b.index('rr'), 2) + self.assertEqual(b.index('t'), 5) + self.assertRaises(ValueError, lambda: b.index('w')) + + def test_count(self): + b = b'mississippi' + self.assertEqual(b.count('i'), 4) + self.assertEqual(b.count('ss'), 2) + self.assertEqual(b.count('w'), 0) + + def test_append(self): + b = b'hell' + b.append(ord('o')) + self.assertEqual(b, b'hello') + self.assertEqual(b.append(100), None) + b = bytes() + b.append(ord('A')) + self.assertEqual(len(b), 1) + + def test_insert(self): + b = b'msssspp' + b.insert(1, ord('i')) + b.insert(4, ord('i')) + b.insert(-2, ord('i')) + b.insert(1000, ord('i')) + self.assertEqual(b, b'mississippi') + + def test_startswith(self): + b = b'hello' + self.assertFalse(bytes().startswith("anything")) + self.assertTrue(b.startswith("hello")) + self.assertTrue(b.startswith("hel")) + self.assertTrue(b.startswith("h")) + self.assertFalse(b.startswith("hellow")) + self.assertFalse(b.startswith("ha")) + + def test_endswith(self): + b = b'hello' + self.assertFalse(bytes().endswith("anything")) + self.assertTrue(b.endswith("hello")) + self.assertTrue(b.endswith("llo")) + self.assertTrue(b.endswith("o")) + self.assertFalse(b.endswith("whello")) + self.assertFalse(b.endswith("no")) + + def test_find(self): + b = b'mississippi' + self.assertEqual(b.find('ss'), 2) + self.assertEqual(b.find('ss', 3), 5) + self.assertEqual(b.find('ss', 1, 7), 2) + self.assertEqual(b.find('ss', 1, 3), -1) + self.assertEqual(b.find('w'), -1) + self.assertEqual(b.find('mississippian'), -1) + + def test_rfind(self): + b = b'mississippi' + self.assertEqual(b.rfind('ss'), 5) + self.assertEqual(b.rfind('ss', 3), 5) + self.assertEqual(b.rfind('ss', 0, 6), 2) + self.assertEqual(b.rfind('w'), -1) + self.assertEqual(b.rfind('mississippian'), -1) + + def test_index(self): + b = b'world' + self.assertEqual(b.index('w'), 0) + self.assertEqual(b.index('orl'), 1) + self.assertRaises(ValueError, lambda: b.index('worm')) + self.assertRaises(ValueError, lambda: b.index('ldo')) + + def test_rindex(self): + # XXX could be more rigorous + b = b'world' + self.assertEqual(b.rindex('w'), 0) + self.assertEqual(b.rindex('orl'), 1) + self.assertRaises(ValueError, lambda: b.rindex('worm')) + self.assertRaises(ValueError, lambda: b.rindex('ldo')) + + def test_replace(self): + b = b'mississippi' + self.assertEqual(b.replace('i', 'a'), b'massassappa') + self.assertEqual(b.replace('ss', 'x'), b'mixixippi') + + def test_translate(self): + b = b'hello' + rosetta = bytes(range(0, 256)) + rosetta[ord('o')] = ord('e') + c = b.translate(rosetta, b'l') + self.assertEqual(b, b'hello') + self.assertEqual(c, b'hee') + + def test_split(self): + b = b'mississippi' + self.assertEqual(b.split('i'), [b'm', b'ss', b'ss', b'pp', b'']) + self.assertEqual(b.split('ss'), [b'mi', b'i', b'ippi']) + self.assertEqual(b.split('w'), [b]) + # require an arg (no magic whitespace split) + self.assertRaises(TypeError, lambda: b.split()) + + def test_rsplit(self): + b = b'mississippi' + self.assertEqual(b.rsplit('i'), [b'm', b'ss', b'ss', b'pp', b'']) + self.assertEqual(b.rsplit('ss'), [b'mi', b'i', b'ippi']) + self.assertEqual(b.rsplit('w'), [b]) + # require an arg (no magic whitespace split) + self.assertRaises(TypeError, lambda: b.rsplit()) + + def test_partition(self): + b = b'mississippi' + self.assertEqual(b.partition(b'ss'), (b'mi', b'ss', b'issippi')) + self.assertEqual(b.rpartition(b'w'), (b'', b'', b'mississippi')) + + def test_rpartition(self): + b = b'mississippi' + self.assertEqual(b.rpartition(b'ss'), (b'missi', b'ss', b'ippi')) + self.assertEqual(b.rpartition(b'i'), (b'mississipp', b'i', b'')) + # Optimizations: # __iter__? (optimization) # __reversed__? (optimization) - # XXX Some list methods? - # extended slicing - # extended slice assignment - # extend (same as b[len(b):] = src) - # reverse (in-place) - # remove - # pop - # NOT sort! - # With int arg: - # index - # count - # append - # insert - # XXX Some string methods? (Those that don't use character properties) - # startswith - # endswidth - # find, rfind - # index, rindex (bytes arg) + # lstrip, rstrip, strip?? (currently un-pepped) # join - # replace - # translate - # split, rsplit - # lstrip, rstrip, strip?? # XXX pickle and marshal support? + + # There are tests in string_tests.py that are more + # comprehensive for things like split, partition, etc. + # Unfortunately they are all bundled with tests that + # are not appropriate for bytes def test_main(): Modified: python/branches/p3yk/Objects/bytesobject.c ============================================================================== --- python/branches/p3yk/Objects/bytesobject.c (original) +++ python/branches/p3yk/Objects/bytesobject.c Tue Feb 27 20:02:19 2007 @@ -6,6 +6,45 @@ #include "Python.h" #include "structmember.h" +/* The nullbytes are used by the stringlib during partition. + * If partition is removed from bytes, nullbytes and its helper + * Init/Fini should also be removed. + */ +static PyBytesObject *nullbytes = NULL; + +void +PyBytes_Fini(void) +{ + Py_CLEAR(nullbytes); +} + +int +PyBytes_Init(void) +{ + nullbytes = PyObject_New(PyBytesObject, &PyBytes_Type); + if (nullbytes == NULL) + return 0; + nullbytes->ob_bytes = NULL; + nullbytes->ob_size = nullbytes->ob_alloc = 0; + return 1; +} + +/* end nullbytes support */ + +static int _getbytevalue(PyObject* arg, int *value) +{ + PyObject *intarg = PyNumber_Int(arg); + if (! intarg) + return 0; + *value = PyInt_AsLong(intarg); + Py_DECREF(intarg); + if (*value < 0 || *value >= 256) { + PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); + return 0; + } + return 1; +} + /* Direct API functions */ PyObject * @@ -858,7 +897,7 @@ { if (index != 0) { PyErr_SetString(PyExc_SystemError, - "accessing non-existent string segment"); + "accessing non-existent bytes segment"); return -1; } *ptr = (void *)self->ob_bytes; @@ -873,6 +912,1502 @@ return 1; } + + +/* -------------------------------------------------------------------- */ +/* Methods */ + +#define STRINGLIB_CHAR char +#define STRINGLIB_CMP memcmp +#define STRINGLIB_LEN PyBytes_GET_SIZE +#define STRINGLIB_NEW PyBytes_FromStringAndSize +#define STRINGLIB_EMPTY nullbytes + +#include "stringlib/fastsearch.h" +#include "stringlib/count.h" +#include "stringlib/find.h" +#include "stringlib/partition.h" + + +/* The following Py_LOCAL_INLINE and Py_LOCAL functions +were copied from the old char* style string object. */ + +Py_LOCAL_INLINE(void) +_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len) +{ + if (*end > len) + *end = len; + else if (*end < 0) + *end += len; + if (*end < 0) + *end = 0; + if (*start < 0) + *start += len; + if (*start < 0) + *start = 0; +} + + +Py_LOCAL_INLINE(Py_ssize_t) +bytes_find_internal(PyBytesObject *self, PyObject *args, int dir) +{ + PyObject *subobj; + const char *sub; + Py_ssize_t sub_len; + Py_ssize_t start=0, end=PY_SSIZE_T_MAX; + + if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", &subobj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return -2; + if (PyBytes_Check(subobj)) { + sub = PyBytes_AS_STRING(subobj); + sub_len = PyBytes_GET_SIZE(subobj); + } + else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len)) + /* XXX - the "expected a character buffer object" is pretty + confusing for a non-expert. remap to something else ? */ + return -2; + + if (dir > 0) + return stringlib_find_slice( + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sub, sub_len, start, end); + else + return stringlib_rfind_slice( + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sub, sub_len, start, end); +} + + +PyDoc_STRVAR(find__doc__, +"B.find(sub [,start [,end]]) -> int\n\ +\n\ +Return the lowest index in B where subsection sub is found,\n\ +such that sub is contained within s[start,end]. Optional\n\ +arguments start and end are interpreted as in slice notation.\n\ +\n\ +Return -1 on failure."); + +static PyObject * +bytes_find(PyBytesObject *self, PyObject *args) +{ + Py_ssize_t result = bytes_find_internal(self, args, +1); + if (result == -2) + return NULL; + return PyInt_FromSsize_t(result); +} + +PyDoc_STRVAR(count__doc__, +"B.count(sub[, start[, end]]) -> int\n\ +\n\ +Return the number of non-overlapping occurrences of subsection sub in\n\ +bytes B[start:end]. Optional arguments start and end are interpreted\n\ +as in slice notation."); + +static PyObject * +bytes_count(PyBytesObject *self, PyObject *args) +{ + PyObject *sub_obj; + const char *str = PyBytes_AS_STRING(self), *sub; + Py_ssize_t sub_len; + Py_ssize_t start = 0, end = PY_SSIZE_T_MAX; + + if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + + if (PyBytes_Check(sub_obj)) { + sub = PyBytes_AS_STRING(sub_obj); + sub_len = PyBytes_GET_SIZE(sub_obj); + } + else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len)) + return NULL; + + _adjust_indices(&start, &end, PyString_GET_SIZE(self)); + + return PyInt_FromSsize_t( + stringlib_count(str + start, end - start, sub, sub_len) + ); +} + + +PyDoc_STRVAR(index__doc__, +"B.index(sub [,start [,end]]) -> int\n\ +\n\ +Like B.find() but raise ValueError when the subsection is not found."); + +static PyObject * +bytes_index(PyBytesObject *self, PyObject *args) +{ + Py_ssize_t result = bytes_find_internal(self, args, +1); + if (result == -2) + return NULL; + if (result == -1) { + PyErr_SetString(PyExc_ValueError, + "subsection not found"); + return NULL; + } + return PyInt_FromSsize_t(result); +} + + +PyDoc_STRVAR(rfind__doc__, +"B.rfind(sub [,start [,end]]) -> int\n\ +\n\ +Return the highest index in B where subsection sub is found,\n\ +such that sub is contained within s[start,end]. Optional\n\ +arguments start and end are interpreted as in slice notation.\n\ +\n\ +Return -1 on failure."); + +static PyObject * +bytes_rfind(PyBytesObject *self, PyObject *args) +{ + Py_ssize_t result = bytes_find_internal(self, args, -1); + if (result == -2) + return NULL; + return PyInt_FromSsize_t(result); +} + + +PyDoc_STRVAR(rindex__doc__, +"B.rindex(sub [,start [,end]]) -> int\n\ +\n\ +Like B.rfind() but raise ValueError when the subsection is not found."); + +static PyObject * +bytes_rindex(PyBytesObject *self, PyObject *args) +{ + Py_ssize_t result = bytes_find_internal(self, args, -1); + if (result == -2) + return NULL; + if (result == -1) { + PyErr_SetString(PyExc_ValueError, + "subsection not found"); + return NULL; + } + return PyInt_FromSsize_t(result); +} + + +/* Matches the end (direction >= 0) or start (direction < 0) of self + * against substr, using the start and end arguments. Returns + * -1 on error, 0 if not found and 1 if found. + */ +Py_LOCAL(int) +_bytes_tailmatch(PyBytesObject *self, PyObject *substr, Py_ssize_t start, + Py_ssize_t end, int direction) +{ + Py_ssize_t len = PyBytes_GET_SIZE(self); + Py_ssize_t slen; + const char* sub; + const char* str; + + if (PyBytes_Check(substr)) { + sub = PyBytes_AS_STRING(substr); + slen = PyBytes_GET_SIZE(substr); + } + else if (PyObject_AsCharBuffer(substr, &sub, &slen)) + return -1; + str = PyBytes_AS_STRING(self); + + _adjust_indices(&start, &end, len); + + if (direction < 0) { + /* startswith */ + if (start+slen > len) + return 0; + } else { + /* endswith */ + if (end-start < slen || start > len) + return 0; + + if (end-slen > start) + start = end - slen; + } + if (end-start >= slen) + return ! memcmp(str+start, sub, slen); + return 0; +} + + +PyDoc_STRVAR(startswith__doc__, +"B.startswith(prefix[, start[, end]]) -> bool\n\ +\n\ +Return True if B starts with the specified prefix, False otherwise.\n\ +With optional start, test B beginning at that position.\n\ +With optional end, stop comparing B at that position.\n\ +prefix can also be a tuple of strings to try."); + +static PyObject * +bytes_startswith(PyBytesObject *self, PyObject *args) +{ + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; + PyObject *subobj; + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + result = _bytes_tailmatch(self, + PyTuple_GET_ITEM(subobj, i), + start, end, -1); + if (result == -1) + return NULL; + else if (result) { + Py_RETURN_TRUE; + } + } + Py_RETURN_FALSE; + } + result = _bytes_tailmatch(self, subobj, start, end, -1); + if (result == -1) + return NULL; + else + return PyBool_FromLong(result); +} + +PyDoc_STRVAR(endswith__doc__, +"B.endswith(suffix[, start[, end]]) -> bool\n\ +\n\ +Return True if B ends with the specified suffix, False otherwise.\n\ +With optional start, test B beginning at that position.\n\ +With optional end, stop comparing B at that position.\n\ +suffix can also be a tuple of strings to try."); + +static PyObject * +bytes_endswith(PyBytesObject *self, PyObject *args) +{ + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; + PyObject *subobj; + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + result = _bytes_tailmatch(self, + PyTuple_GET_ITEM(subobj, i), + start, end, +1); + if (result == -1) + return NULL; + else if (result) { + Py_RETURN_TRUE; + } + } + Py_RETURN_FALSE; + } + result = _bytes_tailmatch(self, subobj, start, end, +1); + if (result == -1) + return NULL; + else + return PyBool_FromLong(result); +} + + + +PyDoc_STRVAR(translate__doc__, +"B.translate(table [,deletechars]) -> bytes\n\ +\n\ +Return a copy of the bytes B, where all characters occurring\n\ +in the optional argument deletechars are removed, and the\n\ +remaining characters have been mapped through the given\n\ +translation table, which must be a bytes of length 256."); + +static PyObject * +bytes_translate(PyBytesObject *self, PyObject *args) +{ + register char *input, *output; + register const char *table; + register Py_ssize_t i, c, changed = 0; + PyObject *input_obj = (PyObject*)self; + const char *table1, *output_start, *del_table=NULL; + Py_ssize_t inlen, tablen, dellen = 0; + PyObject *result; + int trans_table[256]; + PyObject *tableobj, *delobj = NULL; + + if (!PyArg_UnpackTuple(args, "translate", 1, 2, + &tableobj, &delobj)) + return NULL; + + if (PyBytes_Check(tableobj)) { + table1 = PyBytes_AS_STRING(tableobj); + tablen = PyBytes_GET_SIZE(tableobj); + } + else if (PyObject_AsCharBuffer(tableobj, &table1, &tablen)) + return NULL; + + if (tablen != 256) { + PyErr_SetString(PyExc_ValueError, + "translation table must be 256 characters long"); + return NULL; + } + + if (delobj != NULL) { + if (PyBytes_Check(delobj)) { + del_table = PyBytes_AS_STRING(delobj); + dellen = PyBytes_GET_SIZE(delobj); + } + else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen)) + return NULL; + } + else { + del_table = NULL; + dellen = 0; + } + + table = table1; + inlen = PyBytes_GET_SIZE(input_obj); + result = PyBytes_FromStringAndSize((char *)NULL, inlen); + if (result == NULL) + return NULL; + output_start = output = PyBytes_AsString(result); + input = PyBytes_AS_STRING(input_obj); + + if (dellen == 0) { + /* If no deletions are required, use faster code */ + for (i = inlen; --i >= 0; ) { + c = Py_CHARMASK(*input++); + if (Py_CHARMASK((*output++ = table[c])) != c) + changed = 1; + } + if (changed || !PyBytes_CheckExact(input_obj)) + return result; + Py_DECREF(result); + Py_INCREF(input_obj); + return input_obj; + } + + for (i = 0; i < 256; i++) + trans_table[i] = Py_CHARMASK(table[i]); + + for (i = 0; i < dellen; i++) + trans_table[(int) Py_CHARMASK(del_table[i])] = -1; + + for (i = inlen; --i >= 0; ) { + c = Py_CHARMASK(*input++); + if (trans_table[c] != -1) + if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c) + continue; + changed = 1; + } + if (!changed && PyBytes_CheckExact(input_obj)) { + Py_DECREF(result); + Py_INCREF(input_obj); + return input_obj; + } + /* Fix the size of the resulting string */ + if (inlen > 0) + PyBytes_Resize(result, output - output_start); + return result; +} + + +#define FORWARD 1 +#define REVERSE -1 + +/* find and count characters and substrings */ + +#define findchar(target, target_len, c) \ + ((char *)memchr((const void *)(target), c, target_len)) + +/* Don't call if length < 2 */ +#define Py_STRING_MATCH(target, offset, pattern, length) \ + (target[offset] == pattern[0] && \ + target[offset+length-1] == pattern[length-1] && \ + !memcmp(target+offset+1, pattern+1, length-2) ) + + +/* Bytes ops must return a string. */ +/* If the object is subclass of bytes, create a copy */ +Py_LOCAL(PyBytesObject *) +return_self(PyBytesObject *self) +{ + if (PyBytes_CheckExact(self)) { + Py_INCREF(self); + return (PyBytesObject *)self; + } + return (PyBytesObject *)PyBytes_FromStringAndSize( + PyBytes_AS_STRING(self), + PyBytes_GET_SIZE(self)); +} + +Py_LOCAL_INLINE(Py_ssize_t) +countchar(const char *target, int target_len, char c, Py_ssize_t maxcount) +{ + Py_ssize_t count=0; + const char *start=target; + const char *end=target+target_len; + + while ( (start=findchar(start, end-start, c)) != NULL ) { + count++; + if (count >= maxcount) + break; + start += 1; + } + return count; +} + +Py_LOCAL(Py_ssize_t) +findstring(const char *target, Py_ssize_t target_len, + const char *pattern, Py_ssize_t pattern_len, + Py_ssize_t start, + Py_ssize_t end, + int direction) +{ + if (start < 0) { + start += target_len; + if (start < 0) + start = 0; + } + if (end > target_len) { + end = target_len; + } else if (end < 0) { + end += target_len; + if (end < 0) + end = 0; + } + + /* zero-length substrings always match at the first attempt */ + if (pattern_len == 0) + return (direction > 0) ? start : end; + + end -= pattern_len; + + if (direction < 0) { + for (; end >= start; end--) + if (Py_STRING_MATCH(target, end, pattern, pattern_len)) + return end; + } else { + for (; start <= end; start++) + if (Py_STRING_MATCH(target, start, pattern, pattern_len)) + return start; + } + return -1; +} + +Py_LOCAL_INLINE(Py_ssize_t) +countstring(const char *target, Py_ssize_t target_len, + const char *pattern, Py_ssize_t pattern_len, + Py_ssize_t start, + Py_ssize_t end, + int direction, Py_ssize_t maxcount) +{ + Py_ssize_t count=0; + + if (start < 0) { + start += target_len; + if (start < 0) + start = 0; + } + if (end > target_len) { + end = target_len; + } else if (end < 0) { + end += target_len; + if (end < 0) + end = 0; + } + + /* zero-length substrings match everywhere */ + if (pattern_len == 0 || maxcount == 0) { + if (target_len+1 < maxcount) + return target_len+1; + return maxcount; + } + + end -= pattern_len; + if (direction < 0) { + for (; (end >= start); end--) + if (Py_STRING_MATCH(target, end, pattern, pattern_len)) { + count++; + if (--maxcount <= 0) break; + end -= pattern_len-1; + } + } else { + for (; (start <= end); start++) + if (Py_STRING_MATCH(target, start, pattern, pattern_len)) { + count++; + if (--maxcount <= 0) + break; + start += pattern_len-1; + } + } + return count; +} + + +/* Algorithms for different cases of string replacement */ + +/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */ +Py_LOCAL(PyBytesObject *) +replace_interleave(PyBytesObject *self, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *self_s, *result_s; + Py_ssize_t self_len, result_len; + Py_ssize_t count, i, product; + PyBytesObject *result; + + self_len = PyBytes_GET_SIZE(self); + + /* 1 at the end plus 1 after every character */ + count = self_len+1; + if (maxcount < count) + count = maxcount; + + /* Check for overflow */ + /* result_len = count * to_len + self_len; */ + product = count * to_len; + if (product / to_len != count) { + PyErr_SetString(PyExc_OverflowError, + "replace string is too long"); + return NULL; + } + result_len = product + self_len; + if (result_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "replace string is too long"); + return NULL; + } + + if (! (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) ) + return NULL; + + self_s = PyBytes_AS_STRING(self); + result_s = PyBytes_AS_STRING(result); + + /* TODO: special case single character, which doesn't need memcpy */ + + /* Lay the first one down (guaranteed this will occur) */ + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + count -= 1; + + for (i=0; i=1, len(from)==1, to="", maxcount>=1 */ +Py_LOCAL(PyBytesObject *) +replace_delete_single_character(PyBytesObject *self, + char from_c, Py_ssize_t maxcount) +{ + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count; + PyBytesObject *result; + + self_len = PyBytes_GET_SIZE(self); + self_s = PyBytes_AS_STRING(self); + + count = countchar(self_s, self_len, from_c, maxcount); + if (count == 0) { + return return_self(self); + } + + result_len = self_len - count; /* from_len == 1 */ + assert(result_len>=0); + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + start = next+1; + } + Py_MEMCPY(result_s, start, end-start); + + return result; +} + +/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */ + +Py_LOCAL(PyBytesObject *) +replace_delete_substring(PyBytesObject *self, + const char *from_s, Py_ssize_t from_len, + Py_ssize_t maxcount) +{ + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, offset; + PyBytesObject *result; + + self_len = PyBytes_GET_SIZE(self); + self_s = PyBytes_AS_STRING(self); + + count = countstring(self_s, self_len, + from_s, from_len, + 0, self_len, 1, + maxcount); + + if (count == 0) { + /* no matches */ + return return_self(self); + } + + result_len = self_len - (count * from_len); + assert (result_len>=0); + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL ) + return NULL; + + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + offset = findstring(start, end-start, + from_s, from_len, + 0, end-start, FORWARD); + if (offset == -1) + break; + next = start + offset; + + Py_MEMCPY(result_s, start, next-start); + + result_s += (next-start); + start = next+from_len; + } + Py_MEMCPY(result_s, start, end-start); + return result; +} + +/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */ +Py_LOCAL(PyBytesObject *) +replace_single_character_in_place(PyBytesObject *self, + char from_c, char to_c, + Py_ssize_t maxcount) +{ + char *self_s, *result_s, *start, *end, *next; + Py_ssize_t self_len; + PyBytesObject *result; + + /* The result string will be the same size */ + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + next = findchar(self_s, self_len, from_c); + + if (next == NULL) { + /* No matches; return the original bytes */ + return return_self(self); + } + + /* Need to make a new bytes */ + result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); + if (result == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + Py_MEMCPY(result_s, self_s, self_len); + + /* change everything in-place, starting with this one */ + start = result_s + (next-self_s); + *start = to_c; + start++; + end = result_s + self_len; + + while (--maxcount > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + *next = to_c; + start = next+1; + } + + return result; +} + +/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */ +Py_LOCAL(PyBytesObject *) +replace_substring_in_place(PyBytesObject *self, + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *result_s, *start, *end; + char *self_s; + Py_ssize_t self_len, offset; + PyBytesObject *result; + + /* The result bytes will be the same size */ + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + offset = findstring(self_s, self_len, + from_s, from_len, + 0, self_len, FORWARD); + if (offset == -1) { + /* No matches; return the original bytes */ + return return_self(self); + } + + /* Need to make a new bytes */ + result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); + if (result == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + Py_MEMCPY(result_s, self_s, self_len); + + /* change everything in-place, starting with this one */ + start = result_s + offset; + Py_MEMCPY(start, to_s, from_len); + start += from_len; + end = result_s + self_len; + + while ( --maxcount > 0) { + offset = findstring(start, end-start, + from_s, from_len, + 0, end-start, FORWARD); + if (offset==-1) + break; + Py_MEMCPY(start+offset, to_s, from_len); + start += offset+from_len; + } + + return result; +} + +/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */ +Py_LOCAL(PyBytesObject *) +replace_single_character(PyBytesObject *self, + char from_c, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, product; + PyBytesObject *result; + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + count = countchar(self_s, self_len, from_c, maxcount); + if (count == 0) { + /* no matches, return unchanged */ + return return_self(self); + } + + /* use the difference between current and new, hence the "-1" */ + /* result_len = self_len + count * (to_len-1) */ + product = count * (to_len-1); + if (product / (to_len-1) != count) { + PyErr_SetString(PyExc_OverflowError, "replace bytes is too long"); + return NULL; + } + result_len = self_len + product; + if (result_len < 0) { + PyErr_SetString(PyExc_OverflowError, "replace bytes is too long"); + return NULL; + } + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + + if (next == start) { + /* replace with the 'to' */ + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start += 1; + } else { + /* copy the unchanged old then the 'to' */ + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start = next+1; + } + } + /* Copy the remainder of the remaining bytes */ + Py_MEMCPY(result_s, start, end-start); + + return result; +} + +/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */ +Py_LOCAL(PyBytesObject *) +replace_substring(PyBytesObject *self, + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, offset, product; + PyBytesObject *result; + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + count = countstring(self_s, self_len, + from_s, from_len, + 0, self_len, FORWARD, maxcount); + if (count == 0) { + /* no matches, return unchanged */ + return return_self(self); + } + + /* Check for overflow */ + /* result_len = self_len + count * (to_len-from_len) */ + product = count * (to_len-from_len); + if (product / (to_len-from_len) != count) { + PyErr_SetString(PyExc_OverflowError, "replace bytes is too long"); + return NULL; + } + result_len = self_len + product; + if (result_len < 0) { + PyErr_SetString(PyExc_OverflowError, "replace bytes is too long"); + return NULL; + } + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + offset = findstring(start, end-start, + from_s, from_len, + 0, end-start, FORWARD); + if (offset == -1) + break; + next = start+offset; + if (next == start) { + /* replace with the 'to' */ + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start += from_len; + } else { + /* copy the unchanged old then the 'to' */ + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start = next+from_len; + } + } + /* Copy the remainder of the remaining bytes */ + Py_MEMCPY(result_s, start, end-start); + + return result; +} + + +Py_LOCAL(PyBytesObject *) +replace(PyBytesObject *self, + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + if (maxcount < 0) { + maxcount = PY_SSIZE_T_MAX; + } else if (maxcount == 0 || PyBytes_GET_SIZE(self) == 0) { + /* nothing to do; return the original bytes */ + return return_self(self); + } + + if (maxcount == 0 || + (from_len == 0 && to_len == 0)) { + /* nothing to do; return the original bytes */ + return return_self(self); + } + + /* Handle zero-length special cases */ + + if (from_len == 0) { + /* insert the 'to' bytes everywhere. */ + /* >>> "Python".replace("", ".") */ + /* '.P.y.t.h.o.n.' */ + return replace_interleave(self, to_s, to_len, maxcount); + } + + /* Except for "".replace("", "A") == "A" there is no way beyond this */ + /* point for an empty self bytes to generate a non-empty bytes */ + /* Special case so the remaining code always gets a non-empty bytes */ + if (PyBytes_GET_SIZE(self) == 0) { + return return_self(self); + } + + if (to_len == 0) { + /* delete all occurances of 'from' bytes */ + if (from_len == 1) { + return replace_delete_single_character( + self, from_s[0], maxcount); + } else { + return replace_delete_substring(self, from_s, from_len, maxcount); + } + } + + /* Handle special case where both bytes have the same length */ + + if (from_len == to_len) { + if (from_len == 1) { + return replace_single_character_in_place( + self, + from_s[0], + to_s[0], + maxcount); + } else { + return replace_substring_in_place( + self, from_s, from_len, to_s, to_len, maxcount); + } + } + + /* Otherwise use the more generic algorithms */ + if (from_len == 1) { + return replace_single_character(self, from_s[0], + to_s, to_len, maxcount); + } else { + /* len('from')>=2, len('to')>=1 */ + return replace_substring(self, from_s, from_len, to_s, to_len, maxcount); + } +} + +PyDoc_STRVAR(replace__doc__, +"B.replace (old, new[, count]) -> bytes\n\ +\n\ +Return a copy of bytes B with all occurrences of subsection\n\ +old replaced by new. If the optional argument count is\n\ +given, only the first count occurrences are replaced."); + +static PyObject * +bytes_replace(PyBytesObject *self, PyObject *args) +{ + Py_ssize_t count = -1; + PyObject *from, *to; + const char *from_s, *to_s; + Py_ssize_t from_len, to_len; + + if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count)) + return NULL; + + if (PyBytes_Check(from)) { + from_s = PyBytes_AS_STRING(from); + from_len = PyBytes_GET_SIZE(from); + } + else if (PyObject_AsCharBuffer(from, &from_s, &from_len)) + return NULL; + + if (PyBytes_Check(to)) { + to_s = PyBytes_AS_STRING(to); + to_len = PyBytes_GET_SIZE(to); + } + else if (PyObject_AsCharBuffer(to, &to_s, &to_len)) + return NULL; + + return (PyObject *)replace((PyBytesObject *) self, + from_s, from_len, + to_s, to_len, count); +} + + +/* Overallocate the initial list to reduce the number of reallocs for small + split sizes. Eg, "A A A A A A A A A A".split() (10 elements) has three + resizes, to sizes 4, 8, then 16. Most observed string splits are for human + text (roughly 11 words per line) and field delimited data (usually 1-10 + fields). For large strings the split algorithms are bandwidth limited + so increasing the preallocation likely will not improve things.*/ + +#define MAX_PREALLOC 12 + +/* 5 splits gives 6 elements */ +#define PREALLOC_SIZE(maxsplit) \ + (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1) + +#define SPLIT_APPEND(data, left, right) \ + str = PyBytes_FromStringAndSize((data) + (left), \ + (right) - (left)); \ + if (str == NULL) \ + goto onError; \ + if (PyList_Append(list, str)) { \ + Py_DECREF(str); \ + goto onError; \ + } \ + else \ + Py_DECREF(str); + +#define SPLIT_ADD(data, left, right) { \ + str = PyBytes_FromStringAndSize((data) + (left), \ + (right) - (left)); \ + if (str == NULL) \ + goto onError; \ + if (count < MAX_PREALLOC) { \ + PyList_SET_ITEM(list, count, str); \ + } else { \ + if (PyList_Append(list, str)) { \ + Py_DECREF(str); \ + goto onError; \ + } \ + else \ + Py_DECREF(str); \ + } \ + count++; } + +/* Always force the list to the expected size. */ +#define FIX_PREALLOC_SIZE(list) ((PyListObject *)list)->ob_size = count + + +Py_LOCAL_INLINE(PyObject *) +split_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount) +{ + register Py_ssize_t i, j, count=0; + PyObject *str; + PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); + + if (list == NULL) + return NULL; + + i = j = 0; + while ((j < len) && (maxcount-- > 0)) { + for(; j list of bytes\n\ +\n\ +Return a list of the bytes in the string B, using sep as the\n\ +delimiter. If maxsplit is given, at most maxsplit\n\ +splits are done."); + +static PyObject * +bytes_split(PyBytesObject *self, PyObject *args) +{ + Py_ssize_t len = PyBytes_GET_SIZE(self), n, i, j; + Py_ssize_t maxsplit = -1, count=0; + const char *s = PyBytes_AS_STRING(self), *sub; + PyObject *list, *str, *subobj; +#ifdef USE_FAST + Py_ssize_t pos; +#endif + + if (!PyArg_ParseTuple(args, "O|n:split", &subobj, &maxsplit)) + return NULL; + if (maxsplit < 0) + maxsplit = PY_SSIZE_T_MAX; + if (PyBytes_Check(subobj)) { + sub = PyBytes_AS_STRING(subobj); + n = PyBytes_GET_SIZE(subobj); + } + else if (PyObject_AsCharBuffer(subobj, &sub, &n)) + return NULL; + + if (n == 0) { + PyErr_SetString(PyExc_ValueError, "empty separator"); + return NULL; + } + else if (n == 1) + return split_char(s, len, sub[0], maxsplit); + + list = PyList_New(PREALLOC_SIZE(maxsplit)); + if (list == NULL) + return NULL; + +#ifdef USE_FAST + i = j = 0; + while (maxsplit-- > 0) { + pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH); + if (pos < 0) + break; + j = i+pos; + SPLIT_ADD(s, i, j); + i = j + n; + } +#else + i = j = 0; + while ((j+n <= len) && (maxsplit-- > 0)) { + for (; j+n <= len; j++) { + if (Py_STRING_MATCH(s, j, sub, n)) { + SPLIT_ADD(s, i, j); + i = j = j + n; + break; + } + } + } +#endif + SPLIT_ADD(s, i, len); + FIX_PREALLOC_SIZE(list); + return list; + + onError: + Py_DECREF(list); + return NULL; +} + +PyDoc_STRVAR(partition__doc__, +"B.partition(sep) -> (head, sep, tail)\n\ +\n\ +Searches for the separator sep in B, and returns the part before it,\n\ +the separator itself, and the part after it. If the separator is not\n\ +found, returns B and two empty bytes."); + +static PyObject * +bytes_partition(PyBytesObject *self, PyObject *sep_obj) +{ + PyObject *bytesep, *result; + + bytesep = PyBytes_FromObject(sep_obj); + if (! bytesep) + return NULL; + + result = stringlib_partition( + (PyObject*) self, + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + bytesep, + PyBytes_AS_STRING(bytesep), PyBytes_GET_SIZE(bytesep) + ); + + Py_DECREF(bytesep); + return result; +} + +PyDoc_STRVAR(rpartition__doc__, +"B.rpartition(sep) -> (tail, sep, head)\n\ +\n\ +Searches for the separator sep in B, starting at the end of B, and returns\n\ +the part before it, the separator itself, and the part after it. If the\n\ +separator is not found, returns two empty bytes and B."); + +static PyObject * +bytes_rpartition(PyBytesObject *self, PyObject *sep_obj) +{ + PyObject *bytesep, *result; + + bytesep = PyBytes_FromObject(sep_obj); + if (! bytesep) + return NULL; + + result = stringlib_rpartition( + (PyObject*) self, + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + bytesep, + PyBytes_AS_STRING(bytesep), PyBytes_GET_SIZE(bytesep) + ); + + Py_DECREF(bytesep); + return result; +} + +Py_LOCAL_INLINE(PyObject *) +rsplit_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount) +{ + register Py_ssize_t i, j, count=0; + PyObject *str; + PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); + + if (list == NULL) + return NULL; + + i = j = len - 1; + while ((i >= 0) && (maxcount-- > 0)) { + for (; i >= 0; i--) { + if (s[i] == ch) { + SPLIT_ADD(s, i + 1, j + 1); + j = i = i - 1; + break; + } + } + } + if (j >= -1) { + SPLIT_ADD(s, 0, j + 1); + } + FIX_PREALLOC_SIZE(list); + if (PyList_Reverse(list) < 0) + goto onError; + + return list; + + onError: + Py_DECREF(list); + return NULL; +} + +PyDoc_STRVAR(rsplit__doc__, +"B.rsplit(sep [,maxsplit]) -> list of bytes\n\ +\n\ +Return a list of the sections in the byte B, using sep as the\n\ +delimiter, starting at the end of the bytes and working\n\ +to the front. If maxsplit is given, at most maxsplit splits are\n\ +done."); + +static PyObject * +bytes_rsplit(PyBytesObject *self, PyObject *args) +{ + Py_ssize_t len = PyBytes_GET_SIZE(self), n, i, j; + Py_ssize_t maxsplit = -1, count=0; + const char *s = PyBytes_AS_STRING(self), *sub; + PyObject *list, *str, *subobj; + + if (!PyArg_ParseTuple(args, "O|n:rsplit", &subobj, &maxsplit)) + return NULL; + if (maxsplit < 0) + maxsplit = PY_SSIZE_T_MAX; + if (PyBytes_Check(subobj)) { + sub = PyBytes_AS_STRING(subobj); + n = PyBytes_GET_SIZE(subobj); + } + else if (PyObject_AsCharBuffer(subobj, &sub, &n)) + return NULL; + + if (n == 0) { + PyErr_SetString(PyExc_ValueError, "empty separator"); + return NULL; + } + else if (n == 1) + return rsplit_char(s, len, sub[0], maxsplit); + + list = PyList_New(PREALLOC_SIZE(maxsplit)); + if (list == NULL) + return NULL; + + j = len; + i = j - n; + + while ( (i >= 0) && (maxsplit-- > 0) ) { + for (; i>=0; i--) { + if (Py_STRING_MATCH(s, i, sub, n)) { + SPLIT_ADD(s, i + n, j); + j = i; + i -= n; + break; + } + } + } + SPLIT_ADD(s, 0, j); + FIX_PREALLOC_SIZE(list); + if (PyList_Reverse(list) < 0) + goto onError; + return list; + +onError: + Py_DECREF(list); + return NULL; +} + +PyDoc_STRVAR(extend__doc__, +"B.extend(iterable int) -> None\n\ +\n\ +Append all the elements from the iterator or sequence to the\n\ +end of the bytes."); +static PyObject * +bytes_extend(PyBytesObject *self, PyObject *arg) +{ + if (bytes_setslice(self, self->ob_size, self->ob_size, arg) == -1) + return NULL; + Py_RETURN_NONE; +} + + +PyDoc_STRVAR(reverse__doc__, +"B.reverse() -> None\n\ +\n\ +Reverse the order of the values in bytes in place."); +static PyObject * +bytes_reverse(PyBytesObject *self, PyObject *unused) +{ + char swap, *head, *tail; + Py_ssize_t i, j, n = self->ob_size; + + j = n / 2; + head = self->ob_bytes; + tail = head + n - 1; + for (i = 0; i < j; i++) { + swap = *head; + *head++ = *tail; + *tail-- = swap; + } + + Py_RETURN_NONE; +} + +PyDoc_STRVAR(insert__doc__, +"B.insert(index, int) -> None\n\ +\n\ +Insert a single item into the bytes before the given index."); +static PyObject * +bytes_insert(PyBytesObject *self, PyObject *args) +{ + int value; + Py_ssize_t where, n = self->ob_size; + + if (!PyArg_ParseTuple(args, "ni:insert", &where, &value)) + return NULL; + + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more objects to bytes"); + return NULL; + } + if (value < 0 || value >= 256) { + PyErr_SetString(PyExc_ValueError, + "byte must be in range(0, 256)"); + return NULL; + } + if (PyBytes_Resize((PyObject *)self, n + 1) < 0) + return NULL; + + if (where < 0) { + where += n; + if (where < 0) + where = 0; + } + if (where > n) + where = n; + memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where + 1); + self->ob_bytes[where] = value; + + Py_RETURN_NONE; +} + +PyDoc_STRVAR(append__doc__, +"B.append(int) -> None\n\ +\n\ +Append a single item to the end of the bytes."); +static PyObject * +bytes_append(PyBytesObject *self, PyObject *arg) +{ + int value; + Py_ssize_t n = self->ob_size; + + if (! _getbytevalue(arg, &value)) + return NULL; + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more objects to bytes"); + return NULL; + } + if (PyBytes_Resize((PyObject *)self, n + 1) < 0) + return NULL; + + self->ob_bytes[n] = value; + + Py_RETURN_NONE; +} + +PyDoc_STRVAR(pop__doc__, +"B.pop([index]) -> int\n\ +\n\ +Remove and return a single item from the bytes. If no index\n\ +argument is give, will pop the last value."); +static PyObject * +bytes_pop(PyBytesObject *self, PyObject *args) +{ + int value; + Py_ssize_t where = -1, n = self->ob_size; + + if (!PyArg_ParseTuple(args, "|n:pop", &where)) + return NULL; + + if (n == 0) { + PyErr_SetString(PyExc_OverflowError, + "cannot pop an empty bytes"); + return NULL; + } + if (where < 0) + where += self->ob_size; + if (where < 0 || where >= self->ob_size) { + PyErr_SetString(PyExc_IndexError, "pop index out of range"); + return NULL; + } + + value = self->ob_bytes[where]; + memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where); + if (PyBytes_Resize((PyObject *)self, n - 1) < 0) + return NULL; + + return PyInt_FromLong(value); +} + +PyDoc_STRVAR(remove__doc__, +"B.remove(int) -> None\n\ +\n\ +Remove the first occurance of a value in bytes"); +static PyObject * +bytes_remove(PyBytesObject *self, PyObject *arg) +{ + int value; + Py_ssize_t where, n = self->ob_size; + + if (! _getbytevalue(arg, &value)) + return NULL; + + for (where = 0; where < n; where++) { + if (self->ob_bytes[where] == value) + break; + } + if (where == n) { + PyErr_SetString(PyExc_ValueError, "value not found in bytes"); + return NULL; + } + + memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where); + if (PyBytes_Resize((PyObject *)self, n - 1) < 0) + return NULL; + + Py_RETURN_NONE; +} + + PyDoc_STRVAR(decode_doc, "B.decode([encoding[,errors]]) -> unicode obect.\n\ \n\ @@ -1065,6 +2600,26 @@ static PyMethodDef bytes_methods[] = { + {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__}, + {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__}, + {"index", (PyCFunction)bytes_index, METH_VARARGS, index__doc__}, + {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__}, + {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__}, + {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, endswith__doc__}, + {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS, + startswith__doc__}, + {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__}, + {"translate", (PyCFunction)bytes_translate, METH_VARARGS, translate__doc__}, + {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__}, + {"rpartition", (PyCFunction)bytes_rpartition, METH_O, rpartition__doc__}, + {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__}, + {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__}, + {"extend", (PyCFunction)bytes_extend, METH_O, extend__doc__}, + {"insert", (PyCFunction)bytes_insert, METH_VARARGS, insert__doc__}, + {"append", (PyCFunction)bytes_append, METH_O, append__doc__}, + {"reverse", (PyCFunction)bytes_reverse, METH_NOARGS, reverse__doc__}, + {"pop", (PyCFunction)bytes_pop, METH_VARARGS, pop__doc__}, + {"remove", (PyCFunction)bytes_remove, METH_O, remove__doc__}, {"decode", (PyCFunction)bytes_decode, METH_VARARGS, decode_doc}, {"__alloc__", (PyCFunction)bytes_alloc, METH_NOARGS, alloc_doc}, {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, fromhex_doc}, Modified: python/branches/p3yk/Python/pythonrun.c ============================================================================== --- python/branches/p3yk/Python/pythonrun.c (original) +++ python/branches/p3yk/Python/pythonrun.c Tue Feb 27 20:02:19 2007 @@ -186,6 +186,9 @@ if (!_PyLong_Init()) Py_FatalError("Py_Initialize: can't init longs"); + if (!PyBytes_Init()) + Py_FatalError("Py_Initialize: can't init bytes"); + _PyFloat_Init(); interp->modules = PyDict_New(); @@ -457,6 +460,7 @@ PyList_Fini(); PySet_Fini(); PyString_Fini(); + PyBytes_Fini(); PyLong_Fini(); PyFloat_Fini(); From python-3000-checkins at python.org Tue Feb 27 20:06:26 2007 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 27 Feb 2007 20:06:26 +0100 (CET) Subject: [Python-3000-checkins] r54001 - python/branches/p3yk/Modules/getaddrinfo.c python/branches/p3yk/Modules/getnameinfo.c Message-ID: <20070227190626.2D1161E4002@bag.python.org> Author: neal.norwitz Date: Tue Feb 27 20:06:23 2007 New Revision: 54001 Modified: python/branches/p3yk/Modules/getaddrinfo.c python/branches/p3yk/Modules/getnameinfo.c Log: SF patch #1670209, Remove Py_PROTO from socket by Pete Shinners. Modified: python/branches/p3yk/Modules/getaddrinfo.c ============================================================================== --- python/branches/p3yk/Modules/getaddrinfo.c (original) +++ python/branches/p3yk/Modules/getaddrinfo.c Tue Feb 27 20:06:23 2007 @@ -129,12 +129,12 @@ #define IN_LOOPBACKNET 127 #endif -static int get_name Py_PROTO((const char *, struct gai_afd *, +static int get_name(const char *, struct gai_afd *, struct addrinfo **, char *, struct addrinfo *, - int)); -static int get_addr Py_PROTO((const char *, int, struct addrinfo **, - struct addrinfo *, int)); -static int str_isnumber Py_PROTO((const char *)); + int); +static int get_addr(const char *, int, struct addrinfo **, + struct addrinfo *, int); +static int str_isnumber(const char *); static char *ai_errlist[] = { "success.", Modified: python/branches/p3yk/Modules/getnameinfo.c ============================================================================== --- python/branches/p3yk/Modules/getnameinfo.c (original) +++ python/branches/p3yk/Modules/getnameinfo.c Tue Feb 27 20:06:23 2007 @@ -82,8 +82,8 @@ #define ENI_SALEN 6 /* forward declaration to make gcc happy */ -int getnameinfo Py_PROTO((const struct sockaddr *, size_t, char *, size_t, - char *, size_t, int)); +int getnameinfo(const struct sockaddr *, size_t, char *, size_t, + char *, size_t, int); int getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) From python-3000-checkins at python.org Tue Feb 27 21:16:03 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 27 Feb 2007 21:16:03 +0100 (CET) Subject: [Python-3000-checkins] r54002 - python/branches/p3yk/Python/Python-ast.c Message-ID: <20070227201603.6A4F91E4002@bag.python.org> Author: brett.cannon Date: Tue Feb 27 21:16:01 2007 New Revision: 54002 Modified: python/branches/p3yk/Python/Python-ast.c Log: Commit version bump. Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Tue Feb 27 21:16:01 2007 @@ -2,7 +2,7 @@ /* - __version__ 53956. + __version__ 53986. This module must be committed separately after each AST grammar change; The __version__ number is set to the revision number of the commit @@ -3038,7 +3038,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__", "53956") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53986") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) From python-3000-checkins at python.org Tue Feb 27 21:16:41 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 27 Feb 2007 21:16:41 +0100 (CET) Subject: [Python-3000-checkins] r54003 - python/branches/p3yk/Lib/httplib.py Message-ID: <20070227201641.D5BB21E4002@bag.python.org> Author: brett.cannon Date: Tue Feb 27 21:16:38 2007 New Revision: 54003 Modified: python/branches/p3yk/Lib/httplib.py Log: Fix httplib for removal of slicing from exceptions. Modified: python/branches/p3yk/Lib/httplib.py ============================================================================== --- python/branches/p3yk/Lib/httplib.py (original) +++ python/branches/p3yk/Lib/httplib.py Tue Feb 27 21:16:38 2007 @@ -870,7 +870,7 @@ self._send_request(method, url, body, headers) except socket.error as v: # trap 'Broken pipe' if we're allowed to automatically reconnect - if v[0] != 32 or not self.auto_open: + if v.message != 32 or not self.auto_open: raise # try one more time self._send_request(method, url, body, headers) @@ -1020,17 +1020,19 @@ try: buf = self._ssl.read(self._bufsize) except socket.sslerror as err: - if (err[0] == socket.SSL_ERROR_WANT_READ - or err[0] == socket.SSL_ERROR_WANT_WRITE): + err_type = err.message + if (err_type == socket.SSL_ERROR_WANT_READ + or err_type == socket.SSL_ERROR_WANT_WRITE): continue - if (err[0] == socket.SSL_ERROR_ZERO_RETURN - or err[0] == socket.SSL_ERROR_EOF): + if (err_type == socket.SSL_ERROR_ZERO_RETURN + or err_type == socket.SSL_ERROR_EOF): break raise except socket.error as err: - if err[0] == errno.EINTR: + err_type = err.message + if err_type == errno.EINTR: continue - if err[0] == errno.EBADF: + if err_type == errno.EBADF: # XXX socket was closed? break raise From python-3000-checkins at python.org Tue Feb 27 21:57:51 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 27 Feb 2007 21:57:51 +0100 (CET) Subject: [Python-3000-checkins] r54004 - python/branches/p3yk/Objects/bytesobject.c Message-ID: <20070227205751.0C2531E4009@bag.python.org> Author: guido.van.rossum Date: Tue Feb 27 21:57:45 2007 New Revision: 54004 Modified: python/branches/p3yk/Objects/bytesobject.c Log: Fix off-by-one bug in memmove() call in bytes_insert(). Fix by Pete Shinners (for his own bug :-). Modified: python/branches/p3yk/Objects/bytesobject.c ============================================================================== --- python/branches/p3yk/Objects/bytesobject.c (original) +++ python/branches/p3yk/Objects/bytesobject.c Tue Feb 27 21:57:45 2007 @@ -2313,7 +2313,7 @@ } if (where > n) where = n; - memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where + 1); + memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where); self->ob_bytes[where] = value; Py_RETURN_NONE; From python-3000-checkins at python.org Wed Feb 28 01:01:45 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 01:01:45 +0100 (CET) Subject: [Python-3000-checkins] r54008 - python/branches/p3yk/Lib/test/test_pep352.py Message-ID: <20070228000145.CA8E61E4002@bag.python.org> Author: brett.cannon Date: Wed Feb 28 01:01:43 2007 New Revision: 54008 Modified: python/branches/p3yk/Lib/test/test_pep352.py Log: Fix test_pep352 to deal with the removal of the 'exceptions' module. Modified: python/branches/p3yk/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep352.py (original) +++ python/branches/p3yk/Lib/test/test_pep352.py Wed Feb 28 01:01:43 2007 @@ -1,6 +1,5 @@ import unittest import __builtin__ -import exceptions import warnings from test.test_support import run_unittest, guard_warnings_filter import os @@ -21,7 +20,14 @@ def test_inheritance(self): # Make sure the inheritance hierarchy matches the documentation - exc_set = set(x for x in dir(exceptions) if not x.startswith('_')) + exc_set = set() + for object_ in __builtins__.__dict__.values(): + try: + if issubclass(object_, BaseException): + exc_set.add(object_.__name__) + except TypeError: + pass + inheritance_tree = open(os.path.join(os.path.split(__file__)[0], 'exception_hierarchy.txt')) try: From guido at python.org Wed Feb 28 01:29:00 2007 From: guido at python.org (Guido van Rossum) Date: Tue, 27 Feb 2007 18:29:00 -0600 Subject: [Python-3000-checkins] r54008 - python/branches/p3yk/Lib/test/test_pep352.py In-Reply-To: <20070228000145.CA8E61E4002@bag.python.org> References: <20070228000145.CA8E61E4002@bag.python.org> Message-ID: The dependency on __builtins__ is wrong; you should import __builtin__ (no 's') and use that. Also, why the except? On 2/27/07, brett.cannon wrote: > Author: brett.cannon > Date: Wed Feb 28 01:01:43 2007 > New Revision: 54008 > > Modified: > python/branches/p3yk/Lib/test/test_pep352.py > Log: > Fix test_pep352 to deal with the removal of the 'exceptions' module. > > > Modified: python/branches/p3yk/Lib/test/test_pep352.py > ============================================================================== > --- python/branches/p3yk/Lib/test/test_pep352.py (original) > +++ python/branches/p3yk/Lib/test/test_pep352.py Wed Feb 28 01:01:43 2007 > @@ -1,6 +1,5 @@ > import unittest > import __builtin__ > -import exceptions > import warnings > from test.test_support import run_unittest, guard_warnings_filter > import os > @@ -21,7 +20,14 @@ > > def test_inheritance(self): > # Make sure the inheritance hierarchy matches the documentation > - exc_set = set(x for x in dir(exceptions) if not x.startswith('_')) > + exc_set = set() > + for object_ in __builtins__.__dict__.values(): > + try: > + if issubclass(object_, BaseException): > + exc_set.add(object_.__name__) > + except TypeError: > + pass > + > inheritance_tree = open(os.path.join(os.path.split(__file__)[0], > 'exception_hierarchy.txt')) > try: > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From python-3000-checkins at python.org Wed Feb 28 01:32:10 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Wed, 28 Feb 2007 01:32:10 +0100 (CET) Subject: [Python-3000-checkins] r54009 - python/branches/p3yk/Lib/test/test_pep352.py Message-ID: <20070228003210.762021E4002@bag.python.org> Author: brett.cannon Date: Wed Feb 28 01:32:07 2007 New Revision: 54009 Modified: python/branches/p3yk/Lib/test/test_pep352.py Log: Use __builtin__, not __builtins__. Modified: python/branches/p3yk/Lib/test/test_pep352.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep352.py (original) +++ python/branches/p3yk/Lib/test/test_pep352.py Wed Feb 28 01:32:07 2007 @@ -21,7 +21,7 @@ def test_inheritance(self): # Make sure the inheritance hierarchy matches the documentation exc_set = set() - for object_ in __builtins__.__dict__.values(): + for object_ in __builtin__.__dict__.values(): try: if issubclass(object_, BaseException): exc_set.add(object_.__name__) From brett at python.org Wed Feb 28 01:32:39 2007 From: brett at python.org (Brett Cannon) Date: Tue, 27 Feb 2007 18:32:39 -0600 Subject: [Python-3000-checkins] r54008 - python/branches/p3yk/Lib/test/test_pep352.py In-Reply-To: References: <20070228000145.CA8E61E4002@bag.python.org> Message-ID: On 2/27/07, Guido van Rossum wrote: > The dependency on __builtins__ is wrong; you should import __builtin__ > (no 's') and use that. Thanks, fixed. > > Also, why the except? > Because __builtin__ has non-classes like functions and passing it to issubclass raises a TypeError. -Brett > On 2/27/07, brett.cannon wrote: > > Author: brett.cannon > > Date: Wed Feb 28 01:01:43 2007 > > New Revision: 54008 > > > > Modified: > > python/branches/p3yk/Lib/test/test_pep352.py > > Log: > > Fix test_pep352 to deal with the removal of the 'exceptions' module. > > > > > > Modified: python/branches/p3yk/Lib/test/test_pep352.py > > ============================================================================== > > --- python/branches/p3yk/Lib/test/test_pep352.py (original) > > +++ python/branches/p3yk/Lib/test/test_pep352.py Wed Feb 28 01:01:43 2007 > > @@ -1,6 +1,5 @@ > > import unittest > > import __builtin__ > > -import exceptions > > import warnings > > from test.test_support import run_unittest, guard_warnings_filter > > import os > > @@ -21,7 +20,14 @@ > > > > def test_inheritance(self): > > # Make sure the inheritance hierarchy matches the documentation > > - exc_set = set(x for x in dir(exceptions) if not x.startswith('_')) > > + exc_set = set() > > + for object_ in __builtins__.__dict__.values(): > > + try: > > + if issubclass(object_, BaseException): > > + exc_set.add(object_.__name__) > > + except TypeError: > > + pass > > + > > inheritance_tree = open(os.path.join(os.path.split(__file__)[0], > > 'exception_hierarchy.txt')) > > try: > > _______________________________________________ > > Python-3000-checkins mailing list > > Python-3000-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-3000-checkins > > > > > -- > --Guido van Rossum (home page: http://www.python.org/~guido/) > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > From python-3000-checkins at python.org Wed Feb 28 01:40:27 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 28 Feb 2007 01:40:27 +0100 (CET) Subject: [Python-3000-checkins] r54010 - python/branches/p3yk/Lib/symbol.py Message-ID: <20070228004027.ED0FB1E4018@bag.python.org> Author: guido.van.rossum Date: Wed Feb 28 01:40:24 2007 New Revision: 54010 Modified: python/branches/p3yk/Lib/symbol.py Log: Regenerate symbol.py. This fixes test_compiler, test_transformer, and test_parser. Modified: python/branches/p3yk/Lib/symbol.py ============================================================================== --- python/branches/p3yk/Lib/symbol.py (original) +++ python/branches/p3yk/Lib/symbol.py Wed Feb 28 01:40:24 2007 @@ -47,56 +47,57 @@ dotted_as_names = 290 dotted_name = 291 global_stmt = 292 -assert_stmt = 293 -compound_stmt = 294 -if_stmt = 295 -while_stmt = 296 -for_stmt = 297 -try_stmt = 298 -with_stmt = 299 -with_var = 300 -except_clause = 301 -suite = 302 -testlist_safe = 303 -old_test = 304 -old_lambdef = 305 -test = 306 -or_test = 307 -and_test = 308 -not_test = 309 -comparison = 310 -comp_op = 311 -expr = 312 -xor_expr = 313 -and_expr = 314 -shift_expr = 315 -arith_expr = 316 -term = 317 -factor = 318 -power = 319 -atom = 320 -listmaker = 321 -testlist_gexp = 322 -lambdef = 323 -trailer = 324 -subscriptlist = 325 -subscript = 326 -sliceop = 327 -exprlist = 328 -testlist = 329 -dictsetmaker = 330 -classdef = 331 -arglist = 332 -argument = 333 -list_iter = 334 -list_for = 335 -list_if = 336 -gen_iter = 337 -gen_for = 338 -gen_if = 339 -testlist1 = 340 -encoding_decl = 341 -yield_expr = 342 +nonlocal_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 = {} From python-3000-checkins at python.org Wed Feb 28 21:21:38 2007 From: python-3000-checkins at python.org (jack.diederich) Date: Wed, 28 Feb 2007 21:21:38 +0100 (CET) Subject: [Python-3000-checkins] r54035 - python/branches/p3yk/Lib/keyword.py Message-ID: <20070228202138.0CE9F1E4020@bag.python.org> Author: jack.diederich Date: Wed Feb 28 21:21:30 2007 New Revision: 54035 Modified: python/branches/p3yk/Lib/keyword.py Log: regenerated to reflect the addition of 'nonlocal' and removal of 'print' Modified: python/branches/p3yk/Lib/keyword.py ============================================================================== --- python/branches/p3yk/Lib/keyword.py (original) +++ python/branches/p3yk/Lib/keyword.py Wed Feb 28 21:21:30 2007 @@ -34,10 +34,10 @@ 'in', 'is', 'lambda', + 'nonlocal', 'not', 'or', 'pass', - 'print', 'raise', 'return', 'try', From python-3000-checkins at python.org Wed Feb 28 23:03:55 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 28 Feb 2007 23:03:55 +0100 (CET) Subject: [Python-3000-checkins] r54043 - python/branches/p3yk/Lib/inspect.py python/branches/p3yk/Lib/pydoc.py Message-ID: <20070228220355.F1CD51E4004@bag.python.org> Author: guido.van.rossum Date: Wed Feb 28 23:03:49 2007 New Revision: 54043 Modified: python/branches/p3yk/Lib/inspect.py python/branches/p3yk/Lib/pydoc.py Log: Final part of SF# 1607548 by Tony Lownds: fix pydoc and inspect. Modified: python/branches/p3yk/Lib/inspect.py ============================================================================== --- python/branches/p3yk/Lib/inspect.py (original) +++ python/branches/p3yk/Lib/inspect.py Wed Feb 28 23:03:49 2007 @@ -17,6 +17,7 @@ getclasstree() - arrange classes so as to represent their hierarchy getargspec(), getargvalues() - get info about function arguments + getfullargspec() - same, with support for Python-3000 features formatargspec(), formatargvalues() - format an argument spec getouterframes(), getinnerframes() - get info about frames currentframe() - get the current stack frame @@ -672,9 +673,20 @@ def getargs(co): """Get information about the arguments accepted by a code object. - Three things are returned: (args, varargs, varkw), where 'args' is - a list of argument names (possibly containing nested lists), and - 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" + Three things are returned: (args, varargs, varkw), where + 'args' is the list of argument names, possibly containing nested + lists. Keyword-only arguments are appended. 'varargs' and 'varkw' + are the names of the * and ** arguments or None.""" + args, varargs, kwonlyargs, varkw = _getfullargs(co) + return args + kwonlyargs, varargs, varkw + +def _getfullargs(co): + """Get information about the arguments accepted by a code object. + + Four things are returned: (args, varargs, kwonlyargs, varkw), where + 'args' and 'kwonlyargs' are lists of argument names (with 'args' + possibly containing nested lists), and 'varargs' and 'varkw' are the + names of the * and ** arguments or None.""" if not iscode(co): raise TypeError('arg is not a code object') @@ -682,7 +694,9 @@ code = co.co_code nargs = co.co_argcount names = co.co_varnames + nkwargs = co.co_kwonlyargcount args = list(names[:nargs]) + kwonlyargs = list(names[nargs:nargs+nkwargs]) step = 0 # The following acrobatics are for anonymous (tuple) arguments. @@ -719,6 +733,7 @@ if not remain: break args[i] = stack[0] + nargs += nkwargs varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] @@ -726,23 +741,51 @@ varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] - return args, varargs, varkw + return args, varargs, kwonlyargs, varkw def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). + 'args' will include keyword-only argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. + + Use the getfullargspec() API for Python-3000 code, as annotations + and keyword arguments are supported. getargspec() will raise ValueError + if the func has either annotations or keyword arguments. + """ + + args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ + getfullargspec(func) + if kwonlyargs or ann: + raise ValueError, ("Function has keyword-only arguments or annotations" + ", use getfullargspec() API which can support them") + return (args, varargs, varkw, defaults) + +def getfullargspec(func): + """Get the names and default values of a function's arguments. + + A tuple of seven things is returned: (args, varargs, kwonlyargs, + kwonlydefaults, varkw, defaults, annotations). + 'args' is a list of the argument names (it may contain nested lists). + 'varargs' and 'varkw' are the names of the * and ** arguments or None. + 'defaults' is an n-tuple of the default values of the last n arguments. + 'kwonlyargs' is a list of keyword-only argument names. + 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults. + 'annotations' is a dictionary mapping argument names to annotations. + + The first four items in the tuple correspond to getargspec(). """ if ismethod(func): func = func.im_func if not isfunction(func): raise TypeError('arg is not a Python function') - args, varargs, varkw = getargs(func.__code__) - return args, varargs, varkw, func.__defaults__ + args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__) + return (args, varargs, varkw, func.__defaults__, + kwonlyargs, func.__kwdefaults__, func.__annotations__) def getargvalues(frame): """Get information about arguments passed into a particular frame. @@ -767,31 +810,66 @@ else: return convert(object) +def formatannotation(annotation, base_module=None): + if isinstance(annotation, type): + if annotation.__module__ in ('__builtin__', base_module): + return annotation.__name__ + return annotation.__module__+'.'+annotation.__name__ + return repr(annotation) + +def formatannotationrelativeto(object): + module = getattr(object, '__module__', None) + def _formatannotation(annotation): + return formatannotation(annotation, module) + return _formatannotation + def formatargspec(args, varargs=None, varkw=None, defaults=None, + kwonlyargs=(), kwonlydefaults={}, annotations={}, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), + formatreturns=lambda text: ' -> ' + text, + formatannotation=formatannotation, join=joinseq): - """Format an argument spec from the 4 values returned by getargspec. + """Format an argument spec from the values returned by getargspec + or getfullargspec. - The first four arguments are (args, varargs, varkw, defaults). The - other four arguments are the corresponding optional formatting functions - that are called to turn names and values into strings. The ninth - argument is an optional function to format the sequence of arguments.""" + The first seven arguments are (args, varargs, varkw, defaults, + kwonlyargs, kwonlydefaults, annotations). The other five arguments + are the corresponding optional formatting functions that are called to + turn names and values into strings. The last argument is an optional + function to format the sequence of arguments.""" + def formatargandannotation(arg): + result = formatarg(arg) + if arg in annotations: + result += ': ' + formatannotation(annotations[arg]) + return result specs = [] if defaults: firstdefault = len(args) - len(defaults) for i in range(len(args)): - spec = strseq(args[i], formatarg, join) + spec = strseq(args[i], formatargandannotation, join) if defaults and i >= firstdefault: spec = spec + formatvalue(defaults[i - firstdefault]) specs.append(spec) if varargs is not None: - specs.append(formatvarargs(varargs)) + specs.append(formatvarargs(formatargandannotation(varargs))) + else: + if kwonlyargs: + specs.append('*') + if kwonlyargs: + for kwonlyarg in kwonlyargs: + spec = formatargandannotation(kwonlyarg) + if kwonlyarg in kwonlydefaults: + spec += formatvalue(kwonlydefaults[kwonlyarg]) + specs.append(spec) if varkw is not None: - specs.append(formatvarkw(varkw)) - return '(' + string.join(specs, ', ') + ')' + specs.append(formatvarkw(formatargandannotation(varkw))) + result = '(' + string.join(specs, ', ') + ')' + if 'return' in annotations: + result += formatreturns(formatannotation(annotations['return'])) + return result def formatargvalues(args, varargs, varkw, locals, formatarg=str, Modified: python/branches/p3yk/Lib/pydoc.py ============================================================================== --- python/branches/p3yk/Lib/pydoc.py (original) +++ python/branches/p3yk/Lib/pydoc.py Wed Feb 28 23:03:49 2007 @@ -875,11 +875,17 @@ title = '%s = %s' % ( anchor, name, reallink) if inspect.isfunction(object): - args, varargs, varkw, defaults = inspect.getargspec(object) + args, varargs, kwonlyargs, kwdefaults, varkw, defaults, ann = \ + inspect.getfullargspec(object) argspec = inspect.formatargspec( - args, varargs, varkw, defaults, formatvalue=self.formatvalue) + args, varargs, kwonlyargs, kwdefaults, varkw, defaults, ann, + formatvalue=self.formatvalue, + formatannotation=inspect.formatannotationrelativeto(object)) if realname == '': title = '%s lambda ' % name + # XXX lambda's won't usually have func_annotations['return'] + # since the syntax doesn't support but it is possible. + # So removing parentheses isn't truly safe. argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' @@ -1241,11 +1247,17 @@ skipdocs = 1 title = self.bold(name) + ' = ' + realname if inspect.isfunction(object): - args, varargs, varkw, defaults = inspect.getargspec(object) + args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann = \ + inspect.getfullargspec(object) argspec = inspect.formatargspec( - args, varargs, varkw, defaults, formatvalue=self.formatvalue) + args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann, + formatvalue=self.formatvalue, + formatannotation=inspect.formatannotationrelativeto(object)) if realname == '': title = self.bold(name) + ' lambda ' + # XXX lambda's won't usually have func_annotations['return'] + # since the syntax doesn't support but it is possible. + # So removing parentheses isn't truly safe. argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)'